File size: 1,366 Bytes
42128a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Small pure helpers shared by the server modules. No state, no I/O.

import { isIP } from 'node:net';
import { TaperError } from './events.js';
import { paddedJson } from './padding.js';

export const now = () => Date.now();
export const b64url = (buf) => buf.toString('base64url');

// This machine (a host name, or a URL's hostname with IPv6 in brackets).
export const isLoopback = (host) => host === 'localhost' || host === '[::1]' || host === '::1' || (isIP(host) === 4 && host.startsWith('127.'));

// Remove the entries of `map` for which `expired(value, key)`, calling `then(key)`
// for each. Returns how many went.
export function dropWhere(map, expired, then = () => {}) {
  let n = 0;
  for (const [k, v] of map) if (expired(v, k)) { map.delete(k); then(k); n++; }
  return n;
}

// A failed request's error: a TaperError says what went wrong, anything else is logged and stays internal.
export function errorBody(err, method) {
  if (err instanceof TaperError) return { errcode: err.errcode, error: err.message, ...err.extra };
  console.error('internal error in', method, err);
  return { errcode: 'T_UNKNOWN', error: 'Internal server error' };
}

// A JSON frame (padded) or a binary one, if the socket is still open.
export function send(ws, frame) {
  if (ws?.readyState === ws?.OPEN) ws.send(Buffer.isBuffer(frame) ? frame : paddedJson(frame));
}