@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.
@@ -0,0 +1,176 @@
1
+ 'use strict'
2
+
3
+ // Turns the engine's progress events into something a human can read,
4
+ // which is the only thing this file does: the engine emits `{ bytes,
5
+ // total }` per chunk and computes no percentage, rate, or ETA, because it
6
+ // cannot know whether its consumer is a terminal, a test, or a log. Same
7
+ // split as engine/src/code.js owning the code value while cli/src/qr.js
8
+ // owns the drawing.
9
+ //
10
+ // TWO OUTPUT MODES, AND THE CONTRACT BETWEEN THEM:
11
+ //
12
+ // TTY one line, redrawn in place with '\r', throttled to 100 ms,
13
+ // with a guaranteed final render and a closing newline.
14
+ // non-TTY whole lines at fixed percentage milestones.
15
+ //
16
+ // Milestones rather than a timer for the non-TTY case, deliberately. A
17
+ // timer makes the number of lines depend on how fast the transfer ran, so
18
+ // the same code produces different output on a loaded CI box than on a
19
+ // laptop -- and any test that asserts on those lines becomes
20
+ // load-sensitive, which is to say flaky. Every 25% is the same five lines
21
+ // every time.
22
+ //
23
+ // TWO INVARIANTS THIS FILE MUST KEEP, because the existing test suite
24
+ // matches on exact line shapes (/^\[receive\] sha256: [0-9a-f]{64}$/m and
25
+ // friends):
26
+ //
27
+ // 1. No '\r' is ever written to a non-TTY stream. A carriage return in
28
+ // piped output corrupts whatever a test or a log reader does next.
29
+ // 2. Progress never shares a line with 'done:', 'sha256:', or 'saved
30
+ // to:'. On a TTY that is what close() is for; off one, every
31
+ // progress write is already a whole line.
32
+ //
33
+ // A LINE PRINTED WHILE THE BAR IS UP goes through log(), never straight to
34
+ // console.log. The bar ends without a newline so that '\r' can redraw it,
35
+ // so anything else written to the terminal lands on the end of it: the
36
+ // receiver's `manifest:` line once read
37
+ // `[...] 0% 0 B / 10.0 MB[swarm-receive] manifest: test.bin (...)`.
38
+ // log() clears the bar, prints the line, and redraws the bar below it, so
39
+ // the bar keeps moving in place underneath.
40
+ //
41
+ // A STREAM HAS NO TOTAL (`total: null`, PROTOCOL.md section 4.3). On a TTY
42
+ // it gets a running byte count instead of a bar. Off one it gets nothing:
43
+ // there are no percentages to make milestones of, and a line per chunk
44
+ // would break the reason milestones exist -- output that is the same every
45
+ // run. The done/sha256 lines still say how much arrived.
46
+
47
+ // Redrawing faster than this buys nothing a human can see and costs a
48
+ // syscall per chunk -- at 64 KB chunks a fast local transfer emits
49
+ // hundreds of events a second.
50
+ const REDRAW_MS = 100
51
+ const BAR_WIDTH = 24
52
+ const MILESTONE_PERCENT = 25
53
+
54
+ function formatBytes (n) {
55
+ if (n < 1024) return `${n} B`
56
+ const units = ['KB', 'MB', 'GB', 'TB']
57
+ let value = n / 1024
58
+ let unit = 0
59
+ while (value >= 1024 && unit < units.length - 1) {
60
+ value /= 1024
61
+ unit++
62
+ }
63
+ return `${value.toFixed(value >= 100 ? 0 : 1)} ${units[unit]}`
64
+ }
65
+
66
+ function percentOf (bytes, total) {
67
+ // A zero-byte file is complete the moment it starts; anything else
68
+ // would render as NaN.
69
+ if (total <= 0) return 100
70
+ return Math.floor((bytes / total) * 100)
71
+ }
72
+
73
+ /**
74
+ * @param {{
75
+ * label: string,
76
+ * stream?: { isTTY?: boolean, write: (chunk: string) => any },
77
+ * env?: Record<string, string | undefined>,
78
+ * now?: () => number
79
+ * }} options
80
+ * @returns {{ onProgress: (p: { bytes: number, total: number | null }) => void, close: () => void, log: (text: string) => void }}
81
+ */
82
+ function createProgressReporter ({ label, stream = process.stdout, env = process.env, now = Date.now }) {
83
+ // An escape hatch that costs nothing to honor and saves anyone piping
84
+ // this into a log from having to filter it.
85
+ if (env.ADHAL_NO_PROGRESS === '1') {
86
+ return { onProgress: () => {}, close: () => {}, log: (/** @type {string} */ text) => { stream.write(`${text}\n`) } }
87
+ }
88
+
89
+ const isTty = Boolean(stream.isTTY)
90
+ /** @type {number | null} */
91
+ let lastDrawAt = null
92
+ let lastMilestone = -1
93
+ let drewSomething = false
94
+ let finished = false
95
+ // What is on the TTY's current line right now, for log() to restore.
96
+ // Null when the cursor is at the start of a clean line.
97
+ /** @type {string | null} */
98
+ let onScreen = null
99
+
100
+ function drawTty (bytes, total) {
101
+ if (total === null) {
102
+ onScreen = `[${label}] ${formatBytes(bytes)} (streaming, size unknown)`
103
+ stream.write(`\r\x1b[2K${onScreen}`)
104
+ drewSomething = true
105
+ return
106
+ }
107
+ const percent = percentOf(bytes, total)
108
+ const filled = Math.round((percent / 100) * BAR_WIDTH)
109
+ const bar = '#'.repeat(filled) + '-'.repeat(BAR_WIDTH - filled)
110
+ const line = `[${label}] [${bar}] ${String(percent).padStart(3)}% ${formatBytes(bytes)} / ${formatBytes(total)}`
111
+ // Cleared to end of line so a shorter render cannot leave the tail of
112
+ // a longer one behind.
113
+ onScreen = line
114
+ stream.write(`\r\x1b[2K${line}`)
115
+ drewSomething = true
116
+ }
117
+
118
+ function drawLine (bytes, total) {
119
+ stream.write(`[${label}] progress: ${percentOf(bytes, total)}% (${bytes}/${total} bytes)\n`)
120
+ drewSomething = true
121
+ }
122
+
123
+ function onProgress ({ bytes, total }) {
124
+ if (finished) return
125
+ if (total === null && !isTty) return
126
+ const complete = total !== null && bytes >= total
127
+
128
+ if (isTty) {
129
+ const at = now()
130
+ // Two events are never throttled away. The first, or the bar does
131
+ // not appear until 100 ms in -- and on a fast local transfer that
132
+ // can be the whole thing, so it would never appear at all. And the
133
+ // last, because a bar frozen at 97% because the completing event
134
+ // landed inside the window reads as a hang.
135
+ if (lastDrawAt !== null && !complete && at - lastDrawAt < REDRAW_MS) return
136
+ lastDrawAt = at
137
+ drawTty(bytes, total)
138
+ return
139
+ }
140
+
141
+ const percent = percentOf(bytes, total)
142
+ const milestone = Math.floor(percent / MILESTONE_PERCENT) * MILESTONE_PERCENT
143
+ if (milestone <= lastMilestone) return
144
+ lastMilestone = milestone
145
+ drawLine(bytes, total)
146
+ }
147
+
148
+ // Ends the progress line so the caller's next console.log starts clean.
149
+ // Must be called on every exit path, including cancellation and
150
+ // failure, or an interrupted transfer leaves the cursor mid-bar and the
151
+ // error message lands on top of it.
152
+ function close () {
153
+ if (finished) return
154
+ finished = true
155
+ if (isTty && drewSomething) stream.write('\n')
156
+ onScreen = null
157
+ }
158
+
159
+ /**
160
+ * Prints one whole line without breaking the bar. Off a TTY, and on one
161
+ * with no bar showing, it is an ordinary line.
162
+ *
163
+ * @param {string} text
164
+ */
165
+ function log (text) {
166
+ if (isTty && onScreen !== null) {
167
+ stream.write(`\r\x1b[2K${text}\n${onScreen}`)
168
+ return
169
+ }
170
+ stream.write(`${text}\n`)
171
+ }
172
+
173
+ return { onProgress, close, log }
174
+ }
175
+
176
+ module.exports = { createProgressReporter, formatBytes, percentOf }
package/src/qr.js ADDED
@@ -0,0 +1,141 @@
1
+ 'use strict'
2
+
3
+ // Terminal QR rendering for the drop code. This lives in cli/ rather than engine/
4
+ // on purpose: engine/ owns the code as a value (engine/src/code.js), and
5
+ // every surface draws the symbol its own way -- a desktop UI (Stage 3) would
6
+ // hand the same payload to a canvas or an <svg>, not to half-block
7
+ // characters. Only the payload string is shared.
8
+
9
+ const qrcode = require('qrcode-generator')
10
+
11
+ // Error correction level H (recovers ~30% damage) rather than the usual M
12
+ // (~15%), and the uppercasing in `encodeQrPayload` is what keeps that
13
+ // affordable: QR's alphanumeric mode is denser than byte mode, so the same
14
+ // payload costs one version less at every level.
15
+ //
16
+ // Re-measured against the vendored encoder when W15a moved to the EFF
17
+ // large wordlist. The worst case is now 56 characters: the 7-character
18
+ // ADHAL2: scheme, five 9-letter words, and four separators.
19
+ //
20
+ // ECC worst case alnum (56) worst case byte (56)
21
+ // L v3 (29x29) 33x33
22
+ // M v3 (29x29) 33x33
23
+ // Q v4 (33x33) 37x37
24
+ // H v5 (37x37) 41x41
25
+ //
26
+ // Over 20,000 generated codes at H (mean payload 46 characters): 90.6%
27
+ // are 33x33, 9.2% are 37x37, and 0.2% are 29x29.
28
+ //
29
+ // H IS KEPT, and it now costs something. Under the short wordlist every
30
+ // code fit 29x29 at H; the longer words gave that back, and the symbol is
31
+ // a version or two larger than it was. H is still the level that matters
32
+ // for this deliverable's actual failures -- glare, moire against the other
33
+ // display's pixel grid, and a phone camera that will not quite focus off a
34
+ // screen -- and a 33x33 or 37x37 symbol drawn in half-blocks still fits a
35
+ // standard terminal. Q would hold the worst case at 33x33 for ~25% damage
36
+ // tolerance instead of ~30%; that is the lever if the size ever matters
37
+ // more than the margin.
38
+ //
39
+ // The uppercase argument survives unchanged: byte mode costs one more
40
+ // version at every level in the table.
41
+ const ECC_LEVEL = 'H'
42
+
43
+ // The QR specification requires a 4-module light border; a symbol printed
44
+ // flush against surrounding text is materially harder to acquire.
45
+ const QUIET_ZONE = 4
46
+
47
+ // Black on bright white, set explicitly per line. A QR code is only
48
+ // scannable as dark-on-light, and without forcing both halves the symbol
49
+ // inherits the user's theme -- inverted on any dark terminal, which is
50
+ // most of them, and a coin flip as to whether a given decoder copes.
51
+ const DARK_ON_LIGHT = '\x1b[30;107m'
52
+ const RESET = '\x1b[0m'
53
+
54
+ // Two vertical modules per character cell, indexed by (top, bottom). This
55
+ // is what keeps the symbol roughly square: a terminal cell is about twice
56
+ // as tall as it is wide, so packing two modules into one cell undoes that.
57
+ const HALF_BLOCKS = {
58
+ 'light,light': ' ',
59
+ 'dark,light': '▀', // UPPER HALF BLOCK
60
+ 'light,dark': '▄', // LOWER HALF BLOCK
61
+ 'dark,dark': '█' // FULL BLOCK
62
+ }
63
+
64
+ /**
65
+ * Renders `payload` as a QR symbol made of text.
66
+ *
67
+ * @param {string} payload the string to encode, e.g. from encodeQrPayload
68
+ * @param {{ wide?: boolean, color?: boolean }} [options]
69
+ * `wide` uses two full-block characters per module instead of half
70
+ * blocks -- twice the width and twice the height. However, it needs only
71
+ * U+2588, which some older Windows console fonts have when they lack the
72
+ * half blocks. `color` set false omits the ANSI colors (see
73
+ * DARK_ON_LIGHT for why that is a downgrade, not a neutral choice).
74
+ * @returns {string}
75
+ */
76
+ function renderQr (payload, { wide = false, color = true } = {}) {
77
+ // typeNumber 0 lets the library pick the smallest version that fits.
78
+ // 'Alphanumeric' is asserted rather than auto-detected so that a payload
79
+ // which is not uppercase-safe fails loudly here instead of silently
80
+ // costing a version -- encodeQrPayload guarantees the character set.
81
+ const qr = qrcode(0, ECC_LEVEL)
82
+ qr.addData(payload, 'Alphanumeric')
83
+ qr.make()
84
+
85
+ const count = qr.getModuleCount()
86
+ const total = count + QUIET_ZONE * 2
87
+
88
+ // isDark() throws outside the symbol, so the quiet zone is handled here
89
+ // rather than by asking the library for out-of-range modules.
90
+ const isDark = (row, col) => {
91
+ const r = row - QUIET_ZONE
92
+ const c = col - QUIET_ZONE
93
+ if (r < 0 || c < 0 || r >= count || c >= count) return false
94
+ return qr.isDark(r, c)
95
+ }
96
+
97
+ const paint = (line) => (color ? `${DARK_ON_LIGHT}${line}${RESET}` : line)
98
+ const lines = []
99
+
100
+ if (wide) {
101
+ for (let row = 0; row < total; row++) {
102
+ let line = ''
103
+ for (let col = 0; col < total; col++) {
104
+ line += isDark(row, col) ? '██' : ' '
105
+ }
106
+ lines.push(paint(line))
107
+ }
108
+ } else {
109
+ // Step two rows at a time. `total` is even whenever the quiet zone is,
110
+ // since every QR version has an odd module count -- but guard anyway,
111
+ // because a bottom row read past the end must come back light, not
112
+ // dark, or the symbol grows a spurious black edge.
113
+ for (let row = 0; row < total; row += 2) {
114
+ let line = ''
115
+ for (let col = 0; col < total; col++) {
116
+ const top = isDark(row, col) ? 'dark' : 'light'
117
+ const bottom = row + 1 < total && isDark(row + 1, col) ? 'dark' : 'light'
118
+ line += HALF_BLOCKS[`${top},${bottom}`]
119
+ }
120
+ lines.push(paint(line))
121
+ }
122
+ }
123
+
124
+ return lines.join('\n')
125
+ }
126
+
127
+ /**
128
+ * Prints the symbol to stdout, honoring two environment overrides:
129
+ * ADHAL_QR_WIDE=1 for the full-block variant, and NO_COLOR (the usual
130
+ * convention) to drop the ANSI colors.
131
+ *
132
+ * @param {string} payload
133
+ */
134
+ function printQr (payload) {
135
+ console.log(renderQr(payload, {
136
+ wide: process.env.ADHAL_QR_WIDE === '1',
137
+ color: !process.env.NO_COLOR
138
+ }))
139
+ }
140
+
141
+ module.exports = { renderQr, printQr, ECC_LEVEL, QUIET_ZONE }
@@ -0,0 +1,145 @@
1
+ 'use strict'
2
+
3
+ // Getting the drop code into the process without leaving it lying around.
4
+ //
5
+ // THE LEAK. `ad-hal-send acid-acorn-acre-acts-afar bigfile.zip` puts the
6
+ // code in two places nobody thinks about: the shell's history file, where
7
+ // it persists indefinitely, and the process table, where `ps` shows it to
8
+ // every other user on the machine for as long as the drop runs. The code
9
+ // is the *only* secret in the system -- it is the topic, the drop key, and
10
+ // the proof -- so those two are a full compromise of a drop, available to
11
+ // anyone with a shell on either box.
12
+ //
13
+ // That is a bad property for a tool whose pitch is "no account, no
14
+ // server": the threat model people reach for it with is "I do not want a
15
+ // third party to have my file", and a shared build box reading ~/.zsh
16
+ // _history is exactly that third party.
17
+ //
18
+ // ARGV IS REFUSED unless asked for (Q-17, decision 5). It used to be
19
+ // accepted with a note on stderr, but a note arrives after the damage: by
20
+ // the time it prints, the code is already in the history file. So a code
21
+ // on the command line now needs `--code-on-argv`, which says in the
22
+ // command itself that the leak is accepted. The prompt and stdin (`-`)
23
+ // are the normal ways in. The one case that needs the flag is a sender
24
+ // streaming stdin as the file, where stdin cannot also carry the code.
25
+
26
+ const fs = require('fs')
27
+ const readline = require('readline')
28
+
29
+ /**
30
+ * Reads a single line from stdin without echoing it.
31
+ *
32
+ * No-echo matters for a shoulder-surfing reason and a screen-sharing one,
33
+ * and it is why this is not just `rl.question`. It falls back to echoing
34
+ * when stdin is not a TTY, where there is nothing to hide the typing from
35
+ * and `setRawMode` does not exist.
36
+ *
37
+ * @param {string} promptText
38
+ * @returns {Promise<string>}
39
+ */
40
+ function promptForCode (promptText) {
41
+ const input = process.stdin
42
+ const output = process.stderr
43
+
44
+ if (!input.isTTY) {
45
+ // Piped in: one line, no prompt, no echo question.
46
+ return new Promise((resolve, reject) => {
47
+ const rl = readline.createInterface({ input })
48
+ let answered = false
49
+ rl.once('line', (line) => {
50
+ answered = true
51
+ rl.close()
52
+ resolve(line)
53
+ })
54
+ rl.once('close', () => {
55
+ if (!answered) reject(new Error('no code arrived on stdin'))
56
+ })
57
+ rl.once('error', reject)
58
+ })
59
+ }
60
+
61
+ return new Promise((resolve, reject) => {
62
+ const rl = readline.createInterface({ input, output, terminal: true })
63
+ output.write(promptText)
64
+ // Suppress the echo by intercepting what readline would draw.
65
+ const mute = { muted: true }
66
+ const realWrite = output.write.bind(output)
67
+ // @ts-ignore -- deliberately replacing the stream's write for the
68
+ // duration of the question, restored in every exit path below.
69
+ rl.output.write = (/** @type {string} */ chunk) => {
70
+ if (!mute.muted) realWrite(chunk)
71
+ return true
72
+ }
73
+ const restore = () => {
74
+ mute.muted = false
75
+ // @ts-ignore
76
+ rl.output.write = realWrite
77
+ }
78
+ rl.question('', (answer) => {
79
+ restore()
80
+ realWrite('\n')
81
+ rl.close()
82
+ resolve(answer)
83
+ })
84
+ rl.once('error', (err) => {
85
+ restore()
86
+ reject(err)
87
+ })
88
+ })
89
+ }
90
+
91
+ /**
92
+ * Resolves where the code should come from.
93
+ *
94
+ * @param {{
95
+ * argvCode?: string | null,
96
+ * label: string,
97
+ * allowArgv?: boolean,
98
+ * promptText?: string,
99
+ * warn?: (line: string) => void
100
+ * }} options
101
+ * `allowArgv` is the caller's `--code-on-argv`. Without it a code given
102
+ * as an argument is refused, with the ways that do not leak it.
103
+ * @returns {Promise<string>}
104
+ */
105
+ async function readCode ({ argvCode, label, allowArgv = false, promptText = 'drop code: ', warn = (line) => process.stderr.write(`${line}\n`) }) {
106
+ // `-` is the long-standing convention for "read it from stdin", and it
107
+ // is the form that composes: `pass show drop | ad-hal-send - file.zip`.
108
+ if (argvCode === '-' || argvCode === '--code-stdin') {
109
+ const line = await promptForCode(promptText)
110
+ return line.trim()
111
+ }
112
+
113
+ if (argvCode) {
114
+ // The code is not echoed: it is the thing being protected, and this
115
+ // message lands in scrollback like any other.
116
+ if (!allowArgv) {
117
+ throw new Error(
118
+ 'refusing a code given on the command line: it would be saved in your shell history and visible to `ps`. ' +
119
+ 'Pass `-` instead and type or pipe the code in, or add --code-on-argv to accept that risk.'
120
+ )
121
+ }
122
+ warn(
123
+ `[${label}] note: the code was passed as a command-line argument, so it is now in ` +
124
+ 'your shell history and visible to `ps`. Pass `-` instead to read it from stdin.'
125
+ )
126
+ return argvCode
127
+ }
128
+
129
+ return (await promptForCode(promptText)).trim()
130
+ }
131
+
132
+ /**
133
+ * True when stdin can supply a code at all. A receiver launched by a
134
+ * supervisor with stdin closed should generate a code rather than hang
135
+ * on a prompt nobody can answer.
136
+ */
137
+ function stdinCanSupplyCode () {
138
+ try {
139
+ return Boolean(process.stdin) && !fs.fstatSync(0).isDirectory()
140
+ } catch {
141
+ return false
142
+ }
143
+ }
144
+
145
+ module.exports = { readCode, promptForCode, stdinCanSupplyCode }
package/src/report.js ADDED
@@ -0,0 +1,221 @@
1
+ 'use strict'
2
+
3
+ // Turns a TransferError code into a sentence worth reading.
4
+ //
5
+ // The engine's own message already says what happened; what it cannot say
6
+ // is what the person at the terminal should do about it, because that
7
+ // depends on being a CLI. This file is that layer, and it is one file for
8
+ // the same reason cli/src/signals.js is: the alternative is the same
9
+ // mapping pasted into four transport scripts, where the copy that drifts
10
+ // is always the one nobody was looking at.
11
+ //
12
+ // The distinction each line is protecting: before the failure-reporting
13
+ // work, every one of these arrived as `error: <something>` and several
14
+ // arrived as nothing at all. "The peer cancelled", "the bytes are wrong",
15
+ // and "the punch died" are three different situations with three
16
+ // different responses, and telling them apart is the whole point.
17
+ //
18
+ // Switched on `err.code`, never on the message. That is load-bearing
19
+ // rather than tidy: the messages here are free to be reworded, and
20
+ // PROTOCOL.md section 10 makes the codes the contract precisely because
21
+ // this project's own measurement harness once classified failures by
22
+ // regex-matching prose.
23
+
24
+ const { displayName, displayText } = require('@ad-hal/engine')
25
+
26
+ /** @param {any} err */
27
+ function isLocalCancellation (err) {
28
+ return err && (err.name === 'AbortError' || err.code === 'ABORT_ERR')
29
+ }
30
+
31
+ /** @param {any} err */
32
+ function isPeerCancellation (err) {
33
+ return err && err.code === 'ERR_CANCELLED_PEER'
34
+ }
35
+
36
+ /**
37
+ * Either end deliberately stopped. Nothing failed, so nothing about the
38
+ * socket's subsequent death is worth reporting.
39
+ * @param {any} err
40
+ */
41
+ function isCancellation (err) {
42
+ return isLocalCancellation(err) || isPeerCancellation(err)
43
+ }
44
+
45
+ // What an interrupted, resumable receive left behind (err.partial, set by
46
+ // the engine only when it kept one). The old sentences said the partial
47
+ // was discarded, which stopped being true for every interruption once
48
+ // resume existed -- and it is the sentence that tells a person whether
49
+ // trying again costs the whole file or only the rest of it.
50
+ /** @param {any} err */
51
+ function partialNote (err) {
52
+ if (!err.partial) return 'The partial file was discarded.'
53
+ return `Kept ${err.partial.bytes} bytes in ${err.partial.path}: send it again, with a new code, and the transfer resumes from there.`
54
+ }
55
+
56
+ /**
57
+ * A single line, already prefixed by the caller's label.
58
+ *
59
+ * ESCAPED AS A WHOLE, on the way out. The engine cleans every peer string
60
+ * it puts into a message (notJson, validateManifest's quote,
61
+ * sanitizeReason), and this is the backstop for the one it misses, the
62
+ * next branch added below, and the message nobody thought of as
63
+ * peer-controlled. A single escape at the exit is checkable in one place;
64
+ * a rule that every branch must remember is not (Q-11).
65
+ *
66
+ * @param {any} err
67
+ * @returns {string}
68
+ */
69
+ function describeError (err) {
70
+ return displayText(describeUnescaped(err))
71
+ }
72
+
73
+ /**
74
+ * @param {any} err
75
+ * @returns {string}
76
+ */
77
+ function describeUnescaped (err) {
78
+ const code = err && err.code
79
+
80
+ switch (code) {
81
+ case 'ABORT_ERR':
82
+ return `cancelled${typeof err.bytes === 'number' ? ` after ${err.bytes} bytes` : ''}. The peer was told, so it will report a deliberate cancel rather than a dropped connection.`
83
+
84
+ case 'ERR_CANCELLED_PEER':
85
+ // Verbatim, but the engine has already capped it at 256 bytes and
86
+ // stripped control characters -- it is a string chosen by the other
87
+ // end and it is about to be printed into a terminal.
88
+ return err.peerReason
89
+ ? `the peer cancelled the transfer: ${err.peerReason}`
90
+ : 'the peer cancelled the transfer.'
91
+
92
+ case 'ERR_HASH_MISMATCH':
93
+ if (err.reportedBy === 'receiver') {
94
+ return `FAILED: the receiver confirmed a digest that is not the one sent (sent ${err.expected}, it reports ${err.actual}). ` +
95
+ 'An honest receiver refuses a file that does not match; this one claimed it kept it. Treat the receiving side as broken.'
96
+ }
97
+ return `FAILED: the received file does not match the sender's digest, so it was discarded and nothing was saved. ` +
98
+ `Expected ${err.expected}, computed ${err.actual}. This is corruption or a bug, not a network timeout -- do not retry blindly.`
99
+
100
+ case 'ERR_SIZE_MISMATCH':
101
+ // A stream declares no size, so what it can overrun is this
102
+ // receiver's own limit (ADHAL_MAX_SIZE), not a promise.
103
+ if (typeof err.limit === 'number') {
104
+ return `FAILED: the stream passed this receiver's ${err.limit}-byte limit, so it was stopped and nothing was saved. The sender was told. Set ADHAL_MAX_SIZE higher to take it.`
105
+ }
106
+ return `FAILED: the transfer did not match the size its manifest declared (${err.bytes} bytes against ${err.size}). Nothing was saved.`
107
+
108
+ case 'ERR_UNSAFE_NAME':
109
+ // THE OLD WORDING WAS A GUESS, AND USUALLY THE WRONG ONE. It said
110
+ // the name "points outside the output directory" for every
111
+ // refusal, when traversal is only one of the reasons: a NUL byte,
112
+ // control characters, a bidi override, an over-long name, and an
113
+ // empty one all arrive here too, and telling someone their
114
+ // 300-character filename escaped the directory sends them looking
115
+ // for an attack that did not happen. The engine already computes
116
+ // the specific reason -- printing it is strictly better than
117
+ // re-deriving a worse one here.
118
+ return `FAILED: refused the peer's filename ${JSON.stringify(displayName(err.declaredName))}: ${err.detail || 'it is not a name we are willing to write'}. Nothing was written.`
119
+
120
+ case 'ERR_MANIFEST_INVALID':
121
+ return `FAILED: the peer's manifest is invalid${err.field ? ` (field: ${err.field})` : ''}. ${err.message}`
122
+
123
+ case 'ERR_PROTOCOL':
124
+ return `FAILED: protocol error. ${err.message}`
125
+
126
+ case 'ERR_DECLINED':
127
+ // Two sides of one event. The receiver declined (its own check, or
128
+ // a person or policy through onOffer) and knows why; the sender was
129
+ // told, and prints the receiver's sentence -- sanitized by the
130
+ // engine, since the other end chose it.
131
+ if (err.local) {
132
+ return `declined the offer${err.reason ? `: ${err.reason}` : ''}. The sender was told, and nothing was written.`
133
+ }
134
+ return err.peerReason
135
+ ? `the receiver declined the file: ${err.peerReason}. Nothing was sent.`
136
+ : 'the receiver declined the file. Nothing was sent.'
137
+
138
+ case 'ERR_CONNECTION':
139
+ // The sender's cases. `phase` is only set there; the receiver's
140
+ // wording below predates it and still describes the receiver.
141
+ if (err.phase === 'offer') {
142
+ return 'FAILED: the receiver disconnected before answering the offer. No file bytes were sent.'
143
+ }
144
+ if (err.phase === 'result') {
145
+ return 'FAILED: every byte was sent, but the receiver disconnected before confirming the file. ' +
146
+ 'Whether it was saved is unknown -- check the receiver\'s output before sending again.'
147
+ }
148
+ if (err.phase === 'send') {
149
+ return err.size === null
150
+ ? `FAILED: the receiver disconnected after ${err.bytes} bytes of the stream were sent.`
151
+ : `FAILED: the receiver disconnected after ${err.bytes} of ${err.size} bytes were sent.`
152
+ }
153
+ // A single-connection handshake (engine/src/stream-handshake.js).
154
+ // The sender cannot see the receiver's confirmation check -- the
155
+ // receiver verifies first and hangs up on a mismatch -- so from this
156
+ // side a mistyped code looks exactly like this, and saying so is
157
+ // what points a human at the right fix.
158
+ if (err.phase === 'handshake') {
159
+ return err.role === 'sender'
160
+ ? 'FAILED: the receiver hung up during the handshake, before any file byte moved. ' +
161
+ 'The likeliest cause is a mistyped code -- check the receiver\'s output.'
162
+ : 'FAILED: the sender hung up during the handshake, before any file byte moved.'
163
+ }
164
+ return `FAILED: the connection closed before the transfer finished (${err.bytes} bytes received). ${partialNote(err)}`
165
+
166
+ case 'ERR_RECEIVER_FAILED':
167
+ return err.peerReason
168
+ ? `FAILED: the receiver got every byte but could not keep the file: ${err.peerReason}`
169
+ : 'FAILED: the receiver got every byte but could not keep the file.'
170
+
171
+ case 'ERR_STALLED':
172
+ if (err.phase === 'result') {
173
+ return `FAILED: ${err.message}. Check the receiver's output before sending again.`
174
+ }
175
+ if (err.partial) return `FAILED: ${err.message}. ${partialNote(err)}`
176
+ return `FAILED: ${err.message}.`
177
+
178
+ case 'ERR_ATTEMPT_CAP':
179
+ // THE ONLY CASE IN THIS FILE THAT MEANS SOMEONE WAS GUESSING.
180
+ // Everything else here is a fault; this one is a report, and it is
181
+ // the reason PROTOCOL.md section 10 singles it out. Without this
182
+ // case it would fall through to the generic `error: <message>` and
183
+ // get the least prose of any failure -- which is precisely backwards
184
+ // for the only outcome a human has to act on beyond retrying.
185
+ //
186
+ // Three things have to be said, and in this order. What happened,
187
+ // because "burned" is not self-explanatory. That the code is spent,
188
+ // because the instinct is to retry with it and that hands the
189
+ // guesser its next hundred attempts. And that the handover route may
190
+ // be the problem, because a guesser who knew the nameplate got it
191
+ // from somewhere.
192
+ return `FAILED: this drop was burned after ${err.attempts} failed attempts to confirm the code` +
193
+ `${typeof err.max === 'number' ? ` (the limit is ${err.max})` : ''}. ` +
194
+ 'That is not a network problem: somebody was guessing the secret. Nothing was ' +
195
+ 'transferred. Do NOT retry with the same code -- it is spent, and reusing it ' +
196
+ 'would give them another hundred guesses. Generate a new one, and consider ' +
197
+ 'whether the way you shared the last one is how they found it.'
198
+
199
+ case 'ERR_DROP_TAKEN':
200
+ // Two people held the code and the other got there first. Nobody was
201
+ // guessing -- this side proved the secret -- but one of the two
202
+ // peers was not the one intended, and only the humans can tell
203
+ // which. So the line says what happened and what to check, rather
204
+ // than just "retry".
205
+ return 'FAILED: this drop code was already used by another peer, which paired first. ' +
206
+ 'Nothing was transferred. If you expected no one else to have the code, someone ' +
207
+ 'else does: check with the other person, and use a new code rather than this one.'
208
+
209
+ case 'ERR_NO_PEER':
210
+ case 'ERR_NO_HANDSHAKE':
211
+ // These already carry long, carefully-worded diagnostics from
212
+ // engine/src/swarm.js. Repeating them here would only let the two
213
+ // wordings drift apart.
214
+ return err.message
215
+
216
+ default:
217
+ return `error: ${err && err.message ? err.message : String(err)}`
218
+ }
219
+ }
220
+
221
+ module.exports = { describeError, isLocalCancellation, isPeerCancellation, isCancellation }