@ad-hal/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,273 @@
1
+ #!/usr/bin/env node
2
+ 'use strict'
3
+
4
+ // The Hyperswarm work sender half, and the `ad-hal-send` bin. Usage: see
5
+ // --help, in ./usage.js. The code comes from stdin (`-`), or from argv only
6
+ // with --code-on-argv (./read-code.js).
7
+ //
8
+ // A filePath of '-' streams stdin instead (PROTOCOL.md section 4.3), so
9
+ // `tar c dir | swarm-send.js <code> - --name=dir.tar --code-on-argv` works: the receiver
10
+ // is offered a file of unknown length and verifies it against the digest
11
+ // that arrives when stdin ends. --name is what it is offered under
12
+ // (default "stdin"), since a pipe has no name of its own.
13
+ //
14
+ // The code may be five words (the drop code) in any casing or separator
15
+ // style, or the QR payload pasted verbatim -- 'ADHAL2:ACID-ACORN-...' --
16
+ // since that decodes to the same thing a scanner would hand a UI. See
17
+ // engine/src/resolve-code.js for how that is distinguished from an opaque secret.
18
+ //
19
+ // See swarm-receive.js for the ADHAL_BOOTSTRAP override.
20
+
21
+ const { createSwarm, connectOnce, sendFile, sendStream, resolveCode, displayName } = require('@ad-hal/engine')
22
+
23
+ const { createProgressReporter } = require('./progress')
24
+ const { installCancelHandler } = require('./signals')
25
+ const { describeError, isCancellation } = require('./report')
26
+ const { readCode } = require('./read-code')
27
+ const { parseBootstrap } = require('./env')
28
+ const { usage, NOT_ANONYMOUS } = require('./usage')
29
+
30
+
31
+ // See swarm-receive.js for why the public-DHT default is this generous.
32
+ function joinTimeout () {
33
+ const raw = process.env.ADHAL_JOIN_TIMEOUT
34
+ if (!raw) return 120000
35
+ const parsed = Number(raw)
36
+ if (!Number.isFinite(parsed) || parsed < 0) {
37
+ throw new TypeError(`ADHAL_JOIN_TIMEOUT must be a non-negative number, got ${raw}`)
38
+ }
39
+ return parsed
40
+ }
41
+
42
+ // ADHAL_REFRESH_INTERVAL overrides how often we re-run our own DHT
43
+ // announce/lookup, in ms (0 disables it, leaving Hyperswarm's internal
44
+ // 10-minute schedule). See engine/src/swarm.js REFRESH_INTERVAL: the 4s
45
+ // default is validated only for two peers on one machine, and on a
46
+ // cross-ISP path a continuous re-announce is a suspect for churning
47
+ // holepunch relay state.
48
+ function refreshInterval () {
49
+ const raw = process.env.ADHAL_REFRESH_INTERVAL
50
+ if (raw === undefined) return undefined
51
+ const parsed = Number(raw)
52
+ if (!Number.isFinite(parsed) || parsed < 0) {
53
+ throw new TypeError(`ADHAL_REFRESH_INTERVAL must be a non-negative number, got ${raw}`)
54
+ }
55
+ return parsed
56
+ }
57
+
58
+ async function main () {
59
+ const argv = process.argv.slice(2)
60
+ // `--insecure-opaque-code` opts in to non-word codes; see resolveCode. Pulled
61
+ // out before the positionals so it can appear anywhere.
62
+ const allowOpaque = argv.includes('--insecure-opaque-code')
63
+ // Prints the topic hex; see the "joining topic" line.
64
+ const verbose = argv.includes('--verbose')
65
+ // Accepts a code as an argument; see ./read-code.js.
66
+ const allowArgv = argv.includes('--code-on-argv')
67
+ const positional = argv.filter((a) => !a.startsWith('--') || a === '--code-stdin')
68
+ const [codeArg, filePathArg] = positional
69
+ const nameFlag = argv.find((a) => a.startsWith('--name='))
70
+ const streamName = nameFlag ? nameFlag.slice('--name='.length) : 'stdin'
71
+
72
+ if (argv.includes('--help')) {
73
+ console.log(usage('swarm-send'))
74
+ return
75
+ }
76
+ if (!codeArg || !filePathArg) {
77
+ console.error(usage('swarm-send'))
78
+ process.exitCode = 1
79
+ return
80
+ }
81
+ const streaming = filePathArg === '-'
82
+ // One stdin, two possible uses. Reading the code line first would take
83
+ // it out of the data, and the receiver would verify a stream that
84
+ // silently began at the second line.
85
+ 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
88
+ return
89
+ }
90
+ // Typing a file into the terminal by hand is never what was meant, and
91
+ // the transfer would sit waiting for an EOF nobody knows to send.
92
+ 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
95
+ return
96
+ }
97
+
98
+ let codeInput
99
+ try {
100
+ codeInput = await readCode({ argvCode: codeArg, label: 'swarm-send', allowArgv })
101
+ } catch (err) {
102
+ console.error(`[swarm-send] ${err.message}`)
103
+ process.exitCode = 1
104
+ return
105
+ }
106
+
107
+ // A mistyped word is reported here, before any network work, rather than
108
+ // surfacing 120 seconds later as a peer-discovery timeout.
109
+ let topic, code, nameplate, secret
110
+ try {
111
+ ({ topic, code, nameplate, secret } = resolveCode(codeInput, { allowOpaque: allowOpaque || undefined }))
112
+ } catch (err) {
113
+ console.error(`[swarm-send] ${err.message}`)
114
+ process.exitCode = 1
115
+ return
116
+ }
117
+ // Echo only the NAMEPLATE when the input needed normalizing, so a code
118
+ // pasted as a QR payload or with odd separators visibly resolved to the
119
+ // same rendezvous the other device is showing.
120
+ //
121
+ // THE SECRET IS NOT PRINTED, and that is the whole point of this line
122
+ // having been rewritten. It used to echo the full canonical code, which
123
+ // meant the three secret words went to stdout on exactly the inputs
124
+ // ./read-code.js exists to protect: a pasted QR payload and a code
125
+ // pasted out of a chat client both differ from canonical form, so
126
+ // `swarm-send - file` -- the mode whose entire purpose is that the
127
+ // secret never lands anywhere persistent -- wrote it into scrollback,
128
+ // tmux and script logs, and CI output. A sender has no reason to
129
+ // 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)`)
131
+
132
+ let bootstrap
133
+ try {
134
+ bootstrap = parseBootstrap()
135
+ } catch (err) {
136
+ console.error(`[swarm-send] ${err.message}`)
137
+ process.exitCode = 1
138
+ return
139
+ }
140
+
141
+ const swarm = createSwarm({ bootstrap })
142
+ const cancel = installCancelHandler({ label: 'swarm-send' })
143
+ const progress = createProgressReporter({ label: 'swarm-send' })
144
+ /** @type {Error | null} */
145
+ let socketError = null
146
+ // 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)`)
148
+ // Q-09; see swarm-receive.js.
149
+ console.log(`[swarm-send] note: ${NOT_ANONYMOUS}`)
150
+
151
+ try {
152
+ // Set once connectOnce resolves; see swarm-receive.js.
153
+ let paired = false
154
+ const { socket, peerInfo, pending, sendKey, receiveKey, caps } = await connectOnce(swarm, topic, {
155
+ // Proves the peer knows the drop secret before we transmit a byte of
156
+ // the file to it. The topic alone is public once the receiver
157
+ // announces -- it commits to the nameplate, which is a rendezvous
158
+ // label and not a secret -- so without this we would hand the file to
159
+ // whoever answered first. See engine/src/handshake.js.
160
+ nameplate,
161
+ secret,
162
+ timeout: joinTimeout(),
163
+ refreshInterval: refreshInterval(),
164
+ // Ctrl-C while still looking for a peer. This is the likeliest
165
+ // moment for someone to give up -- it is the part of a drop that
166
+ // can sit for two minutes with nothing to show -- and until the failure-reporting work
167
+ // there was no way to cancel it.
168
+ signal: cancel.signal,
169
+ // See swarm-receive.js: without these, "connected to several peers
170
+ // that all died before confirming" is indistinguishable from
171
+ // "never found anyone".
172
+ onCandidate: (info) => {
173
+ console.log(`[swarm-send] candidate ${info.publicKey.toString('hex').slice(0, 12)}..., awaiting HELLO`)
174
+ },
175
+ // See swarm-receive.js: after pairing, only counted failures arrive.
176
+ onCandidateDropped: (info, reason) => {
177
+ const who = `candidate ${info.publicKey.toString('hex').slice(0, 12)}...`
178
+ console.log(paired
179
+ ? `[swarm-send] ${who} failed to prove the code during the transfer (${reason}); it counts toward this drop's attempt limit`
180
+ : `[swarm-send] ${who} dropped before proving (${reason}); still looking`)
181
+ },
182
+ 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.`)
184
+ }
185
+ })
186
+ paired = true
187
+ console.log(`[swarm-send] connected to ${peerInfo.publicKey.toString('hex').slice(0, 12)}...`)
188
+ // Without a listener, a late socket-level error (e.g. after the
189
+ // transfer completes, while tearing down) throws as an uncaught
190
+ // exception instead of something we can handle gracefully.
191
+ //
192
+ // Silent once we are canceling, and that is the whole point of item
193
+ // 5 rather than tidiness: tearing down a canceled transfer reliably
194
+ // produces "connection reset by peer", which is byte for byte what a
195
+ // dead hole punch looks like. Printing it right after "canceled"
196
+ // would hand back exactly the ambiguity the CANCEL frame was added to
197
+ // remove.
198
+ //
199
+ // RECORDED RATHER THAN PRINTED, because printing it immediately is
200
+ // how a deliberate cancel ended up followed by "connection reset by
201
+ // peer" -- byte for byte what a dead hole punch looks like, and the
202
+ // exact ambiguity the CANCEL frame exists to remove. A socket that
203
+ // dies while a canceled or completed transfer tears down explains
204
+ // nothing; one that dies during a transfer that then failed for an
205
+ // unclear reason explains a great deal, so it is reported there.
206
+ socket.on('error', (err) => { socketError = err })
207
+
208
+ const options = {
209
+ // The channel keys the handshake just derived. Every frame from here
210
+ // on is sealed under them, so authentication no longer rests on the
211
+ // Noise session that happens to carry the bytes.
212
+ sendKey,
213
+ receiveKey,
214
+ // Anything the receiver coalesced after its proof. Ordinarily
215
+ // empty, but a CANCEL could be in there, and dropping it would lose
216
+ // exactly the message the CANCEL frame exists to deliver.
217
+ pending,
218
+ signal: cancel.signal,
219
+ onProgress: progress.onProgress
220
+ }
221
+ const result = streaming
222
+ // The capability list the handshake negotiated: sendStream refuses
223
+ // unless it contains "stream".
224
+ ? await sendStream(socket, process.stdin, { ...options, name: streamName, caps })
225
+ // caps here too: with "resume" negotiated the receiver may already
226
+ // hold a prefix from an interrupted drop, and the file is sent from
227
+ // there.
228
+ : await sendFile(socket, filePathArg, { ...options, caps })
229
+ progress.close()
230
+ // Our own file's name, not a peer-supplied one -- but printed
231
+ // through the same sanitizer anyway, so there is one rule for names
232
+ // reaching a terminal rather than one rule and an exception.
233
+ console.log(`[swarm-send] done: ${displayName(result.name)}`)
234
+ if (result.resumedFrom > 0) {
235
+ console.log(`[swarm-send] resumed: the receiver already held ${result.resumedFrom} of ${result.size} bytes from an earlier attempt`)
236
+ }
237
+ console.log(`[swarm-send] sha256: ${result.sha256}`)
238
+ // sendFile resolves only on the receiver's RESULT carrying this same
239
+ // 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`)
241
+
242
+ // The file is confirmed, so nothing below can lose data. This wait
243
+ // used to be the only thing standing between "sent" and "delivered",
244
+ // and its 5s fallback was the cause of 6 in 100 real transfers
245
+ // failing on the receiver -- see RESULT_TIMEOUT_MS in
246
+ // engine/src/transfer.js. It is kept as courtesy: ending cleanly
247
+ // lets the receiver's own close wait finish now rather than by timer.
248
+ socket.end()
249
+ /** @type {Promise<void>} */
250
+ const closed = new Promise((resolve) => {
251
+ const timer = setTimeout(resolve, 5000)
252
+ socket.once('close', () => {
253
+ clearTimeout(timer)
254
+ resolve()
255
+ })
256
+ })
257
+ await closed
258
+ } catch (err) {
259
+ 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}`)
263
+ }
264
+ // A cancellation already set 130/143 in the signal handler. Flattening
265
+ // it to 1 would throw away the distinction this item is about.
266
+ if (!cancel.cancelled()) process.exitCode = 1
267
+ } finally {
268
+ cancel.dispose()
269
+ await swarm.destroy()
270
+ }
271
+ }
272
+
273
+ main()
package/src/usage.js ADDED
@@ -0,0 +1,95 @@
1
+ 'use strict'
2
+
3
+ // Every CLI's --help text, and the notices more than one of them prints.
4
+ // One file, for the reason env.js and report.js are one file each: four
5
+ // copies of a usage string drift, and the one that drifts is the one that
6
+ // is wrong about a security property.
7
+
8
+ // Q-09. Printed by both swarm CLIs when they start, and in their --help.
9
+ // ad-hal hides the file, not the people: the peer learns your address when
10
+ // it connects, and so do the DHT nodes that store and serve the topic's
11
+ // announce records. Saying so up front is cheaper than anyone assuming
12
+ // otherwise.
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
+
15
+ // Q-13. The loopback pair is a harness for tests and demos, and nothing
16
+ // about it is meant for a real drop: it listens on 127.0.0.1 only.
17
+ const TEST_ONLY = 'TEST-ONLY: the loopback harness, over 127.0.0.1. For a real drop use ad-hal-send / ad-hal-receive.'
18
+
19
+ const USAGE = {
20
+ 'swarm-receive': `Adhal receive: wait for a file from someone who has the drop code.
21
+
22
+ Usage: ad-hal-receive [--new] [outputDir] generate a code and show it (the default)
23
+ ad-hal-receive - [outputDir] read a code from stdin, or type it at the prompt
24
+ ad-hal-receive <code> [outputDir] --code-on-argv
25
+
26
+ With one argument and no --new, the argument is the code, not the directory.
27
+
28
+ Options:
29
+ --yes accept the offer without being asked. A risky file
30
+ name is still warned about.
31
+ --replace overwrite an existing file of the same name
32
+ --code-stdin the same as passing - as the code
33
+ --code-on-argv allow a code as an argument. It is then in your shell
34
+ history and visible to \`ps\` for as long as the drop runs.
35
+ --insecure-opaque-code accept a code that is not drop-code words. This
36
+ removes the protection the code's secret half gives.
37
+ --verbose also print the DHT topic
38
+ --help show this text
39
+
40
+ Each offer is shown with its name, size and SHA-256, and you are asked
41
+ before anything is written. With no terminal to ask on and no --yes, the
42
+ offer is declined.
43
+
44
+ Note: ${NOT_ANONYMOUS}.`,
45
+
46
+ 'swarm-send': `Adhal send: send a file to the receiver showing a drop code.
47
+
48
+ Usage: ad-hal-send - <file> read the code from stdin, or type it at the prompt
49
+ ad-hal-send <code> <file> --code-on-argv
50
+ ad-hal-send <code> - [--name=<name>] --code-on-argv
51
+ stream stdin as the file. stdin cannot
52
+ also carry the code, so it goes on argv.
53
+
54
+ Options:
55
+ --code-stdin the same as passing - as the code
56
+ --code-on-argv allow a code as an argument. It is then in your shell
57
+ history and visible to \`ps\` for as long as the drop runs.
58
+ --name=<name> what a stream is offered as (default "stdin")
59
+ --insecure-opaque-code accept a code that is not drop-code words. This
60
+ removes the protection the code's secret half gives.
61
+ --verbose also print the DHT topic
62
+ --help show this text
63
+
64
+ Note: ${NOT_ANONYMOUS}.`,
65
+
66
+ receive: `receive.js: ${TEST_ONLY}
67
+
68
+ Usage: receive.js <port> [outputDir] [--yes]
69
+ port 0 asks the OS for a free port. The bound port and a fresh drop code
70
+ are printed for send.js.
71
+
72
+ Options:
73
+ --yes accept the offer without being asked
74
+ --help show this text`,
75
+
76
+ send: `send.js: ${TEST_ONLY}
77
+
78
+ Usage: send.js <port> - <file|-> read the code from stdin
79
+ send.js <port> <code> <file|-> --code-on-argv
80
+ A file of - streams stdin, offered as "stdin".
81
+
82
+ Options:
83
+ --code-on-argv allow a code as an argument (shell history, \`ps\`)
84
+ --help show this text`
85
+ }
86
+
87
+ /**
88
+ * @param {keyof typeof USAGE} cli
89
+ * @returns {string}
90
+ */
91
+ function usage (cli) {
92
+ return USAGE[cli]
93
+ }
94
+
95
+ module.exports = { usage, NOT_ANONYMOUS, TEST_ONLY }