Files
unkernel/js/core/tailscale/control-hpack.ts
Pooya Parsa d382f7fa9b js: add a pure-JS Tailscale network device (work in progress)
The guest joins a tailnet from Node or the page: ts2021 control over
WebSocket, DERP relays, WireGuard and the packet filter in JS, loaded as
a separate chunk only when the option is used. SDK net option, CLI
--tailscale* flags and a page panel. Relay only; exit nodes, IPv6 and
real peer traffic are not covered yet.
2026-11-28 22:06:18 +00:00

486 lines
16 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// HPACK (RFC 7541) for the control client's HTTP/2 (h2.ts): a decoder with
// the dynamic table and Huffman strings, and an encoder that indexes
// headers incrementally and Huffman-codes strings when that is shorter.
/** One header field: [name, value], names in lower case. */
export type HeaderField = [name: string, value: string];
/** Thrown on a malformed header block (an HTTP/2 COMPRESSION_ERROR). */
export class HpackError extends Error {
override name = "HpackError";
}
// RFC 7541 Appendix A, entries 1..61.
const STATIC: readonly (readonly [string, string])[] = [
[":authority", ""],
[":method", "GET"],
[":method", "POST"],
[":path", "/"],
[":path", "/index.html"],
[":scheme", "http"],
[":scheme", "https"],
[":status", "200"],
[":status", "204"],
[":status", "206"],
[":status", "304"],
[":status", "400"],
[":status", "404"],
[":status", "500"],
["accept-charset", ""],
["accept-encoding", "gzip, deflate"],
["accept-language", ""],
["accept-ranges", ""],
["accept", ""],
["access-control-allow-origin", ""],
["age", ""],
["allow", ""],
["authorization", ""],
["cache-control", ""],
["content-disposition", ""],
["content-encoding", ""],
["content-language", ""],
["content-length", ""],
["content-location", ""],
["content-range", ""],
["content-type", ""],
["cookie", ""],
["date", ""],
["etag", ""],
["expect", ""],
["expires", ""],
["from", ""],
["host", ""],
["if-match", ""],
["if-modified-since", ""],
["if-none-match", ""],
["if-range", ""],
["if-unmodified-since", ""],
["last-modified", ""],
["link", ""],
["location", ""],
["max-forwards", ""],
["proxy-authenticate", ""],
["proxy-authorization", ""],
["range", ""],
["referer", ""],
["refresh", ""],
["retry-after", ""],
["server", ""],
["set-cookie", ""],
["strict-transport-security", ""],
["transfer-encoding", ""],
["user-agent", ""],
["vary", ""],
["via", ""],
["www-authenticate", ""],
];
// RFC 7541 Appendix B: the code (right-aligned) and bit length of each
// symbol 0..255 and of EOS (256).
const HUFF_CODES = new Uint32Array([
0x1ff8, 0x7fffd8, 0xfffffe2, 0xfffffe3, 0xfffffe4, 0xfffffe5, 0xfffffe6, 0xfffffe7,
0xfffffe8, 0xffffea, 0x3ffffffc, 0xfffffe9, 0xfffffea, 0x3ffffffd, 0xfffffeb, 0xfffffec,
0xfffffed, 0xfffffee, 0xfffffef, 0xffffff0, 0xffffff1, 0xffffff2, 0x3ffffffe, 0xffffff3,
0xffffff4, 0xffffff5, 0xffffff6, 0xffffff7, 0xffffff8, 0xffffff9, 0xffffffa, 0xffffffb,
0x14, 0x3f8, 0x3f9, 0xffa, 0x1ff9, 0x15, 0xf8, 0x7fa,
0x3fa, 0x3fb, 0xf9, 0x7fb, 0xfa, 0x16, 0x17, 0x18,
0x0, 0x1, 0x2, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
0x1e, 0x1f, 0x5c, 0xfb, 0x7ffc, 0x20, 0xffb, 0x3fc,
0x1ffa, 0x21, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62,
0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a,
0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72,
0xfc, 0x73, 0xfd, 0x1ffb, 0x7fff0, 0x1ffc, 0x3ffc, 0x22,
0x7ffd, 0x3, 0x23, 0x4, 0x24, 0x5, 0x25, 0x26,
0x27, 0x6, 0x74, 0x75, 0x28, 0x29, 0x2a, 0x7,
0x2b, 0x76, 0x2c, 0x8, 0x9, 0x2d, 0x77, 0x78,
0x79, 0x7a, 0x7b, 0x7ffe, 0x7fc, 0x3ffd, 0x1ffd, 0xffffffc,
0xfffe6, 0x3fffd2, 0xfffe7, 0xfffe8, 0x3fffd3, 0x3fffd4, 0x3fffd5, 0x7fffd9,
0x3fffd6, 0x7fffda, 0x7fffdb, 0x7fffdc, 0x7fffdd, 0x7fffde, 0xffffeb, 0x7fffdf,
0xffffec, 0xffffed, 0x3fffd7, 0x7fffe0, 0xffffee, 0x7fffe1, 0x7fffe2, 0x7fffe3,
0x7fffe4, 0x1fffdc, 0x3fffd8, 0x7fffe5, 0x3fffd9, 0x7fffe6, 0x7fffe7, 0xffffef,
0x3fffda, 0x1fffdd, 0xfffe9, 0x3fffdb, 0x3fffdc, 0x7fffe8, 0x7fffe9, 0x1fffde,
0x7fffea, 0x3fffdd, 0x3fffde, 0xfffff0, 0x1fffdf, 0x3fffdf, 0x7fffeb, 0x7fffec,
0x1fffe0, 0x1fffe1, 0x3fffe0, 0x1fffe2, 0x7fffed, 0x3fffe1, 0x7fffee, 0x7fffef,
0xfffea, 0x3fffe2, 0x3fffe3, 0x3fffe4, 0x7ffff0, 0x3fffe5, 0x3fffe6, 0x7ffff1,
0x3ffffe0, 0x3ffffe1, 0xfffeb, 0x7fff1, 0x3fffe7, 0x7ffff2, 0x3fffe8, 0x1ffffec,
0x3ffffe2, 0x3ffffe3, 0x3ffffe4, 0x7ffffde, 0x7ffffdf, 0x3ffffe5, 0xfffff1, 0x1ffffed,
0x7fff2, 0x1fffe3, 0x3ffffe6, 0x7ffffe0, 0x7ffffe1, 0x3ffffe7, 0x7ffffe2, 0xfffff2,
0x1fffe4, 0x1fffe5, 0x3ffffe8, 0x3ffffe9, 0xffffffd, 0x7ffffe3, 0x7ffffe4, 0x7ffffe5,
0xfffec, 0xfffff3, 0xfffed, 0x1fffe6, 0x3fffe9, 0x1fffe7, 0x1fffe8, 0x7ffff3,
0x3fffea, 0x3fffeb, 0x1ffffee, 0x1ffffef, 0xfffff4, 0xfffff5, 0x3ffffea, 0x7ffff4,
0x3ffffeb, 0x7ffffe6, 0x3ffffec, 0x3ffffed, 0x7ffffe7, 0x7ffffe8, 0x7ffffe9, 0x7ffffea,
0x7ffffeb, 0xffffffe, 0x7ffffec, 0x7ffffed, 0x7ffffee, 0x7ffffef, 0x7fffff0, 0x3ffffee,
0x3fffffff,
]);
const HUFF_LENS = new Uint8Array([
13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28,
28, 28, 28, 28, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 28,
6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, 8, 6, 6, 6,
5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10,
13, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 13, 19, 13, 14, 6,
15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, 6, 5,
6, 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28,
20, 22, 20, 20, 22, 22, 22, 23, 22, 23, 23, 23, 23, 23, 24, 23,
24, 24, 22, 23, 24, 23, 23, 23, 23, 21, 22, 23, 22, 23, 23, 24,
22, 21, 20, 22, 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23,
21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22, 23, 22, 22, 23,
26, 26, 20, 19, 22, 23, 22, 25, 26, 26, 26, 27, 27, 26, 24, 25,
19, 21, 26, 27, 27, 26, 27, 24, 21, 21, 26, 26, 28, 27, 27, 27,
20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23,
26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26,
30,
]);
/** Size of a table entry (RFC 7541 4.1): octets of name and value + 32. */
function entrySize(name: string, value: string): number {
return utf8Length(name) + utf8Length(value) + 32;
}
const enc = new TextEncoder();
const dec = new TextDecoder();
function utf8Length(s: string): number {
let n = 0;
for (let i = 0; i < s.length; i++) {
const c = s.charCodeAt(i);
if (c < 0x80) n += 1;
else if (c < 0x800) n += 2;
else if (c >= 0xd800 && c < 0xdc00) { n += 4; i++; }
else n += 3;
}
return n;
}
/** The dynamic table: newest entry first. */
class DynamicTable {
entries: HeaderField[] = [];
size = 0;
maxSize: number;
constructor(maxSize: number) {
this.maxSize = maxSize;
}
add(name: string, value: string): void {
const s = entrySize(name, value);
this.entries.unshift([name, value]);
this.size += s;
this.evict();
}
resize(maxSize: number): void {
this.maxSize = maxSize;
this.evict();
}
evict(): void {
while (this.size > this.maxSize && this.entries.length) {
const [n, v] = this.entries.pop()!;
this.size -= entrySize(n, v);
}
}
}
// ---- Huffman ----
// Decoding trie: node i has children at TRIE[2i] (bit 0) and TRIE[2i+1]
// (bit 1); a value >= 0 is a child node, -1 - sym is a leaf.
const TRIE: Int32Array = (() => {
const t: number[] = [0, 0];
let nodes = 1;
for (let sym = 0; sym < 257; sym++) {
const code = HUFF_CODES[sym]!;
const len = HUFF_LENS[sym]!;
let node = 0;
for (let b = len - 1; b >= 0; b--) {
const bit = (code >>> b) & 1;
const slot = 2 * node + bit;
if (b === 0) {
t[slot] = -1 - sym;
} else {
if (!t[slot]) {
t[slot] = nodes++;
t.push(0, 0);
}
node = t[slot]!;
}
}
}
return Int32Array.from(t);
})();
/** Decodes a Huffman-coded string (RFC 7541 5.2). */
export function huffmanDecode(data: Uint8Array): Uint8Array {
const out: number[] = [];
let node = 0;
let depth = 0; // bits since the last symbol
let allOnes = true; // those bits were all ones
for (let i = 0; i < data.length; i++) {
const byte = data[i]!;
for (let b = 7; b >= 0; b--) {
const bit = (byte >> b) & 1;
const next = TRIE[2 * node + bit]!;
depth++;
if (!bit) allOnes = false;
if (next < 0) {
const sym = -1 - next;
if (sym === 256) throw new HpackError("hpack: EOS in Huffman string");
out.push(sym);
node = 0;
depth = 0;
allOnes = true;
} else if (next === 0) {
throw new HpackError("hpack: invalid Huffman code");
} else {
node = next;
}
}
}
if (depth > 7 || !allOnes) throw new HpackError("hpack: invalid Huffman padding");
return Uint8Array.from(out);
}
/** Length in octets of the Huffman coding of data. */
function huffmanLength(data: Uint8Array): number {
let bits = 0;
for (let i = 0; i < data.length; i++) bits += HUFF_LENS[data[i]!]!;
return (bits + 7) >> 3;
}
/** Huffman-codes data (RFC 7541 5.2), padded with ones. */
export function huffmanEncode(data: Uint8Array): Uint8Array {
const out = new Uint8Array(huffmanLength(data));
let acc = 0; // pending bits, at most 7 + 30 so kept as a float-safe number
let nbits = 0;
let o = 0;
for (let i = 0; i < data.length; i++) {
const sym = data[i]!;
acc = acc * 2 ** HUFF_LENS[sym]! + HUFF_CODES[sym]!;
nbits += HUFF_LENS[sym]!;
while (nbits >= 8) {
nbits -= 8;
out[o++] = Math.floor(acc / 2 ** nbits) & 0xff;
acc %= 2 ** nbits;
}
}
if (nbits > 0) out[o++] = ((acc << (8 - nbits)) | (0xff >> nbits)) & 0xff;
return out;
}
// ---- Decoder ----
/** The largest decoded header list accepted (control's responses carry a few hundred bytes). */
export const MAX_HEADER_LIST_SIZE = 256 << 10;
/** Decodes header blocks; one per connection direction (server to client). */
export class HpackDecoder {
#table: DynamicTable;
/** The limit the table size updates may raise the table to (SETTINGS_HEADER_TABLE_SIZE). */
maxAllowedSize: number;
constructor(maxTableSize = 4096) {
this.#table = new DynamicTable(maxTableSize);
this.maxAllowedSize = maxTableSize;
}
/** Current dynamic table, newest first (for tests). */
get dynamicTable(): readonly HeaderField[] {
return this.#table.entries;
}
/** Current dynamic table size in RFC 7541 octets (for tests). */
get dynamicTableSize(): number {
return this.#table.size;
}
#entry(index: number): HeaderField {
if (index <= 0) throw new HpackError("hpack: index 0");
if (index <= STATIC.length) {
const e = STATIC[index - 1]!;
return [e[0], e[1]];
}
const e = this.#table.entries[index - STATIC.length - 1];
if (!e) throw new HpackError(`hpack: index ${index} out of range`);
return [e[0], e[1]];
}
/**
* Decodes one complete header block. The decoded list may hold at most
* `maxListSize` octets (RFC 7540 6.5.2's size: name + value + 32 per
* field), since a small block can name large table entries many times.
*/
decode(block: Uint8Array, maxListSize = MAX_HEADER_LIST_SIZE): HeaderField[] {
const out: HeaderField[] = [];
let listSize = 0;
const push = (f: HeaderField) => {
listSize += f[0].length + f[1].length + 32;
if (listSize > maxListSize) throw new HpackError(`hpack: header list over ${maxListSize} octets`);
out.push(f);
};
let p = 0;
let fieldSeen = false;
const int = (prefix: number): number => {
const r = decodeInt(block, p, prefix);
p = r.next;
return r.value;
};
const str = (): string => {
if (p >= block.length) throw new HpackError("hpack: truncated string");
const huff = (block[p]! & 0x80) !== 0;
const len = int(7);
if (p + len > block.length) throw new HpackError("hpack: truncated string");
const raw = block.subarray(p, p + len);
p += len;
return dec.decode(huff ? huffmanDecode(raw) : raw);
};
while (p < block.length) {
const b = block[p]!;
if (b & 0x80) {
// Indexed (6.1)
push(this.#entry(int(7)));
fieldSeen = true;
} else if (b & 0x40) {
// Literal with incremental indexing (6.2.1)
const idx = int(6);
const name = idx ? this.#entry(idx)[0] : str();
const value = str();
this.#table.add(name, value);
push([name, value]);
fieldSeen = true;
} else if (b & 0x20) {
// Dynamic table size update (6.3), only at the start of a block
if (fieldSeen) throw new HpackError("hpack: table size update after a field");
const size = int(5);
if (size > this.maxAllowedSize) throw new HpackError(`hpack: table size ${size} over the limit`);
this.#table.resize(size);
} else {
// Literal without indexing (6.2.2) or never indexed (6.2.3)
const idx = int(4);
const name = idx ? this.#entry(idx)[0] : str();
const value = str();
push([name, value]);
fieldSeen = true;
}
}
return out;
}
}
function decodeInt(buf: Uint8Array, p: number, prefix: number): { value: number; next: number } {
if (p >= buf.length) throw new HpackError("hpack: truncated integer");
const max = (1 << prefix) - 1;
let value = buf[p++]! & max;
if (value < max) return { value, next: p };
let m = 0;
for (;;) {
if (p >= buf.length) throw new HpackError("hpack: truncated integer");
const b = buf[p++]!;
value += (b & 0x7f) * 2 ** m;
m += 7;
if (!(b & 0x80)) break;
if (m > 28) throw new HpackError("hpack: integer overflow");
}
return { value, next: p };
}
// ---- Encoder ----
export interface HpackEncodeOptions {
/** Huffman-code strings: true always, false never, "auto" (default) when shorter. */
huffman?: boolean | "auto";
}
/** Encodes header blocks; one per connection direction (client to server). */
export class HpackEncoder {
#table: DynamicTable;
#pendingSizeUpdate: number | null = null;
/** Add literals to the dynamic table (default true); false sends every literal without indexing. */
indexing: boolean;
constructor(maxTableSize = 4096, indexing = true) {
this.#table = new DynamicTable(maxTableSize);
this.indexing = indexing;
}
/** Current dynamic table, newest first (for tests). */
get dynamicTable(): readonly HeaderField[] {
return this.#table.entries;
}
/**
* Applies the peer's SETTINGS_HEADER_TABLE_SIZE: the next block starts
* with a table size update.
*/
setMaxTableSize(size: number): void {
const s = Math.min(size, 4096);
if (s === this.#table.maxSize && this.#pendingSizeUpdate === null) return;
this.#table.resize(s);
this.#pendingSizeUpdate = s;
}
/** Encodes one header block. Names must already be lower case. */
encode(headers: readonly HeaderField[], opts: HpackEncodeOptions = {}): Uint8Array {
const out: number[] = [];
const huffman = opts.huffman ?? "auto";
if (this.#pendingSizeUpdate !== null) {
encodeInt(out, this.#pendingSizeUpdate, 5, 0x20);
this.#pendingSizeUpdate = null;
}
for (const [name, value] of headers) {
const sensitive = name === "authorization";
let nameIdx = 0;
let fullIdx = 0;
for (let i = 0; i < STATIC.length && !fullIdx; i++) {
const e = STATIC[i]!;
if (e[0] !== name) continue;
if (!nameIdx) nameIdx = i + 1;
if (e[1] === value) fullIdx = i + 1;
}
const dyn = this.#table.entries;
for (let i = 0; i < dyn.length && !fullIdx; i++) {
const e = dyn[i]!;
if (e[0] !== name) continue;
if (!nameIdx) nameIdx = STATIC.length + i + 1;
if (e[1] === value) fullIdx = STATIC.length + i + 1;
}
if (fullIdx && !sensitive) {
encodeInt(out, fullIdx, 7, 0x80);
continue;
}
if (sensitive) encodeInt(out, nameIdx, 4, 0x10);
else if (this.indexing) encodeInt(out, nameIdx, 6, 0x40);
else encodeInt(out, nameIdx, 4, 0x00);
if (!nameIdx) encodeString(out, name, huffman);
encodeString(out, value, huffman);
if (this.indexing && !sensitive) this.#table.add(name, value);
}
return Uint8Array.from(out);
}
}
function encodeInt(out: number[], value: number, prefix: number, flags: number): void {
const max = (1 << prefix) - 1;
if (value < max) {
out.push(flags | value);
return;
}
out.push(flags | max);
value -= max;
while (value >= 128) {
out.push((value % 128) | 0x80);
value = Math.floor(value / 128);
}
out.push(value);
}
function encodeString(out: number[], s: string, huffman: boolean | "auto"): void {
const raw = enc.encode(s);
const useHuff = huffman === true || (huffman === "auto" && huffmanLength(raw) < raw.length);
const data = useHuff ? huffmanEncode(raw) : raw;
encodeInt(out, data.length, 7, useHuff ? 0x80 : 0);
for (let i = 0; i < data.length; i++) out.push(data[i]!);
}