swarmwire-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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tibotibotibotibotibotibotibotibotibotibotibo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # swarmwire-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Send a file or a folder to someone with a link. Peer to peer, from the terminal: no account, no
4
+ server, no upload. Built on [`swarmwire-lib`](https://github.com/tibocub/swarmwire).
5
+
6
+ ```
7
+ npm i -g swarmwire-cli
8
+
9
+ swarmwire send ./holiday-photos # prints a link, keeps serving until you press ctrl-c
10
+ swarmwire get "<link>" # on the other machine: downloads it, resumable
11
+ ```
12
+
13
+ Anyone who knows what a file contains can find the people sharing it, whatever each calls it: two
14
+ people sending the same file are one swarm. Pass `--private` to `send` for a link that carries a secret, so that only people
15
+ holding the link can find you.
16
+
17
+ Both commands keep a two-line status current. Receiving looks like this:
18
+
19
+ ```
20
+ [=========> ] 45% [2/3] TOTAL: [154.2/344.0] MB
21
+ UP: 1.1 MB/s DOWN: 8.2 MB/s Seeders: 1 Peers: 0
22
+ ```
23
+
24
+ When the download is done the bar is replaced by `[Done] you are now seeding.` and `get` keeps
25
+ running so others can fetch from you; ctrl-c stops it, `--exit` leaves as soon as it is done.
26
+ Sending shows `[Seeding]` in place of the bar.
27
+
28
+ *Seeders* are the peers connected to you that hold all of it, *Peers* the other ones. They are
29
+ your direct connections only, never counting yourself and not the whole swarm. Someone who
30
+ vanishes without saying goodbye (a pulled cable) drops off after the connection times out, about
31
+ fifteen seconds. The speeds are bytes on the wire, so a little above the size of the data. Sizes
32
+ are decimal: 1 MB is 1,000,000 bytes.
33
+
34
+ ## Options
35
+
36
+ | | |
37
+ |---|---|
38
+ | `send <path> [--private]` | share a file or folder; prints a link |
39
+ | `get <link> [output] [--exit]` | fetch by link, then keep seeding it (`--exit`: leave instead); the output defaults to the name in the link |
40
+ | `--bootstrap host:port` | use a private DHT instead of the public one (for tests) |
41
+
42
+ Needs Node 20 or later. Files are shared where they lie: nothing is copied or written next to them.
43
+
44
+ ## Development
45
+
46
+ ```
47
+ npm test # real processes over a private DHT, no internet needed
48
+ ```
49
+
50
+ MIT.
@@ -0,0 +1,318 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * swarmwire send <path> [--private] [--bootstrap host:port]
4
+ * swarmwire get <link> [output] [--bootstrap host:port]
5
+ *
6
+ * Deliberately two commands. Sending prints a link and keeps serving the file where it is;
7
+ * getting takes that link and nothing else.
8
+ */
9
+
10
+ import { randomBytes } from 'crypto'
11
+ import { stat } from 'fs/promises'
12
+ import Hyperswarm from 'hyperswarm'
13
+ import DHT from 'hyperdht'
14
+ import b4a from 'b4a'
15
+ import { Swarmwire, parseLink, groupLength, DEFAULT_GROUP_LOG } from 'swarmwire-lib'
16
+
17
+ const USAGE = `swarmwire - content-addressed file transfer, peer to peer
18
+
19
+ swarmwire send <path> [options] share a file or folder; prints a link
20
+ swarmwire get <link> [output] fetch a file or folder by link
21
+
22
+ Options:
23
+ --private only people holding the link can find you (default: anyone who knows the hash can)
24
+ --exit get: leave when the download is done instead of seeding it
25
+ --bootstrap <h:p> use a private DHT instead of the public one
26
+ --help
27
+ `
28
+
29
+ // A terminal gets a two-line status rewritten in place. Anything else gets a line only when
30
+ // who is connected changes: speeds and a bar would be a new line every half second.
31
+ let shown = ''
32
+ let drawn = false
33
+ let lastPlain = ''
34
+
35
+ const FLAGS = { private: false, exit: false, help: false, bootstrap: true } // true: takes a value
36
+
37
+ async function main () {
38
+ const { command, args, flags } = parseArgs(process.argv.slice(2))
39
+
40
+ if (flags.help || !command) return print(USAGE)
41
+ if (command === 'send') return send(args[0], flags)
42
+ if (command === 'get') return get(args[0], args[1], flags)
43
+
44
+ throw new Error(`unknown command: ${command}\n\n${USAGE}`)
45
+ }
46
+
47
+ async function send (path, flags) {
48
+ if (!path) throw new Error('send needs a path\n\n' + USAGE)
49
+
50
+ const swarm = createSwarm(flags)
51
+ const node = new Swarmwire({ swarm })
52
+
53
+ // A private link carries its own secret, so only people holding it can find you.
54
+ const secret = flags.private ? randomBytes(32).toString('hex') : null
55
+ const folder = await isDirectory(path)
56
+
57
+ const { link, size, files } = folder
58
+ ? await node.serveCollection(path, { secret })
59
+ : await node.serve(path, { secret })
60
+
61
+ print(link)
62
+ warn(
63
+ folder
64
+ ? `serving ${path} (${files} files, ${bytes(size)})${flags.private ? ' privately' : ''}`
65
+ : `serving ${path} (${bytes(size)})${flags.private ? ' privately' : ''}`
66
+ )
67
+ warn('keep this running; ctrl-c to stop')
68
+
69
+ const poll = watch(node, swarm, link, () => '[Seeding]')
70
+
71
+ await interrupted()
72
+
73
+ clearInterval(poll)
74
+ warn('stopping')
75
+ await node.destroy()
76
+ await swarm.destroy()
77
+ }
78
+
79
+ async function get (link, output, flags) {
80
+ if (!link) throw new Error('get needs a link\n\n' + USAGE)
81
+
82
+ const parsed = parseLink(link)
83
+ const out = output ?? safeName(parsed.name) ?? parsed.root.slice(0, 16)
84
+
85
+ const swarm = createSwarm(flags)
86
+ const node = new Swarmwire({ swarm })
87
+
88
+ warn(`fetching ${parsed.root.slice(0, 16)}... into ${out}`)
89
+
90
+ // What the status line shows of the transfer: bytes of the whole thing, and which file.
91
+ const progress = { done: 0, total: parsed.size, file: 0, files: 0, finished: false }
92
+ let download = null
93
+
94
+ const poll = watch(node, swarm, parsed, () => {
95
+ if (progress.finished) return '[Done] you are now seeding.'
96
+ if (download) progress.done = Math.min(download.have * groupLength(DEFAULT_GROUP_LOG), parsed.size)
97
+
98
+ const counter = progress.files > 1 ? ` [${Math.min(progress.file + 1, progress.files)}/${progress.files}]` : ''
99
+ return `${bar(progress.done / progress.total)} ${Math.floor((progress.done / progress.total) * 100)}%${counter} TOTAL: ${pair(progress.done, progress.total)}`
100
+ })
101
+
102
+ const work = (async () => {
103
+ if (parsed.type === 'collection') {
104
+ const list = await node.readList(parsed)
105
+ warn(`${list.files.length} files, ${bytes(list.size)}`)
106
+ progress.files = list.files.length
107
+
108
+ await node.downloadCollection(parsed, out, {
109
+ onfile: () => { progress.file++ },
110
+ onprogress: ({ bytes, total }) => Object.assign(progress, { done: bytes, total })
111
+ })
112
+
113
+ } else {
114
+ download = node.download(parsed, out)
115
+ await download
116
+ }
117
+ })()
118
+
119
+ const stopped = await Promise.race([work.then(() => false), interrupted().then(() => true)])
120
+
121
+ if (!stopped) {
122
+ progress.finished = true
123
+ if (!process.stderr.isTTY) warn(flags.exit ? '[Done]' : '[Done] you are now seeding.')
124
+ clearStatus() // the path goes below nothing: printed inside the status, the next redraw leaves its old bar behind
125
+ print(out)
126
+
127
+ if (!flags.exit) await interrupted()
128
+ }
129
+
130
+ clearInterval(poll)
131
+ warn('stopping')
132
+ await node.destroy()
133
+ await swarm.destroy()
134
+ }
135
+
136
+ /** Resolves on ctrl-c or a polite kill, so serving can end cleanly. */
137
+ function interrupted () {
138
+ return new Promise((resolve) => {
139
+ process.once('SIGINT', resolve)
140
+ process.once('SIGTERM', resolve)
141
+ })
142
+ }
143
+
144
+ /**
145
+ * Keep the status current: `lead()` is the first line, then speeds and who is connected.
146
+ * Peers are everyone connected who does not hold all of it; seeders are counted apart.
147
+ */
148
+ function watch (node, swarm, link, lead) {
149
+ const meter = new Meter(swarm)
150
+
151
+ const show = () => {
152
+ const { peers, seeders } = node.counts(link)
153
+ const people = `Seeders: ${seeders} Peers: ${peers - seeders}`
154
+ const { up, down } = meter.rates()
155
+
156
+ status(lead(), `UP: ${rate(up)} DOWN: ${rate(down)} ${people}`, people)
157
+ }
158
+
159
+ node.on('peer-connected', show)
160
+ node.on('peer-disconnected', show)
161
+ show()
162
+
163
+ return setInterval(show, 500) // a peer finishing, or progress, is not a connection event
164
+ }
165
+
166
+ /** Bytes on the wire in each direction, summed over every connection, past and present. */
167
+ class Meter {
168
+ constructor (swarm) {
169
+ this.closed = { up: 0, down: 0 }
170
+ this.live = new Set()
171
+ this.samples = [] // recent { at, up, down }, for a rate smoothed over a couple of seconds
172
+
173
+ swarm.on('connection', (stream) => {
174
+ this.live.add(stream)
175
+ stream.once('close', () => {
176
+ this.live.delete(stream)
177
+ this.closed.up += stream.rawBytesWritten
178
+ this.closed.down += stream.rawBytesRead
179
+ })
180
+ })
181
+ }
182
+
183
+ rates () {
184
+ let { up, down } = this.closed
185
+ for (const stream of this.live) {
186
+ up += stream.rawBytesWritten
187
+ down += stream.rawBytesRead
188
+ }
189
+
190
+ const now = Date.now()
191
+ this.samples.push({ at: now, up, down })
192
+ while (this.samples.length > 5) this.samples.shift()
193
+
194
+ const first = this.samples[0]
195
+ const seconds = (now - first.at) / 1000
196
+ return seconds > 0 ? { up: (up - first.up) / seconds, down: (down - first.down) / seconds } : { up: 0, down: 0 }
197
+ }
198
+ }
199
+
200
+ function createSwarm ({ bootstrap }) {
201
+ if (!bootstrap) return new Hyperswarm()
202
+
203
+ const [host, port] = String(bootstrap).split(':')
204
+ const loopback = host === '127.0.0.1' || host === 'localhost'
205
+
206
+ const dht = new DHT({
207
+ bootstrap: [{ host, port: Number(port) }],
208
+ ephemeral: false,
209
+ firewalled: false,
210
+ // On a loopback DHT, bind there too: announcing a LAN address to peers that can only
211
+ // reach 127.0.0.1 leaves everyone findable and nobody connectable.
212
+ host: loopback ? '127.0.0.1' : undefined
213
+ })
214
+
215
+ return new Hyperswarm({ dht })
216
+ }
217
+
218
+ async function isDirectory (path) {
219
+ const info = await stat(path).catch(() => null)
220
+ if (info === null) throw new Error(`no such file or folder: ${path}`)
221
+
222
+ return info.isDirectory()
223
+ }
224
+
225
+ /** A filename hint is a hint: never let it climb out of the working directory. */
226
+ function safeName (name) {
227
+ if (!name) return null
228
+
229
+ const base = name.split(/[\\/]/).pop()
230
+ return base && base !== '.' && base !== '..' ? base : null
231
+ }
232
+
233
+ function parseArgs (argv) {
234
+ const args = []
235
+ const flags = {}
236
+ let command = null
237
+
238
+ for (let i = 0; i < argv.length; i++) {
239
+ const arg = argv[i]
240
+
241
+ if (!arg.startsWith('--')) {
242
+ if (command === null) command = arg
243
+ else args.push(arg)
244
+ continue
245
+ }
246
+
247
+ const [key, inline] = arg.slice(2).split('=')
248
+ if (!(key in FLAGS)) throw new Error(`unknown option: --${key}\n\n${USAGE}`)
249
+
250
+ flags[key] = FLAGS[key] ? (inline ?? argv[++i]) : true
251
+ if (flags[key] === undefined) throw new Error(`--${key} needs a value`)
252
+ }
253
+
254
+ return { command, args, flags }
255
+ }
256
+
257
+ const UNITS = ['B', 'KB', 'MB', 'GB', 'TB']
258
+
259
+ /** The unit that keeps a size readable: 1 or more, below 1000. */
260
+ function unitOf (n) {
261
+ return Math.min(Math.max(Math.floor(Math.log10(Math.max(n, 1)) / 3), 0), UNITS.length - 1)
262
+ }
263
+
264
+ function scaled (n, unit) {
265
+ return unit === 0 ? String(Math.round(n)) : (n / 1000 ** unit).toFixed(1)
266
+ }
267
+
268
+ function bytes (n) {
269
+ const unit = unitOf(n)
270
+ return `${scaled(n, unit)} ${UNITS[unit]}`
271
+ }
272
+
273
+ /** Progress in the unit of the total: "[254.0/344.0] MB". */
274
+ function pair (done, total) {
275
+ const unit = unitOf(total)
276
+ return `[${scaled(done, unit)}/${scaled(total, unit)}] ${UNITS[unit]}`
277
+ }
278
+
279
+ function rate (perSecond) {
280
+ return `${bytes(perSecond)}/s`
281
+ }
282
+
283
+ function bar (fraction, width = 20) {
284
+ const filled = Math.min(width, Math.max(0, Math.floor(fraction * width)))
285
+ return '[' + '='.repeat(filled) + (filled < width ? '>' : '') + ' '.repeat(Math.max(0, width - filled - 1)) + ']'
286
+ }
287
+
288
+ function print (line) {
289
+ console.log(line)
290
+ }
291
+
292
+ function status (lead, detail, plain) {
293
+ const text = lead + '\n' + detail
294
+ if (text === shown) return
295
+ shown = text
296
+
297
+ if (!process.stderr.isTTY) return plain === lastPlain ? undefined : console.error((lastPlain = plain))
298
+
299
+ process.stderr.write((drawn ? '\x1b[2A' : '') + `\r\x1b[K${lead}\n\x1b[K${detail}\n`)
300
+ drawn = true
301
+ }
302
+
303
+ /** Erase the status so a line can be printed where it was; the next redraw starts below it. */
304
+ function clearStatus () {
305
+ if (process.stderr.isTTY && drawn) process.stderr.write('\r\x1b[2A\x1b[J')
306
+ drawn = false
307
+ shown = ''
308
+ }
309
+
310
+ function warn (line) {
311
+ clearStatus()
312
+ console.error(line)
313
+ }
314
+
315
+ main().catch((err) => {
316
+ warn(String(err.message ?? err))
317
+ process.exit(1)
318
+ })
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "swarmwire-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Send a file or folder to someone with a link. Peer to peer, from the terminal.",
5
+ "keywords": [
6
+ "cli",
7
+ "p2p",
8
+ "hyperswarm",
9
+ "file-transfer"
10
+ ],
11
+ "homepage": "https://github.com/tibocub/swarmwire-cli#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/tibocub/swarmwire-cli/issues"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/tibocub/swarmwire-cli.git"
18
+ },
19
+ "license": "MIT",
20
+ "author": "tibotibotibo",
21
+ "type": "module",
22
+ "bin": {
23
+ "swarmwire": "bin/swarmwire.js"
24
+ },
25
+ "files": [
26
+ "bin/"
27
+ ],
28
+ "engines": {
29
+ "node": ">=20"
30
+ },
31
+ "scripts": {
32
+ "test": "brittle test/*.test.js"
33
+ },
34
+ "dependencies": {
35
+ "b4a": "^1.9.0",
36
+ "hyperdht": "^6.0.0",
37
+ "hyperswarm": "^4.17.2",
38
+ "swarmwire-lib": "^0.4.0"
39
+ },
40
+ "devDependencies": {
41
+ "@hyperswarm/testnet": "^3.1.4",
42
+ "brittle": "^3.19.1"
43
+ }
44
+ }