Files
FFF_vtt_frozen/tools/lib.mjs
T

64 lines
2.4 KiB
JavaScript

// Shared by the Node harnesses (DESIGN 10.4: Node 26, built-ins only, no npm deps).
// The global WebSocket accepts a non-standard {headers} second argument; wsheaders.test.mjs
// re-verifies on the wire that Cookie and Origin reach the server (the old "Node 22" note in
// the prototype's lib.mjs was stale; here the pin is the devbox node 26).
import fs from 'node:fs'
import net from 'node:net'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
export const sleep = ms => new Promise(r => setTimeout(r, ms))
export const projectRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
export const baseUrl = port => `http://127.0.0.1:${port}`
// Ports of a live dev session: never let a test stack touch them (prototype withserver.sh rule).
export function refuseLivePort(port) {
if ([8088, 8080, 9000].includes(port)) throw new Error(`refusing live port ${port}`)
}
export async function freePort() {
const srv = net.createServer()
await new Promise((res, rej) => { srv.once('error', rej); srv.listen(0, '127.0.0.1', res) })
const { port } = srv.address()
await new Promise(res => srv.close(res))
return port
}
function decodeIPv4(hex) {
const b = []
for (let i = 0; i < 8; i += 2) b.unshift(parseInt(hex.slice(i, i + 2), 16))
return b.join('.')
}
function decodeIPv6(hex) {
// /proc/net/tcp6 stores four 32-bit words, each little-endian.
const words = []
for (let w = 0; w < 4; w++) {
const h = hex.slice(w * 8, w * 8 + 8)
words.push(h.slice(6, 8) + h.slice(4, 6) + h.slice(2, 4) + h.slice(0, 2))
}
let groups = []
for (const w of words) groups.push(w.slice(0, 4), w.slice(4, 8))
const compact = groups.join(':').replace(/(^|:)0(:0)+(:|$)/, '::')
return compact
}
// Listening sockets of this host, from /proc (Linux only; the server side is NixOS).
export function listeningSockets(port) {
const out = []
for (const [file, proto] of [['/proc/net/tcp', 'tcp'], ['/proc/net/tcp6', 'tcp6']]) {
let text
try { text = fs.readFileSync(file, 'utf8') } catch { continue }
for (const line of text.trim().split('\n').slice(1)) {
const f = line.trim().split(/\s+/)
if (f.length < 4 || f[3] !== '0A') continue // 0A = LISTEN
const [addrHex, portHex] = f[1].split(':')
if (parseInt(portHex, 16) !== port) continue
out.push({ proto, hex: addrHex, addr: proto === 'tcp' ? decodeIPv4(addrHex) : decodeIPv6(addrHex) })
}
}
return out
}