visendx 0.0.0-stage → 1.0.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/bin/visend.js ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ //
3
+ // visend - send files and text to yourself via Telegram.
4
+ // visend is a fast cross-platform tool way to send anything to telegram.
5
+ //
6
+ // Author: vishota
7
+ // Repo: https://github.com/vishota/visend
8
+ // Docs: https://github.com/vishota/visend#readme
9
+ //
10
+ 'use strict';
11
+
12
+ require('../lib/cli').main();
package/lib/binary.js ADDED
@@ -0,0 +1,77 @@
1
+ 'use strict';
2
+
3
+ const SAMPLE_SIZE = 8192;
4
+
5
+ /**
6
+ * Heuristic binary-content detection for piped data the user is about to
7
+ * send as text: NUL bytes, invalid UTF-8 or a high ratio of control chars.
8
+ */
9
+ function inspect(buf) {
10
+ let sample = buf.length > SAMPLE_SIZE ? buf.slice(0, SAMPLE_SIZE) : buf;
11
+ for (let i = 0; i < sample.length; i++) {
12
+ if (sample[i] === 0) return { binary: true, reason: 'contains NUL bytes' };
13
+ }
14
+ if (sample.length < buf.length) {
15
+ // A multi-byte char split at the sample edge must not read as invalid
16
+ // UTF-8 (Cyrillic files would trip the binary warning ~50% of the
17
+ // time): strip the trailing incomplete sequence before decoding.
18
+ let back = 0;
19
+ while (back < 3 && sample.length - 1 - back >= 0 && (sample[sample.length - 1 - back] & 0xc0) === 0x80) {
20
+ back++;
21
+ }
22
+ const leadIdx = sample.length - 1 - back;
23
+ if (leadIdx >= 0) {
24
+ const lead = sample[leadIdx];
25
+ if (lead >= 0xc2 && lead <= 0xf4) {
26
+ const need = lead < 0xe0 ? 1 : lead < 0xf0 ? 2 : 3;
27
+ if (back < need) sample = sample.slice(0, leadIdx);
28
+ }
29
+ // A byte that is not a lead byte here means the invalid sequence is
30
+ // fully inside the sample - keep it so real invalid UTF-8 is caught.
31
+ }
32
+ }
33
+ const text = sample.toString('utf8');
34
+ if (text.indexOf('\uFFFD') !== -1) {
35
+ // A literal U+FFFD in the bytes (EF BF BD) is VALID UTF-8 - text that was
36
+ // mangled by an earlier conversion should not be flagged as binary. Only
37
+ // replacement chars the decoder produced for broken sequences count.
38
+ let literal = 0;
39
+ for (let i = 0; i + 2 < sample.length; i++) {
40
+ if (sample[i] === 0xef && sample[i + 1] === 0xbf && sample[i + 2] === 0xbd) literal++;
41
+ }
42
+ let decoded = 0;
43
+ for (let i = 0; i < text.length; i++) {
44
+ if (text.charCodeAt(i) === 0xfffd) decoded++;
45
+ }
46
+ if (decoded > literal) return { binary: true, reason: 'is not valid UTF-8' };
47
+ }
48
+ let control = 0;
49
+ for (let i = 0; i < text.length; i++) {
50
+ const code = text.charCodeAt(i);
51
+ if ((code < 32 && code !== 9 && code !== 10 && code !== 13) || code === 127) control++;
52
+ }
53
+ if (text.length && control / text.length > 0.05) {
54
+ return { binary: true, reason: 'contains many control characters' };
55
+ }
56
+ return { binary: false, reason: '' };
57
+ }
58
+
59
+ // One-line escaped preview of the first `limit` bytes.
60
+ function preview(buf, limit) {
61
+ const n = Math.min(buf.length, limit === undefined ? 64 : limit);
62
+ let text = buf.slice(0, n).toString('utf8');
63
+ let out = '';
64
+ for (let i = 0; i < text.length; i++) {
65
+ const ch = text[i];
66
+ const code = text.charCodeAt(i);
67
+ if (ch === '\n') out += '\\n';
68
+ else if (ch === '\r') out += '\\r';
69
+ else if (ch === '\t') out += '\\t';
70
+ else if (code < 32 || code === 127) out += '\\x' + code.toString(16).padStart(2, '0');
71
+ else out += ch;
72
+ }
73
+ if (buf.length > n) out += '...';
74
+ return out;
75
+ }
76
+
77
+ module.exports = { inspect: inspect, preview: preview };
package/lib/cli.js ADDED
@@ -0,0 +1,126 @@
1
+ 'use strict';
2
+
3
+ const { VisendError } = require('./errors');
4
+ const stdin = require('./stdin');
5
+
6
+ const commands = {
7
+ setup: require('./commands/setup'),
8
+ text: require('./commands/text'),
9
+ file: require('./commands/file'),
10
+ forget: require('./commands/forget'),
11
+ server: require('./commands/server'),
12
+ settings: require('./commands/settings'),
13
+ help: require('./commands/help'),
14
+ };
15
+
16
+ const VALID_COMMANDS = ['setup', 'text', 'file', 'forget', 'server', 'settings', 'help'];
17
+
18
+ const VERSION = require('../package.json').version;
19
+
20
+ function usageError(argv) {
21
+ throw new VisendError(
22
+ 'Unknown command "' + argv[0] + '". Run `visend help` to see the available commands.'
23
+ );
24
+ }
25
+
26
+ function parseArgs(argv) {
27
+ const positionals = [];
28
+ const flags = { yes: false, forceAsText: false, name: null, help: false, version: false };
29
+ for (let i = 0; i < argv.length; i++) {
30
+ const a = argv[i];
31
+ if (a === '--') {
32
+ for (let j = i + 1; j < argv.length; j++) positionals.push(argv[j]);
33
+ break;
34
+ }
35
+ if (a === '-y' || a === '--yes') {
36
+ flags.yes = true;
37
+ } else if (a === '--force-as-text') {
38
+ flags.forceAsText = true;
39
+ } else if (a === '-h' || a === '--help') {
40
+ flags.help = true;
41
+ } else if (a === '-v' || a === '--version') {
42
+ flags.version = true;
43
+ } else if (a === '--name') {
44
+ if (i + 1 >= argv.length) throw new VisendError('--name requires a value: --name <name>');
45
+ const next = argv[i + 1];
46
+ // A following flag is almost certainly a mistake ("--name --yes")
47
+ // rather than a file name that starts with a dash; use --name=<value>.
48
+ if (next.length > 1 && next.indexOf('-') === 0) {
49
+ throw new VisendError('--name requires a value: --name <name> (for a name starting with "-", use --name=<name>)');
50
+ }
51
+ flags.name = next;
52
+ i++;
53
+ } else if (a.indexOf('--') === 0 && a.indexOf('=') !== -1) {
54
+ const eq = a.indexOf('=');
55
+ const key = a.slice(2, eq);
56
+ const value = a.slice(eq + 1);
57
+ if (key === 'name') flags.name = value;
58
+ else if (key === 'yes') {
59
+ if (value !== 'true') throw new VisendError('--yes does not take a value (use -y / --yes on its own).');
60
+ flags.yes = true;
61
+ } else if (key === 'force-as-text') {
62
+ if (value !== 'true') throw new VisendError('--force-as-text does not take a value (use it on its own).');
63
+ flags.forceAsText = true;
64
+ } else throw new VisendError('Unknown flag "--' + key + '". Run `visend help`.');
65
+ } else if (a.indexOf('-') === 0 && a.length > 1 && !(a === '-')) {
66
+ throw new VisendError('Unknown flag "' + a + '". Run `visend help`.');
67
+ } else {
68
+ positionals.push(a);
69
+ }
70
+ }
71
+ return { positionals: positionals, flags: flags };
72
+ }
73
+
74
+ async function main() {
75
+ const argv = process.argv.slice(2);
76
+ const parsed = parseArgs(argv);
77
+ const positionals = parsed.positionals;
78
+ const flags = parsed.flags;
79
+
80
+ if (flags.version) {
81
+ process.stdout.write('visend ' + VERSION + '\n');
82
+ return;
83
+ }
84
+
85
+ let cmd = positionals.shift();
86
+ if (cmd === undefined) {
87
+ // Bare `visend`: piped data means `text`, otherwise `help`.
88
+ cmd = stdin.isPiped() ? 'text' : 'help';
89
+ }
90
+ if (cmd === 'help' || flags.help) {
91
+ cmd = 'help';
92
+ } else if (VALID_COMMANDS.indexOf(cmd) === -1) {
93
+ usageError([cmd]);
94
+ }
95
+
96
+ await commands[cmd].run(positionals, flags);
97
+ }
98
+
99
+ function entry() {
100
+ // A closed downstream pipe (`visend help | head`) must not crash the
101
+ // process with an unhandled EPIPE on stdout.
102
+ process.stdout.on('error', function (err) {
103
+ if (err && err.code === 'EPIPE') process.exit(0);
104
+ throw err;
105
+ });
106
+ process.stderr.on('error', function (err) {
107
+ if (err && err.code === 'EPIPE') process.exit(0);
108
+ throw err;
109
+ });
110
+ main().then(
111
+ function () {
112
+ // Not process.exit(): pending async stdout writes (pipes on macOS,
113
+ // TTY on Windows) would be dropped on a hard exit.
114
+ process.exitCode = 0;
115
+ },
116
+ function (err) {
117
+ const msg = err && err.name === 'VisendError'
118
+ ? err.message
119
+ : (err && err.stack ? err.stack : String(err));
120
+ process.stderr.write('Error: ' + msg + '\n');
121
+ process.exitCode = 1;
122
+ }
123
+ );
124
+ }
125
+
126
+ module.exports = { main: entry };
@@ -0,0 +1,78 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const send = require('../send');
6
+ const stdin = require('../stdin');
7
+ const { VisendError } = require('../errors');
8
+
9
+ const TELEGRAM_FILE_LIMIT = 50 * 1024 * 1024;
10
+
11
+ async function run(args, flags) {
12
+ const pathArg = args[0];
13
+ const fromStdinMarker = pathArg === '-'; // conventional "read stdin" idiom
14
+ const usePath = pathArg && !fromStdinMarker;
15
+ const hasStdin = stdin.isPiped();
16
+ let buf;
17
+ let name;
18
+
19
+ if (usePath && hasStdin) {
20
+ process.stderr.write('Warning: stdin ignored - the file path takes priority.\n');
21
+ }
22
+
23
+ if (usePath) {
24
+ let st;
25
+ try {
26
+ st = fs.statSync(pathArg);
27
+ } catch (err) {
28
+ throw new VisendError('Cannot read "' + pathArg + '": ' + err.message);
29
+ }
30
+ if (st.isDirectory()) {
31
+ throw new VisendError('"' + pathArg + '" is a directory. Pass a file path.');
32
+ }
33
+ // Check by stat BEFORE reading: a multi-GB file must not be pulled
34
+ // into memory (and readFileSync would die with a raw RangeError
35
+ // past ~2 GB) just to be rejected afterwards.
36
+ if (st.size > TELEGRAM_FILE_LIMIT) {
37
+ const mb = Math.round(st.size / (1024 * 1024) * 10) / 10;
38
+ throw new VisendError(
39
+ 'The file is ' + mb + ' MB, but Telegram bots can only send files up to 50 MB.'
40
+ );
41
+ }
42
+ try {
43
+ buf = fs.readFileSync(pathArg);
44
+ } catch (err) {
45
+ throw new VisendError('Cannot read "' + pathArg + '": ' + err.message);
46
+ }
47
+ name = flags.name || path.basename(pathArg);
48
+ } else if (hasStdin) {
49
+ buf = await stdin.readAll();
50
+ if (!buf.length) {
51
+ throw new VisendError(
52
+ 'Nothing to send - stdin is empty. Pipe something in (`cat report.pdf | visend file`)' +
53
+ ' or pass a file path (`visend file report.pdf`).'
54
+ );
55
+ }
56
+ name = flags.name || 'visend.txt';
57
+ } else {
58
+ throw new VisendError(
59
+ 'Nothing to send. Pipe something in (`cat report.pdf | visend file`)' +
60
+ ' or pass a file path (`visend file report.pdf`).'
61
+ );
62
+ }
63
+
64
+ const cfg = send.requireConfig();
65
+
66
+ if (buf.length > TELEGRAM_FILE_LIMIT) {
67
+ const mb = Math.round(buf.length / (1024 * 1024) * 10) / 10;
68
+ throw new VisendError(
69
+ 'The file is ' + mb + ' MB, but Telegram bots can only send files up to 50 MB.'
70
+ );
71
+ }
72
+
73
+ process.stdout.write(
74
+ await send.deliverFile(cfg, buf, name) + '\n'
75
+ );
76
+ }
77
+
78
+ module.exports = { run: run };
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+
3
+ const config = require('../config');
4
+ const tty = require('../tty');
5
+ const { VisendError } = require('../errors');
6
+
7
+ async function run(args, flags) {
8
+ const path = config.configPath();
9
+ let existing = null;
10
+ try {
11
+ existing = config.load();
12
+ } catch (err) {
13
+ existing = {};
14
+ }
15
+ const hasAnything = !!(existing.mode || existing.bot_token || existing.server_token || existing.user_id);
16
+ if (!hasAnything) {
17
+ process.stdout.write('Nothing to forget - visend is not configured.\n');
18
+ return;
19
+ }
20
+ const ok = await tty.confirm(
21
+ 'Delete all visend settings (bot token, server token, user id)? The server URL is kept.',
22
+ flags.yes
23
+ );
24
+ if (!ok) throw new VisendError('Aborted.');
25
+ // Everything except the server URL.
26
+ config.save({ server_url: existing.server_url });
27
+ process.stdout.write('Settings removed (' + path + '). Run `visend setup` to start over.\n');
28
+ }
29
+
30
+ module.exports = { run: run };
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ const HELP = [
4
+ 'visend - send files and text to yourself via Telegram',
5
+ '',
6
+ 'Usage:',
7
+ ' visend same as `visend text` when stdin is piped,',
8
+ ' otherwise shows this help',
9
+ ' visend text [text...] [--force-as-text]',
10
+ ' send text; multiple arguments are joined with',
11
+ ' spaces; piped stdin is sent as the text',
12
+ ' visend file [path] [--name <name>] send a file; with piped stdin sends it as a',
13
+ ' file named visend.txt (or --name);',
14
+ ' `visend file -` reads the file from stdin',
15
+ ' visend setup pair visend with your Telegram (own bot or',
16
+ ' shared server)',
17
+ ' visend settings show current settings',
18
+ ' visend forget [-y|--yes] delete all settings except the server URL',
19
+ ' visend server show server URL, status and bot link',
20
+ ' visend server set <url> [-y|--yes] switch to another visend server',
21
+ ' visend server reset [-y|--yes] switch back to the default server',
22
+ ' visend help show this help',
23
+ '',
24
+ 'Options:',
25
+ ' -y, --yes answer "yes" to all confirmation prompts',
26
+ ' --name <name> file name to use for `visend file`',
27
+ ' --force-as-text send text longer than 4096 chars as text anyway (it will be cut',
28
+ ' to the Telegram limit)',
29
+ ' -v, --version print the version and exit',
30
+ ' -h, --help show this help',
31
+ '',
32
+ 'Flags go after positional arguments: `visend text hello --force-as-text`.',
33
+ 'Use `--` to send an argument that starts with a dash: `visend text -- "-not a flag"`.',
34
+ '',
35
+ 'Examples:',
36
+ ' ls | visend',
37
+ ' cat log.txt | visend text',
38
+ ' visend text hello world',
39
+ ' visend file report.pdf',
40
+ ' cat data.csv | visend file --name data.csv',
41
+ '',
42
+ 'Docs: https://github.com/vishota/visend',
43
+ ].join('\n');
44
+
45
+ async function run() {
46
+ process.stdout.write(HELP + '\n');
47
+ }
48
+
49
+ module.exports = { run: run };
@@ -0,0 +1,173 @@
1
+ 'use strict';
2
+
3
+ const config = require('../config');
4
+ const serverapi = require('../serverapi');
5
+ const tty = require('../tty');
6
+ const { VisendError } = require('../errors');
7
+
8
+ function out(line) {
9
+ process.stdout.write(line + '\n');
10
+ }
11
+
12
+ function warn(line) {
13
+ process.stderr.write('Warning: ' + line + '\n');
14
+ }
15
+
16
+ function humanizeUptime(seconds) {
17
+ const s = Math.max(0, Math.floor(seconds));
18
+ const h = Math.floor(s / 3600);
19
+ const m = Math.floor((s % 3600) / 60);
20
+ if (h) return h + 'h ' + m + 'm';
21
+ if (m) return m + 'm ' + (s % 60) + 's';
22
+ return s + 's';
23
+ }
24
+
25
+ async function showStatus() {
26
+ const cfg = config.load();
27
+ const url = config.effectiveServerUrl(cfg);
28
+ out('Server: ' + url);
29
+ try {
30
+ const status = await serverapi.fetchStatus(url);
31
+ out('Status: online (uptime ' + humanizeUptime(status.uptime_seconds || 0) + ')');
32
+ } catch (err) {
33
+ out('Status: unreachable - the server did not respond.');
34
+ out('');
35
+ out('You can host your own visend server from the official docker image and point');
36
+ out('visend at it with `visend server set <url>` - see the README (Self-hosting).');
37
+ return;
38
+ }
39
+ try {
40
+ const cfgInfo = await serverapi.fetchConfig(url);
41
+ if (cfgInfo.bot) {
42
+ out('Bot: ' + cfgInfo.bot + ' (send /start to it to get your user id and a code)');
43
+ }
44
+ } catch (err) {
45
+ out('Bot: unknown (could not fetch server config).');
46
+ }
47
+ }
48
+
49
+ function normalizeUrl(raw) {
50
+ const text = String(raw || '').trim();
51
+ if (!/^https?:\/\//i.test(text)) {
52
+ throw new VisendError('Invalid URL "' + raw + '": it must start with http:// or https://');
53
+ }
54
+ let u;
55
+ try {
56
+ u = new URL(text);
57
+ } catch (err) {
58
+ throw new VisendError('Invalid URL "' + raw + '": ' + err.message);
59
+ }
60
+ if (!u.hostname) {
61
+ throw new VisendError('Invalid URL "' + raw + '": the host part is missing.');
62
+ }
63
+ // Things that would silently break every later request to this URL.
64
+ if (u.username || u.password) {
65
+ throw new VisendError('Invalid URL "' + raw + '": credentials in the URL are not supported.');
66
+ }
67
+ if (u.search || u.hash) {
68
+ throw new VisendError('Invalid URL "' + raw + '": query strings and #fragments are not supported.');
69
+ }
70
+ if (u.pathname.indexOf('//') !== -1) {
71
+ throw new VisendError('Invalid URL "' + raw + '": empty path segments (//) are not supported.');
72
+ }
73
+ return u.origin + u.pathname.replace(/\/+$/, '');
74
+ }
75
+
76
+ // Persist the new URL; wipe the server token in server mode (the new server
77
+ // will not accept it) and tell the user to re-run setup.
78
+ async function applyServerUrl(newUrl, yes) {
79
+ const cfg = config.load();
80
+ const current = config.effectiveServerUrl(cfg);
81
+ const unchanged = newUrl === current;
82
+ cfg.server_url = newUrl === config.DEFAULT_SERVER_URL ? '' : newUrl;
83
+ if (unchanged) {
84
+ config.save(cfg);
85
+ out('Server URL is already ' + newUrl + ' - nothing to change.');
86
+ return;
87
+ }
88
+ if (cfg.mode === 'server' && (cfg.server_token || cfg.server_refresh_token)) {
89
+ delete cfg.server_token;
90
+ delete cfg.server_refresh_token;
91
+ config.save(cfg);
92
+ out('Server URL saved.');
93
+ out('');
94
+ out('Note: for security the old token pair has been removed - the new server will');
95
+ out('not accept it. Run `visend setup` again and enter a new one-time code.');
96
+ return;
97
+ }
98
+ config.save(cfg);
99
+ out('Server URL saved.');
100
+ }
101
+
102
+ async function setUrl(rawUrl, yes) {
103
+ const url = normalizeUrl(rawUrl);
104
+ if (/^http:\/\//i.test(url)) {
105
+ warn('this URL uses plain http:// - your pairing code, token and data will');
106
+ warn('travel over the network unencrypted.');
107
+ const ok = await tty.confirm('Continue anyway?', yes);
108
+ if (!ok) throw new VisendError('Aborted.');
109
+ }
110
+ out('Checking ' + url + ' ...');
111
+ let online = false;
112
+ try {
113
+ await serverapi.fetchStatus(url);
114
+ online = true;
115
+ } catch (err) {
116
+ online = false;
117
+ }
118
+ if (online) {
119
+ out('Server is up.');
120
+ } else {
121
+ warn('the server did not respond.');
122
+ const ok = await tty.confirm('Save this URL anyway?', yes);
123
+ if (!ok) throw new VisendError('Aborted.');
124
+ }
125
+ await applyServerUrl(url, yes);
126
+ }
127
+
128
+ async function reset(yes) {
129
+ // No-op detection first: don't ask for confirmation on a no-op.
130
+ const cfgNow = config.load();
131
+ if (!cfgNow.server_url) {
132
+ out('The server URL is already the default.');
133
+ return;
134
+ }
135
+ out('Reset the server URL to ' + config.DEFAULT_SERVER_URL + '?');
136
+ const ok = await tty.confirm('Continue?', yes);
137
+ if (!ok) throw new VisendError('Aborted.');
138
+ out('Checking ' + config.DEFAULT_SERVER_URL + ' ...');
139
+ let online = false;
140
+ try {
141
+ await serverapi.fetchStatus(config.DEFAULT_SERVER_URL);
142
+ online = true;
143
+ } catch (err) {
144
+ online = false;
145
+ }
146
+ if (!online) {
147
+ warn('the default server did not respond.');
148
+ const ok2 = await tty.confirm('Reset anyway?', yes);
149
+ if (!ok2) throw new VisendError('Aborted.');
150
+ }
151
+ await applyServerUrl(config.DEFAULT_SERVER_URL, yes);
152
+ }
153
+
154
+ async function run(args, flags) {
155
+ const sub = args[0];
156
+ if (sub === 'set') {
157
+ if (!args[1]) {
158
+ throw new VisendError('Usage: visend server set <url> e.g. visend server set http://example.com:6767/test/misc/visend');
159
+ }
160
+ await setUrl(args[1], flags.yes);
161
+ return;
162
+ }
163
+ if (sub === 'reset') {
164
+ await reset(flags.yes);
165
+ return;
166
+ }
167
+ if (sub) {
168
+ throw new VisendError('Unknown subcommand "' + sub + '". Use `visend server`, `visend server set <url>` or `visend server reset`.');
169
+ }
170
+ await showStatus();
171
+ }
172
+
173
+ module.exports = { run: run };
@@ -0,0 +1,25 @@
1
+ 'use strict';
2
+
3
+ const config = require('../config');
4
+
5
+ function mask(secret) {
6
+ // Fully masked: even first/last characters of a secret half-leak it.
7
+ return secret ? '****' : 'not set';
8
+ }
9
+
10
+ async function run() {
11
+ const cfg = config.load();
12
+ const out = process.stdout;
13
+ out.write('Settings file: ' + config.configPath() + '\n');
14
+ if (cfg.mode === 'bot') out.write('Mode: own bot (direct Telegram API)\n');
15
+ else if (cfg.mode === 'server') out.write('Mode: shared server\n');
16
+ else out.write('Mode: not configured (run `visend setup`)\n');
17
+ out.write('User id: ' + (cfg.user_id || 'not set') + '\n');
18
+ out.write('Server URL: ' + config.effectiveServerUrl(cfg) +
19
+ (cfg.server_url ? '' : ' (default)') + '\n');
20
+ out.write('Bot token: ' + mask(cfg.bot_token) + '\n');
21
+ out.write('Server token: ' + mask(cfg.server_token) + '\n');
22
+ out.write('Refresh token: ' + mask(cfg.server_refresh_token) + '\n');
23
+ }
24
+
25
+ module.exports = { run: run };