@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.
package/src/signals.js ADDED
@@ -0,0 +1,102 @@
1
+ 'use strict'
2
+
3
+ // Ctrl-C, turned into something the far side can understand.
4
+ //
5
+ // THE PROBLEM THIS SOLVES. Without it, Ctrl-C tears the process down and
6
+ // the peer's socket resets. What the peer prints is "connection reset by
7
+ // peer" -- byte for byte what a dead hole punch looks like, which is the
8
+ // exact confusion the Hyperswarm work spent a week learning to separate (see
9
+ // engine/src/swarm.js's comment about a half-failed punch that neither
10
+ // side reported honestly). A deliberate cancellation must not be
11
+ // indistinguishable from the failure mode this project has the hardest
12
+ // time diagnosing.
13
+ //
14
+ // So the first signal aborts an AbortController rather than exiting. The
15
+ // normal catch/finally path then runs: the engine writes a CANCEL frame
16
+ // and waits for it to flush, the CLI ends the socket and destroys the
17
+ // swarm, and only then does the process exit with the conventional
18
+ // 128+signal code.
19
+ //
20
+ // The second signal exits immediately. That is not a nicety: swarm.destroy()
21
+ // can take seconds, and a Ctrl-C that appears to do nothing is a tool
22
+ // people learn to kill -9 instead.
23
+ //
24
+ // One helper rather than four copies, because four copies of signal
25
+ // handling drift, and the copy that drifts is the one nobody tested.
26
+ //
27
+ // WINDOWS, because two things here are not obvious from the code and one
28
+ // of them was believed backwards for a while.
29
+ //
30
+ // Ctrl-C works. Node documents 'SIGINT' from the terminal as supported
31
+ // on all platforms: Windows delivers the console Ctrl+C event as
32
+ // SIGINT, so a human pressing it here takes the clean path below
33
+ // exactly as on POSIX. What does *not* work is `child.kill('SIGINT')`,
34
+ // which on Windows is documented as unconditional termination -- a
35
+ // different thing from a console control event, and the reason the
36
+ // end-to-end tests have a separate Windows path.
37
+ //
38
+ // SIGBREAK is the Windows-only half of that pair, raised by Ctrl+Break.
39
+ // Unhandled, it tore the process down abruptly and the peer saw a
40
+ // socket reset -- the precise "deliberate cancel is indistinguishable
41
+ // from a dead hole punch" confusion this file exists to prevent. It is
42
+ // handled now, so Ctrl+Break cancels as cleanly as Ctrl-C.
43
+ //
44
+ // SIGTERM is registered but can never fire on Windows (Node: "SIGTERM
45
+ // is not supported on Windows, it can be listened on"). Harmless dead
46
+ // weight there, not a bug -- listening costs nothing and keeping the
47
+ // table uniform is worth more than a platform branch.
48
+
49
+ // 128 + the signal number, the shell convention: SIGINT 2, SIGTERM 15,
50
+ // SIGBREAK 21. cli/test/signals.test.js checks 149 against
51
+ // os.constants.signals.SIGBREAK where that constant exists, so the number
52
+ // is self-checked on the one platform that can confirm it.
53
+ const EXIT_CODES = { SIGINT: 130, SIGTERM: 143, SIGBREAK: 149 }
54
+
55
+ // What to tell someone to press again. Printing the raw signal name told
56
+ // a Ctrl+Break user to "press SIGBREAK again".
57
+ /** @type {Record<string, string>} */
58
+ const KEYSTROKES = { SIGINT: 'Ctrl-C', SIGBREAK: 'Ctrl-Break' }
59
+
60
+ /**
61
+ * @param {{ label: string, log?: (line: string) => void, proc?: NodeJS.Process }} options
62
+ * @returns {{ signal: AbortSignal, cancelled: () => boolean, dispose: () => void }}
63
+ */
64
+ function installCancelHandler ({ label, log = console.log, proc = process }) {
65
+ const controller = new AbortController()
66
+ let cancelled = false
67
+
68
+ /** @type {Array<[NodeJS.Signals, () => void]>} */
69
+ const installed = []
70
+
71
+ for (const name of /** @type {NodeJS.Signals[]} */ (Object.keys(EXIT_CODES))) {
72
+ const code = EXIT_CODES[name]
73
+ const handler = () => {
74
+ if (cancelled) {
75
+ // Already tearing down and asked again: stop waiting for a clean
76
+ // exit and go.
77
+ log(`[${label}] second ${name}: exiting now, without waiting for teardown`)
78
+ proc.exit(code)
79
+ return
80
+ }
81
+ cancelled = true
82
+ log(`[${label}] cancelled (${name}): telling the peer and shutting down; press ${KEYSTROKES[name] ?? name} again to exit immediately`)
83
+ // Set here rather than in the catch block so the code is right even
84
+ // if teardown itself throws. A `reason` that is a plain string is
85
+ // what the engine puts in the CANCEL frame for the peer to print.
86
+ proc.exitCode = code
87
+ controller.abort('cancelled at the keyboard')
88
+ }
89
+ proc.on(name, handler)
90
+ installed.push([name, handler])
91
+ }
92
+
93
+ return {
94
+ signal: controller.signal,
95
+ cancelled: () => cancelled,
96
+ dispose: () => {
97
+ for (const [name, handler] of installed) proc.removeListener(name, handler)
98
+ }
99
+ }
100
+ }
101
+
102
+ module.exports = { installCancelHandler, EXIT_CODES }
@@ -0,0 +1,357 @@
1
+ #!/usr/bin/env node
2
+ 'use strict'
3
+
4
+ // Hyperswarm receiver half: "same CLI over Hyperswarm on one LAN." Reuses
5
+ // the exact manifest/chunk protocol from the loopback milestone
6
+ // (engine/src/transfer.js);
7
+ // only the transport changes, from a bare TCP socket to an end-to-end
8
+ // Noise-encrypted Hyperswarm connection.
9
+ //
10
+ // Usage: see --help, in ./usage.js. This is the `ad-hal-receive` bin.
11
+ //
12
+ // With no code, or with --new, one is generated and shown as both five
13
+ // words and a QR symbol. An explicit code comes from stdin (`-`), or from
14
+ // argv only with --code-on-argv (./read-code.js). It may be five words in any
15
+ // casing/separator style, or an opaque secret -- see
16
+ // engine/src/resolve-code.js for why both are accepted, how they are told
17
+ // apart, and why an opaque one voids v2's central property.
18
+ //
19
+ // ADHAL_BOOTSTRAP=<json bootstrap array> overrides the DHT bootstrap nodes
20
+ // -- used by the automated test to run against an isolated local testnet
21
+ // instead of the public DHT.
22
+
23
+ const path = require('path')
24
+ const fs = require('fs')
25
+ const { createSwarm, acceptOnce, receiveFile, closeAfterResult, generateCode, encodeQrPayload, resolveCode, displayName } = require('@ad-hal/engine')
26
+
27
+ const { printQr } = require('./qr')
28
+ const { readCode } = require('./read-code')
29
+ const { createProgressReporter } = require('./progress')
30
+ const { installCancelHandler } = require('./signals')
31
+ const { describeError, isCancellation } = require('./report')
32
+ const { parseBootstrap } = require('./env')
33
+ const { createConsent } = require('./consent')
34
+ const { createContentionMonitor } = require('./contention')
35
+ const { usage, NOT_ANONYMOUS } = require('./usage')
36
+
37
+
38
+ // ADHAL_JOIN_TIMEOUT overrides how long we wait for a peer, in ms (0
39
+ // disables the timeout). 30s is deliberate: on the public DHT a join that
40
+ // is going to work lands in ~5-7s, and one that has hit the
41
+ // lookup-before-announce race described in engine/src/swarm.js never
42
+ // recovers no matter how long you wait -- measured, a 120s budget rescued
43
+ // zero stuck runs. So a longer default just makes failures slower to
44
+ // report. The override exists for diagnosing slow networks.
45
+ function joinTimeout () {
46
+ const raw = process.env.ADHAL_JOIN_TIMEOUT
47
+ if (!raw) return 30000
48
+ const parsed = Number(raw)
49
+ if (!Number.isFinite(parsed) || parsed < 0) {
50
+ throw new TypeError(`ADHAL_JOIN_TIMEOUT must be a non-negative number, got ${raw}`)
51
+ }
52
+ return parsed
53
+ }
54
+
55
+ // ADHAL_MAX_SIZE overrides the largest transfer this receiver will accept,
56
+ // in bytes. `0` means no limit at all and has to be written down, because
57
+ // with no cap a manifest declaring 9 PB validates cleanly and the only
58
+ // thing standing between the receiver and that number is the free-space
59
+ // check. The engine's own default (8 GiB) applies when this is unset.
60
+ function maxSize () {
61
+ const raw = process.env.ADHAL_MAX_SIZE
62
+ if (raw === undefined) return undefined
63
+ const parsed = Number(raw)
64
+ if (!Number.isFinite(parsed) || parsed < 0) {
65
+ throw new TypeError(`ADHAL_MAX_SIZE must be a non-negative number, got ${raw}`)
66
+ }
67
+ return parsed === 0 ? null : parsed
68
+ }
69
+
70
+ // Splits argv into an optional code and an optional output directory.
71
+ // `--new` is explicit rather than inferred so that the one-positional form
72
+ // stays unambiguously "that's a code", exactly as the Hyperswarm CLI defined it: a bare
73
+ // path and a bare code are not reliably distinguishable, and guessing wrong
74
+ // 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'])
76
+
77
+ function parseArgs (argv) {
78
+ const flags = argv.filter((a) => a.startsWith('--'))
79
+ const positional = argv.filter((a) => !a.startsWith('--'))
80
+ const wantsNew = flags.includes('--new')
81
+
82
+ for (const flag of flags) {
83
+ if (!KNOWN_FLAGS.has(flag)) throw new Error(`unknown flag ${flag}`)
84
+ }
85
+
86
+ const common = {
87
+ allowOpaque: flags.includes('--insecure-opaque-code'),
88
+ // Opt back in to overwriting an existing file. Off by default: see
89
+ // `publish` in engine/src/transfer.js for why the old overwrite
90
+ // default was a security bug rather than a UI question.
91
+ replace: flags.includes('--replace'),
92
+ fromStdin: flags.includes('--code-stdin'),
93
+ verbose: flags.includes('--verbose'),
94
+ // Accept the offer without asking; see ./consent.js.
95
+ yes: flags.includes('--yes'),
96
+ allowArgv: flags.includes('--code-on-argv'),
97
+ help: flags.includes('--help')
98
+ }
99
+
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 }
106
+ }
107
+
108
+ // ADHAL_REFRESH_INTERVAL overrides how often we re-run our own DHT
109
+ // announce/lookup, in ms (0 disables it, leaving Hyperswarm's internal
110
+ // 10-minute schedule). See engine/src/swarm.js REFRESH_INTERVAL: the 4s
111
+ // default is validated only for two peers on one machine, and on a
112
+ // cross-ISP path a continuous re-announce is a suspect for churning
113
+ // holepunch relay state.
114
+ function refreshInterval () {
115
+ const raw = process.env.ADHAL_REFRESH_INTERVAL
116
+ if (raw === undefined) return undefined
117
+ const parsed = Number(raw)
118
+ if (!Number.isFinite(parsed) || parsed < 0) {
119
+ throw new TypeError(`ADHAL_REFRESH_INTERVAL must be a non-negative number, got ${raw}`)
120
+ }
121
+ return parsed
122
+ }
123
+
124
+ async function main () {
125
+ let parsed
126
+ try {
127
+ parsed = parseArgs(process.argv.slice(2))
128
+ } catch (err) {
129
+ console.error(`[swarm-receive] ${err.message}`)
130
+ console.error(usage('swarm-receive'))
131
+ process.exitCode = 1
132
+ return
133
+ }
134
+ if (parsed.help) {
135
+ console.log(usage('swarm-receive'))
136
+ return
137
+ }
138
+
139
+ // A generated code is the default: the code generator exists because
140
+ // hand-typing a code on both machines was the friction worth removing.
141
+ // `--code-stdin` is the other way in, for a code that must not touch
142
+ // the shell history or the process table -- see ./read-code.js.
143
+ const generated = parsed.codeArg === null && !parsed.fromStdin
144
+ let resolved
145
+ try {
146
+ const input = generated
147
+ ? generateCode()
148
+ : await readCode({ argvCode: parsed.fromStdin ? '-' : parsed.codeArg, label: 'swarm-receive', allowArgv: parsed.allowArgv })
149
+ resolved = resolveCode(input, { allowOpaque: parsed.allowOpaque || undefined })
150
+ } catch (err) {
151
+ console.error(`[swarm-receive] ${err.message}`)
152
+ process.exitCode = 1
153
+ return
154
+ }
155
+ const { code, topic, nameplate, secret } = resolved
156
+
157
+ let bootstrap
158
+ try {
159
+ bootstrap = parseBootstrap()
160
+ } catch (err) {
161
+ console.error(`[swarm-receive] ${err.message}`)
162
+ process.exitCode = 1
163
+ return
164
+ }
165
+
166
+ const outputDir = parsed.outputDirArg ? path.resolve(parsed.outputDirArg) : process.cwd()
167
+ await fs.promises.mkdir(outputDir, { recursive: true })
168
+
169
+ const swarm = createSwarm({ bootstrap })
170
+ const cancel = installCancelHandler({ label: 'swarm-receive' })
171
+ const progress = createProgressReporter({ label: 'swarm-receive' })
172
+ /** @type {Error | null} */
173
+ let socketError = null
174
+ // The topic is a commitment to the nameplate, and this line lands in
175
+ // scrollback, CI logs, and bug reports. It is shown only when asked for
176
+ // (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)`)
178
+ // 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 })
182
+
183
+ try {
184
+ // Set once acceptOnce resolves; the late-candidate callbacks above
185
+ // read it, because they keep firing after that.
186
+ let paired = false
187
+ const { socket, peerInfo, pending, sendKey, receiveKey, caps } = await acceptOnce(swarm, topic, {
188
+ // Announcing the topic makes the NAMEPLATE public; the secret stays
189
+ // private, and it is what proves a peer is the intended one rather
190
+ // than a stranger who walked the DHT. Without it we would accept a
191
+ // file from anyone and write it into `outputDir`.
192
+ //
193
+ // Under v2 the topic commits only to the nameplate, so the secret is
194
+ // not recoverable from anything an observer can obtain -- a guess
195
+ // costs a live protocol run against this process, which counts them
196
+ // (PROTOCOL.md section 6). See engine/src/handshake.js.
197
+ nameplate,
198
+ secret,
199
+ timeout: joinTimeout(),
200
+ refreshInterval: refreshInterval(),
201
+ // Ctrl-C while waiting for a peer -- which, for a receiver showing
202
+ // a QR code, is almost the whole of its life. Before that work, this
203
+ // was the one state with no way out but killing the process, and
204
+ // the sender then saw a reset indistinguishable from a dead punch.
205
+ signal: cancel.signal,
206
+ // Log each candidate and each discarded one. A drop that fails
207
+ // because peers connect and then vanish looks identical to one that
208
+ // found nobody unless these lines are visible.
209
+ onCandidate: (info) => {
210
+ console.log(`[swarm-receive] candidate ${info.publicKey.toString('hex').slice(0, 12)}..., sent HELLO, awaiting REPLY`)
211
+ },
212
+ // After pairing, the engine reports only failures it COUNTED -- a
213
+ // peer guessing at the code while the transfer runs -- so the line
214
+ // stops saying "still waiting", which is no longer true.
215
+ onCandidateDropped: (info, reason, code) => {
216
+ const who = `candidate ${info.publicKey.toString('hex').slice(0, 12)}...`
217
+ console.log(paired
218
+ ? `[swarm-receive] ${who} failed to prove the code during the transfer (${reason}); it counts toward this drop's attempt limit`
219
+ : `[swarm-receive] ${who} dropped before proving (${reason}); still waiting`)
220
+ // The pattern, once there is one (Q-04); see ./contention.js.
221
+ contention.dropped(info, reason, code)
222
+ },
223
+ // A second peer proved the code after we paired, and was told the
224
+ // drop is taken. The race is invisible to this human otherwise, and
225
+ // it means someone other than the intended sender holds the code.
226
+ 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.`)
228
+ },
229
+ // Only now are we actually discoverable. The sender must not start
230
+ // looking before this point -- see engine/src/swarm.js. This is
231
+ // therefore also the first moment the code may be shown to a human,
232
+ // which is why the QR is printed here and not before the join:
233
+ // showing it earlier invites exactly the lookup-before-announce race
234
+ // that engine/src/swarm.js documents. demo-swarm.js waits for this
235
+ // line before spawning the sender.
236
+ 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()
244
+ }
245
+ }
246
+ })
247
+ paired = true
248
+ contention.paired()
249
+ console.log(`[swarm-receive] connection from ${peerInfo.publicKey.toString('hex').slice(0, 12)}...`)
250
+ // Without a listener, a late socket-level error (e.g. after the
251
+ // transfer completes, while tearing down) throws as an uncaught
252
+ // exception instead of something we can handle gracefully.
253
+ //
254
+ // Silent once we are canceling, and that is the whole point of item
255
+ // 5 rather than tidiness: tearing down a canceled transfer reliably
256
+ // produces "connection reset by peer", which is byte for byte what a
257
+ // dead hole punch looks like. Printing it right after "canceled"
258
+ // would hand back exactly the ambiguity the CANCEL frame was added to
259
+ // remove.
260
+ //
261
+ // RECORDED RATHER THAN PRINTED, because printing it immediately is
262
+ // how a deliberate cancel ended up followed by "connection reset by
263
+ // peer" -- byte for byte what a dead hole punch looks like, and the
264
+ // exact ambiguity the CANCEL frame exists to remove. A socket that
265
+ // dies while a canceled or completed transfer tears down explains
266
+ // nothing; one that dies during a transfer that then failed for an
267
+ // unclear reason explains a great deal, so it is reported there.
268
+ socket.on('error', (err) => { socketError = err })
269
+
270
+ const result = await receiveFile(socket, outputDir, {
271
+ // The channel keys the handshake derived; every frame is opened
272
+ // under them. See swarm-send.js.
273
+ sendKey,
274
+ receiveKey,
275
+ // What the same handshake negotiated. A streamed offer is declined
276
+ // unless "stream" is in it.
277
+ caps,
278
+ // Bytes the handshake read alongside the ACK, if the sender
279
+ // coalesced them; dropping these would corrupt the first frame.
280
+ pending,
281
+ signal: cancel.signal,
282
+ onProgress: progress.onProgress,
283
+ // Off unless asked for. The engine now refuses to replace a file it
284
+ // did not create, and lands `report (1).pdf` beside the original
285
+ // instead -- so the flag is the only way back to the old behavior.
286
+ replace: parsed.replace,
287
+ // Explicit rather than relying on the engine's default, so the
288
+ // number a receiver enforces is visible at the call site and one
289
+ // env var away from being changed for a legitimate large drop.
290
+ maxSize: maxSize(),
291
+ // A person says yes before anything is written, unless --yes said it
292
+ // for them (Q-02). The engine has already refused what it would
293
+ // refuse anyway, so nobody is asked about an unsafe name.
294
+ onOffer: consent.onOffer,
295
+ onManifest: (manifest, { resumeFrom }) => {
296
+ // THE FIRST PEER-CHOSEN STRING THIS PROCESS PRINTS. Straight to a
297
+ // terminal, before anything has validated that it is printable.
298
+ // A name carrying ESC or a bidi override forged whatever it liked
299
+ // on this line until displayName existed.
300
+ progress.log(`[swarm-receive] manifest: ${displayName(manifest.name)} (${manifest.size === null ? 'streamed, size unknown until it ends' : `${manifest.size} bytes`})`)
301
+ // A partial from an interrupted drop was found, re-hashed, and is
302
+ // being continued. It is verified with the rest at the end: if it
303
+ // was not this file's, the digest says so and it is discarded.
304
+ if (resumeFrom > 0) progress.log(`[swarm-receive] resuming from byte ${resumeFrom} of an earlier, interrupted attempt`)
305
+ }
306
+ })
307
+
308
+ progress.close()
309
+ console.log(`[swarm-receive] done: ${displayName(result.name)}`)
310
+ console.log(`[swarm-receive] sha256: ${result.sha256}`)
311
+ // The line that turns plan phase-1 bar the drop-code work from an eyeball
312
+ // comparison of two hex strings into an assertion the receiver makes
313
+ // for itself. Until that work, this comparison happened nowhere that
314
+ // shipped.
315
+ console.log('[swarm-receive] verified: the file matches the sender\'s manifest digest')
316
+ if (result.name !== result.declaredName) {
317
+ // Covers both reasons the name can differ -- the write policy
318
+ // transformed it, or an existing file meant it landed suffixed --
319
+ // 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))}`)
321
+ }
322
+ console.log(`[swarm-receive] saved to: ${result.path}`)
323
+ // See `publish` in engine/src/transfer.js (Q-19).
324
+ 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.')
327
+ }
328
+
329
+ // receiveFile has written RESULT, but "written" is a local flush.
330
+ // Destroying now could drop it and leave the sender reporting an
331
+ // unconfirmed file -- the same mistake the sender used to make with
332
+ // the last chunks. So end, and wait until the transport confirms the
333
+ // sender has RESULT and the sender closes in reply. The bound only
334
+ // covers a sender that vanished: the file is already verified and
335
+ // saved. See closeAfterResult in engine/src/transfer.js.
336
+ 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.')
339
+ }
340
+ } catch (err) {
341
+ // First, so the reason does not land on the question's line.
342
+ consent.close()
343
+ 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}`)
347
+ }
348
+ if (!cancel.cancelled()) process.exitCode = 1
349
+ } finally {
350
+ // A question still on screen after the transfer ended some other way.
351
+ consent.close()
352
+ cancel.dispose()
353
+ await swarm.destroy()
354
+ }
355
+ }
356
+
357
+ main()