@ad-hal/cli 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -35,6 +35,21 @@ The receiver is shown the file's name, size, and SHA-256, and is asked
35
35
  before anything is written. `--help` on either command lists every flag.
36
36
  `ad-hal-code` prints a fresh drop code and its QR symbol.
37
37
 
38
+ For pipes and scripts:
39
+
40
+ ```bash
41
+ # stream a directory across, and unpack it on arrival
42
+ tar c ./project | ad-hal-send <code> - --name=project.tar --code-on-argv
43
+ set -o pipefail; ad-hal-receive --stdout --yes | tar x
44
+
45
+ # one JSON event per line, for a program to read
46
+ ad-hal-receive --json --yes ~/Downloads
47
+ ```
48
+
49
+ With `--stdout`, the bytes are verified only if `ad-hal-receive` exits 0,
50
+ so check it. What each exit status and event means is in
51
+ [`docs/CLI-CONTRACT.md`](https://github.com/khartig/adhal/blob/main/docs/CLI-CONTRACT.md).
52
+
38
53
  ## Before you use it
39
54
 
40
55
  - **The code is a bearer capability.** Whoever holds it can complete the
@@ -42,6 +57,13 @@ before anything is written. `--help` on either command lists every flag.
42
57
  - **Adhal is not anonymous.** Each side's IP address is visible to the
43
58
  other, and to the DHT nodes near the drop's topic.
44
59
  - **Windows is not supported for security purposes** yet.
60
+ - **A relay sees both IP addresses.** `--relay=<key>` connects through a
61
+ relay you name, only when a direct connection fails. The relay's
62
+ operator sees both IP addresses, connection times, and byte counts,
63
+ never the file: what passes through is sealed under keys from the code
64
+ ([`THREAT-MODEL.md`](https://github.com/khartig/adhal/blob/main/docs/THREAT-MODEL.md)
65
+ §8, where each safeguard has a test). Without it, a drop follows a relay the peer names, unless you pass
66
+ `--refuse-peer-relay`.
45
67
  - **This is 0.x.** The wire protocol is frozen at v2, but the commands and
46
68
  their flags may still change.
47
69
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ad-hal/cli",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Adhal command-line tools: send and receive a file directly between two machines with a one-shot code.",
5
5
  "keywords": [
6
6
  "p2p",
@@ -34,11 +34,11 @@
34
34
  "node": ">=24"
35
35
  },
36
36
  "dependencies": {
37
- "@ad-hal/engine": "0.1.1",
37
+ "@ad-hal/engine": "0.1.3",
38
38
  "qrcode-generator": "2.0.4"
39
39
  },
40
40
  "devDependencies": {
41
- "hyperdht": "6.34.0",
41
+ "hyperdht": "6.36.0",
42
42
  "jsqr": "1.4.0"
43
43
  },
44
44
  "publishConfig": {
package/src/consent.js CHANGED
@@ -15,7 +15,9 @@
15
15
  // - a terminal on stdin: show the offer and ask, defaulting to no.
16
16
  // - neither: decline, and say how to accept unattended. Hanging on a
17
17
  // prompt nobody can see, or silently accepting, are the two failures
18
- // this replaces.
18
+ // this replaces. `ask: false` is "neither" on purpose, for --json,
19
+ // which never asks (docs/CLI-CONTRACT.md section 3): the event stream
20
+ // is for a program, and a question beside it is for nobody.
19
21
  //
20
22
  // A risky name is warned about in every case, `--yes` included: the flag
21
23
  // says "take whatever arrives", not "and don't tell me what it was".
@@ -120,6 +122,7 @@ function describeOffer (offer) {
120
122
  * @param {{
121
123
  * yes: boolean,
122
124
  * label: string,
125
+ * ask?: boolean,
123
126
  * log?: (line: string) => void,
124
127
  * input?: NodeJS.ReadableStream & { isTTY?: boolean },
125
128
  * output?: NodeJS.WritableStream,
@@ -138,6 +141,7 @@ function describeOffer (offer) {
138
141
  function createConsent ({
139
142
  yes,
140
143
  label,
144
+ ask = true,
141
145
  log = console.log,
142
146
  input = process.stdin,
143
147
  output = process.stderr,
@@ -179,7 +183,7 @@ function createConsent ({
179
183
  for (const line of describeOffer(offer)) say(line)
180
184
  if (risk) say(`WARNING: ${risk}`)
181
185
 
182
- if (!input.isTTY) {
186
+ if (!ask || !input.isTTY) {
183
187
  say('no terminal to ask on, so the offer is declined. Pass --yes to accept offers without being asked.')
184
188
  // What the sender reads. It says why without saying anything about
185
189
  // this machine.
package/src/contention.js CHANGED
@@ -35,7 +35,9 @@ const CONFIRMATION_THRESHOLD = 3
35
35
  const SILENT_THRESHOLD = 5
36
36
 
37
37
  /**
38
- * @param {{ label: string, log?: (line: string) => void, maxAttempts?: number }} options
38
+ * @param {{ label: string, log?: (line: string, details: { failed: number, silent: number, keys: number, message: string }) => void, maxAttempts?: number }} options
39
+ * `log` gets the line, and the counts behind it for the --json
40
+ * `warning` event, with `message` the line without its label.
39
41
  * @returns {{ dropped: (peerInfo: any, reason: string, code?: string) => void, paired: () => void }}
40
42
  */
41
43
  function createContentionMonitor ({ label, log = console.log, maxAttempts = MAX_ATTEMPTS }) {
@@ -47,6 +49,9 @@ function createContentionMonitor ({ label, log = console.log, maxAttempts = MAX_
47
49
  /** @type {Set<string>} */
48
50
  const keys = new Set()
49
51
 
52
+ /** @param {string} message */
53
+ const report = (message) => log(`[${label}] ${message}`, { failed, silent, keys: keys.size, message })
54
+
50
55
  /**
51
56
  * Feed it everything onCandidateDropped hears.
52
57
  * @param {any} peerInfo
@@ -61,18 +66,18 @@ function createContentionMonitor ({ label, log = console.log, maxAttempts = MAX_
61
66
  if (failed < nextFailedWarning) return
62
67
  nextFailedWarning *= 2
63
68
  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. ` +
69
+ report(keys.size > 1
70
+ ? `WARNING: ${failed} peers, from ${keys.size} different keys, found this drop and could not prove its code, and none has succeeded. ` +
66
71
  'Either another drop is using the same first two words (a code collision), or someone is guessing. ' +
67
72
  `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: ` +
73
+ : `WARNING: one peer has failed to prove the code ${failed} times. Most likely the sender has mistyped it: ` +
69
74
  `check the code on both sides. That is ${limit}.`)
70
75
  return
71
76
  }
72
77
  silent++
73
78
  if (silent < nextSilentWarning) return
74
79
  nextSilentWarning *= 2
75
- log(`[${label}] note: ${silent} candidates connected and went silent before finishing the handshake. ` +
80
+ report(`note: ${silent} candidates connected and went silent before finishing the handshake. ` +
76
81
  '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
82
  }
78
83
 
package/src/events.js ADDED
@@ -0,0 +1,145 @@
1
+ 'use strict'
2
+
3
+ // The --json event stream: one JSON object per line, the contract in
4
+ // docs/CLI-CONTRACT.md section 3. One file for both swarm CLIs, for the
5
+ // reason report.js is one file: two copies of a schema drift, and the
6
+ // copy that drifts is the one a script was reading.
7
+ //
8
+ // WHAT THIS FILE GUARANTEES, and the tests in cli/test/json-events.test.js
9
+ // check: every line is a JSON object that parses, every object carries
10
+ // `v`, `event`, `ms`, and `role`, and a failure's `code` comes from
11
+ // `err.code`, never from its message (PROTOCOL.md section 10).
12
+ //
13
+ // Peer-chosen strings are passed through as the engine has them. JSON
14
+ // escapes the C0 controls; a consumer that displays a declared name or a
15
+ // peer's reason must escape the rest itself (CLI-CONTRACT.md section 3.4).
16
+
17
+ const { performance } = require('node:perf_hooks')
18
+ const { connectionStats } = require('@ad-hal/engine')
19
+ const { version } = require('../package.json')
20
+
21
+ // Bumped only by a breaking change: CLI-CONTRACT.md section 5.
22
+ const SCHEMA_VERSION = 1
23
+
24
+ // A progress event at most this often, plus one at the end. Fast enough
25
+ // for a wrapper's bar, slow enough that a local transfer at hundreds of
26
+ // chunks a second does not turn the stream into progress and nothing else.
27
+ const PROGRESS_MS = 250
28
+
29
+ // The error fields worth a script's attention, copied onto `failed` when
30
+ // the error has them. A list, not the whole error: `expected` and
31
+ // `actual` are useful, a stack is not, and an error the engine never
32
+ // built could carry anything.
33
+ const ERROR_FIELDS = ['phase', 'reportedBy', 'peerReason', 'declineCode', 'detail', 'field', 'attempts', 'max', 'limit', 'size', 'expected', 'actual', 'partial', 'holepunchRefused', 'holepunchFailed', 'relayAttempts', 'relayCapped', 'peerRelays', 'relayedCandidates']
34
+
35
+ /**
36
+ * The 12 hex characters the human lines show, from the candidate's
37
+ * ephemeral public key.
38
+ * @param {any} peerInfo
39
+ * @returns {string | null}
40
+ */
41
+ function peerId (peerInfo) {
42
+ return peerInfo && peerInfo.publicKey ? peerInfo.publicKey.toString('hex').slice(0, 12) : null
43
+ }
44
+
45
+ /**
46
+ * The `connection` field of a final event: the paired connection's
47
+ * transport counters (engine/src/swarm.js connectionStats), or nothing at
48
+ * all before a peer paired, or on a transport with no counters to read.
49
+ * Spread into the event, so an absent field stays absent.
50
+ * @param {any} socket
51
+ * @returns {{ connection?: NonNullable<ReturnType<typeof connectionStats>> }}
52
+ */
53
+ function connectionField (socket) {
54
+ const stats = socket ? connectionStats(socket) : null
55
+ return stats ? { connection: stats } : {}
56
+ }
57
+
58
+ /**
59
+ * The `code` a failure is reported under: the error's own, except for a
60
+ * consumer that closed its end of stdout, which has a CLI-level code of
61
+ * its own (CLI-CONTRACT.md section 4).
62
+ * @param {any} err
63
+ * @returns {string | null}
64
+ */
65
+ function failureCode (err) {
66
+ if (!err) return null
67
+ if (err.code === 'EPIPE') return 'ERR_OUTPUT_CLOSED'
68
+ return typeof err.code === 'string' ? err.code : null
69
+ }
70
+
71
+ /**
72
+ * @param {{
73
+ * role: 'send' | 'receive',
74
+ * stream?: { write: (chunk: string) => any },
75
+ * now?: () => number
76
+ * }} options
77
+ * `now` is milliseconds since the process started, from a monotonic
78
+ * clock: performance.now() is exactly that.
79
+ */
80
+ function createEventStream ({ role, stream = process.stdout, now = () => performance.now() }) {
81
+ // Nothing moves before the offer is answered, but the engine reports 0
82
+ // bytes as soon as it sets a transfer up, which on both sides is before
83
+ // ACCEPT. Reported then, it would put `progress` ahead of `accepted`,
84
+ // against the order CLI-CONTRACT.md section 3.2 gives.
85
+ let accepted = false
86
+
87
+ /**
88
+ * @param {string} event
89
+ * @param {Record<string, any>} [fields]
90
+ */
91
+ function emit (event, fields = {}) {
92
+ if (event === 'accepted') accepted = true
93
+ stream.write(`${JSON.stringify({ v: SCHEMA_VERSION, event, ms: Math.round(now()), role, ...fields })}\n`)
94
+ }
95
+
96
+ /** @type {number | null} */
97
+ let lastAt = null
98
+ /** @type {{ bytes: number, total: number | null } | null} */
99
+ let unsent = null
100
+
101
+ /** @param {{ bytes: number, total: number | null }} p */
102
+ function onProgress ({ bytes, total }) {
103
+ if (!accepted) return
104
+ const at = now()
105
+ const complete = total !== null && bytes >= total
106
+ if (lastAt !== null && !complete && at - lastAt < PROGRESS_MS) {
107
+ unsent = { bytes, total }
108
+ return
109
+ }
110
+ lastAt = at
111
+ unsent = null
112
+ emit('progress', { bytes, total })
113
+ }
114
+
115
+ // The last count, if throttling held it back: a stream has no total to
116
+ // be complete at, so its final count would otherwise never be sent.
117
+ function flushProgress () {
118
+ if (!unsent) return
119
+ const last = unsent
120
+ unsent = null
121
+ emit('progress', last)
122
+ }
123
+
124
+ /**
125
+ * The one `failed` event. `message` is the CLI's own sentence, already
126
+ * escaped for a terminal.
127
+ * @param {any} err
128
+ * @param {string} message
129
+ * @param {Record<string, any>} [extra]
130
+ */
131
+ function failed (err, message, extra = {}) {
132
+ flushProgress()
133
+ /** @type {Record<string, any>} */
134
+ const fields = { code: failureCode(err), message }
135
+ fields.bytes = err && typeof err.bytes === 'number' ? err.bytes : null
136
+ for (const key of ERROR_FIELDS) {
137
+ if (err && err[key] !== undefined) fields[key] = err[key]
138
+ }
139
+ emit('failed', { ...fields, ...extra })
140
+ }
141
+
142
+ return { emit, onProgress, flushProgress, failed }
143
+ }
144
+
145
+ module.exports = { createEventStream, peerId, connectionField, failureCode, SCHEMA_VERSION, PROGRESS_MS, version }
package/src/qr.js CHANGED
@@ -125,14 +125,16 @@ function renderQr (payload, { wide = false, color = true } = {}) {
125
125
  }
126
126
 
127
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.
128
+ * Prints the symbol, to stdout unless `log` says otherwise, honoring two
129
+ * environment overrides: ADHAL_QR_WIDE=1 for the full-block variant, and
130
+ * NO_COLOR (the usual convention) to drop the ANSI colors.
131
131
  *
132
132
  * @param {string} payload
133
+ * @param {(text: string) => void} [log] where the lines go; a receiver
134
+ * writing the file to stdout sends them to stderr
133
135
  */
134
- function printQr (payload) {
135
- console.log(renderQr(payload, {
136
+ function printQr (payload, log = console.log) {
137
+ log(renderQr(payload, {
136
138
  wide: process.env.ADHAL_QR_WIDE === '1',
137
139
  color: !process.env.NO_COLOR
138
140
  }))
@@ -0,0 +1,34 @@
1
+ 'use strict'
2
+
3
+ // --relay=<key>, shared by both swarm CLIs, for the reason env.js is one
4
+ // file. The key is a relay's public key (parseRelayKey in the engine), and
5
+ // the relay is used only after a hole punch to the peer fails
6
+ // (relayOnlyAfterFailedPunch in engine/src/swarm.js).
7
+ //
8
+ // `=` and never a space, as with --name=: every argument not starting with
9
+ // `--` is a positional, so `--relay <key>` would hand the key to the code
10
+ // or the file slot. A bare --relay is therefore refused, rather than run
11
+ // with no relay, which is what the user would not notice until two
12
+ // randomized NATs failed to connect.
13
+
14
+ const { parseRelayKey } = require('@ad-hal/engine')
15
+
16
+ /**
17
+ * @param {string[]} argv
18
+ * @returns {Buffer | null} the relay's key, or null without --relay
19
+ */
20
+ function relayFlag (argv) {
21
+ if (argv.includes('--relay')) {
22
+ throw new Error('--relay takes its key after an equals sign: --relay=<key>')
23
+ }
24
+ const given = argv.filter((a) => a.startsWith('--relay='))
25
+ if (given.length === 0) return null
26
+ if (given.length > 1) throw new Error('--relay was given more than once; pass one relay')
27
+ try {
28
+ return parseRelayKey(given[0].slice('--relay='.length))
29
+ } catch (err) {
30
+ throw new Error(`--relay: ${/** @type {Error} */ (err).message}`)
31
+ }
32
+ }
33
+
34
+ module.exports = { relayFlag }
package/src/report.js CHANGED
@@ -206,6 +206,14 @@ function describeUnescaped (err) {
206
206
  'Nothing was transferred. If you expected no one else to have the code, someone ' +
207
207
  'else does: check with the other person, and use a new code rather than this one.'
208
208
 
209
+ case 'EPIPE':
210
+ // --stdout, and the reader went away: `| head` that had enough, or
211
+ // a consumer that crashed. Reported as ERR_OUTPUT_CLOSED in --json
212
+ // (./events.js); here it is the sentence. What it had already read
213
+ // was never verified, which is the thing worth saying.
214
+ return `FAILED: the program reading stdout closed it after ${typeof err.bytes === 'number' ? `${err.bytes} bytes` : 'part of the file'}, so the transfer was stopped and the sender was told. ` +
215
+ 'What it had read was never verified.'
216
+
209
217
  case 'ERR_NO_PEER':
210
218
  case 'ERR_NO_HANDSHAKE':
211
219
  // These already carry long, carefully-worded diagnostics from
@@ -218,4 +226,40 @@ function describeUnescaped (err) {
218
226
  }
219
227
  }
220
228
 
221
- module.exports = { describeError, isLocalCancellation, isPeerCancellation, isCancellation }
229
+ // A RELAYED DROP THAT WAS CUT OFF MID-TRANSFER (THREAT-MODEL.md section 8,
230
+ // gate 5). A relay can end a connection on a limit of its own -- bytes,
231
+ // time, an idle pairing -- and from either end that looks exactly like any
232
+ // other lost path: the socket closes, or goes quiet. Nothing on the wire
233
+ // says which, so this says both, and says how to pick the drop up again.
234
+ //
235
+ // Only for failures in the middle of a transfer: an ERR_CONNECTION while
236
+ // sending, after the last byte, or on the receiver mid-file, and an
237
+ // ERR_STALLED once bytes had moved. Before the first file byte there is
238
+ // nothing to resume, and the existing sentences already say what to check.
239
+ //
240
+ // The receiver's resume advice is partialNote's, already in its sentence.
241
+ // The sender's is here: it cannot see whether the receiver kept a partial,
242
+ // and a stream (`-`) cannot resume at all.
243
+ /**
244
+ * @param {any} err
245
+ * @param {{ relayed: boolean, role: 'sender' | 'receiver', stream: boolean }} context
246
+ * `relayed` whether the paired connection went through a relay when it
247
+ * ended (connectionStats in engine/src/swarm.js)
248
+ * @returns {string} the sentence to append, or '' when it does not apply
249
+ */
250
+ function relayCutNote (err, { relayed, role, stream }) {
251
+ if (!relayed || !err) return ''
252
+ const midTransfer =
253
+ (err.code === 'ERR_CONNECTION' && (err.phase === undefined || err.phase === 'send' || err.phase === 'result')) ||
254
+ (err.code === 'ERR_STALLED' && (err.phase === 'result' || (err.phase === undefined && err.bytes > 0)))
255
+ if (!midTransfer) return ''
256
+ const note = 'This connection went through a relay, which can end a connection on a limit of its own, ' +
257
+ 'such as a cap on bytes or time, as well as lose it the way any path can.'
258
+ if (role === 'sender' && !stream && err.phase === 'send') {
259
+ return note + ' If the receiver kept the part that arrived, send the file again with a new code, ' +
260
+ 'received into the same folder, and only the rest is sent.'
261
+ }
262
+ return note
263
+ }
264
+
265
+ module.exports = { describeError, relayCutNote, isLocalCancellation, isPeerCancellation, isCancellation }
@@ -19,20 +19,29 @@
19
19
  // ADHAL_BOOTSTRAP=<json bootstrap array> overrides the DHT bootstrap nodes
20
20
  // -- used by the automated test to run against an isolated local testnet
21
21
  // instead of the public DHT.
22
+ //
23
+ // --stdout writes the file to stdout, for `ad-hal-receive --stdout | tar
24
+ // x`, and moves every other line to stderr. --json replaces the human
25
+ // lines with the event stream in ./events.js. Both are the contract in
26
+ // docs/CLI-CONTRACT.md, and the first thing that contract says is the one
27
+ // to remember here: with --stdout, the bytes are verified only once this
28
+ // process exits 0.
22
29
 
23
30
  const path = require('path')
24
31
  const fs = require('fs')
25
- const { createSwarm, acceptOnce, receiveFile, closeAfterResult, generateCode, encodeQrPayload, resolveCode, displayName } = require('@ad-hal/engine')
32
+ const { createSwarm, onPeerRelayRefused, onRelayCapReached, isRelayed, connectionStats, acceptOnce, receiveFile, closeAfterResult, generateCode, encodeQrPayload, resolveCode, displayName, KNOWN_CAPS } = require('@ad-hal/engine')
26
33
 
27
34
  const { printQr } = require('./qr')
28
35
  const { readCode } = require('./read-code')
29
36
  const { createProgressReporter } = require('./progress')
30
37
  const { installCancelHandler } = require('./signals')
31
- const { describeError, isCancellation } = require('./report')
38
+ const { describeError, relayCutNote, isCancellation } = require('./report')
32
39
  const { parseBootstrap } = require('./env')
33
- const { createConsent } = require('./consent')
40
+ const { createConsent, riskWarning } = require('./consent')
34
41
  const { createContentionMonitor } = require('./contention')
35
- const { usage, NOT_ANONYMOUS } = require('./usage')
42
+ const { createEventStream, peerId, connectionField, version } = require('./events')
43
+ const { usage, NOT_ANONYMOUS, DOUBLE_RANDOMIZED_NAT, DOUBLE_RANDOMIZED_NAT_RELAYING, HOLEPUNCH_FAILED, HOLEPUNCH_FAILED_RELAYING, RELAYED, PEER_RELAY_REFUSED, relayCapReachedNote } = require('./usage')
44
+ const { relayFlag } = require('./relay-flag')
36
45
 
37
46
 
38
47
  // ADHAL_JOIN_TIMEOUT overrides how long we wait for a peer, in ms (0
@@ -72,15 +81,17 @@ function maxSize () {
72
81
  // stays unambiguously "that's a code", exactly as the Hyperswarm CLI defined it: a bare
73
82
  // path and a bare code are not reliably distinguishable, and guessing wrong
74
83
  // would silently save into a directory named after a word.
75
- const KNOWN_FLAGS = new Set(['--new', '--insecure-opaque-code', '--replace', '--code-stdin', '--verbose', '--yes', '--code-on-argv', '--help'])
84
+ const KNOWN_FLAGS = new Set(['--new', '--insecure-opaque-code', '--replace', '--code-stdin', '--verbose', '--yes', '--code-on-argv', '--stdout', '--json', '--refuse-peer-relay', '--help'])
76
85
 
77
86
  function parseArgs (argv) {
78
87
  const flags = argv.filter((a) => a.startsWith('--'))
79
88
  const positional = argv.filter((a) => !a.startsWith('--'))
80
89
  const wantsNew = flags.includes('--new')
90
+ // The one flag with a value, so it is not in KNOWN_FLAGS; see ./relay-flag.js.
91
+ const relayThrough = relayFlag(flags)
81
92
 
82
93
  for (const flag of flags) {
83
- if (!KNOWN_FLAGS.has(flag)) throw new Error(`unknown flag ${flag}`)
94
+ if (!KNOWN_FLAGS.has(flag) && !flag.startsWith('--relay=')) throw new Error(`unknown flag ${flag}`)
84
95
  }
85
96
 
86
97
  const common = {
@@ -94,15 +105,23 @@ function parseArgs (argv) {
94
105
  // Accept the offer without asking; see ./consent.js.
95
106
  yes: flags.includes('--yes'),
96
107
  allowArgv: flags.includes('--code-on-argv'),
108
+ // The file to stdout, everything else to stderr; see the top.
109
+ toStdout: flags.includes('--stdout'),
110
+ json: flags.includes('--json'),
111
+ refusePeerRelay: flags.includes('--refuse-peer-relay'),
112
+ relayThrough,
97
113
  help: flags.includes('--help')
98
114
  }
99
115
 
100
- if (wantsNew) {
101
- if (positional.length > 1) throw new Error('too many arguments')
102
- return { codeArg: null, outputDirArg: positional[0], ...common }
103
- }
104
- if (positional.length > 2) throw new Error('too many arguments')
105
- return { codeArg: positional[0] || null, outputDirArg: positional[1], ...common }
116
+ const parsed = wantsNew
117
+ ? { codeArg: null, outputDirArg: positional[0], ...common }
118
+ : { codeArg: positional[0] || null, outputDirArg: positional[1], ...common }
119
+ if (positional.length > (wantsNew ? 1 : 2)) throw new Error('too many arguments')
120
+ // One place for the bytes. --replace is about a file that already
121
+ // exists, and stdout has none.
122
+ if (parsed.toStdout && parsed.outputDirArg !== undefined) throw new Error('--stdout takes the place of an output directory; pass one or the other')
123
+ if (parsed.toStdout && parsed.replace) throw new Error('--replace has nothing to replace with --stdout')
124
+ return parsed
106
125
  }
107
126
 
108
127
  // ADHAL_REFRESH_INTERVAL overrides how often we re-run our own DHT
@@ -122,12 +141,20 @@ function refreshInterval () {
122
141
  }
123
142
 
124
143
  async function main () {
144
+ const argv = process.argv.slice(2)
125
145
  let parsed
126
146
  try {
127
- parsed = parseArgs(process.argv.slice(2))
147
+ parsed = parseArgs(argv)
128
148
  } catch (err) {
129
- console.error(`[swarm-receive] ${err.message}`)
130
- console.error(usage('swarm-receive'))
149
+ // Asked for by flag, so honored even when the flags did not parse:
150
+ // a script that passed --json reads events, not prose.
151
+ if (argv.includes('--json')) {
152
+ createEventStream({ role: 'receive', stream: argv.includes('--stdout') ? process.stderr : process.stdout })
153
+ .failed({ code: 'ERR_USAGE' }, err.message)
154
+ } else {
155
+ console.error(`[swarm-receive] ${err.message}`)
156
+ console.error(usage('swarm-receive'))
157
+ }
131
158
  process.exitCode = 1
132
159
  return
133
160
  }
@@ -136,6 +163,46 @@ async function main () {
136
163
  return
137
164
  }
138
165
 
166
+ // WHERE EACH KIND OF OUTPUT GOES (docs/CLI-CONTRACT.md sections 2-3).
167
+ // With --stdout, stdout carries the file's bytes and nothing else, so
168
+ // the human lines move to stderr; with --json, the events go wherever
169
+ // the file does not, and the human lines are not written at all.
170
+ const humanOut = parsed.toStdout ? process.stderr : process.stdout
171
+ const events = parsed.json
172
+ ? createEventStream({ role: 'receive', stream: parsed.toStdout ? process.stderr : process.stdout })
173
+ : null
174
+ const say = events ? () => {} : (/** @type {string} */ line = '') => { humanOut.write(`${line}\n`) }
175
+ /** @type {Array<{ kind: string, message: string }>} warnings raised before `start` */
176
+ const held = []
177
+ const sayError = events ? () => {} : (/** @type {string} */ line) => { process.stderr.write(`${line}\n`) }
178
+ /**
179
+ * A failure before the drop began. `code` is CLI-level (CONTRACT
180
+ * section 4), since none of these touched the network.
181
+ * @param {string} code
182
+ * @param {any} err
183
+ */
184
+ const refuse = (code, err) => {
185
+ if (events) events.failed({ code }, err.message)
186
+ else sayError(`[swarm-receive] ${err.message}`)
187
+ process.exitCode = 1
188
+ }
189
+
190
+ // Binary on a terminal is never what was meant: the mirror of
191
+ // ad-hal-send refusing to stream from one.
192
+ if (parsed.toStdout && process.stdout.isTTY) {
193
+ refuse('ERR_USAGE', new Error('refusing to write a file to a terminal: redirect or pipe stdout, e.g. ad-hal-receive --stdout | tar x'))
194
+ return
195
+ }
196
+
197
+ let timeout, refresh
198
+ try {
199
+ timeout = joinTimeout()
200
+ refresh = refreshInterval()
201
+ } catch (err) {
202
+ refuse('ERR_USAGE', err)
203
+ return
204
+ }
205
+
139
206
  // A generated code is the default: the code generator exists because
140
207
  // hand-typing a code on both machines was the friction worth removing.
141
208
  // `--code-stdin` is the other way in, for a code that must not touch
@@ -145,11 +212,19 @@ async function main () {
145
212
  try {
146
213
  const input = generated
147
214
  ? generateCode()
148
- : await readCode({ argvCode: parsed.fromStdin ? '-' : parsed.codeArg, label: 'swarm-receive', allowArgv: parsed.allowArgv })
215
+ : await readCode({
216
+ argvCode: parsed.fromStdin ? '-' : parsed.codeArg,
217
+ label: 'swarm-receive',
218
+ allowArgv: parsed.allowArgv,
219
+ // Held, not emitted: the code is read before `start`, which the
220
+ // contract puts first (CLI-CONTRACT.md section 3.2).
221
+ warn: events
222
+ ? (line) => { held.push({ kind: 'code-on-argv', message: line.replace(/^\[swarm-receive\] note: /, '') }) }
223
+ : undefined
224
+ })
149
225
  resolved = resolveCode(input, { allowOpaque: parsed.allowOpaque || undefined })
150
226
  } catch (err) {
151
- console.error(`[swarm-receive] ${err.message}`)
152
- process.exitCode = 1
227
+ refuse('ERR_CODE_INVALID', err)
153
228
  return
154
229
  }
155
230
  const { code, topic, nameplate, secret } = resolved
@@ -158,27 +233,62 @@ async function main () {
158
233
  try {
159
234
  bootstrap = parseBootstrap()
160
235
  } catch (err) {
161
- console.error(`[swarm-receive] ${err.message}`)
162
- process.exitCode = 1
236
+ refuse('ERR_USAGE', err)
163
237
  return
164
238
  }
165
239
 
166
- const outputDir = parsed.outputDirArg ? path.resolve(parsed.outputDirArg) : process.cwd()
167
- await fs.promises.mkdir(outputDir, { recursive: true })
240
+ const outputDir = parsed.toStdout ? null : parsed.outputDirArg ? path.resolve(parsed.outputDirArg) : process.cwd()
241
+ if (outputDir) await fs.promises.mkdir(outputDir, { recursive: true })
242
+ // A reader that goes away mid-file is reported through the transfer
243
+ // (ERR_OUTPUT_CLOSED); one that goes away after it must not be an
244
+ // uncaught exception.
245
+ if (parsed.toStdout) process.stdout.on('error', () => {})
168
246
 
169
- const swarm = createSwarm({ bootstrap })
170
- const cancel = installCancelHandler({ label: 'swarm-receive' })
171
- const progress = createProgressReporter({ label: 'swarm-receive' })
247
+ const swarm = createSwarm({ bootstrap, refusePeerRelay: parsed.refusePeerRelay, relayThrough: parsed.relayThrough })
248
+ // --refuse-peer-relay: never pair through a relay the peer names
249
+ // (refusePeerRelays in engine/src/swarm.js). Said once, like the
250
+ // refused punch: if the punch cannot connect either, this drop will not.
251
+ onPeerRelayRefused(swarm, (refused) => {
252
+ if (refused !== 1) return
253
+ if (events) events.emit('warning', { kind: 'peer-relay-refused', message: PEER_RELAY_REFUSED })
254
+ say(`[swarm-receive] note: ${PEER_RELAY_REFUSED}`)
255
+ })
256
+ // Once, when the drop stops offering its relay: past MAX_RELAY_ATTEMPTS
257
+ // the relay is not dialed again (THREAT-MODEL.md section 8, gate 5).
258
+ onRelayCapReached(swarm, (count) => {
259
+ const message = relayCapReachedNote(count)
260
+ if (events) events.emit('warning', { kind: 'relay-attempts-capped', message, relayAttempts: count })
261
+ say(`[swarm-receive] note: ${message}`)
262
+ })
263
+ const cancel = installCancelHandler({ label: 'swarm-receive', log: say })
264
+ const progress = events
265
+ ? { onProgress: events.onProgress, close: events.flushProgress, log: () => {} }
266
+ : createProgressReporter({ label: 'swarm-receive', stream: humanOut })
172
267
  /** @type {Error | null} */
173
268
  let socketError = null
269
+ // The paired connection, kept outside the try so a failure can report
270
+ // its transport counters too (CLI-CONTRACT.md section 3.5). Read after
271
+ // the socket closed, which connectionStats allows.
272
+ /** @type {any} */
273
+ let connection = null
274
+ if (events) {
275
+ events.emit('start', { version, time: new Date().toISOString(), joinTimeout: timeout, refreshInterval: refresh ?? 4000, stdout: parsed.toStdout, relay: parsed.relayThrough !== null, refusePeerRelay: parsed.refusePeerRelay })
276
+ events.emit('warning', { kind: 'not-anonymous', message: NOT_ANONYMOUS })
277
+ for (const warning of held) events.emit('warning', warning)
278
+ }
174
279
  // The topic is a commitment to the nameplate, and this line lands in
175
280
  // scrollback, CI logs, and bug reports. It is shown only when asked for
176
281
  // (Q-17); the nameplate itself is already on screen in the code.
177
- console.log(`[swarm-receive] joining topic${parsed.verbose ? ` ${topic.toString('hex')}` : ''} (refresh=${refreshInterval() ?? 4000}ms, timeout=${joinTimeout()}ms)`)
282
+ say(`[swarm-receive] joining topic${parsed.verbose ? ` ${topic.toString('hex')}` : ''} (refresh=${refresh ?? 4000}ms, timeout=${timeout}ms)`)
178
283
  // Q-09: before anything connects, so nobody learns it afterwards.
179
- console.log(`[swarm-receive] note: ${NOT_ANONYMOUS}`)
180
- const contention = createContentionMonitor({ label: 'swarm-receive' })
181
- const consent = createConsent({ yes: parsed.yes, label: 'swarm-receive', signal: cancel.signal })
284
+ say(`[swarm-receive] note: ${NOT_ANONYMOUS}`)
285
+ const contention = createContentionMonitor({
286
+ label: 'swarm-receive',
287
+ log: events
288
+ ? (_line, { message, ...counts }) => events.emit('warning', { kind: 'contention', message, ...counts })
289
+ : say
290
+ })
291
+ const consent = createConsent({ yes: parsed.yes, ask: !events, label: 'swarm-receive', log: say, signal: cancel.signal })
182
292
 
183
293
  try {
184
294
  // Set once acceptOnce resolves; the late-candidate callbacks above
@@ -196,8 +306,12 @@ async function main () {
196
306
  // (PROTOCOL.md section 6). See engine/src/handshake.js.
197
307
  nameplate,
198
308
  secret,
199
- timeout: joinTimeout(),
200
- refreshInterval: refreshInterval(),
309
+ timeout,
310
+ refreshInterval: refresh,
311
+ // Stdout has no partial to resume from, so this receiver does not
312
+ // offer to. The sender then sends from byte 0, and never waits on a
313
+ // CHECKPOINT nobody will send.
314
+ caps: parsed.toStdout ? KNOWN_CAPS.filter((/** @type {string} */ c) => c !== 'resume') : undefined,
201
315
  // Ctrl-C while waiting for a peer -- which, for a receiver showing
202
316
  // a QR code, is almost the whole of its life. Before that work, this
203
317
  // was the one state with no way out but killing the process, and
@@ -207,14 +321,16 @@ async function main () {
207
321
  // because peers connect and then vanish looks identical to one that
208
322
  // found nobody unless these lines are visible.
209
323
  onCandidate: (info) => {
210
- console.log(`[swarm-receive] candidate ${info.publicKey.toString('hex').slice(0, 12)}..., sent HELLO, awaiting REPLY`)
324
+ if (events) events.emit('candidate', { peer: peerId(info) })
325
+ say(`[swarm-receive] candidate ${info.publicKey.toString('hex').slice(0, 12)}..., sent HELLO, awaiting REPLY`)
211
326
  },
212
327
  // After pairing, the engine reports only failures it COUNTED -- a
213
328
  // peer guessing at the code while the transfer runs -- so the line
214
329
  // stops saying "still waiting", which is no longer true.
215
- onCandidateDropped: (info, reason, code) => {
330
+ onCandidateDropped: (info, reason, code, counted) => {
331
+ if (events) events.emit('candidate-dropped', { peer: peerId(info), code: code ?? null, counted: Boolean(counted), paired })
216
332
  const who = `candidate ${info.publicKey.toString('hex').slice(0, 12)}...`
217
- console.log(paired
333
+ say(paired
218
334
  ? `[swarm-receive] ${who} failed to prove the code during the transfer (${reason}); it counts toward this drop's attempt limit`
219
335
  : `[swarm-receive] ${who} dropped before proving (${reason}); still waiting`)
220
336
  // The pattern, once there is one (Q-04); see ./contention.js.
@@ -223,8 +339,25 @@ async function main () {
223
339
  // A second peer proved the code after we paired, and was told the
224
340
  // drop is taken. The race is invisible to this human otherwise, and
225
341
  // it means someone other than the intended sender holds the code.
342
+ // Said once: hyperdht refuses every punch between the same two NATs,
343
+ // so repeating it would only fill the screen.
344
+ onHolepunchRefused: (refused) => {
345
+ if (refused !== 1) return
346
+ const message = parsed.relayThrough ? DOUBLE_RANDOMIZED_NAT_RELAYING : DOUBLE_RANDOMIZED_NAT
347
+ if (events) events.emit('warning', { kind: 'double-randomized-nat', message })
348
+ say(`[swarm-receive] note: ${message}`)
349
+ },
350
+ // Said once, as above. The hint that a relay would connect this pair,
351
+ // or that the relay is being tried.
352
+ onHolepunchFailed: (failed) => {
353
+ if (failed !== 1) return
354
+ const message = parsed.relayThrough ? HOLEPUNCH_FAILED_RELAYING : HOLEPUNCH_FAILED
355
+ if (events) events.emit('warning', { kind: 'holepunch-failed', message })
356
+ say(`[swarm-receive] note: ${message}`)
357
+ },
226
358
  onDropTaken: (info) => {
227
- console.log(`[swarm-receive] another peer (${info.publicKey.toString('hex').slice(0, 12)}...) also has this code and tried to send; it was told the drop is taken. If you gave the code to only one person, someone else has it.`)
359
+ if (events) events.emit('drop-taken', { peer: peerId(info) })
360
+ say(`[swarm-receive] another peer (${info.publicKey.toString('hex').slice(0, 12)}...) also has this code and tried to send; it was told the drop is taken. If you gave the code to only one person, someone else has it.`)
228
361
  },
229
362
  // Only now are we actually discoverable. The sender must not start
230
363
  // looking before this point -- see engine/src/swarm.js. This is
@@ -234,19 +367,31 @@ async function main () {
234
367
  // that engine/src/swarm.js documents. demo-swarm.js waits for this
235
368
  // line before spawning the sender.
236
369
  onAnnounced: () => {
237
- console.log('[swarm-receive] announced, waiting for a peer...')
238
- if (generated) {
239
- console.log()
240
- printQr(encodeQrPayload(code))
241
- console.log()
242
- console.log(` scan the code above, or type: ${code}`)
243
- console.log()
370
+ if (events) {
371
+ events.emit('announced')
372
+ // The secret, in the event stream: the same exposure as the
373
+ // human output's, which prints it for a person to read out
374
+ // (CLI-CONTRACT.md section 3.2).
375
+ if (generated) events.emit('code', { code, payload: encodeQrPayload(code) })
376
+ }
377
+ say('[swarm-receive] announced, waiting for a peer...')
378
+ if (generated && !events) {
379
+ say()
380
+ printQr(encodeQrPayload(code), say)
381
+ say()
382
+ say(` scan the code above, or type: ${code}`)
383
+ say()
244
384
  }
245
385
  }
246
386
  })
247
387
  paired = true
388
+ connection = socket
248
389
  contention.paired()
249
- console.log(`[swarm-receive] connection from ${peerInfo.publicKey.toString('hex').slice(0, 12)}...`)
390
+ // See swarm-send.js: relayed as it pairs, and `done` says where it ended.
391
+ const relayed = isRelayed(socket)
392
+ if (events) events.emit('paired', { peer: peerId(peerInfo), relayed })
393
+ say(`[swarm-receive] connection from ${peerInfo.publicKey.toString('hex').slice(0, 12)}...${relayed ? ' through a relay' : ''}`)
394
+ if (relayed) say(`[swarm-receive] note: ${RELAYED}`)
250
395
  // Without a listener, a late socket-level error (e.g. after the
251
396
  // transfer completes, while tearing down) throws as an uncaught
252
397
  // exception instead of something we can handle gracefully.
@@ -275,6 +420,8 @@ async function main () {
275
420
  // What the same handshake negotiated. A streamed offer is declined
276
421
  // unless "stream" is in it.
277
422
  caps,
423
+ // The file's bytes, as they arrive, in place of a directory.
424
+ sink: parsed.toStdout ? process.stdout : undefined,
278
425
  // Bytes the handshake read alongside the ACK, if the sender
279
426
  // coalesced them; dropping these would corrupt the first frame.
280
427
  pending,
@@ -291,8 +438,16 @@ async function main () {
291
438
  // A person says yes before anything is written, unless --yes said it
292
439
  // for them (Q-02). The engine has already refused what it would
293
440
  // refuse anyway, so nobody is asked about an unsafe name.
294
- onOffer: consent.onOffer,
441
+ onOffer: (offer) => {
442
+ if (events) {
443
+ const risk = riskWarning(offer.name)
444
+ events.emit('offer', { name: offer.name, declaredName: offer.declaredName, size: offer.size, sha256: offer.sha256, partial: offer.partial, risk })
445
+ if (risk) events.emit('warning', { kind: 'risky-name', message: risk })
446
+ }
447
+ return consent.onOffer(offer)
448
+ },
295
449
  onManifest: (manifest, { resumeFrom }) => {
450
+ if (events) events.emit('accepted', { resumeFrom })
296
451
  // THE FIRST PEER-CHOSEN STRING THIS PROCESS PRINTS. Straight to a
297
452
  // terminal, before anything has validated that it is printable.
298
453
  // A name carrying ESC or a bidi override forged whatever it liked
@@ -306,24 +461,26 @@ async function main () {
306
461
  })
307
462
 
308
463
  progress.close()
309
- console.log(`[swarm-receive] done: ${displayName(result.name)}`)
310
- console.log(`[swarm-receive] sha256: ${result.sha256}`)
464
+ say(`[swarm-receive] done: ${displayName(result.name)}`)
465
+ say(`[swarm-receive] sha256: ${result.sha256}`)
311
466
  // The line that turns plan phase-1 bar the drop-code work from an eyeball
312
467
  // comparison of two hex strings into an assertion the receiver makes
313
468
  // for itself. Until that work, this comparison happened nowhere that
314
469
  // shipped.
315
- console.log('[swarm-receive] verified: the file matches the sender\'s manifest digest')
470
+ say('[swarm-receive] verified: the file matches the sender\'s manifest digest')
316
471
  if (result.name !== result.declaredName) {
317
472
  // Covers both reasons the name can differ -- the write policy
318
473
  // transformed it, or an existing file meant it landed suffixed --
319
474
  // and shows the peer's original so nothing is silently substituted.
320
- console.log(`[swarm-receive] renamed: the peer asked for ${JSON.stringify(displayName(result.declaredName))}`)
475
+ say(`[swarm-receive] renamed: the peer asked for ${JSON.stringify(displayName(result.declaredName))}`)
321
476
  }
322
- console.log(`[swarm-receive] saved to: ${result.path}`)
477
+ say(result.path === null ? '[swarm-receive] written to stdout' : `[swarm-receive] saved to: ${result.path}`)
323
478
  // See `publish` in engine/src/transfer.js (Q-19).
324
479
  if (result.published === 'check-then-rename') {
325
- console.log('[swarm-receive] note: this filesystem has no hard links, so the file was landed with a check-then-rename; ' +
326
- 'another process creating the same name at that instant could have been overwritten. Prefer an output directory on a local disk.')
480
+ const note = 'this filesystem has no hard links, so the file was landed with a check-then-rename; ' +
481
+ 'another process creating the same name at that instant could have been overwritten. Prefer an output directory on a local disk.'
482
+ if (events) events.emit('warning', { kind: 'check-then-rename', message: note })
483
+ say(`[swarm-receive] note: ${note}`)
327
484
  }
328
485
 
329
486
  // receiveFile has written RESULT, but "written" is a local flush.
@@ -334,16 +491,38 @@ async function main () {
334
491
  // covers a sender that vanished: the file is already verified and
335
492
  // saved. See closeAfterResult in engine/src/transfer.js.
336
493
  const { outcome } = await closeAfterResult(socket)
337
- if (outcome === 'lost' || outcome === 'timeout') {
338
- console.log('[swarm-receive] note: the sender never acknowledged the confirmation, so it may report the file as unconfirmed. The file here is complete and verified.')
494
+ const acknowledged = outcome !== 'lost' && outcome !== 'timeout'
495
+ if (!acknowledged) {
496
+ say('[swarm-receive] note: the sender never acknowledged the confirmation, so it may report the file as unconfirmed. The file here is complete and verified.')
497
+ }
498
+ // Last, after the close wait, so it can say whether the sender heard
499
+ // (CLI-CONTRACT.md section 3.2).
500
+ if (events) {
501
+ events.emit('done', {
502
+ name: result.name,
503
+ declaredName: result.declaredName,
504
+ size: result.size,
505
+ sha256: result.sha256,
506
+ resumedFrom: result.resumedFrom,
507
+ path: result.path,
508
+ published: result.published,
509
+ acknowledged,
510
+ ...connectionField(connection)
511
+ })
339
512
  }
340
513
  } catch (err) {
341
514
  // First, so the reason does not land on the question's line.
342
515
  consent.close()
343
516
  progress.close()
344
- console.error(`[swarm-receive] ${describeError(err)}`)
345
- if (socketError && !isCancellation(err)) {
346
- console.error(`[swarm-receive] the socket also reported: ${socketError.message}`)
517
+ const stats = connection ? connectionStats(connection) : null
518
+ const cutNote = relayCutNote(err, { relayed: Boolean(stats && stats.relayed), role: 'receiver', stream: parsed.toStdout })
519
+ const message = cutNote ? `${describeError(err)} ${cutNote}` : describeError(err)
520
+ const alsoSocket = socketError && !isCancellation(err) ? socketError.message : null
521
+ if (events) {
522
+ events.failed(err, message, { ...(alsoSocket ? { socketError: alsoSocket } : {}), ...connectionField(connection) })
523
+ } else {
524
+ sayError(`[swarm-receive] ${message}`)
525
+ if (alsoSocket) sayError(`[swarm-receive] the socket also reported: ${alsoSocket}`)
347
526
  }
348
527
  if (!cancel.cancelled()) process.exitCode = 1
349
528
  } finally {
package/src/swarm-send.js CHANGED
@@ -17,15 +17,20 @@
17
17
  // engine/src/resolve-code.js for how that is distinguished from an opaque secret.
18
18
  //
19
19
  // See swarm-receive.js for the ADHAL_BOOTSTRAP override.
20
+ //
21
+ // --json replaces the human lines with the event stream in ./events.js, on
22
+ // stdout: docs/CLI-CONTRACT.md section 3.
20
23
 
21
- const { createSwarm, connectOnce, sendFile, sendStream, resolveCode, displayName } = require('@ad-hal/engine')
24
+ const { createSwarm, onPeerRelayRefused, onRelayCapReached, isRelayed, connectionStats, connectOnce, sendFile, sendStream, resolveCode, displayName } = require('@ad-hal/engine')
22
25
 
23
26
  const { createProgressReporter } = require('./progress')
24
27
  const { installCancelHandler } = require('./signals')
25
- const { describeError, isCancellation } = require('./report')
28
+ const { describeError, relayCutNote, isCancellation } = require('./report')
26
29
  const { readCode } = require('./read-code')
27
30
  const { parseBootstrap } = require('./env')
28
- const { usage, NOT_ANONYMOUS } = require('./usage')
31
+ const { createEventStream, peerId, connectionField, version } = require('./events')
32
+ const { usage, NOT_ANONYMOUS, DOUBLE_RANDOMIZED_NAT, DOUBLE_RANDOMIZED_NAT_RELAYING, HOLEPUNCH_FAILED, HOLEPUNCH_FAILED_RELAYING, RELAYED, PEER_RELAY_REFUSED, relayCapReachedNote } = require('./usage')
33
+ const { relayFlag } = require('./relay-flag')
29
34
 
30
35
 
31
36
  // See swarm-receive.js for why the public-DHT default is this generous.
@@ -64,6 +69,7 @@ async function main () {
64
69
  const verbose = argv.includes('--verbose')
65
70
  // Accepts a code as an argument; see ./read-code.js.
66
71
  const allowArgv = argv.includes('--code-on-argv')
72
+ const refusePeerRelay = argv.includes('--refuse-peer-relay')
67
73
  const positional = argv.filter((a) => !a.startsWith('--') || a === '--code-stdin')
68
74
  const [codeArg, filePathArg] = positional
69
75
  const nameFlag = argv.find((a) => a.startsWith('--name='))
@@ -73,8 +79,27 @@ async function main () {
73
79
  console.log(usage('swarm-send'))
74
80
  return
75
81
  }
82
+
83
+ // The human lines, or nothing: with --json the events are the output.
84
+ const events = argv.includes('--json') ? createEventStream({ role: 'send' }) : null
85
+ const say = events ? () => {} : (/** @type {string} */ line) => { process.stdout.write(`${line}\n`) }
86
+ /** @type {Array<{ kind: string, message: string }>} warnings raised before `start` */
87
+ const held = []
88
+ const sayError = events ? () => {} : (/** @type {string} */ line) => { process.stderr.write(`${line}\n`) }
89
+ /**
90
+ * A failure before the drop began; see swarm-receive.js.
91
+ * @param {string} code
92
+ * @param {string} message
93
+ */
94
+ const refuse = (code, message) => {
95
+ if (events) events.failed({ code }, message)
96
+ else sayError(`[swarm-send] ${message}`)
97
+ process.exitCode = 1
98
+ }
99
+
76
100
  if (!codeArg || !filePathArg) {
77
- console.error(usage('swarm-send'))
101
+ if (events) refuse('ERR_USAGE', 'a code and a file are both needed')
102
+ else console.error(usage('swarm-send'))
78
103
  process.exitCode = 1
79
104
  return
80
105
  }
@@ -83,24 +108,39 @@ async function main () {
83
108
  // it out of the data, and the receiver would verify a stream that
84
109
  // silently began at the second line.
85
110
  if (streaming && codeArg === '-') {
86
- console.error('[swarm-send] stdin can carry the code or the data, not both: when streaming, pass the code as an argument, with --code-on-argv')
87
- process.exitCode = 1
111
+ refuse('ERR_USAGE', 'stdin can carry the code or the data, not both: when streaming, pass the code as an argument, with --code-on-argv')
88
112
  return
89
113
  }
90
114
  // Typing a file into the terminal by hand is never what was meant, and
91
115
  // the transfer would sit waiting for an EOF nobody knows to send.
92
116
  if (streaming && process.stdin.isTTY) {
93
- console.error('[swarm-send] refusing to stream from a terminal: pipe the data in, e.g. tar c dir | ad-hal-send <code> - --code-on-argv')
94
- process.exitCode = 1
117
+ refuse('ERR_USAGE', 'refusing to stream from a terminal: pipe the data in, e.g. tar c dir | ad-hal-send <code> - --code-on-argv')
118
+ return
119
+ }
120
+
121
+ let timeout, refresh
122
+ try {
123
+ timeout = joinTimeout()
124
+ refresh = refreshInterval()
125
+ } catch (err) {
126
+ refuse('ERR_USAGE', err.message)
95
127
  return
96
128
  }
97
129
 
98
130
  let codeInput
99
131
  try {
100
- codeInput = await readCode({ argvCode: codeArg, label: 'swarm-send', allowArgv })
132
+ codeInput = await readCode({
133
+ argvCode: codeArg,
134
+ label: 'swarm-send',
135
+ allowArgv,
136
+ // Held, not emitted: the code is read before `start`, which the
137
+ // contract puts first (CLI-CONTRACT.md section 3.2).
138
+ warn: events
139
+ ? (line) => { held.push({ kind: 'code-on-argv', message: line.replace(/^\[swarm-send\] note: /, '') }) }
140
+ : undefined
141
+ })
101
142
  } catch (err) {
102
- console.error(`[swarm-send] ${err.message}`)
103
- process.exitCode = 1
143
+ refuse('ERR_CODE_INVALID', err.message)
104
144
  return
105
145
  }
106
146
 
@@ -110,8 +150,7 @@ async function main () {
110
150
  try {
111
151
  ({ topic, code, nameplate, secret } = resolveCode(codeInput, { allowOpaque: allowOpaque || undefined }))
112
152
  } catch (err) {
113
- console.error(`[swarm-send] ${err.message}`)
114
- process.exitCode = 1
153
+ refuse('ERR_CODE_INVALID', err.message)
115
154
  return
116
155
  }
117
156
  // Echo only the NAMEPLATE when the input needed normalizing, so a code
@@ -127,26 +166,52 @@ async function main () {
127
166
  // secret never lands anywhere persistent -- wrote it into scrollback,
128
167
  // tmux and script logs, and CI output. A sender has no reason to
129
168
  // display the code at all: it is not showing it to anybody.
130
- if (code !== codeInput) console.log(`[swarm-send] code resolved to nameplate ${nameplate} (secret not shown)`)
169
+ if (code !== codeInput) say(`[swarm-send] code resolved to nameplate ${nameplate} (secret not shown)`)
131
170
 
132
- let bootstrap
171
+ let bootstrap, relayThrough
133
172
  try {
134
173
  bootstrap = parseBootstrap()
174
+ relayThrough = relayFlag(argv)
135
175
  } catch (err) {
136
- console.error(`[swarm-send] ${err.message}`)
137
- process.exitCode = 1
176
+ refuse('ERR_USAGE', err.message)
138
177
  return
139
178
  }
140
179
 
141
- const swarm = createSwarm({ bootstrap })
142
- const cancel = installCancelHandler({ label: 'swarm-send' })
143
- const progress = createProgressReporter({ label: 'swarm-send' })
180
+ const swarm = createSwarm({ bootstrap, refusePeerRelay, relayThrough })
181
+ // --refuse-peer-relay: never pair through a relay the peer names
182
+ // (refusePeerRelays in engine/src/swarm.js). Said once, like the
183
+ // refused punch: if the punch cannot connect either, this drop will not.
184
+ onPeerRelayRefused(swarm, (refused) => {
185
+ if (refused !== 1) return
186
+ if (events) events.emit('warning', { kind: 'peer-relay-refused', message: PEER_RELAY_REFUSED })
187
+ say(`[swarm-send] note: ${PEER_RELAY_REFUSED}`)
188
+ })
189
+ // Once, when the drop stops offering its relay: past MAX_RELAY_ATTEMPTS
190
+ // the relay is not dialed again (THREAT-MODEL.md section 8, gate 5).
191
+ onRelayCapReached(swarm, (count) => {
192
+ const message = relayCapReachedNote(count)
193
+ if (events) events.emit('warning', { kind: 'relay-attempts-capped', message, relayAttempts: count })
194
+ say(`[swarm-send] note: ${message}`)
195
+ })
196
+ const cancel = installCancelHandler({ label: 'swarm-send', log: say })
197
+ const progress = events
198
+ ? { onProgress: events.onProgress, close: events.flushProgress }
199
+ : createProgressReporter({ label: 'swarm-send' })
144
200
  /** @type {Error | null} */
145
201
  let socketError = null
202
+ // The paired connection, for its transport counters on the final event;
203
+ // see swarm-receive.js.
204
+ /** @type {any} */
205
+ let connection = null
206
+ if (events) {
207
+ events.emit('start', { version, time: new Date().toISOString(), joinTimeout: timeout, refreshInterval: refresh ?? 4000, stream: streaming, relay: relayThrough !== null, refusePeerRelay })
208
+ events.emit('warning', { kind: 'not-anonymous', message: NOT_ANONYMOUS })
209
+ for (const warning of held) events.emit('warning', warning)
210
+ }
146
211
  // See swarm-receive.js: the topic hex only on request (Q-17).
147
- console.log(`[swarm-send] joining topic${verbose ? ` ${topic.toString('hex')}` : ''} (refresh=${refreshInterval() ?? 4000}ms, timeout=${joinTimeout()}ms)`)
212
+ say(`[swarm-send] joining topic${verbose ? ` ${topic.toString('hex')}` : ''} (refresh=${refresh ?? 4000}ms, timeout=${timeout}ms)`)
148
213
  // Q-09; see swarm-receive.js.
149
- console.log(`[swarm-send] note: ${NOT_ANONYMOUS}`)
214
+ say(`[swarm-send] note: ${NOT_ANONYMOUS}`)
150
215
 
151
216
  try {
152
217
  // Set once connectOnce resolves; see swarm-receive.js.
@@ -159,8 +224,8 @@ async function main () {
159
224
  // whoever answered first. See engine/src/handshake.js.
160
225
  nameplate,
161
226
  secret,
162
- timeout: joinTimeout(),
163
- refreshInterval: refreshInterval(),
227
+ timeout,
228
+ refreshInterval: refresh,
164
229
  // Ctrl-C while still looking for a peer. This is the likeliest
165
230
  // moment for someone to give up -- it is the part of a drop that
166
231
  // can sit for two minutes with nothing to show -- and until the failure-reporting work
@@ -170,21 +235,46 @@ async function main () {
170
235
  // that all died before confirming" is indistinguishable from
171
236
  // "never found anyone".
172
237
  onCandidate: (info) => {
173
- console.log(`[swarm-send] candidate ${info.publicKey.toString('hex').slice(0, 12)}..., awaiting HELLO`)
238
+ if (events) events.emit('candidate', { peer: peerId(info) })
239
+ say(`[swarm-send] candidate ${info.publicKey.toString('hex').slice(0, 12)}..., awaiting HELLO`)
174
240
  },
175
241
  // See swarm-receive.js: after pairing, only counted failures arrive.
176
- onCandidateDropped: (info, reason) => {
242
+ onCandidateDropped: (info, reason, code, counted) => {
243
+ if (events) events.emit('candidate-dropped', { peer: peerId(info), code: code ?? null, counted: Boolean(counted), paired })
177
244
  const who = `candidate ${info.publicKey.toString('hex').slice(0, 12)}...`
178
- console.log(paired
245
+ say(paired
179
246
  ? `[swarm-send] ${who} failed to prove the code during the transfer (${reason}); it counts toward this drop's attempt limit`
180
247
  : `[swarm-send] ${who} dropped before proving (${reason}); still looking`)
181
248
  },
249
+ // Said once: hyperdht refuses every punch between the same two NATs,
250
+ // so repeating it would only fill the screen.
251
+ onHolepunchRefused: (refused) => {
252
+ if (refused !== 1) return
253
+ const message = relayThrough ? DOUBLE_RANDOMIZED_NAT_RELAYING : DOUBLE_RANDOMIZED_NAT
254
+ if (events) events.emit('warning', { kind: 'double-randomized-nat', message })
255
+ say(`[swarm-send] note: ${message}`)
256
+ },
257
+ // Said once, as above. The hint that a relay would connect this pair,
258
+ // or that the relay is being tried.
259
+ onHolepunchFailed: (failed) => {
260
+ if (failed !== 1) return
261
+ const message = relayThrough ? HOLEPUNCH_FAILED_RELAYING : HOLEPUNCH_FAILED
262
+ if (events) events.emit('warning', { kind: 'holepunch-failed', message })
263
+ say(`[swarm-send] note: ${message}`)
264
+ },
182
265
  onDropTaken: (info) => {
183
- console.log(`[swarm-send] another receiver (${info.publicKey.toString('hex').slice(0, 12)}...) also has this code; it was told the drop is taken. If you gave the code to only one person, someone else has it.`)
266
+ if (events) events.emit('drop-taken', { peer: peerId(info) })
267
+ say(`[swarm-send] another receiver (${info.publicKey.toString('hex').slice(0, 12)}...) also has this code; it was told the drop is taken. If you gave the code to only one person, someone else has it.`)
184
268
  }
185
269
  })
186
270
  paired = true
187
- console.log(`[swarm-send] connected to ${peerInfo.publicKey.toString('hex').slice(0, 12)}...`)
271
+ connection = socket
272
+ // Whether it is relayed as it pairs; `done` says where it ended, since
273
+ // hyperdht can move it onto a direct path (isRelayed).
274
+ const relayed = isRelayed(socket)
275
+ if (events) events.emit('paired', { peer: peerId(peerInfo), relayed })
276
+ say(`[swarm-send] connected to ${peerInfo.publicKey.toString('hex').slice(0, 12)}...${relayed ? ' through a relay' : ''}`)
277
+ if (relayed) say(`[swarm-send] note: ${RELAYED}`)
188
278
  // Without a listener, a late socket-level error (e.g. after the
189
279
  // transfer completes, while tearing down) throws as an uncaught
190
280
  // exception instead of something we can handle gracefully.
@@ -216,7 +306,8 @@ async function main () {
216
306
  // exactly the message the CANCEL frame exists to deliver.
217
307
  pending,
218
308
  signal: cancel.signal,
219
- onProgress: progress.onProgress
309
+ onProgress: progress.onProgress,
310
+ onAccepted: events ? (/** @type {{ resumeFrom: number }} */ a) => events.emit('accepted', a) : undefined
220
311
  }
221
312
  const result = streaming
222
313
  // The capability list the handshake negotiated: sendStream refuses
@@ -230,14 +321,14 @@ async function main () {
230
321
  // Our own file's name, not a peer-supplied one -- but printed
231
322
  // through the same sanitizer anyway, so there is one rule for names
232
323
  // reaching a terminal rather than one rule and an exception.
233
- console.log(`[swarm-send] done: ${displayName(result.name)}`)
324
+ say(`[swarm-send] done: ${displayName(result.name)}`)
234
325
  if (result.resumedFrom > 0) {
235
- console.log(`[swarm-send] resumed: the receiver already held ${result.resumedFrom} of ${result.size} bytes from an earlier attempt`)
326
+ say(`[swarm-send] resumed: the receiver already held ${result.resumedFrom} of ${result.size} bytes from an earlier attempt`)
236
327
  }
237
- console.log(`[swarm-send] sha256: ${result.sha256}`)
328
+ say(`[swarm-send] sha256: ${result.sha256}`)
238
329
  // sendFile resolves only on the receiver's RESULT carrying this same
239
330
  // digest, so this line is the receiver's claim, not our hope.
240
- console.log(`[swarm-send] verified: the receiver confirmed all ${result.size} bytes with the same digest`)
331
+ say(`[swarm-send] verified: the receiver confirmed all ${result.size} bytes with the same digest`)
241
332
 
242
333
  // The file is confirmed, so nothing below can lose data. This wait
243
334
  // used to be the only thing standing between "sent" and "delivered",
@@ -255,11 +346,27 @@ async function main () {
255
346
  })
256
347
  })
257
348
  await closed
349
+ if (events) {
350
+ events.emit('done', {
351
+ name: result.name,
352
+ declaredName: result.name,
353
+ size: result.size,
354
+ sha256: result.sha256,
355
+ resumedFrom: result.resumedFrom,
356
+ ...connectionField(connection)
357
+ })
358
+ }
258
359
  } catch (err) {
259
360
  progress.close()
260
- console.error(`[swarm-send] ${describeError(err)}`)
261
- if (socketError && !isCancellation(err)) {
262
- console.error(`[swarm-send] the socket also reported: ${socketError.message}`)
361
+ const stats = connection ? connectionStats(connection) : null
362
+ const cutNote = relayCutNote(err, { relayed: Boolean(stats && stats.relayed), role: 'sender', stream: streaming })
363
+ const message = cutNote ? `${describeError(err)} ${cutNote}` : describeError(err)
364
+ const alsoSocket = socketError && !isCancellation(err) ? socketError.message : null
365
+ if (events) {
366
+ events.failed(err, message, { ...(alsoSocket ? { socketError: alsoSocket } : {}), ...connectionField(connection) })
367
+ } else {
368
+ sayError(`[swarm-send] ${message}`)
369
+ if (alsoSocket) sayError(`[swarm-send] the socket also reported: ${alsoSocket}`)
263
370
  }
264
371
  // A cancellation already set 130/143 in the signal handler. Flattening
265
372
  // it to 1 would throw away the distinction this item is about.
package/src/usage.js CHANGED
@@ -12,6 +12,50 @@
12
12
  // otherwise.
13
13
  const NOT_ANONYMOUS = 'not anonymous: your IP address is visible to the peer, and to the DHT nodes near this drop\'s topic'
14
14
 
15
+ // Printed by both swarm CLIs the first time hyperdht refuses a hole punch
16
+ // because both NATs are randomized (HOLEPUNCH_REFUSED in
17
+ // engine/src/swarm.js). "A peer", not "the peer": anyone who finds the
18
+ // topic can be the one refused, so the drop keeps waiting, and says why
19
+ // it may never connect.
20
+ const DOUBLE_RANDOMIZED_NAT = 'a peer was found, but hyperdht will not hole-punch to it: this side\'s NAT and the peer\'s are both randomized, ' +
21
+ 'which a VPN at both ends usually causes. Two randomized NATs cannot connect directly. ' +
22
+ 'Still waiting, in case another peer can connect; to connect to this one, pass --relay=<key> at either end, or turn the VPN off at one end'
23
+
24
+ // The same, when this side has a relay to fall back on: Hyperswarm retries
25
+ // that peer through it (relayOnlyAfterFailedPunch in engine/src/swarm.js).
26
+ const DOUBLE_RANDOMIZED_NAT_RELAYING = 'a peer was found, but hyperdht will not hole-punch to it: this side\'s NAT and the peer\'s are both randomized, ' +
27
+ 'which a VPN at both ends usually causes. Trying the relay given with --relay instead'
28
+
29
+ // Printed by both swarm CLIs the first time a hole punch to a peer fails
30
+ // for any other reason (onHolepunchFailed in engine/src/swarm.js). Not the
31
+ // end of the drop: a later punch can work, and the peer that failed need
32
+ // not be the intended one.
33
+ const HOLEPUNCH_FAILED = 'a peer was found, but the hole punch to it failed. Still trying; ' +
34
+ 'if it keeps failing, this path cannot connect directly, and a relay can connect it: run the drop again with --relay=<key> at either end'
35
+
36
+ // The same, when this side has a relay to fall back on.
37
+ const HOLEPUNCH_FAILED_RELAYING = 'a peer was found, but the hole punch to it failed. Trying the relay given with --relay instead'
38
+
39
+ // Printed by both swarm CLIs, once, when this side stops offering its relay
40
+ // because the drop reached its cap on relay dials (relayOnlyAfterFailedPunch
41
+ // in engine/src/swarm.js, THREAT-MODEL.md section 8, gate 5).
42
+ /** @param {number} count */
43
+ const relayCapReachedNote = (count) => `the relay given with --relay was tried ${count} times without a connection that lasted, ` +
44
+ 'the most one drop tries. Still waiting for a direct connection, or one through a relay the peer names; ' +
45
+ 'if neither comes, check that the relay is running and reachable from both sides'
46
+
47
+ // Printed by both swarm CLIs when the paired connection goes through a
48
+ // relay, whichever side chose it (isRelayed in engine/src/swarm.js). Q-09's
49
+ // notice, for the relay: what its operator learns, and what it does not.
50
+ const RELAYED = 'this connection goes through a relay. Its operator sees both sides\' IP addresses and when and how much was sent, ' +
51
+ 'not the file: the drop stays end-to-end encrypted. hyperdht moves to a direct path if a hole punch succeeds later'
52
+
53
+ // Printed by both swarm CLIs the first time --refuse-peer-relay refuses
54
+ // a relay a peer named (onPeerRelayRefused in engine/src/swarm.js). "A
55
+ // peer", as above: it was refused before it proved the code.
56
+ const PEER_RELAY_REFUSED = 'a peer asked to connect through a relay it chose, and --refuse-peer-relay refused it. ' +
57
+ 'Still waiting for a direct connection; if one is not possible, this drop will not connect. Run without --refuse-peer-relay to allow it'
58
+
15
59
  // Q-13. The loopback pair is a harness for tests and demos, and nothing
16
60
  // about it is meant for a real drop: it listens on 127.0.0.1 only.
17
61
  const TEST_ONLY = 'TEST-ONLY: the loopback harness, over 127.0.0.1. For a real drop use ad-hal-send / ad-hal-receive.'
@@ -22,13 +66,27 @@ const USAGE = {
22
66
  Usage: ad-hal-receive [--new] [outputDir] generate a code and show it (the default)
23
67
  ad-hal-receive - [outputDir] read a code from stdin, or type it at the prompt
24
68
  ad-hal-receive <code> [outputDir] --code-on-argv
69
+ ad-hal-receive [-] --stdout | tar x write the file to stdout instead
25
70
 
26
71
  With one argument and no --new, the argument is the code, not the directory.
27
72
 
28
73
  Options:
29
74
  --yes accept the offer without being asked. A risky file
30
75
  name is still warned about.
76
+ --stdout write the file to stdout, and everything else to
77
+ stderr. The bytes are verified only if this exits 0:
78
+ check it (set -o pipefail). No resume.
79
+ --json report the drop as JSON lines, on stdout, or on
80
+ stderr with --stdout. Never asks: without --yes, the
81
+ offer is declined. See docs/CLI-CONTRACT.md.
31
82
  --replace overwrite an existing file of the same name
83
+ --relay=<key> if a hole punch to the peer fails, connect through
84
+ this relay, named by its public key (64 hex or 52
85
+ z-base-32 characters). Never used when a direct
86
+ connection works. Its operator sees both IP addresses.
87
+ --refuse-peer-relay never connect through a relay the peer names. By
88
+ default hyperdht follows one if the peer asks, which
89
+ shows your IP address to that relay's operator.
32
90
  --code-stdin the same as passing - as the code
33
91
  --code-on-argv allow a code as an argument. It is then in your shell
34
92
  history and visible to \`ps\` for as long as the drop runs.
@@ -56,6 +114,15 @@ Options:
56
114
  --code-on-argv allow a code as an argument. It is then in your shell
57
115
  history and visible to \`ps\` for as long as the drop runs.
58
116
  --name=<name> what a stream is offered as (default "stdin")
117
+ --relay=<key> if a hole punch to the peer fails, connect through
118
+ this relay, named by its public key (64 hex or 52
119
+ z-base-32 characters). Never used when a direct
120
+ connection works. Its operator sees both IP addresses.
121
+ --refuse-peer-relay never connect through a relay the peer names. By
122
+ default hyperdht follows one if the peer asks, which
123
+ shows your IP address to that relay's operator.
124
+ --json report the drop as JSON lines on stdout, in place of
125
+ these lines. See docs/CLI-CONTRACT.md.
59
126
  --insecure-opaque-code accept a code that is not drop-code words. This
60
127
  removes the protection the code's secret half gives.
61
128
  --verbose also print the DHT topic
@@ -92,4 +159,4 @@ function usage (cli) {
92
159
  return USAGE[cli]
93
160
  }
94
161
 
95
- module.exports = { usage, NOT_ANONYMOUS, TEST_ONLY }
162
+ module.exports = { usage, NOT_ANONYMOUS, DOUBLE_RANDOMIZED_NAT, DOUBLE_RANDOMIZED_NAT_RELAYING, HOLEPUNCH_FAILED, HOLEPUNCH_FAILED_RELAYING, RELAYED, PEER_RELAY_REFUSED, relayCapReachedNote, TEST_ONLY }