telstore 0.1.9 → 0.1.10

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/cli.js CHANGED
@@ -1,9 +1,24 @@
1
1
  import { basename } from 'node:path'
2
2
  import { parseArgs } from 'node:util'
3
3
 
4
+ import { deleteCommand } from './shell.js'
5
+ import { archiveName } from './tar.js'
6
+
7
+ // The shortcuts dispatch by name, not through SUBCOMMANDS: what they return is not a command
8
+ // called `tarc`, it is an upload (or, for `tarx`, a restore) with the line already
9
+ // rewritten into the form that command understands — there is no `runTarc` for SUBCOMMANDS to
10
+ // route to. They still belong in the set below all the same, because SUBCOMMANDS is the list of
11
+ // words telstore will not read as a file name, and a shortcut claims one exactly as a
12
+ // subcommand does.
13
+ const SHORTCUTS = new Map([
14
+ ['tarc', tarcLine],
15
+ ['tarx', tarxLine],
16
+ ])
17
+
4
18
  const SUBCOMMANDS = new Set([
5
19
  'login',
6
20
  'logout',
21
+ 'down',
7
22
  'list',
8
23
  'restore',
9
24
  'verify',
@@ -12,9 +27,10 @@ const SUBCOMMANDS = new Set([
12
27
  'config',
13
28
  'token',
14
29
  'help',
30
+ ...SHORTCUTS.keys(),
15
31
  ])
16
32
 
17
- const OPTIONS = {
33
+ export const OPTIONS = {
18
34
  chat: { type: 'string' },
19
35
  'chunk-size': { type: 'string' },
20
36
  'upload-concurrency': { type: 'string' },
@@ -35,6 +51,10 @@ export const HELP = `telstore — split large files into chunks and store them o
35
51
  Usage:
36
52
  npx telstore login Log in to Telegram, only needed once
37
53
  npx telstore <file|folder|pattern>... Split files and upload them to Telegram
54
+ npx telstore <name> -- <command>... Store what a command writes, under <name>
55
+ npx telstore tarc <name> <path>... Archive paths with tar and store the archive
56
+ npx telstore tarx <backup-id> Restore a backup and extract it with tar
57
+ npx telstore restore <id> -- <cmd>... Restore onto a command instead of a file
38
58
  npx telstore list List the backups stored in the destination
39
59
  npx telstore list --search <text> List only the backups that text appears in
40
60
  npx telstore restore <backup-id>... Download the chunks and reassemble the files
@@ -43,6 +63,7 @@ Usage:
43
63
  npx telstore status Show the account, the destination and unfinished uploads and restores
44
64
  npx telstore config Show every setting and where its value comes from
45
65
  npx telstore logout Remove the saved session
66
+ npx telstore down Remove everything telstore keeps on this machine
46
67
 
47
68
  Running on a machine you do not trust:
48
69
  npx telstore token Print a session token for another machine
@@ -54,6 +75,32 @@ backup. A folder means the files one level inside it, and a pattern means the na
54
75
  one file is listed and confirmed before the first byte goes out. Run telstore again with only
55
76
  the files that are left to carry on after an interruption.
56
77
 
78
+ A name followed by -- makes the backup out of what a command writes, so nothing has to be on
79
+ disk first: npx telstore a.tar -- tar cf - ./a. The manifest goes out only if that command's
80
+ output ended and the command exited 0 — an end after a crash looks exactly like an end after
81
+ success, and running the command is how telstore tells them apart. A backup made this way
82
+ cannot be resumed, so a run that fails, and a Ctrl-C, remove the chunks already sent rather
83
+ than keeping them for a second run there will never be. No shell stands in between: a pipeline
84
+ goes in as -- bash -c 'set -o pipefail; ...', which is also where compression or encryption
85
+ belongs. The pipefail is not decoration — a shell reports the last command's exit status, so
86
+ without it a producer that dies halfway through a pipeline still exits 0 and the manifest goes
87
+ out for a truncated backup.
88
+
89
+ tarc and tarx are the common case written out once: "npx telstore tarc a.tar.gz ./dir"
90
+ is "npx telstore a.tar.gz -- tar czf - ./dir", and tarx is the same for "restore <id> --
91
+ tar xzf -". telstore prints the long form as it runs, so the shortcut teaches what it is
92
+ short for. tarc always compresses, so it makes the name say so: a.tar becomes a.tar.gz,
93
+ and a name with no tar in it at all gets .tar.gz. --verbose adds tar's own file listing
94
+ to both. For tarx, --out is the directory it extracts into, and tar's own semantics apply
95
+ there: it overwrites files already in it without asking, unlike restore's one-file [y/N]
96
+ prompt — --out is how you aim it somewhere empty instead. Anything beyond archiving
97
+ the paths — -C, --exclude, a pipeline, another compressor — is what -- is still for.
98
+
99
+ down is logout taken all the way: it removes ~/.telstore entirely — the session, the api_id
100
+ and api_hash, every setting and every resume record — and asks once before it does. It opens
101
+ no connection and deletes nothing from Telegram: the backups stay in the chat, and the session
102
+ stays alive on Telegram's side until you terminate it under Settings → Devices.
103
+
57
104
  restore, verify and delete take several ids the same way: one connection, one line each, and
58
105
  an exit code that reports any that failed. delete shows everything it is about to destroy and
59
106
  asks once. verify downloads nothing: it asks the chat whether every chunk message is still
@@ -96,7 +143,8 @@ Options apply to one run and are never saved. Use config to change a setting for
96
143
  purpose: a token written on the command line would sit in
97
144
  "ps" for the whole life of the command, and stay in that
98
145
  machine's shell history afterwards.
99
- --yes Upload a batch, or delete, without being asked to confirm.
146
+ --yes Upload a batch, delete, or wipe this machine with down,
147
+ without being asked to confirm.
100
148
  --verbose Show Telegram connection logs for this run.
101
149
  -h, --help Show this help.
102
150
  `
@@ -105,7 +153,54 @@ Options apply to one run and are never saved. Use config to change a setting for
105
153
  // finished chunk to a state file, restore has not. Naming the backup matters because the
106
154
  // id is what `status` lists and what a later `restore` needs — the chunks are already in
107
155
  // the chat under that id, whether or not this run ever finishes.
108
- export function interruptMessage(command, { backupId, done = [] } = {}) {
156
+ export function interruptMessage(
157
+ command,
158
+ { backupId, done = [], stream = false, again = false, chat = null } = {},
159
+ ) {
160
+ // A backup made from a command is the one upload Ctrl-C cannot leave where it is. The bytes
161
+ // have gone past and the next run cuts them differently, so a chunk already in the chat is
162
+ // a chunk no manifest will ever name — which is why this run is asked to remove them and
163
+ // the process waits, rather than promising the resume the file wording promises.
164
+ if (command === 'upload' && stream) {
165
+ // Nothing is in the chat until there is an id to put it under, and a run stopped before
166
+ // that has nothing for anyone to clean up.
167
+ if (!backupId) {
168
+ return '\nStopped before anything was sent.\n'
169
+ }
170
+
171
+ if (again) {
172
+ // "may still" because this is said while the removal is halfway through and nobody
173
+ // knows how far it got. `deleteCommand` is what names the chat, and why: a later
174
+ // `delete` resolves its destination from config, and these ids fired at the wrong peer
175
+ // destroy whatever happens to carry them there. A null chat here is a Ctrl-C that
176
+ // landed before the run said where it was sending — the chatless branch documented
177
+ // beside that function is for exactly this caller.
178
+ const removal = deleteCommand(backupId, chat)
179
+
180
+ return (
181
+ `\nLeaving now. Backup ${backupId} may still have chunks in the chat with no manifest ` +
182
+ `pointing at them — run "${removal}" to remove them.\n`
183
+ )
184
+ }
185
+
186
+ return (
187
+ `\nStopping. Backup ${backupId} was made from a command and cannot be resumed, so ` +
188
+ 'telstore is removing the chunks it already sent. This takes a moment — press Ctrl-C ' +
189
+ 'again to leave now and clean up by hand.\n'
190
+ )
191
+ }
192
+
193
+ // The restore direction of the same idea, and the difference is the whole message: a stream
194
+ // upload has to unwind what it put in the chat, while this one put nothing there. What it
195
+ // cannot put back is what the command already did with the bytes it was given.
196
+ if (command === 'restore' && stream) {
197
+ return (
198
+ '\nStopped. Nothing in the chat changed and nothing was kept on this machine, but the ' +
199
+ 'command had already been given part of the backup, so whatever it wrote from that is ' +
200
+ 'incomplete. A restore into a command cannot be resumed — run it again from the start.\n'
201
+ )
202
+ }
203
+
109
204
  if (command === 'upload') {
110
205
  const backup = backupId ? `Backup ${backupId} is saved` : 'Progress is saved'
111
206
 
@@ -179,6 +274,18 @@ export function interruptMessage(command, { backupId, done = [] } = {}) {
179
274
  return '\nStopped.\n'
180
275
  }
181
276
 
277
+ // The one `--` this file did not write. protectNegativeChatIds, below, inserts one of its
278
+ // own to rescue a negative chat id from parseArgs, so the position has to be taken off the
279
+ // argv as typed — afterwards the two are indistinguishable, and `config chat -100123` would
280
+ // become a command telstore tries to run.
281
+ function splitAtTerminator(argv) {
282
+ const at = argv.indexOf('--')
283
+
284
+ if (at === -1) return { head: argv, childArgv: null }
285
+
286
+ return { head: argv.slice(0, at), childArgv: argv.slice(at + 1) }
287
+ }
288
+
182
289
  // A channel id is negative, and typing it separated by a space is the natural reflex — but
183
290
  // parseArgs rejects anything starting with a dash as an option, and reports it as one:
184
291
  // `config chat -100123` fails with "Unknown option '-1'", naming a flag nobody typed.
@@ -233,9 +340,80 @@ function filesNamedAfterNote(tokens) {
233
340
  return tokens.some((token) => token.kind === 'positional' && token.index > note.index)
234
341
  }
235
342
 
343
+ // tarc is the long form with the three decisions that never change already made: `c` for
344
+ // create, `z` for gzip, `f -` for "write it to stdout, which is where telstore is listening".
345
+ // The missing `-` is not a hypothetical mistake — this project's own help text and README
346
+ // shipped exactly that omission once, and paid for it with an example that exited 2 instead
347
+ // of writing a backup.
348
+ //
349
+ // An expansion rather than a command of its own: `runStreamUpload` is reached with exactly the
350
+ // argv the `--` form reaches it with, so there is no second upload path, no second rollback
351
+ // and no second guarantee. It also prints that argv, so the shortcut teaches the long form
352
+ // instead of hiding it.
353
+ function tarcLine(rest, values, filesAfterNote) {
354
+ const [name, ...paths] = rest
355
+
356
+ if (name === undefined) {
357
+ throw new Error(
358
+ 'Missing a name for the backup. tarc stores the archive under a name you choose. ' +
359
+ 'Example: npx telstore tarc a.tar.gz ./a',
360
+ )
361
+ }
362
+
363
+ // Refused rather than answered with a guess: a rule that read one positional as a name and
364
+ // two as a name plus a path would make `telstore tarc ./x ./y` archive ./y under the name
365
+ // ./x, which is the silent wrong answer this project exists to refuse.
366
+ if (paths.length === 0) {
367
+ throw new Error(
368
+ `Nothing to archive: tarc needs the paths to put in ${name}. ` +
369
+ 'Example: npx telstore tarc a.tar.gz ./a',
370
+ )
371
+ }
372
+
373
+ return {
374
+ command: 'upload',
375
+ args: [archiveName(name)],
376
+ options: values,
377
+ filesAfterNote,
378
+ childArgv: ['tar', values.verbose ? 'czvf' : 'czf', '-', ...paths],
379
+ shortcut: 'tarc',
380
+ }
381
+ }
382
+
383
+ // The mirror of tarcLine. `x` for extract, `z` because tarc always compressed, `f -` because
384
+ // the bytes arrive on stdin.
385
+ function tarxLine(rest, values, filesAfterNote) {
386
+ requireOneBackupId(rest, 'tarx')
387
+
388
+ const childArgv = ['tar', values.verbose ? 'xzvf' : 'xzf', '-']
389
+
390
+ // Pushed after `-` on purpose, which is the order measured to work on GNU tar 1.35:
391
+ // `tar xzf - -C ./here`. See the probe table in the spec.
392
+ if (values.out !== undefined) childArgv.push('-C', values.out)
393
+
394
+ return { command: 'restore', args: rest, options: values, filesAfterNote, childArgv, shortcut: 'tarx' }
395
+ }
396
+
397
+ // One command reads one stream, so a line that names two backups is a line with no answer:
398
+ // extracting two archives into one working directory in sequence is a question nobody asked.
399
+ function requireOneBackupId(ids, what) {
400
+ if (ids.length === 0) {
401
+ throw new Error(`Missing backup id. Example: npx telstore ${what} telstore-20260905-7f3a91`)
402
+ }
403
+
404
+ if (ids.length > 1) {
405
+ throw new Error(
406
+ `One command reads one stream, so ${what} takes one backup id and got ${ids.length}: ` +
407
+ `${ids.join(', ')}. Run telstore once per backup.`,
408
+ )
409
+ }
410
+ }
411
+
236
412
  export function route(argv) {
413
+ const { head, childArgv } = splitAtTerminator(argv)
414
+
237
415
  const { values, positionals, tokens } = parseArgs({
238
- args: protectNegativeChatIds(argv),
416
+ args: protectNegativeChatIds(head),
239
417
  options: OPTIONS,
240
418
  allowPositionals: true,
241
419
  tokens: true,
@@ -244,26 +422,103 @@ export function route(argv) {
244
422
  const [first, ...rest] = positionals
245
423
  const filesAfterNote = filesNamedAfterNote(tokens)
246
424
 
425
+ // --help (or -h, or the `help` subcommand) always wins, terminator or not: someone typing
426
+ // `telstore --help -- tar cf - ./a` is asking what telstore does, not making a mistake for
427
+ // one of the checks below to catch.
428
+ if (values.help || first === 'help') {
429
+ return { command: 'help', args: [], options: values, filesAfterNote, childArgv, shortcut: null }
430
+ }
431
+
432
+ if (childArgv !== null && childArgv.length === 0) {
433
+ throw new Error(
434
+ 'Missing the command after --: telstore has nothing to run and store. ' +
435
+ 'Example: npx telstore a.tar -- tar cf - ./a',
436
+ )
437
+ }
438
+
439
+ // A terminator changes what "no name" and "which command" mean, so it is read before the
440
+ // ordinary help/chat fallbacks get a chance to answer for it — those apply to a line that
441
+ // never named a command to run at all.
442
+ if (childArgv !== null) {
443
+ // Reached before the generic "takes no command after --" below, because for these two the
444
+ // reason is different and so is the way out: they are not a subcommand that happens not to
445
+ // run commands, they are a command already.
446
+ if (SHORTCUTS.has(first)) {
447
+ throw new Error(
448
+ `${first} already is the command it runs, so it cannot be followed by another one. ` +
449
+ `Drop the -- to use ${first}, or drop ${first} to write the command out yourself.`,
450
+ )
451
+ }
452
+
453
+ if (first !== undefined && SUBCOMMANDS.has(first)) {
454
+ // restore is let through rather than refused here, and the binary is what turns it away.
455
+ // The shape is the spec's stage 2, so the parser keeps it whole — but a refusal that
456
+ // says "not built yet, restore to a file and pipe that" belongs where the command runs,
457
+ // beside the alternative it is offering, not in an argument parser.
458
+ if (first !== 'restore') {
459
+ throw new Error(
460
+ `${first} takes no command after --. An upload (npx telstore a.tar -- tar cf - ./a) ` +
461
+ 'and a restore (npx telstore restore <id> -- tar xf -) are the two that run one.',
462
+ )
463
+ }
464
+
465
+ requireOneBackupId(rest, 'restore')
466
+
467
+ // --out places a file, and this path writes none: the bytes go to the command on its
468
+ // stdin. Left to pass silently it would read as "restore into the command AND write
469
+ // the file over there", which is not what happens.
470
+ if (values.out !== undefined) {
471
+ throw new Error(
472
+ 'A restore into a command writes no file, so --out has nothing to place: the bytes ' +
473
+ 'go to the command on its stdin. Tell the command where to put them instead ' +
474
+ '(npx telstore restore <id> -- tar xf - -C ./here).',
475
+ )
476
+ }
477
+
478
+ return { command: first, args: rest, options: values, filesAfterNote, childArgv, shortcut: null }
479
+ }
480
+
481
+ if (positionals.length === 0) {
482
+ throw new Error(
483
+ 'Missing a name before --. telstore stores what the command writes under a name you ' +
484
+ 'choose, and there is nothing to take one from. Example: npx telstore a.tar -- tar cf - ./a',
485
+ )
486
+ }
487
+
488
+ if (positionals.length > 1) {
489
+ throw new Error(
490
+ `One command produces one stream, so telstore takes one name before -- and got ` +
491
+ `${positionals.length}: ${positionals.join(', ')}. Run telstore once per backup.`,
492
+ )
493
+ }
494
+
495
+ return { command: 'upload', args: positionals, options: values, filesAfterNote, childArgv, shortcut: null }
496
+ }
497
+
247
498
  // `telstore --chat @chan` with no file used to mean "remember this destination". Flags no
248
499
  // longer write anything, so that line now asks for a run that has nothing to upload —
249
500
  // say where the destination actually lives instead of printing help at someone who was
250
- // perfectly clear about what they wanted.
251
- if (first === undefined && values.chat && !values.help) {
501
+ // perfectly clear about what they wanted. (values.help already returned above, so reaching
502
+ // here means it was never set.)
503
+ if (first === undefined && values.chat) {
252
504
  throw new Error(
253
505
  `Nothing to upload. To change the destination for good, run "npx telstore config chat ${values.chat}". ` +
254
506
  'To use it for one run, pass --chat alongside a file or a command.',
255
507
  )
256
508
  }
257
509
 
258
- if (values.help || first === undefined || first === 'help') {
259
- return { command: 'help', args: [], options: values, filesAfterNote }
510
+ if (first === undefined) {
511
+ return { command: 'help', args: [], options: values, filesAfterNote, childArgv, shortcut: null }
260
512
  }
261
513
 
514
+ const shortcut = SHORTCUTS.get(first)
515
+ if (shortcut) return shortcut(rest, values, filesAfterNote)
516
+
262
517
  if (SUBCOMMANDS.has(first)) {
263
- return { command: first, args: rest, options: values, filesAfterNote }
518
+ return { command: first, args: rest, options: values, filesAfterNote, childArgv, shortcut: null }
264
519
  }
265
520
 
266
521
  // Every positional, not just the first: `telstore a b c` used to upload `a` and drop the
267
522
  // rest without a word, which is the one thing this project never does.
268
- return { command: 'upload', args: positionals, options: values, filesAfterNote }
523
+ return { command: 'upload', args: positionals, options: values, filesAfterNote, childArgv, shortcut: null }
269
524
  }
package/src/client.js CHANGED
@@ -76,9 +76,15 @@ async function* iterMessagePages(client, peer, { search, what, options }) {
76
76
  max = Infinity,
77
77
  retryOptions = {},
78
78
  stallMs = DEFAULT_STALL_MS,
79
+ // Where the walk begins, as the id of the message just above the first one wanted. 0 is
80
+ // "the newest in the chat", which is what list asks for. delete starts at a backup's own
81
+ // manifest instead when the chat has shown it one: the manifest is the last message a
82
+ // backup's run sends, so nothing of that backup is newer, and everything posted since is
83
+ // a page of documents read for nothing.
84
+ offsetId: startId = 0,
79
85
  } = options
80
86
 
81
- let offsetId = 0
87
+ let offsetId = startId
82
88
  let read = 0
83
89
 
84
90
  while (read < max) {