@headwall/websnapper-cli 0.0.0-stage → 1.0.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,102 @@
1
+ import { homedir } from 'node:os';
2
+ import path from 'node:path';
3
+ export const LOG_LEVELS = ['warn', 'info', 'debug'];
4
+ /** Thrown when settings are invalid; lists every problem found. */
5
+ export class SettingsError extends Error {
6
+ problems;
7
+ constructor(problems) {
8
+ super(`Invalid settings:\n${problems.map((problem) => ` - ${problem}`).join('\n')}`);
9
+ this.name = 'SettingsError';
10
+ this.problems = problems;
11
+ }
12
+ }
13
+ const VARIABLE_PREFIX = 'WSNAP_';
14
+ /** Every WSNAP_ variable this tool reads. Any other is reported as a likely typo. */
15
+ export const KNOWN_VARIABLES = [
16
+ 'WSNAP_CONFIG', 'WSNAP_CONNECT_TIMEOUT_MS', 'WSNAP_TIMEOUT_MS', 'WSNAP_LOG_LEVEL',
17
+ ];
18
+ const CONFIG_DIRECTORY_NAME = 'wsnap';
19
+ const CONFIG_FILE_NAME = 'config.json';
20
+ const DEFAULT_CONNECT_TIMEOUT_MS = 5_000;
21
+ const DEFAULT_TIMEOUT_MS = 90_000;
22
+ const MINIMUM_TIMEOUT_MS = 100;
23
+ const MAXIMUM_CONNECT_TIMEOUT_MS = 60_000;
24
+ const MAXIMUM_TIMEOUT_MS = 600_000;
25
+ const DEFAULT_LOG_LEVEL = 'warn';
26
+ /** Collects problems while reading typed values; each reader returns a fallback so parsing carries on. */
27
+ class SettingsReader {
28
+ problems = [];
29
+ /** Returns a trimmed value, or undefined when unset or empty. */
30
+ static raw(value) {
31
+ const trimmed = value?.trim();
32
+ return trimmed === undefined || trimmed === '' ? undefined : trimmed;
33
+ }
34
+ /** Reads a whole number in range; source names the variable or flag in problem messages. */
35
+ integer(source, value, fallback, minimum, maximum) {
36
+ const text = SettingsReader.raw(value);
37
+ const parsed = text === undefined ? fallback : Number(text);
38
+ const isValid = Number.isInteger(parsed) && parsed >= minimum && parsed <= maximum;
39
+ if (!isValid) {
40
+ this.problems.push(`${source} must be a whole number from ${minimum} to ${maximum}; got "${value}".`);
41
+ }
42
+ return isValid ? parsed : fallback;
43
+ }
44
+ /** Reads one of a fixed set of values. */
45
+ choice(source, value, choices, fallback) {
46
+ const text = SettingsReader.raw(value) ?? fallback;
47
+ const matched = choices.find((candidate) => candidate === text);
48
+ if (matched === undefined) {
49
+ this.problems.push(`${source} must be one of ${choices.join(', ')}; got "${text}".`);
50
+ }
51
+ return matched ?? fallback;
52
+ }
53
+ /** Reads an absolute path, or records a problem and returns the fallback. */
54
+ absolutePath(source, value, fallback) {
55
+ const text = SettingsReader.raw(value);
56
+ let result = fallback;
57
+ if (text !== undefined && path.isAbsolute(text)) {
58
+ result = text;
59
+ }
60
+ else if (text !== undefined) {
61
+ this.problems.push(`${source} must be an absolute path; got "${text}".`);
62
+ }
63
+ return result;
64
+ }
65
+ }
66
+ /** Default host store path: $XDG_CONFIG_HOME/wsnap/config.json, else ~/.config/wsnap/config.json. */
67
+ function defaultConfigPath(reader, variables, homeDirectory) {
68
+ const fallbackBase = path.join(homeDirectory, '.config');
69
+ const base = reader.absolutePath('XDG_CONFIG_HOME', variables.XDG_CONFIG_HOME, fallbackBase);
70
+ return path.join(base, CONFIG_DIRECTORY_NAME, CONFIG_FILE_NAME);
71
+ }
72
+ /** Validates and normalises settings from a variable map and flags. Throws SettingsError listing every problem. */
73
+ export function loadSettings(variables, flags, homeDirectory) {
74
+ const reader = new SettingsReader();
75
+ const knownVariables = KNOWN_VARIABLES;
76
+ for (const name of Object.keys(variables)) {
77
+ if (name.startsWith(VARIABLE_PREFIX) && !knownVariables.includes(name)) {
78
+ reader.problems.push(`Unknown setting ${name}. Check for a typo.`);
79
+ }
80
+ }
81
+ const fallbackConfigPath = defaultConfigPath(reader, variables, homeDirectory);
82
+ const environmentConnectTimeoutMs = reader.integer('WSNAP_CONNECT_TIMEOUT_MS', variables.WSNAP_CONNECT_TIMEOUT_MS, DEFAULT_CONNECT_TIMEOUT_MS, MINIMUM_TIMEOUT_MS, MAXIMUM_CONNECT_TIMEOUT_MS);
83
+ const environmentTimeoutMs = reader.integer('WSNAP_TIMEOUT_MS', variables.WSNAP_TIMEOUT_MS, DEFAULT_TIMEOUT_MS, MINIMUM_TIMEOUT_MS, MAXIMUM_TIMEOUT_MS);
84
+ const settings = {
85
+ configPath: reader.absolutePath('WSNAP_CONFIG', variables.WSNAP_CONFIG, fallbackConfigPath),
86
+ connectTimeoutMs: reader.integer('--connect-timeout', flags.connectTimeoutMs, environmentConnectTimeoutMs, MINIMUM_TIMEOUT_MS, MAXIMUM_CONNECT_TIMEOUT_MS),
87
+ timeoutMs: reader.integer('--timeout', flags.timeoutMs, environmentTimeoutMs, MINIMUM_TIMEOUT_MS, MAXIMUM_TIMEOUT_MS),
88
+ logLevel: reader.choice('WSNAP_LOG_LEVEL', variables.WSNAP_LOG_LEVEL, LOG_LEVELS, DEFAULT_LOG_LEVEL),
89
+ };
90
+ if (settings.connectTimeoutMs > settings.timeoutMs) {
91
+ reader.problems.push(`The connect timeout (${settings.connectTimeoutMs} ms) must not be longer than the overall timeout (${settings.timeoutMs} ms).`);
92
+ }
93
+ if (reader.problems.length > 0) {
94
+ throw new SettingsError(reader.problems);
95
+ }
96
+ return settings;
97
+ }
98
+ /** Loads settings from the process environment and the given flags. The only process.env read. */
99
+ export function loadSettingsFromEnvironment(flags) {
100
+ return loadSettings(process.env, flags, homedir());
101
+ }
102
+ //# sourceMappingURL=env.js.map
@@ -0,0 +1,267 @@
1
+ import { constants } from 'node:fs';
2
+ import { mkdir, open, rename, rm, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { normaliseHostUrl, sendsKeyInClear } from '../hosts.js';
5
+ export const STORE_VERSION = 1;
6
+ /** Thrown when the host store can't be read, is invalid, or can't be written; lists every problem. */
7
+ export class StoreError extends Error {
8
+ problems;
9
+ code;
10
+ constructor(problems, code, options) {
11
+ super(problems.join('\n'), options);
12
+ this.name = 'StoreError';
13
+ this.problems = problems;
14
+ this.code = code;
15
+ }
16
+ }
17
+ const FILE_MODE = 0o600;
18
+ const DIRECTORY_MODE = 0o700;
19
+ const GROUP_AND_OTHER_PERMISSIONS = 0o077;
20
+ const GROUP_AND_OTHER_WRITE = 0o022;
21
+ const PERMISSION_BITS = 0o777;
22
+ const STORE_FIELDS = ['version', 'hosts'];
23
+ const HOST_FIELDS = ['url', 'key', 'addedAt', 'allowInsecureKey'];
24
+ /** RFC 6750 bearer token characters: what an Authorization header can carry, and what websnapper issues. */
25
+ const KEY_PATTERN = /^[A-Za-z0-9\-._~+/]+=*$/;
26
+ const KEY_RULE = 'An API key may contain only letters, digits and - . _ ~ + /, with any = at the end.';
27
+ const JSON_POSITION_PATTERN = /line (\d+) column (\d+)/;
28
+ /** An empty store, used when the file doesn't exist yet. */
29
+ export function emptyStore() {
30
+ return { version: STORE_VERSION, hosts: [] };
31
+ }
32
+ /** True for a plain JSON object. */
33
+ function isRecord(value) {
34
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
35
+ }
36
+ /** Checks an API key against the bearer token syntax. */
37
+ export function keyProblem(key) {
38
+ return KEY_PATTERN.test(key) ? undefined : KEY_RULE;
39
+ }
40
+ /** The problem with sending a host's key over plain http:// without the user's agreement. */
41
+ export function insecureKeyProblem(host) {
42
+ return host.key !== undefined && host.allowInsecureKey !== true && sendsKeyInClear(host.url)
43
+ ? `${host.url} would receive its API key unencrypted over http://. Use https://, or add it again with --allow-insecure-key.`
44
+ : undefined;
45
+ }
46
+ /** Validates one host entry, pushing problems; returns the entry when it is usable. */
47
+ function parseHost(value, label, problems) {
48
+ let host;
49
+ if (!isRecord(value)) {
50
+ problems.push(`${label} must be an object.`);
51
+ }
52
+ else {
53
+ const startingCount = problems.length;
54
+ for (const field of Object.keys(value).filter((name) => !HOST_FIELDS.includes(name))) {
55
+ problems.push(`${label} has an unknown field "${field}".`);
56
+ }
57
+ const { url, key, addedAt, allowInsecureKey } = value;
58
+ const normalised = typeof url === 'string' ? normaliseHostUrl(url) : undefined;
59
+ if (normalised === undefined || !('url' in normalised) || normalised.url !== url) {
60
+ problems.push(`${label}.url must be a normalised http or https URL; got ${JSON.stringify(url)}.`);
61
+ }
62
+ if (key !== undefined && (typeof key !== 'string' || keyProblem(key) !== undefined)) {
63
+ problems.push(`${label}.key: ${KEY_RULE}`);
64
+ }
65
+ if (typeof addedAt !== 'string' || Number.isNaN(Date.parse(addedAt))) {
66
+ problems.push(`${label}.addedAt must be an ISO 8601 time; got ${JSON.stringify(addedAt)}.`);
67
+ }
68
+ if (allowInsecureKey !== undefined && allowInsecureKey !== true) {
69
+ problems.push(`${label}.allowInsecureKey must be true when present.`);
70
+ }
71
+ if (problems.length === startingCount) {
72
+ host = {
73
+ url: url,
74
+ ...(key === undefined ? {} : { key: key }),
75
+ addedAt: addedAt,
76
+ ...(allowInsecureKey === true ? { allowInsecureKey } : {}),
77
+ };
78
+ const insecure = insecureKeyProblem(host);
79
+ if (insecure !== undefined) {
80
+ problems.push(`${label}: ${insecure}`);
81
+ host = undefined;
82
+ }
83
+ }
84
+ }
85
+ return host;
86
+ }
87
+ /** Parses and validates store JSON. Throws StoreError listing every problem. */
88
+ export function parseStore(text, source) {
89
+ let parsed;
90
+ try {
91
+ parsed = JSON.parse(text);
92
+ }
93
+ catch (error) {
94
+ // The parser's own message can quote the file, key included: report only where it went wrong.
95
+ const position = JSON_POSITION_PATTERN.exec(error.message);
96
+ const where = position === null ? '' : ` at line ${position[1]}, column ${position[2]}`;
97
+ throw new StoreError([`${source} is not valid JSON${where}.`], 'config_error');
98
+ }
99
+ if (isRecord(parsed) && typeof parsed.version === 'number' && parsed.version > STORE_VERSION) {
100
+ throw new StoreError([
101
+ `${source} was written by a newer wsnap (format version ${parsed.version}; this one reads ${STORE_VERSION}). Upgrade wsnap.`,
102
+ ], 'config_error');
103
+ }
104
+ const problems = [];
105
+ const hosts = [];
106
+ if (!isRecord(parsed)) {
107
+ problems.push(`${source} must hold a JSON object.`);
108
+ }
109
+ else {
110
+ for (const field of Object.keys(parsed).filter((name) => !STORE_FIELDS.includes(name))) {
111
+ problems.push(`${source} has an unknown field "${field}".`);
112
+ }
113
+ if (parsed.version !== STORE_VERSION) {
114
+ problems.push(`${source}: version must be ${STORE_VERSION}; got ${JSON.stringify(parsed.version)}.`);
115
+ }
116
+ if (!Array.isArray(parsed.hosts)) {
117
+ problems.push(`${source}: hosts must be a list.`);
118
+ }
119
+ else {
120
+ for (const [index, value] of parsed.hosts.entries()) {
121
+ const host = parseHost(value, `${source}: hosts[${index}]`, problems);
122
+ if (host !== undefined && hosts.some((existing) => existing.url === host.url)) {
123
+ problems.push(`${source}: hosts[${index}] repeats ${host.url}.`);
124
+ }
125
+ else if (host !== undefined) {
126
+ hosts.push(host);
127
+ }
128
+ }
129
+ }
130
+ }
131
+ if (problems.length > 0) {
132
+ throw new StoreError(problems, 'config_error');
133
+ }
134
+ return { version: STORE_VERSION, hosts };
135
+ }
136
+ /** Formats permission bits as four octal digits. */
137
+ function octalMode(mode) {
138
+ return (mode & PERMISSION_BITS).toString(8).padStart(4, '0');
139
+ }
140
+ /** Problems with who owns the store and who can read or replace it; ssh-style, since it holds API keys. */
141
+ export function permissionProblems(filePath, fileStats, directoryStats, currentUid) {
142
+ const problems = [];
143
+ const directoryPath = path.dirname(filePath);
144
+ if (currentUid !== undefined && directoryStats.uid !== currentUid) {
145
+ problems.push(`${directoryPath} belongs to another user (uid ${directoryStats.uid}), not you (uid ${currentUid}). `
146
+ + `If it was created with sudo, run: sudo chown -R ${currentUid} ${directoryPath}`);
147
+ }
148
+ if ((directoryStats.mode & GROUP_AND_OTHER_WRITE) !== 0) {
149
+ problems.push(`${directoryPath} can be changed by other users (mode ${octalMode(directoryStats.mode)}), who could replace the store. `
150
+ + `Run: chmod 700 ${directoryPath}`);
151
+ }
152
+ if (fileStats !== undefined && currentUid !== undefined && fileStats.uid !== currentUid) {
153
+ problems.push(`${filePath} belongs to another user (uid ${fileStats.uid}), not you (uid ${currentUid}). `
154
+ + `If it was created with sudo, run: sudo chown ${currentUid} ${filePath}`);
155
+ }
156
+ if (fileStats !== undefined && (fileStats.mode & GROUP_AND_OTHER_PERMISSIONS) !== 0) {
157
+ problems.push(`${filePath} is accessible to other users (mode ${octalMode(fileStats.mode)}) and holds API keys. Run: chmod 600 ${filePath}`);
158
+ }
159
+ return problems;
160
+ }
161
+ /** True when a filesystem error means the path doesn't exist. */
162
+ function isNotFound(error) {
163
+ return error.code === 'ENOENT';
164
+ }
165
+ /** Stats a path, or undefined when it doesn't exist. */
166
+ async function statIfExists(target) {
167
+ let stats;
168
+ try {
169
+ stats = await stat(target);
170
+ }
171
+ catch (error) {
172
+ if (!isNotFound(error)) {
173
+ throw error;
174
+ }
175
+ }
176
+ return stats;
177
+ }
178
+ /** Reads the store through one handle, so the file checked is the file read. Undefined when it doesn't exist. */
179
+ async function readStoreFile(filePath, currentUid, directoryStats) {
180
+ let text;
181
+ let handle;
182
+ try {
183
+ // O_NOFOLLOW: a symlink planted at the store's path fails with ELOOP instead of being followed.
184
+ handle = await open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
185
+ }
186
+ catch (error) {
187
+ if (!isNotFound(error)) {
188
+ throw error;
189
+ }
190
+ }
191
+ if (handle !== undefined) {
192
+ try {
193
+ const fileStats = await handle.stat();
194
+ const problems = fileStats.isFile() ? permissionProblems(filePath, fileStats, directoryStats, currentUid) : [`${filePath} is not a regular file.`];
195
+ if (problems.length > 0) {
196
+ throw new StoreError(problems, 'config_error');
197
+ }
198
+ text = await handle.readFile('utf8');
199
+ }
200
+ finally {
201
+ await handle.close();
202
+ }
203
+ }
204
+ return text;
205
+ }
206
+ /** Loads the host store; a missing file is an empty store. Checks the directory even then. Throws StoreError. */
207
+ export async function loadStore(filePath, currentUid) {
208
+ let store = emptyStore();
209
+ try {
210
+ const directoryStats = await statIfExists(path.dirname(filePath));
211
+ const text = directoryStats === undefined ? undefined : await readStoreFile(filePath, currentUid, directoryStats);
212
+ if (directoryStats !== undefined && text === undefined) {
213
+ const problems = permissionProblems(filePath, undefined, directoryStats, currentUid);
214
+ if (problems.length > 0) {
215
+ throw new StoreError(problems, 'config_error');
216
+ }
217
+ }
218
+ store = text === undefined ? store : parseStore(text, filePath);
219
+ }
220
+ catch (error) {
221
+ if (error instanceof StoreError) {
222
+ throw error;
223
+ }
224
+ const detail = error.code === 'ELOOP' ? 'it is a symbolic link, which wsnap does not follow for its store' : error.message;
225
+ throw new StoreError([`Cannot read ${filePath}: ${detail}`], 'config_error', { cause: error });
226
+ }
227
+ return store;
228
+ }
229
+ /** Writes the host store atomically: a 0600 temp file in a 0700 directory, fsync, rename. Throws StoreError. */
230
+ export async function saveStore(filePath, store) {
231
+ const directoryPath = path.dirname(filePath);
232
+ const temporaryPath = `${filePath}.${process.pid}.tmp`;
233
+ let temporaryCreated = false;
234
+ try {
235
+ await mkdir(directoryPath, { recursive: true, mode: DIRECTORY_MODE });
236
+ const fileHandle = await open(temporaryPath, 'wx', FILE_MODE);
237
+ temporaryCreated = true;
238
+ try {
239
+ await fileHandle.writeFile(`${JSON.stringify(store, null, 2)}\n`);
240
+ await fileHandle.sync();
241
+ }
242
+ finally {
243
+ await fileHandle.close();
244
+ }
245
+ await rename(temporaryPath, filePath);
246
+ const directoryHandle = await open(directoryPath, 'r');
247
+ try {
248
+ await directoryHandle.sync();
249
+ }
250
+ finally {
251
+ await directoryHandle.close();
252
+ }
253
+ }
254
+ catch (error) {
255
+ const problems = [`Cannot write ${filePath}: ${error.message}`];
256
+ if (temporaryCreated) {
257
+ try {
258
+ await rm(temporaryPath, { force: true });
259
+ }
260
+ catch (cleanupError) {
261
+ problems.push(`Cannot remove the temporary file ${temporaryPath}: ${cleanupError.message}`);
262
+ }
263
+ }
264
+ throw new StoreError(problems, 'write_error', { cause: error });
265
+ }
266
+ }
267
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1,17 @@
1
+ /** Exit codes: part of the public contract, never renumbered. */
2
+ export const ExitCode = {
3
+ success: 0,
4
+ /** Usage or local error: bad arguments, no hosts configured, unreadable config, unwritable output. */
5
+ localError: 1,
6
+ /** websnapper reached the target and the target failed (502/504). */
7
+ targetFailed: 2,
8
+ /** websnapper refused the request: invalid parameters or URL policy (400/403). */
9
+ refused: 3,
10
+ /** No working websnapper host. */
11
+ noHost: 4,
12
+ /** SIGINT, 128 + 2. */
13
+ interrupted: 130,
14
+ /** stdout closed by its reader (EPIPE), 128 + SIGPIPE. */
15
+ brokenPipe: 141,
16
+ };
17
+ //# sourceMappingURL=exit-codes.js.map
@@ -0,0 +1,91 @@
1
+ import { loadStore } from './config/store.js';
2
+ import { ExitCode } from './exit-codes.js';
3
+ import { displayHost, findHost } from './hosts.js';
4
+ import { describeOutcome, isFailover, outcomeFields } from './http/classify.js';
5
+ import { columns, escapeControlCharacters } from './output.js';
6
+ import { CLI_NAME, ClientError, localError } from './results.js';
7
+ const NO_HOST_MESSAGE = 'No working websnapper host.';
8
+ /** Loads the store and picks the hosts to use; no hosts or an unknown --host is a result to report. */
9
+ export async function selectHosts(context) {
10
+ const { hosts } = await loadStore(context.settings.configPath, context.currentUid);
11
+ const wanted = context.args.strings.host;
12
+ const found = wanted === undefined ? undefined : findHost(hosts, wanted);
13
+ let selection;
14
+ if (hosts.length === 0) {
15
+ selection = { result: localError(ClientError.notConfigured, [`Not yet configured. Add a host with: ${CLI_NAME} host add <host>`]) };
16
+ }
17
+ else if (found === undefined) {
18
+ selection = { hosts };
19
+ }
20
+ else if ('problem' in found) {
21
+ selection = { result: localError(ClientError.unknownHost, [found.problem]) };
22
+ }
23
+ else {
24
+ selection = { hosts: [found.host] };
25
+ }
26
+ return selection;
27
+ }
28
+ /** Tries hosts in order until one gives an outcome that isn't a host failure, or attempt says stop. */
29
+ export async function tryHosts(hosts, context, attemptHost) {
30
+ const attempts = [];
31
+ let last;
32
+ for (const host of hosts) {
33
+ last = { ...await attemptHost(host), host };
34
+ attempts.push({ host, outcome: last.outcome });
35
+ if (last.stop === true || !isFailover(last.outcome) || context.signal.aborted) {
36
+ break;
37
+ }
38
+ context.logger.info(escapeControlCharacters(`${displayHost(host.url)}: ${describeOutcome(last.outcome)}; trying the next host`));
39
+ }
40
+ if (last === undefined) {
41
+ throw new Error('tryHosts needs at least one host.');
42
+ }
43
+ return { last, attempts };
44
+ }
45
+ /** An attempt as it appears in --json: the host URL, the outcome kind and its fields. */
46
+ export function attemptData(attempt) {
47
+ return { host: attempt.host.url, outcome: attempt.outcome.kind, ...outcomeFields(attempt.outcome) };
48
+ }
49
+ /** Exit 4: every host failed. Lists each attempt; says when every host only asked to wait, with the soonest retry. */
50
+ export function noHostResult(attempts) {
51
+ const waits = attempts.map((attempt) => attempt.outcome).filter((outcome) => outcome.kind === 'busy' || outcome.kind === 'rate_limited');
52
+ const retryAfters = waits.flatMap((outcome) => ('retryAfter' in outcome && outcome.retryAfter !== undefined ? [outcome.retryAfter] : []));
53
+ const soonest = retryAfters.length === 0 ? undefined : Math.min(...retryAfters);
54
+ const lines = [
55
+ 'No working websnapper host:',
56
+ ...columns(attempts.map((attempt) => [displayHost(attempt.host.url), describeOutcome(attempt.outcome)])).map((line) => ` ${line}`),
57
+ ];
58
+ if (waits.length === attempts.length) {
59
+ lines.push(`Every host is busy or rate limited.${soonest === undefined ? '' : ` Try again in ${soonest} s.`}`);
60
+ }
61
+ return {
62
+ exitCode: ExitCode.noHost,
63
+ data: {
64
+ error: ClientError.noHost,
65
+ message: NO_HOST_MESSAGE,
66
+ attempts: attempts.map(attemptData),
67
+ ...(soonest === undefined || waits.length !== attempts.length ? {} : { retryAfter: soonest }),
68
+ },
69
+ text: lines.join('\n'),
70
+ };
71
+ }
72
+ /** The result for a last attempt that didn't succeed: target failed (2), refused (3), or no working host (4). */
73
+ export function failureResult(last, attempts) {
74
+ const { outcome } = last;
75
+ const via = displayHost(last.host.url);
76
+ let result;
77
+ if (outcome.kind === 'target_failed' || outcome.kind === 'refused') {
78
+ const message = outcome.message ?? outcome.error;
79
+ const failed = outcome.kind === 'target_failed';
80
+ result = {
81
+ exitCode: failed ? ExitCode.targetFailed : ExitCode.refused,
82
+ data: { error: outcome.error, message, host: last.host.url, ...outcomeFields(outcome) },
83
+ text: `${failed ? 'Target failed' : 'Refused'}: ${message} (via ${via})`,
84
+ };
85
+ }
86
+ else {
87
+ result = noHostResult(attempts);
88
+ }
89
+ return result;
90
+ }
91
+ //# sourceMappingURL=failover.js.map
package/dist/hosts.js ADDED
@@ -0,0 +1,84 @@
1
+ const SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\/\//i;
2
+ const DEFAULT_SCHEME = 'https://';
3
+ const ALLOWED_PROTOCOLS = ['http:', 'https:'];
4
+ const TRAILING_SLASHES_PATTERN = /\/+$/;
5
+ const KEY_PREFIX_SEPARATOR = '_';
6
+ const KEY_PREFIX_MAXIMUM_LENGTH = 8;
7
+ const KEY_VISIBLE_SUFFIX_LENGTH = 4;
8
+ /** The mask always hides at least this many characters, dropping the suffix and then the prefix to do so. */
9
+ const KEY_MINIMUM_HIDDEN_LENGTH = 8;
10
+ const KEY_MASK = '…';
11
+ const LOOPBACK_HOSTNAMES = ['localhost', '[::1]'];
12
+ const LOOPBACK_IPV4_PATTERN = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
13
+ /** Normalises a host name or URL: a bare host means https://, an explicit http(s) URL keeps its port and path. */
14
+ export function normaliseHostUrl(input) {
15
+ const trimmed = input.trim();
16
+ const candidate = SCHEME_PATTERN.test(trimmed) ? trimmed : `${DEFAULT_SCHEME}${trimmed}`;
17
+ const parsed = URL.canParse(candidate) ? new URL(candidate) : undefined;
18
+ let result;
19
+ if (trimmed === '' || parsed === undefined || parsed.hostname === '') {
20
+ result = { problem: `"${input}" is not a host name or URL.` };
21
+ }
22
+ else if (!ALLOWED_PROTOCOLS.includes(parsed.protocol)) {
23
+ result = { problem: `"${input}" must be a host name, or a URL starting http:// or https://.` };
24
+ }
25
+ else if (parsed.username !== '' || parsed.password !== '') {
26
+ result = { problem: `"${input}" must not contain a user name or password.` };
27
+ }
28
+ else if (parsed.search !== '' || parsed.hash !== '') {
29
+ result = { problem: `"${input}" must not contain a query string or fragment.` };
30
+ }
31
+ else {
32
+ result = { url: `${parsed.protocol}//${parsed.host}${parsed.pathname.replace(TRAILING_SLASHES_PATTERN, '')}` };
33
+ }
34
+ return result;
35
+ }
36
+ /** Short form for people: the bare host for plain https URLs, otherwise the whole URL. */
37
+ export function displayHost(url) {
38
+ const parsed = new URL(url);
39
+ return parsed.protocol === 'https:' && parsed.pathname === '/' ? parsed.host : url;
40
+ }
41
+ /** Finds a stored host by its URL, or by a bare host name that matches exactly one stored URL. */
42
+ export function findHost(hosts, query) {
43
+ const normalised = normaliseHostUrl(query);
44
+ const exact = 'url' in normalised ? hosts.find((host) => host.url === normalised.url) : undefined;
45
+ const bareName = query.trim().toLowerCase();
46
+ const byName = hosts.filter((host) => {
47
+ const parsed = new URL(host.url);
48
+ return parsed.hostname === bareName || parsed.host === bareName;
49
+ });
50
+ let result;
51
+ // A bare name matching several hosts is ambiguous even when one of them is its https:// root.
52
+ if (byName.length > 1) {
53
+ result = { problem: `"${query}" matches ${byName.length} hosts: ${byName.map((host) => host.url).join(', ')}. Give the full URL.` };
54
+ }
55
+ else if (exact !== undefined) {
56
+ result = { host: exact };
57
+ }
58
+ else if (byName.length === 1 && byName[0] !== undefined) {
59
+ result = { host: byName[0] };
60
+ }
61
+ else {
62
+ result = { problem: `No configured host matches "${query}". "wsnap host list" shows them.` };
63
+ }
64
+ return result;
65
+ }
66
+ /** Masks an API key for display: its prefix, an ellipsis and the last four characters. */
67
+ export function maskKey(key) {
68
+ const separatorAt = key.indexOf(KEY_PREFIX_SEPARATOR);
69
+ const fullPrefix = separatorAt >= 0 && separatorAt < KEY_PREFIX_MAXIMUM_LENGTH ? key.slice(0, separatorAt + 1) : '';
70
+ const withSuffix = key.length - fullPrefix.length - KEY_VISIBLE_SUFFIX_LENGTH >= KEY_MINIMUM_HIDDEN_LENGTH;
71
+ const prefix = withSuffix || key.length - fullPrefix.length >= KEY_MINIMUM_HIDDEN_LENGTH ? fullPrefix : '';
72
+ const suffix = withSuffix ? key.slice(-KEY_VISIBLE_SUFFIX_LENGTH) : '';
73
+ return `${prefix}${KEY_MASK}${suffix}`;
74
+ }
75
+ /** True for localhost, 127.x.x.x and [::1], where plain http:// never leaves the machine. */
76
+ export function isLoopbackHost(url) {
77
+ const { hostname } = new URL(url);
78
+ return LOOPBACK_HOSTNAMES.includes(hostname) || LOOPBACK_IPV4_PATTERN.test(hostname);
79
+ }
80
+ /** True when a key for this host would cross the network unencrypted: http:// to anything but loopback. */
81
+ export function sendsKeyInClear(url) {
82
+ return new URL(url).protocol === 'http:' && !isLoopbackHost(url);
83
+ }
84
+ //# sourceMappingURL=hosts.js.map