@ad-hal/cli 0.0.0-stage → 0.1.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kevin Hartig
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,59 @@
1
- # Temporary Holding Version
1
+ # @ad-hal/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The command-line tools for [Adhal](https://github.com/khartig/adhal): move
4
+ a file directly between two machines with a one-shot drop code. No
5
+ account, and no server holding the bytes.
6
+
7
+ This is the official way to install Adhal. The source is
8
+ [github.com/khartig/adhal](https://github.com/khartig/adhal), and the only
9
+ official npm packages are this one and
10
+ [`@ad-hal/engine`](https://www.npmjs.com/package/@ad-hal/engine). Treat
11
+ any other package that claims to be Adhal as unofficial.
12
+
13
+ ## Install
14
+
15
+ Node.js ≥ 24, on macOS or Linux.
16
+
17
+ ```bash
18
+ npm install --global @ad-hal/cli
19
+ ```
20
+
21
+ ## Use
22
+
23
+ The receiver generates the code and shows it, as words and as a QR
24
+ symbol, once it can be found:
25
+
26
+ ```bash
27
+ # on the receiving machine
28
+ ad-hal-receive --new ~/Downloads
29
+
30
+ # on the sending machine: type the words at the prompt
31
+ ad-hal-send - ./report.pdf
32
+ ```
33
+
34
+ The receiver is shown the file's name, size, and SHA-256, and is asked
35
+ before anything is written. `--help` on either command lists every flag.
36
+ `ad-hal-code` prints a fresh drop code and its QR symbol.
37
+
38
+ ## Before you use it
39
+
40
+ - **The code is a bearer capability.** Whoever holds it can complete the
41
+ drop, so hand it over by a route only the intended person sees.
42
+ - **Adhal is not anonymous.** Each side's IP address is visible to the
43
+ other, and to the DHT nodes near the drop's topic.
44
+ - **Windows is not supported for security purposes** yet.
45
+ - **This is 0.x.** The wire protocol is frozen at v2, but the commands and
46
+ their flags may still change.
47
+
48
+ What changed in each version, and which versions have security fixes, is
49
+ in the [release notes](https://github.com/khartig/adhal/releases). A
50
+ version with a known vulnerability is also deprecated on npm, so
51
+ installing it prints a warning.
52
+
53
+ Report a vulnerability through the repository's
54
+ [security policy](https://github.com/khartig/adhal/blob/main/SECURITY.md),
55
+ not in a public issue.
56
+
57
+ ## License
58
+
59
+ MIT
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@ad-hal/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "Adhal command-line tools: send and receive a file directly between two machines with a one-shot code.",
5
+ "keywords": [
6
+ "p2p",
7
+ "file-transfer",
8
+ "cli",
9
+ "pake",
10
+ "hyperswarm"
11
+ ],
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/khartig/adhal.git",
16
+ "directory": "cli"
17
+ },
18
+ "homepage": "https://github.com/khartig/adhal#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/khartig/adhal/issues"
21
+ },
22
+ "files": [
23
+ "src",
24
+ "!src/send.js",
25
+ "!src/receive.js",
26
+ "!src/demo-*.js"
27
+ ],
28
+ "bin": {
29
+ "ad-hal-send": "src/swarm-send.js",
30
+ "ad-hal-receive": "src/swarm-receive.js",
31
+ "ad-hal-code": "src/code.js"
32
+ },
33
+ "engines": {
34
+ "node": ">=24"
35
+ },
36
+ "dependencies": {
37
+ "@ad-hal/engine": "0.1.1",
38
+ "qrcode-generator": "2.0.4"
39
+ },
40
+ "devDependencies": {
41
+ "hyperdht": "6.34.0",
42
+ "jsqr": "1.4.0"
43
+ },
44
+ "publishConfig": {
45
+ "access": "public"
46
+ },
47
+ "scripts": {
48
+ "test": "node --test",
49
+ "test:fast": "ADHAL_FAST=1 node --test",
50
+ "fuzz": "ADHAL_FUZZ_ITERATIONS=100000 node --test --test-timeout=1800000 test/fuzz.test.js"
51
+ }
6
52
  }
package/src/code.js ADDED
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ 'use strict'
3
+
4
+ // The drop code as a thing you can look at: a 5-word code plus a QR
5
+ // encoding of the same payload. UX object exists; you can screenshot it.
6
+ //
7
+ // Usage: code.js generate a new drop code and show its QR
8
+ // code.js <code> re-render an existing code (verifies it too)
9
+ // code.js --payload print only the QR payload string, no symbol
10
+ //
11
+ // ADHAL_QR_WIDE=1 switches to full-block rendering for console fonts
12
+ // lacking the half-block glyphs; NO_COLOR drops the ANSI colors.
13
+
14
+ const {
15
+ generateCode,
16
+ parseCode,
17
+ splitCode,
18
+ encodeQrPayload,
19
+ resolveCode,
20
+ NAMEPLATE_ENTROPY_BITS,
21
+ SECRET_ENTROPY_BITS,
22
+ NAMEPLATE_WORDS,
23
+ SECRET_WORDS
24
+ } = require('@ad-hal/engine')
25
+ const { printQr } = require('./qr')
26
+
27
+ function main () {
28
+ const args = process.argv.slice(2)
29
+ const payloadOnly = args.includes('--payload')
30
+ const positional = args.filter((a) => !a.startsWith('--'))
31
+
32
+ if (positional.length > 1) {
33
+ console.error('Usage: code.js [code] [--payload]')
34
+ process.exitCode = 1
35
+ return
36
+ }
37
+
38
+ let code
39
+ if (positional.length === 1) {
40
+ // Round-trip an existing code, so this doubles as a "why won't my code
41
+ // work" check: parseCode names the bad word rather than just failing.
42
+ try {
43
+ code = parseCode(positional[0])
44
+ } catch (err) {
45
+ console.error(`[code] not a valid drop code: ${err.message}`)
46
+ process.exitCode = 1
47
+ return
48
+ }
49
+ } else {
50
+ code = generateCode()
51
+ }
52
+
53
+ const payload = encodeQrPayload(code)
54
+
55
+ if (payloadOnly) {
56
+ console.log(payload)
57
+ return
58
+ }
59
+
60
+ console.log()
61
+ printQr(payload)
62
+ console.log()
63
+ const { nameplate, secret } = splitCode(code)
64
+ console.log(` code: ${code}`)
65
+ console.log(` payload: ${payload}`)
66
+ // Shown split, because under v2 the two halves are not the same kind of
67
+ // thing and a reader who treats them alike will draw the wrong
68
+ // conclusion from the topic line below. The nameplate is public the
69
+ // moment the receiver announces; the secret is the only secret.
70
+ console.log(` parts: nameplate=${nameplate} secret=${secret}`)
71
+ // The topic is printed because it is what the DHT actually sees, which
72
+ // makes this the fastest way to get an argument for
73
+ // engine/scratch-lookup.js. Note it is derived from the NAMEPLATE alone
74
+ // -- that is the v2 change, and printing both on adjacent lines is what
75
+ // makes it checkable by eye: the secret must not be recoverable from
76
+ // anything here.
77
+ console.log(` topic: ${resolveCode(code).topic.toString('hex')}`)
78
+ // Two figures, not one. A single combined number would let ~64.6 bits
79
+ // stand in for the strength of a ~38.8-bit secret, and only the secret's
80
+ // entropy is load-bearing -- a nameplate collision is a rendezvous
81
+ // accident the PAKE then separates, not a compromise.
82
+ console.log(
83
+ ` entropy: nameplate ${NAMEPLATE_ENTROPY_BITS.toFixed(1)} bits (${NAMEPLATE_WORDS} words, public), ` +
84
+ `secret ${SECRET_ENTROPY_BITS.toFixed(1)} bits (${SECRET_WORDS} words)`
85
+ )
86
+ console.log()
87
+ }
88
+
89
+ main()
package/src/consent.js ADDED
@@ -0,0 +1,227 @@
1
+ 'use strict'
2
+
3
+ // Asking a person before a file is written (Q-02, decision 5).
4
+ //
5
+ // THE GAP THIS CLOSES. The engine has had an accept gate since W11: an
6
+ // offer is answered ACCEPT or DECLINE before a byte of the file moves. But
7
+ // neither receiver passed `onOffer`, so the only party answering was the
8
+ // engine's own checks, and anyone holding the code could put any file that
9
+ // passed them into the output directory. Holding the code is meant to be
10
+ // the right to OFFER a file, not the right to deliver one.
11
+ //
12
+ // THREE ANSWERS, in the order they are tried:
13
+ // - `--yes`: accept without asking. For scripts, and for a person who
14
+ // has already decided.
15
+ // - a terminal on stdin: show the offer and ask, defaulting to no.
16
+ // - neither: decline, and say how to accept unattended. Hanging on a
17
+ // prompt nobody can see, or silently accepting, are the two failures
18
+ // this replaces.
19
+ //
20
+ // A risky name is warned about in every case, `--yes` included: the flag
21
+ // says "take whatever arrives", not "and don't tell me what it was".
22
+
23
+ const readline = require('node:readline/promises')
24
+ const { displayName } = require('@ad-hal/engine')
25
+ const { formatBytes } = require('./progress')
26
+
27
+ // Extensions that make a file dangerous to open, by what opening them
28
+ // does. Lowercase, without the dot. Not exhaustive and cannot be: the
29
+ // point is the common cases, where a person double-clicking would run
30
+ // something rather than view it.
31
+ /** @type {Array<[string, string[]]>} */
32
+ const RISKY = [
33
+ ['a program or installer', [
34
+ 'exe', 'com', 'scr', 'pif', 'cpl', 'msi', 'msp', 'msix', 'msixbundle', 'appx', 'appxbundle',
35
+ 'app', 'apk', 'aab', 'ipa', 'deb', 'rpm', 'pkg', 'mpkg', 'run', 'appimage', 'jar', 'xpi', 'crx',
36
+ 'gadget', 'dll', 'sys', 'drv', 'ocx', 'so', 'dylib'
37
+ ]],
38
+ ['a script', [
39
+ 'sh', 'bash', 'zsh', 'ksh', 'csh', 'fish', 'command', 'tool', 'bat', 'cmd', 'ps1', 'psm1', 'psd1',
40
+ 'vbs', 'vbe', 'js', 'jse', 'wsf', 'wsh', 'hta', 'py', 'pyw', 'pl', 'rb', 'php', 'lua', 'scpt',
41
+ 'applescript', 'workflow', 'ahk'
42
+ ]],
43
+ ['a shortcut or settings file that can run commands', [
44
+ 'lnk', 'url', 'desktop', 'inf', 'reg', 'scf', 'library-ms', 'settingcontent-ms'
45
+ ]],
46
+ // Mounting one is a double-click, and what it holds is not checked by
47
+ // anything that checks a downloaded file.
48
+ ['a disk image', ['dmg', 'iso', 'img', 'vhd', 'vhdx']],
49
+ ['a document that can carry macros', ['docm', 'dotm', 'xlsm', 'xltm', 'xlam', 'pptm', 'potm', 'ppam', 'sldm']],
50
+ ['an archive', ['zip', '7z', 'rar', 'tar', 'gz', 'tgz', 'bz2', 'tbz2', 'xz', 'txz', 'zst', 'lz', 'lzma', 'cab', 'arj', 'z', 'ace']]
51
+ ]
52
+
53
+ /** @type {Map<string, string>} */
54
+ const RISK_BY_EXTENSION = new Map(RISKY.flatMap(([what, list]) => list.map((ext) => [ext, what])))
55
+
56
+ // What a disguised program pretends to be. `invoice.pdf.exe` shows as
57
+ // `invoice.pdf` wherever known extensions are hidden, which is the Windows
58
+ // default.
59
+ const DECOYS = new Set([
60
+ 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp', 'rtf', 'txt', 'csv', 'md',
61
+ 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'heic', 'tif', 'tiff', 'svg',
62
+ 'mp3', 'mp4', 'm4a', 'mov', 'avi', 'mkv', 'wav', 'flac', 'html', 'htm'
63
+ ])
64
+
65
+ /**
66
+ * The warning a file's name deserves, or null.
67
+ *
68
+ * Judged on the name that will be WRITTEN, not the one the peer asked
69
+ * for: what opening the file does depends on the name on disk. That name
70
+ * has already had its trailing dots and spaces stripped and any bidi
71
+ * override refused (safeWriteName), so neither can hide an extension here.
72
+ *
73
+ * @param {string} name
74
+ * @returns {string | null}
75
+ */
76
+ function riskWarning (name) {
77
+ const parts = name.toLowerCase().split('.')
78
+ if (parts.length < 2) return null
79
+ const ext = parts[parts.length - 1]
80
+ const what = RISK_BY_EXTENSION.get(ext)
81
+ if (!what) return null
82
+ const shown = JSON.stringify(displayName(name))
83
+
84
+ // An archive of photos may well be `holiday.jpg.zip`; a program called
85
+ // `invoice.pdf.exe` has no innocent reading.
86
+ const before = parts.length > 2 ? parts[parts.length - 2].trim() : ''
87
+ if (DECOYS.has(before) && what !== 'an archive') {
88
+ return `${shown} is ${what} (.${ext}) made to look like a .${before} file, which is how malware is disguised. Do not open it.`
89
+ }
90
+ if (what === 'an archive') {
91
+ return `${shown} is an archive (.${ext}), which can hold programs. Check what is inside before opening anything in it.`
92
+ }
93
+ return `${shown} is ${what} (.${ext}). Opening it can run code on this machine: open it only if you know who sent it and expected it.`
94
+ }
95
+
96
+ /**
97
+ * The offer, as lines a person can decide on.
98
+ *
99
+ * @param {{ name: string, declaredName: string, size: number | null, sha256: string | null, partial?: number }} offer
100
+ * @returns {string[]}
101
+ */
102
+ function describeOffer (offer) {
103
+ const size = offer.size === null
104
+ ? 'streamed, size unknown'
105
+ : `${formatBytes(offer.size)}${offer.size >= 1024 ? `, ${offer.size} bytes` : ''}`
106
+ const lines = [`offer: ${JSON.stringify(displayName(offer.name))} (${size})`]
107
+ if (offer.name !== offer.declaredName) {
108
+ lines.push(` the sender asked for ${JSON.stringify(displayName(offer.declaredName))}; it would be saved under the name above`)
109
+ }
110
+ lines.push(offer.sha256 === null
111
+ ? ' sha256: sent when the stream ends, and checked then'
112
+ : ` sha256: ${offer.sha256} (the sender's claim; the file is checked against it before it is saved)`)
113
+ if (offer.partial && offer.size !== null) {
114
+ lines.push(` resume: an earlier, interrupted attempt left ${formatBytes(offer.partial)} of this file; if those bytes match the sender's, only the rest is fetched`)
115
+ }
116
+ return lines
117
+ }
118
+
119
+ /**
120
+ * @param {{
121
+ * yes: boolean,
122
+ * label: string,
123
+ * log?: (line: string) => void,
124
+ * input?: NodeJS.ReadableStream & { isTTY?: boolean },
125
+ * output?: NodeJS.WritableStream,
126
+ * signal?: AbortSignal,
127
+ * onInterrupt?: () => void
128
+ * }} options
129
+ * `signal` is the CLI's cancel signal: a cancel while the question is on
130
+ * screen takes the question down. `onInterrupt` is Ctrl-C at the
131
+ * question, which a terminal in raw mode delivers to readline rather
132
+ * than as a signal; the CLIs route it back to their cancel handler.
133
+ * @returns {{ onOffer: (offer: any) => Promise<boolean | string>, close: () => void }}
134
+ * `close` takes down a question still waiting once the transfer has
135
+ * ended some other way -- the sender canceled or gave up -- so that it
136
+ * does not hold the process open.
137
+ */
138
+ function createConsent ({
139
+ yes,
140
+ label,
141
+ log = console.log,
142
+ input = process.stdin,
143
+ output = process.stderr,
144
+ signal,
145
+ onInterrupt = () => { process.emit('SIGINT', 'SIGINT') }
146
+ }) {
147
+ const say = (/** @type {string} */ line) => log(`[${label}] ${line}`)
148
+ let closed = false
149
+ // The question on screen, if any. Taking it down closes the interface
150
+ // and ends its line, synchronously, so whatever the CLI prints next --
151
+ // the cancel handler's line, or the reason the transfer failed -- starts
152
+ // on a line of its own. Not readline's own `signal` option: an aborted
153
+ // question writes its own line ending, after whatever the abort's other
154
+ // listeners have already printed on the question's line.
155
+ /** @type {import('node:readline/promises').Interface | null} */
156
+ let current = null
157
+ const takeDown = () => {
158
+ if (!current) return
159
+ const rl = current
160
+ current = null
161
+ rl.close()
162
+ output.write('\n')
163
+ }
164
+ // A verdict that never comes. The transfer is already ending some other
165
+ // way, and answering now would put a DECLINE on the wire behind a
166
+ // CANCEL, and report "declined" for something that was canceled.
167
+ /** @returns {Promise<never>} */
168
+ const unanswered = () => new Promise(() => {})
169
+
170
+ /** @param {any} offer */
171
+ async function onOffer (offer) {
172
+ const risk = riskWarning(offer.name)
173
+
174
+ if (yes) {
175
+ if (risk) say(`WARNING: ${risk}`)
176
+ return true
177
+ }
178
+
179
+ for (const line of describeOffer(offer)) say(line)
180
+ if (risk) say(`WARNING: ${risk}`)
181
+
182
+ if (!input.isTTY) {
183
+ say('no terminal to ask on, so the offer is declined. Pass --yes to accept offers without being asked.')
184
+ // What the sender reads. It says why without saying anything about
185
+ // this machine.
186
+ return 'the receiver is not at a terminal to accept it, and was not started with --yes'
187
+ }
188
+
189
+ if (closed || (signal && signal.aborted)) return unanswered()
190
+ const rl = readline.createInterface({ input, output, terminal: true })
191
+ current = rl
192
+ rl.on('SIGINT', () => {
193
+ takeDown()
194
+ onInterrupt()
195
+ })
196
+ if (signal) signal.addEventListener('abort', takeDown, { once: true })
197
+ let answer
198
+ try {
199
+ answer = await rl.question('accept this file? [y/N] ')
200
+ } catch {
201
+ takeDown()
202
+ return unanswered()
203
+ } finally {
204
+ if (signal) signal.removeEventListener('abort', takeDown)
205
+ }
206
+ // Taken down while an answer was on its way in.
207
+ if (current !== rl) return unanswered()
208
+ current = null
209
+ rl.close()
210
+ // Anything but a yes is a no, an empty line included: the default is
211
+ // the answer that writes nothing. A no carries its own reason, because
212
+ // a bare `false` sends the engine's default sentence, and the sender's
213
+ // report then reads "the receiver declined the file: the receiver
214
+ // declined the file".
215
+ return /^\s*y(es)?\s*$/i.test(answer) || 'not accepted at the prompt'
216
+ }
217
+
218
+ return {
219
+ onOffer,
220
+ close: () => {
221
+ closed = true
222
+ takeDown()
223
+ }
224
+ }
225
+ }
226
+
227
+ module.exports = { createConsent, riskWarning, describeOffer, RISK_BY_EXTENSION }
@@ -0,0 +1,82 @@
1
+ 'use strict'
2
+
3
+ // Making drop contention visible (Q-04).
4
+ //
5
+ // Each dropped candidate already gets a line of its own, and that is the
6
+ // problem: ten "dropped before proving" lines scroll past looking like
7
+ // ten separate network hiccups, when three of them failing CONFIRMATION
8
+ // is the one thing in the log a person should act on. So the pattern gets
9
+ // a line of its own, once it is a pattern.
10
+ //
11
+ // TWO KINDS OF FAILURE, kept apart exactly as swarm.js keeps them apart
12
+ // for counting:
13
+ // - A failed confirmation: a peer reached the nameplate and did not
14
+ // hold the secret. From one key, most likely the sender mistyped the
15
+ // code. From several keys with no success, it is another drop that
16
+ // happens to share the nameplate, or someone guessing, and the line
17
+ // says so. These count toward the attempt limit.
18
+ // - A silent candidate: connected, then closed or went quiet before the
19
+ // handshake finished. That is nearly always the DHT's stale records
20
+ // or a dead hole punch, and it is NOT counted, because counting it
21
+ // would let the network's own noise burn a legitimate drop
22
+ // (PROTOCOL.md section 6). The line says that too, so nobody reads it
23
+ // as an attack.
24
+ //
25
+ // Only until pairing. After it, only counted failures are reported at
26
+ // all, each with its own line, and "none has proved the code" is no
27
+ // longer true.
28
+
29
+ const { ERR_CONFIRMATION, MAX_ATTEMPTS } = require('@ad-hal/engine')
30
+
31
+ // When a pattern is worth a line, and then each doubling after it, so a
32
+ // long wait under attack reports the attack growing without printing a
33
+ // line per candidate.
34
+ const CONFIRMATION_THRESHOLD = 3
35
+ const SILENT_THRESHOLD = 5
36
+
37
+ /**
38
+ * @param {{ label: string, log?: (line: string) => void, maxAttempts?: number }} options
39
+ * @returns {{ dropped: (peerInfo: any, reason: string, code?: string) => void, paired: () => void }}
40
+ */
41
+ function createContentionMonitor ({ label, log = console.log, maxAttempts = MAX_ATTEMPTS }) {
42
+ let failed = 0
43
+ let silent = 0
44
+ let isPaired = false
45
+ let nextFailedWarning = CONFIRMATION_THRESHOLD
46
+ let nextSilentWarning = SILENT_THRESHOLD
47
+ /** @type {Set<string>} */
48
+ const keys = new Set()
49
+
50
+ /**
51
+ * Feed it everything onCandidateDropped hears.
52
+ * @param {any} peerInfo
53
+ * @param {string} _reason
54
+ * @param {string} [code]
55
+ */
56
+ function dropped (peerInfo, _reason, code) {
57
+ if (isPaired) return
58
+ if (code === ERR_CONFIRMATION) {
59
+ failed++
60
+ if (peerInfo && peerInfo.publicKey) keys.add(peerInfo.publicKey.toString('hex'))
61
+ if (failed < nextFailedWarning) return
62
+ nextFailedWarning *= 2
63
+ const limit = `${failed} of the ${maxAttempts} failures this drop allows before it ends`
64
+ log(keys.size > 1
65
+ ? `[${label}] WARNING: ${failed} peers, from ${keys.size} different keys, found this drop and could not prove its code, and none has succeeded. ` +
66
+ 'Either another drop is using the same first two words (a code collision), or someone is guessing. ' +
67
+ `That is ${limit}. If your sender is not reporting a wrong code, cancel and use a new one.`
68
+ : `[${label}] WARNING: one peer has failed to prove the code ${failed} times. Most likely the sender has mistyped it: ` +
69
+ `check the code on both sides. That is ${limit}.`)
70
+ return
71
+ }
72
+ silent++
73
+ if (silent < nextSilentWarning) return
74
+ nextSilentWarning *= 2
75
+ log(`[${label}] note: ${silent} candidates connected and went silent before finishing the handshake. ` +
76
+ 'That is usually the network (stale DHT records, or hole punches that failed), not an attack, and it does not count toward the attempt limit.')
77
+ }
78
+
79
+ return { dropped, paired: () => { isPaired = true } }
80
+ }
81
+
82
+ module.exports = { createContentionMonitor, CONFIRMATION_THRESHOLD, SILENT_THRESHOLD }
package/src/env.js ADDED
@@ -0,0 +1,49 @@
1
+ 'use strict'
2
+
3
+ // Environment overrides shared by the swarm CLIs. One file for the reason
4
+ // report.js is one file: two copies of a parser drift, and the copy that
5
+ // drifts is the one nobody is testing.
6
+
7
+ // The largest bootstrap list worth accepting. A real one is a handful of
8
+ // nodes; anything longer is a mistake or a paste gone wrong.
9
+ const MAX_BOOTSTRAP_NODES = 64
10
+
11
+ /**
12
+ * ADHAL_BOOTSTRAP=<json> overrides the DHT bootstrap nodes: a JSON array
13
+ * of `{ "host": string, "port": 1-65535 }`. Tests point it at an isolated
14
+ * hyperdht testnet; nobody should need it on the public DHT.
15
+ *
16
+ * VALIDATED, NOT PASSED THROUGH (Q-17). This used to be `JSON.parse(raw)`
17
+ * with no try/catch, handed to the DHT as-is: a typo crashed the CLI with
18
+ * a stack trace, and a well-formed but wrong value went into HyperDHT to
19
+ * fail somewhere less legible. Now a bad value is refused before any
20
+ * network work, with a message naming the variable and the expected shape.
21
+ * The value itself is not echoed back, beyond its length.
22
+ *
23
+ * @param {string | undefined} [raw]
24
+ * @returns {Array<{ host: string, port: number }> | undefined}
25
+ */
26
+ function parseBootstrap (raw = process.env.ADHAL_BOOTSTRAP) {
27
+ if (raw === undefined || raw === '') return undefined
28
+ const shape = 'a JSON array of {"host": "<name or address>", "port": <1-65535>}'
29
+
30
+ let parsed
31
+ try {
32
+ parsed = JSON.parse(raw)
33
+ } catch {
34
+ throw new Error(`ADHAL_BOOTSTRAP is not valid JSON (${raw.length} characters); expected ${shape}`)
35
+ }
36
+ if (!Array.isArray(parsed) || parsed.length === 0 || parsed.length > MAX_BOOTSTRAP_NODES) {
37
+ throw new Error(`ADHAL_BOOTSTRAP must be ${shape}, with 1 to ${MAX_BOOTSTRAP_NODES} entries`)
38
+ }
39
+ return parsed.map((node, i) => {
40
+ const ok = node !== null && typeof node === 'object' &&
41
+ typeof node.host === 'string' && node.host.length > 0 && node.host.length <= 253 &&
42
+ /^[A-Za-z0-9.:\-[\]]+$/.test(node.host) &&
43
+ Number.isInteger(node.port) && node.port >= 1 && node.port <= 65535
44
+ if (!ok) throw new Error(`ADHAL_BOOTSTRAP entry ${i + 1} is not {"host": string, "port": 1-65535}`)
45
+ return { host: node.host, port: node.port }
46
+ })
47
+ }
48
+
49
+ module.exports = { parseBootstrap, MAX_BOOTSTRAP_NODES }