@x-tech-laboratories/x-app 0.107.0 → 0.109.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,86 @@
1
+ // The models an OpenAI-compatible endpoint offers, from its GET /models, so the user can pick one rather than type its
2
+ // name. A llama.cpp router also says of each model whether it is in memory, which is kept; any failure is no list, with
3
+ // the reason in plain words that never hold the key. Needs only fetch, so it runs in a page as on Node.
4
+ // ── Reading ──────────────────────────────────────────────────────────────────
5
+ // How long the endpoint has to answer before the list is given up.
6
+ export const list_timeout_ms = 5000;
7
+ // The most models kept from one answer, so an odd server cannot flood the page.
8
+ export const most_models = 500;
9
+ const states = ["loaded", "loading", "unloaded", "failed"];
10
+ const is_record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11
+ // A model's load state as a llama.cpp router gives it: `status` as `{ value }` or a plain word, or a `loaded` switch.
12
+ export function state_of(entry) {
13
+ const status = is_record(entry.status) ? entry.status.value : entry.status;
14
+ if (typeof status === "string" && states.includes(status))
15
+ return status;
16
+ if (is_record(entry.status) && entry.status.failed === true)
17
+ return "failed";
18
+ if (typeof entry.loaded === "boolean")
19
+ return entry.loaded ? "loaded" : "unloaded";
20
+ return "";
21
+ }
22
+ // The models in an OpenAI-format answer, `{ data: [{ id }] }`, each once, in the order given.
23
+ export function models_of(body) {
24
+ if (!is_record(body) || !Array.isArray(body.data))
25
+ return null;
26
+ const seen = new Set();
27
+ const models = [];
28
+ for (const entry of body.data) {
29
+ if (!is_record(entry) || typeof entry.id !== "string")
30
+ continue;
31
+ const id = entry.id.trim();
32
+ if (!id || id.length > 200 || seen.has(id))
33
+ continue;
34
+ seen.add(id);
35
+ models.push({ id, state: state_of(entry) });
36
+ if (models.length >= most_models)
37
+ break;
38
+ }
39
+ return models;
40
+ }
41
+ // Where the endpoint is, by host and port alone, for a reason shown to the user.
42
+ function place_of(endpoint) {
43
+ try {
44
+ return new URL(endpoint).host;
45
+ }
46
+ catch {
47
+ return "the endpoint";
48
+ }
49
+ }
50
+ // The models the endpoint lists, asked with the key when there is one; never throws.
51
+ export async function list_endpoint_models(endpoint, api_key, signal, fetcher = fetch) {
52
+ const base = endpoint.trim().replace(/\/+$/, "");
53
+ const place = place_of(base);
54
+ const timeout = AbortSignal.timeout(list_timeout_ms);
55
+ try {
56
+ const response = await fetcher(`${base}/models`, {
57
+ headers: { accept: "application/json", ...(api_key ? { authorization: `Bearer ${api_key}` } : {}) },
58
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
59
+ });
60
+ if (response.status === 401 || response.status === 403)
61
+ return { models: [], problem: `${place} refused the API key when asked for its models.` };
62
+ if (!response.ok)
63
+ return { models: [], problem: `${place} does not list its models (it answered ${response.status}).` };
64
+ const models = models_of(await response.json().catch(() => null));
65
+ if (models === null)
66
+ return { models: [], problem: `${place} answered, but not with a list of models.` };
67
+ return { models, problem: models.length === 0 ? `${place} lists no models.` : "" };
68
+ }
69
+ catch {
70
+ return { models: [], problem: timeout.aborted ? `${place} did not list its models in time.` : `${place} could not be reached to list its models.` };
71
+ }
72
+ }
73
+ // ── Showing ──────────────────────────────────────────────────────────────────
74
+ const state_words = { loaded: "loaded", loading: "loading", unloaded: "not loaded", failed: "failed to load" };
75
+ // A model's name with what its server says of it, such as "qwen3 (loaded)".
76
+ export function model_label(model) {
77
+ return model.state ? `${model.id} (${state_words[model.state]})` : model.id;
78
+ }
79
+ // Whether the next request to this model may wait while its server loads it: it is listed as not loaded, or, where the
80
+ // server does not say, it was only just chosen.
81
+ export function may_load(listing, model, just_chosen) {
82
+ const found = listing?.models.find((each) => each.id === model);
83
+ if (found?.state)
84
+ return found.state !== "loaded";
85
+ return just_chosen;
86
+ }
@@ -0,0 +1,30 @@
1
+ export declare function is_local_endpoint(endpoint: string): boolean;
2
+ export declare function host_of(endpoint: string, default_endpoint?: string): string;
3
+ export interface PlainError {
4
+ message: string;
5
+ detail?: string;
6
+ }
7
+ export declare class PlainFailure extends Error {
8
+ readonly detail: string | undefined;
9
+ constructor(message: string, detail?: string);
10
+ }
11
+ export declare class ContextOverflow extends Error {
12
+ readonly prompt_tokens: number | null;
13
+ constructor(message: string, prompt_tokens?: number | null);
14
+ }
15
+ export declare function hide_keys(text: string): string;
16
+ export declare function overflow_of(error: unknown): ContextOverflow | null;
17
+ export interface EndpointWhere {
18
+ endpoint: string;
19
+ default_endpoint?: string;
20
+ model?: string;
21
+ label?: string;
22
+ settings?: string;
23
+ key_name?: string;
24
+ serves?: string;
25
+ retry?: string;
26
+ rate_limit_advice?: string;
27
+ overflow_advice?: string;
28
+ keep_unknown?: boolean;
29
+ }
30
+ export declare function explain_endpoint_failure(error: unknown, where: EndpointWhere): PlainError;
@@ -0,0 +1,150 @@
1
+ // An API endpoint a user points an app at, such as a model server's: whether it answers on the user's own machine or
2
+ // network, and its failures put in plain words that say what happened and what to do, with the raw detail kept for a
3
+ // Details disclosure. No message names a key, and the endpoint is named by host and port alone.
4
+ // ── Hosting ──────────────────────────────────────────────────────────────────
5
+ // The four numbers of an IPv4 address, or null for anything else.
6
+ function ipv4_parts(host) {
7
+ const parts = host.split(".");
8
+ if (parts.length !== 4 || !parts.every((part) => /^\d{1,3}$/.test(part)))
9
+ return null;
10
+ const numbers = parts.map(Number);
11
+ return numbers.every((number) => number <= 255) ? numbers : null;
12
+ }
13
+ // Loopback (127/8), private (10/8, 172.16/12, 192.168/16) or link-local (169.254/16).
14
+ function is_local_ipv4([first, second]) {
15
+ return first === 127 || first === 10 || (first === 172 && second >= 16 && second <= 31) || (first === 192 && second === 168) || (first === 169 && second === 254);
16
+ }
17
+ // Loopback (::1), unique local (fc00::/7), link-local (fe80::/10) or an IPv4 address mapped into IPv6.
18
+ function is_local_ipv6(host) {
19
+ const bare = host.replace(/^\[|\]$/g, "").toLowerCase();
20
+ if (bare === "::1")
21
+ return true;
22
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(bare);
23
+ if (mapped) {
24
+ const parts = ipv4_parts(mapped[1]);
25
+ return parts !== null && is_local_ipv4(parts);
26
+ }
27
+ // The same, as URL writes it: two groups of hex, such as ::ffff:c0a8:102 for 192.168.1.2.
28
+ const mapped_hex = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(bare);
29
+ if (mapped_hex) {
30
+ const [high, low] = [parseInt(mapped_hex[1], 16), parseInt(mapped_hex[2], 16)];
31
+ return is_local_ipv4([high >> 8, high & 255, low >> 8, low & 255]);
32
+ }
33
+ return /^f[cd][0-9a-f]{0,2}:/.test(bare) || /^fe[89ab][0-9a-f]?:/.test(bare);
34
+ }
35
+ // Whether the endpoint's host is loopback or a private-network address; an empty or unreadable endpoint is not.
36
+ export function is_local_endpoint(endpoint) {
37
+ let host;
38
+ try {
39
+ host = new URL(endpoint.trim()).hostname.toLowerCase();
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ if (host === "localhost" || host.endsWith(".localhost"))
45
+ return true;
46
+ const parts = ipv4_parts(host);
47
+ if (parts)
48
+ return is_local_ipv4(parts);
49
+ return host.includes(":") && is_local_ipv6(host);
50
+ }
51
+ // The endpoint's host and port, never its path, user or password; the default endpoint when it is empty.
52
+ export function host_of(endpoint, default_endpoint = "") {
53
+ try {
54
+ const url = new URL(endpoint.trim() || default_endpoint);
55
+ const port = url.port || (url.protocol === "https:" ? "443" : url.protocol === "http:" ? "80" : "");
56
+ return port ? `${url.hostname}:${port}` : url.hostname;
57
+ }
58
+ catch {
59
+ return "the address in its settings";
60
+ }
61
+ }
62
+ export class PlainFailure extends Error {
63
+ detail;
64
+ constructor(message, detail) {
65
+ super(message);
66
+ this.name = "PlainFailure";
67
+ this.detail = detail;
68
+ }
69
+ }
70
+ // A request the endpoint refused as larger than its model's context, with the tokens it counted when it said.
71
+ export class ContextOverflow extends Error {
72
+ prompt_tokens;
73
+ constructor(message, prompt_tokens = null) {
74
+ super(message);
75
+ this.name = "ContextOverflow";
76
+ this.prompt_tokens = prompt_tokens;
77
+ }
78
+ }
79
+ // Anything shaped like an API key, which some providers quote back in part, is hidden.
80
+ export function hide_keys(text) {
81
+ return text.replace(/\b(?:sk|pk|rk)[-_][A-Za-z0-9*_.-]{5,}[A-Za-z0-9*_-]/gi, "[hidden]");
82
+ }
83
+ function status_of(error) {
84
+ const status = error?.status;
85
+ return typeof status === "number" ? status : null;
86
+ }
87
+ function message_of(error) {
88
+ return error instanceof Error ? error.message : String(error);
89
+ }
90
+ function codes_of(error) {
91
+ const codes = [];
92
+ for (let at = error, depth = 0; at && typeof at === "object" && depth < 5; at = at.cause, depth += 1) {
93
+ const code = at.code;
94
+ if (typeof code === "string")
95
+ codes.push(code);
96
+ }
97
+ return codes;
98
+ }
99
+ const overflow_words = /context (?:length|size|window)|exceeds the available context|prompt is too long|too many tokens|maximum context|context_length_exceeded|input is too long/i;
100
+ // The endpoint refused a request as larger than its context, with the size it counted when it said; null for another failure.
101
+ export function overflow_of(error) {
102
+ if (error instanceof ContextOverflow)
103
+ return error;
104
+ const status = status_of(error);
105
+ const message = message_of(error);
106
+ if (status !== 413 && !(status === 400 && overflow_words.test(message)))
107
+ return null;
108
+ const counted = /request \((\d+) tokens\)|resulted in (\d+) tokens|too long: (\d+) tokens|prompt has (\d+) tokens/i.exec(message);
109
+ const tokens = counted ? Number(counted.slice(1).find(Boolean)) : null;
110
+ return new ContextOverflow(hide_keys(message), tokens);
111
+ }
112
+ const connection_codes = new Set(["ECONNREFUSED", "ENOTFOUND", "EHOSTUNREACH", "ENETUNREACH", "ECONNRESET", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"]);
113
+ // The SDKs' error classes keep the name "Error", so their class is told by its constructor too.
114
+ function is_named(error, name) {
115
+ const given = error;
116
+ return given?.name === name || given?.constructor?.name === name;
117
+ }
118
+ function is_timeout(error) {
119
+ return is_named(error, "APIConnectionTimeoutError") || codes_of(error).includes("ETIMEDOUT") || /^Request timed out\.?$/i.test(message_of(error));
120
+ }
121
+ function is_unreachable(error) {
122
+ return is_named(error, "APIConnectionError") || codes_of(error).some((code) => connection_codes.has(code)) || /^(Connection error\.|fetch failed)$/i.test(message_of(error));
123
+ }
124
+ // A failure reaching or asking the endpoint in plain words, with the raw text, its keys hidden, as its detail.
125
+ export function explain_endpoint_failure(error, where) {
126
+ const at = `The ${where.label ?? "service"} at ${host_of(where.endpoint, where.default_endpoint)}`;
127
+ const under = where.settings ? ` under ${where.settings}` : "";
128
+ const status = status_of(error);
129
+ const raw = hide_keys(message_of(error));
130
+ const codes = codes_of(error).filter((code) => !raw.includes(code));
131
+ const detail = codes.length > 0 ? `${raw} (${codes.join(", ")})` : raw;
132
+ const plain = (message) => ({ message, detail });
133
+ if (is_timeout(error))
134
+ return plain(`${at} did not answer in time. Check that its server is running and not overloaded${where.retry ? `, then ${where.retry}` : ""}.`);
135
+ if (status === null && is_unreachable(error))
136
+ return plain(`${at} cannot be reached. Check that its server is running and that its endpoint${under} is right.`);
137
+ if (overflow_of(error))
138
+ return plain(`The request was too large for the model's context.${where.overflow_advice ? ` ${where.overflow_advice}` : ""}`);
139
+ if (status === 401 || status === 403)
140
+ return plain(`${at} refused the API key. Check its ${where.key_name ?? "API key"}${under}.`);
141
+ if (status === 404 && /model/i.test(raw))
142
+ return plain(`${at} does not know the model “${where.model ?? ""}”. Check the model's name${under}.`);
143
+ if (status === 404)
144
+ return plain(`${at} has no ${where.serves ?? "API"} at that address. Check its endpoint${under}; it usually ends in /v1.`);
145
+ if (status === 429)
146
+ return plain(`${at} is limiting how often it is asked. ${where.rate_limit_advice ?? "Wait a minute and try again."}`);
147
+ if (status === null && where.keep_unknown)
148
+ return { message: raw };
149
+ return plain(`${at} could not answer.`);
150
+ }
@@ -0,0 +1,6 @@
1
+ export declare function unescape_html(text: string): string;
2
+ export interface PageText {
3
+ title: string;
4
+ text: string;
5
+ }
6
+ export declare function html_to_text(html: string, base?: string): PageText;
@@ -0,0 +1,122 @@
1
+ // A web page's readable text: its title, then its words a block to a line, scripts, styles and drawings left out, and
2
+ // each link kept as plain text with its address after it. It needs nothing of Node or a page, so it runs anywhere.
3
+ // ── Entities ─────────────────────────────────────────────────────────────────
4
+ const named_entities = {
5
+ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", copy: "©", reg: "®", trade: "™", hellip: "…",
6
+ mdash: "—", ndash: "–", lsquo: "‘", rsquo: "’", ldquo: "“", rdquo: "”", laquo: "«", raquo: "»", bull: "•",
7
+ middot: "·", euro: "€", pound: "£", yen: "¥", cent: "¢", sect: "§", deg: "°", times: "×", divide: "÷", minus: "−",
8
+ };
9
+ // Character references such as &amp; and &#8217; as the characters they name.
10
+ export function unescape_html(text) {
11
+ return text.replace(/&(#[0-9]+|#[xX][0-9a-fA-F]+|[A-Za-z][A-Za-z0-9]*);?/g, (whole, name) => {
12
+ if (name.startsWith("#")) {
13
+ const code = name[1] === "x" || name[1] === "X" ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
14
+ return code > 0 && code <= 0x10ffff && !(code >= 0xd800 && code <= 0xdfff) ? String.fromCodePoint(code) : "�";
15
+ }
16
+ return named_entities[name] ?? named_entities[name.toLowerCase()] ?? whole;
17
+ });
18
+ }
19
+ // ── Text ─────────────────────────────────────────────────────────────────────
20
+ const block_tags = new Set(["address", "article", "aside", "blockquote", "br", "dd", "div", "dl", "dt", "figcaption", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "li", "main", "nav", "ol", "p", "pre", "section", "table", "td", "th", "tr", "ul"]);
21
+ const hidden_tags = new Set(["script", "style", "noscript", "svg", "template", "iframe", "object", "canvas"]);
22
+ // Read as they are up to their closing tag, since what is inside is not markup.
23
+ const raw_text_tags = new Set(["script", "style"]);
24
+ function attribute(attributes, name) {
25
+ const found = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i").exec(attributes);
26
+ return found ? unescape_html(found[1] ?? found[2] ?? found[3] ?? "") : null;
27
+ }
28
+ // A link's address made whole against the page's, when it leads to another web page.
29
+ function link_address(href, base) {
30
+ if (!href)
31
+ return null;
32
+ try {
33
+ const address = new URL(href, base || undefined);
34
+ return address.protocol === "http:" || address.protocol === "https:" ? address.href : null;
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ // The page's title and readable text; `base` is the page's address, which makes its relative links whole.
41
+ export function html_to_text(html, base = "") {
42
+ const parts = [];
43
+ const title_parts = [];
44
+ let hidden = 0;
45
+ let in_title = false;
46
+ // Each open link: its address, and where its text starts among the parts.
47
+ const links = [];
48
+ const data = (raw, unescape = true) => {
49
+ if (!raw || hidden)
50
+ return;
51
+ const text = unescape ? unescape_html(raw) : raw;
52
+ if (in_title)
53
+ title_parts.push(text);
54
+ else
55
+ parts.push(text);
56
+ };
57
+ const start_tag = (name, attributes) => {
58
+ if (hidden_tags.has(name))
59
+ hidden += 1;
60
+ if (hidden)
61
+ return;
62
+ if (name === "title")
63
+ in_title = true;
64
+ if (block_tags.has(name))
65
+ parts.push("\n");
66
+ if (name === "a")
67
+ links.push({ address: link_address(attribute(attributes, "href"), base), start: parts.length });
68
+ };
69
+ const end_tag = (name) => {
70
+ if (hidden_tags.has(name) && hidden) {
71
+ hidden -= 1;
72
+ return;
73
+ }
74
+ if (hidden)
75
+ return;
76
+ if (name === "title")
77
+ in_title = false;
78
+ if (name === "a") {
79
+ const link = links.pop();
80
+ const said = link ? parts.slice(link.start).join("").replace(/\s+/g, " ").trim() : "";
81
+ if (link?.address && said !== link.address)
82
+ parts.push(said ? ` (${link.address})` : link.address);
83
+ }
84
+ if (block_tags.has(name))
85
+ parts.push("\n");
86
+ };
87
+ const tag = /<(\/?)([A-Za-z][^\s/>]*)((?:[^>"']|"[^"]*"|'[^']*')*)>|<!--[\s\S]*?(?:-->|$)|<![^>]*>|<\?[^>]*>/g;
88
+ let position = 0;
89
+ for (let match = tag.exec(html); match !== null; match = tag.exec(html)) {
90
+ data(html.slice(position, match.index));
91
+ position = tag.lastIndex;
92
+ if (match[2] === undefined)
93
+ continue;
94
+ const name = match[2].toLowerCase();
95
+ const attributes = match[3] ?? "";
96
+ if (match[1]) {
97
+ end_tag(name);
98
+ continue;
99
+ }
100
+ start_tag(name, attributes);
101
+ if (attributes.trimEnd().endsWith("/"))
102
+ end_tag(name);
103
+ else if (raw_text_tags.has(name)) {
104
+ const close = new RegExp(`</${name}\\s*>`, "ig");
105
+ close.lastIndex = position;
106
+ const end = close.exec(html);
107
+ data(html.slice(position, end ? end.index : html.length), false);
108
+ if (end) {
109
+ end_tag(name);
110
+ position = close.lastIndex;
111
+ }
112
+ else
113
+ position = html.length;
114
+ tag.lastIndex = position;
115
+ }
116
+ }
117
+ data(html.slice(position));
118
+ const words = (text) => text.split(/\s+/).filter(Boolean).join(" ");
119
+ const title = words(title_parts.join(" "));
120
+ const lines = parts.join("").split(/\r\n|\r|\n/).map(words).filter(Boolean);
121
+ return { title: Array.from(title).slice(0, 500).join(""), text: lines.join("\n") };
122
+ }
@@ -0,0 +1,4 @@
1
+ export declare const repeat_window_chars = 1200;
2
+ export declare const repeat_check_chars = 200;
3
+ export declare function is_repeating(text: string): boolean;
4
+ export declare function repetition_watch(): (text: string) => boolean;
@@ -0,0 +1,26 @@
1
+ // Notices text going round in circles, such as a model's reply stuck in a loop: looping text packs far smaller than
2
+ // prose, code or data does. On fflate, so it runs in a page as on Node.
3
+ // ── Imports ──────────────────────────────────────────────────────────────────
4
+ import { deflateSync, strToU8 } from "fflate";
5
+ // ── Repetition ───────────────────────────────────────────────────────────────
6
+ export const repeat_window_chars = 1200;
7
+ // How much new text arrives between checks.
8
+ export const repeat_check_chars = 200;
9
+ const repeat_ratio = 0.2;
10
+ // Whether the last repeat_window_chars of the text pack to under a fifth of their size.
11
+ export function is_repeating(text) {
12
+ if (text.length < repeat_window_chars)
13
+ return false;
14
+ const tail = strToU8(text.slice(-repeat_window_chars));
15
+ return deflateSync(tail).length / tail.length < repeat_ratio;
16
+ }
17
+ // Says, as text streams in, whether it has started repeating; checks every repeat_check_chars.
18
+ export function repetition_watch() {
19
+ let checked = 0;
20
+ return (text) => {
21
+ if (text.length - checked < repeat_check_chars)
22
+ return false;
23
+ checked = text.length;
24
+ return is_repeating(text);
25
+ };
26
+ }
@@ -0,0 +1,13 @@
1
+ import { type LookupFunction } from "node:net";
2
+ export declare function is_public_address(address: string): boolean;
3
+ export type Resolver = (hostname: string) => Promise<string[]>;
4
+ export interface GuardOptions {
5
+ resolve?: Resolver;
6
+ allowed_ports?: ReadonlySet<number>;
7
+ ports_hint?: string;
8
+ allow_address?: (address: string) => boolean;
9
+ }
10
+ export declare function ports_of(setting: unknown): Set<number>;
11
+ export declare function checked_web_address(url: string, options?: GuardOptions): URL;
12
+ export declare function public_addresses(hostname: string, options?: GuardOptions): Promise<string[]>;
13
+ export declare function guarded_lookup(options?: GuardOptions): LookupFunction;
@@ -0,0 +1,129 @@
1
+ // Which web addresses a server may fetch for its user or a program: plain http or https, no credentials in the
2
+ // address, the usual port unless the app allows another, and a host that resolves only to public addresses, checked
3
+ // again as the connection is made, so a name that changes its answer cannot lead to this computer or its network.
4
+ // ── Imports ──────────────────────────────────────────────────────────────────
5
+ import { lookup } from "node:dns/promises";
6
+ import { BlockList, isIP } from "node:net";
7
+ // ── Public addresses ─────────────────────────────────────────────────────────
8
+ const non_public_ipv4 = new BlockList();
9
+ for (const [network, prefix] of [
10
+ ["0.0.0.0", 8], ["10.0.0.0", 8], ["100.64.0.0", 10], ["127.0.0.0", 8], ["169.254.0.0", 16], ["172.16.0.0", 12],
11
+ ["192.0.0.0", 24], ["192.0.2.0", 24], ["192.88.99.0", 24], ["192.168.0.0", 16], ["198.18.0.0", 15],
12
+ ["198.51.100.0", 24], ["203.0.113.0", 24], ["224.0.0.0", 4], ["240.0.0.0", 4],
13
+ ]) {
14
+ non_public_ipv4.addSubnet(network, prefix, "ipv4");
15
+ }
16
+ const non_public_ipv6 = new BlockList();
17
+ for (const [network, prefix] of [
18
+ ["64:ff9b:1::", 48], ["100::", 64], ["2001::", 23], ["2001:db8::", 32], ["2002::", 16], ["3fff::", 20], ["5f00::", 16],
19
+ ["fc00::", 7], ["fe80::", 10], ["fec0::", 10], ["ff00::", 8],
20
+ ]) {
21
+ non_public_ipv6.addSubnet(network, prefix, "ipv6");
22
+ }
23
+ // An IPv6 address as its sixteen bytes, or null when it is not one.
24
+ function ipv6_bytes(address) {
25
+ if (isIP(address) !== 6)
26
+ return null;
27
+ let text = address.split("%")[0].toLowerCase();
28
+ const dotted = /(\d+\.\d+\.\d+\.\d+)$/.exec(text);
29
+ if (dotted) {
30
+ const quad = dotted[1].split(".").map(Number);
31
+ text = `${text.slice(0, dotted.index)}${((quad[0] << 8) | quad[1]).toString(16)}:${((quad[2] << 8) | quad[3]).toString(16)}`;
32
+ }
33
+ const [head, tail] = text.split("::");
34
+ const groups_of = (part) => (part ? part.split(":").filter(Boolean) : []);
35
+ const front = groups_of(head);
36
+ const back = groups_of(tail);
37
+ const groups = tail === undefined ? front : [...front, ...Array(8 - front.length - back.length).fill("0"), ...back];
38
+ if (groups.length !== 8)
39
+ return null;
40
+ return groups.flatMap((group) => {
41
+ const value = parseInt(group, 16);
42
+ return [value >> 8, value & 255];
43
+ });
44
+ }
45
+ // Whether an address is reachable on the public internet; an IPv4 address carried inside IPv6, mapped or through the
46
+ // NAT64 prefix, is judged as itself.
47
+ export function is_public_address(address) {
48
+ const family = isIP(address);
49
+ if (family === 4)
50
+ return !non_public_ipv4.check(address, "ipv4");
51
+ const bytes = ipv6_bytes(address);
52
+ if (!bytes)
53
+ return false;
54
+ const embedded = bytes.slice(12).join(".");
55
+ const zero_until = (end) => bytes.slice(0, end).every((byte) => byte === 0);
56
+ // ::ffff:a.b.c.d, mapped.
57
+ if (zero_until(10) && bytes[10] === 255 && bytes[11] === 255)
58
+ return is_public_address(embedded);
59
+ // ::a.b.c.d and every address under ::/96, :: and ::1 among them.
60
+ if (zero_until(12))
61
+ return false;
62
+ // 64:ff9b::a.b.c.d, the NAT64 prefix.
63
+ if (bytes[0] === 0 && bytes[1] === 0x64 && bytes[2] === 0xff && bytes[3] === 0x9b && bytes.slice(4, 12).every((byte) => byte === 0))
64
+ return is_public_address(embedded);
65
+ return !non_public_ipv6.check(address.split("%")[0], "ipv6");
66
+ }
67
+ async function system_resolver(hostname) {
68
+ return (await lookup(hostname, { all: true, verbatim: true })).map((found) => found.address);
69
+ }
70
+ // The ports a setting such as "8080, 8443" lists; anything else in it is left out.
71
+ export function ports_of(setting) {
72
+ return new Set(String(setting ?? "")
73
+ .split(/[\s,;]+/)
74
+ .map(Number)
75
+ .filter((port) => Number.isInteger(port) && port > 0 && port < 65536));
76
+ }
77
+ // The address as a URL when its form may be fetched: http or https, no name or password, and its port the usual one
78
+ // or one the app allows, without its #fragment. Throws a plain error saying why not.
79
+ export function checked_web_address(url, options = {}) {
80
+ let parsed;
81
+ try {
82
+ parsed = new URL(String(url).trim());
83
+ }
84
+ catch {
85
+ throw new Error("Give a whole web address, starting with http:// or https://.");
86
+ }
87
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
88
+ throw new Error(`Only http and https addresses can be read, not ${parsed.protocol.replace(/:$/, "")}.`);
89
+ if (!parsed.hostname)
90
+ throw new Error("Give a whole web address, with its host.");
91
+ if (parsed.username || parsed.password)
92
+ throw new Error("An address with a name or password in it is not read.");
93
+ if (parsed.port && !options.allowed_ports?.has(Number(parsed.port)))
94
+ throw new Error(`Port ${parsed.port} is not allowed; only 80 and 443 are${options.ports_hint ? `, ${options.ports_hint}` : ""}.`);
95
+ parsed.hash = "";
96
+ return parsed;
97
+ }
98
+ // The host's addresses, when every one of them is public (or a test lets it through); throws a plain error otherwise.
99
+ export async function public_addresses(hostname, options = {}) {
100
+ const host = hostname.replace(/^\[|\]$/g, "").replace(/\.+$/, "");
101
+ if (!host)
102
+ throw new Error("Give a whole web address, with its host.");
103
+ let addresses;
104
+ try {
105
+ addresses = isIP(host) ? [host] : await (options.resolve ?? system_resolver)(host);
106
+ }
107
+ catch {
108
+ throw new Error(`The host ${host} could not be found.`);
109
+ }
110
+ if (addresses.length === 0)
111
+ throw new Error(`The host ${host} could not be found.`);
112
+ const refused = addresses.find((address) => !is_public_address(address) && options.allow_address?.(address) !== true);
113
+ if (refused !== undefined)
114
+ throw new Error(`${host} is not a public address (it leads to ${refused}), so it is not read: only pages on the public web are.`);
115
+ return addresses;
116
+ }
117
+ // The lookup a connection is made with, as node:http's `lookup` option, so it reaches only the addresses just checked,
118
+ // however the name answers.
119
+ export function guarded_lookup(options = {}) {
120
+ const guarded = (hostname, given, callback) => {
121
+ public_addresses(hostname, options).then((addresses) => {
122
+ if (typeof given === "object" && given?.all)
123
+ callback(null, addresses.map((address) => ({ address, family: isIP(address) })));
124
+ else
125
+ callback(null, addresses[0], isIP(addresses[0]));
126
+ }, (error) => callback(error));
127
+ };
128
+ return guarded;
129
+ }
@@ -35,5 +35,15 @@ export declare class HelpRequested extends Error {
35
35
  export declare const loopback_hosts: string[];
36
36
  export declare function is_loopback(host: string): boolean;
37
37
  export declare function read_secret_file(path: string): string;
38
+ export declare const max_secret_chars = 1024;
39
+ export type SecretReader = (command: string[]) => Promise<string>;
40
+ export interface SecretCommandWords {
41
+ what?: string;
42
+ secret?: string;
43
+ }
44
+ export declare function command_words(line: string, words_for?: SecretCommandWords): string[];
45
+ export declare function secret_command_reader(words_for?: SecretCommandWords): SecretReader;
46
+ export declare const read_secret_command: SecretReader;
47
+ export declare function secret_from_command(command_line: string, read?: SecretReader, words_for?: SecretCommandWords): Promise<string>;
38
48
  export declare function read_server_config<Name extends string = never>(spec: ServerConfigSpec<Name>): ServerConfig<Name>;
39
49
  export {};