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.
@@ -0,0 +1,265 @@
1
+ 'use strict';
2
+
3
+ const config = require('../config');
4
+ const telegram = require('../telegram');
5
+ const serverapi = require('../serverapi');
6
+ const send = require('../send');
7
+ const tty = require('../tty');
8
+ const { VisendError } = require('../errors');
9
+
10
+ // How long to wait for /start before falling back to manual user id input.
11
+ // VISEND_TEST_WAIT_MS exists for the test-suite only.
12
+ const WAIT_LIMIT_MS = Number(process.env.VISEND_TEST_WAIT_MS) || 120000;
13
+
14
+ function out(line) {
15
+ process.stdout.write(line + '\n');
16
+ }
17
+
18
+ function warn(line) {
19
+ process.stderr.write('Warning: ' + line + '\n');
20
+ }
21
+
22
+ async function chooseMode(serverUrl) {
23
+ let status = null;
24
+ let cfgInfo = null;
25
+ // Fetched separately: a /status that works with a /config that fails must
26
+ // still offer pairing (only the bot link is missing), not disable it.
27
+ try {
28
+ status = await serverapi.fetchStatus(serverUrl);
29
+ } catch (err) {
30
+ status = null;
31
+ }
32
+ if (status) {
33
+ try {
34
+ cfgInfo = await serverapi.fetchConfig(serverUrl);
35
+ } catch (err) {
36
+ cfgInfo = null;
37
+ }
38
+ }
39
+ for (;;) {
40
+ out('How do you want to receive your messages?');
41
+ out('');
42
+ out(' 1) Through the shared visend server (' + serverUrl + ')' +
43
+ (status ? '' : ' [currently unavailable]'));
44
+ out(' 2) Through my own Telegram bot (needs a token from @BotFather)');
45
+ out(' 3) Cancel');
46
+ const answer = (await tty.prompt('Choice [1-3]: ')).trim();
47
+ if (answer === '3') throw new VisendError('Setup cancelled.');
48
+ if (answer === '1') {
49
+ if (!status) {
50
+ out('');
51
+ out('The configured server did not respond, so this option is unavailable right now.');
52
+ out('Check `visend server` for details, or host your own server (see README).');
53
+ out('');
54
+ continue;
55
+ }
56
+ return { mode: 'server', status: status, config: cfgInfo };
57
+ }
58
+ if (answer === '2') return { mode: 'bot' };
59
+ out('Please enter 1, 2 or 3.');
60
+ out('');
61
+ }
62
+ }
63
+
64
+ async function setupServer(serverUrl, statusInfo, cfgInfo) {
65
+ out('');
66
+ out('Warning: with the shared server your text, files and pairing codes pass through');
67
+ out('a third-party server before reaching Telegram. Treat it as a dev tool - do not use');
68
+ out('it for sensitive data. For full control you can host your own server from the');
69
+ out('official docker image - see `visend server` and the README.');
70
+ out('');
71
+ const botLink = (cfgInfo && cfgInfo.bot) || null;
72
+ if (botLink) {
73
+ out('1. Open ' + botLink + ' and send /start to the bot.');
74
+ } else {
75
+ out('1. Send /start to the visend bot of this server (see `visend server` for the link).');
76
+ }
77
+ out('2. The bot will reply with your user id and a one-time code (valid for 1 hour).');
78
+ out('');
79
+ const userId = await tty.askUserId('Your user id: ');
80
+ const code = (await tty.askRequired('One-time code: ')).toUpperCase();
81
+ out('Connecting to ' + serverUrl + ' ...');
82
+ let token;
83
+ let refreshToken;
84
+ try {
85
+ const result = await serverapi.connect(serverUrl, userId, code);
86
+ token = result.token;
87
+ refreshToken = result.refresh_token || '';
88
+ } catch (err) {
89
+ if (err instanceof serverapi.ServerError) {
90
+ if (err.status === 429) throw new VisendError('The server rate-limited you. Wait a minute and try again.');
91
+ if (err.code === 'not_allowed') throw new VisendError('This server does not accept your user id (the admin restricts who can connect).');
92
+ if (err.code === 'code_burned') throw new VisendError('Too many wrong attempts - the code is burned. Send /start to the bot again for a new one.');
93
+ if (err.status === 403) throw new VisendError('The code or user id is wrong (or the code expired). Send /start to the bot again and retry.');
94
+ throw new VisendError('Server connect failed: ' + err.message);
95
+ }
96
+ // Raw network errors (ECONNRESET, TLS failures) must not dump a stack
97
+ // trace mid-setup.
98
+ throw new VisendError('Server connect failed (network error): ' + err.message);
99
+ }
100
+ const cfg = config.load();
101
+ cfg.mode = 'server';
102
+ cfg.user_id = userId;
103
+ cfg.server_token = token;
104
+ if (refreshToken) cfg.server_refresh_token = refreshToken;
105
+ else delete cfg.server_refresh_token;
106
+ config.save(cfg);
107
+ out('Paired with the server.');
108
+ // Confirm end-to-end delivery.
109
+ try {
110
+ await serverapi.sendText(serverUrl, token, Buffer.from('visend is set up! Everything you pipe will arrive here.', 'utf8'));
111
+ out('Test message sent to your Telegram. Setup complete.');
112
+ } catch (err) {
113
+ warn('pairing succeeded, but the test message failed: ' + send.describeServerError(err));
114
+ }
115
+ }
116
+
117
+ function extractStart(updates) {
118
+ for (let i = 0; i < updates.length; i++) {
119
+ const m = updates[i].message;
120
+ if (!m || !m.chat || m.chat.type !== 'private') continue;
121
+ if (typeof m.text !== 'string') continue;
122
+ if (m.text.split(/\s+/)[0] === '/start') {
123
+ const from = m.from || {};
124
+ return { userId: from.id, username: from.username || null };
125
+ }
126
+ }
127
+ return null;
128
+ }
129
+
130
+ async function waitForStart(token, yes) {
131
+ // First call only establishes the baseline update_id; queued (stale)
132
+ // updates are never shown to the user.
133
+ let lastId = 0;
134
+ let first;
135
+ for (;;) {
136
+ try {
137
+ first = await telegram.getUpdates(token);
138
+ break;
139
+ } catch (err) {
140
+ if (err instanceof telegram.TelegramError && err.errorCode === 409) {
141
+ const proceed = await handleWebhookConflict(token, yes);
142
+ if (!proceed) return null;
143
+ continue;
144
+ }
145
+ throw new VisendError('Checking the bot failed (network error): ' + err.message);
146
+ }
147
+ }
148
+ for (let i = 0; i < first.length; i++) {
149
+ if (first[i].update_id > lastId) lastId = first[i].update_id;
150
+ }
151
+ const deadline = Date.now() + WAIT_LIMIT_MS;
152
+ process.stdout.write('Waiting for your /start...');
153
+ for (;;) {
154
+ process.stdout.write('.');
155
+ let updates;
156
+ // Never start a long poll that would outlive the deadline: cap its
157
+ // timeout to the time that is actually left.
158
+ const remainingSec = Math.max(0, Math.ceil((deadline - Date.now()) / 1000));
159
+ if (remainingSec <= 0) {
160
+ process.stdout.write('\n');
161
+ return null;
162
+ }
163
+ try {
164
+ updates = await telegram.getUpdates(token, lastId + 1, Math.min(25, remainingSec));
165
+ } catch (err) {
166
+ if (err instanceof telegram.TelegramError && err.errorCode === 409) {
167
+ process.stdout.write('\n');
168
+ const proceed = await handleWebhookConflict(token, yes);
169
+ if (!proceed) return null;
170
+ out('Continuing to wait...');
171
+ continue;
172
+ }
173
+ throw new VisendError('Waiting for /start failed (network error): ' + err.message);
174
+ }
175
+ // Ack every batch so updates are never processed twice.
176
+ for (let i = 0; i < updates.length; i++) {
177
+ if (updates[i].update_id > lastId) lastId = updates[i].update_id;
178
+ }
179
+ const found = extractStart(updates);
180
+ if (found) {
181
+ process.stdout.write('\n');
182
+ return found;
183
+ }
184
+ if (Date.now() >= deadline) {
185
+ process.stdout.write('\n');
186
+ return null;
187
+ }
188
+ }
189
+ }
190
+
191
+ async function handleWebhookConflict(token, yes) {
192
+ out('Another getUpdates poller or a webhook is active on this bot (HTTP 409).');
193
+ out('This usually means the bot is used by another integration.');
194
+ const drop = await tty.confirm(
195
+ 'Delete the webhook? WARNING: this will break the existing integration.', yes
196
+ );
197
+ if (!drop) return false;
198
+ await telegram.deleteWebhook(token);
199
+ out('Webhook deleted.');
200
+ return true;
201
+ }
202
+
203
+ async function setupBot(yes) {
204
+ const token = (await tty.askRequired('Bot token (from @BotFather): ')).trim();
205
+ if (!/^\d{5,}:[A-Za-z0-9_-]{30,}$/.test(token)) {
206
+ throw new VisendError('That does not look like a bot token. Expected format: 123456789:AA...');
207
+ }
208
+ let me;
209
+ try {
210
+ me = await telegram.getMe(token);
211
+ } catch (err) {
212
+ throw new VisendError('Token check (getMe) failed: ' + err.message);
213
+ }
214
+ out('Token is valid. Bot: @' + (me.username || me.first_name));
215
+ out('');
216
+ out('Now open Telegram and send /start to @' + (me.username || 'your bot') + '.');
217
+ const found = await waitForStart(token, yes);
218
+ let userId;
219
+ if (found) {
220
+ out('Got it: user_id ' + found.userId + (found.username ? ' (@' + found.username + ')' : ' (no @username)'));
221
+ const answer = await tty.prompt(
222
+ 'Press Enter to save this user id, or type another one (yours from @userinfobot): '
223
+ );
224
+ const trimmed = answer.trim();
225
+ if (!trimmed) {
226
+ userId = found.userId;
227
+ } else if (/^\d{1,16}$/.test(trimmed)) {
228
+ userId = Number(trimmed);
229
+ } else {
230
+ out('That is not a valid id; saving the detected one (' + found.userId + ').');
231
+ userId = found.userId;
232
+ }
233
+ } else {
234
+ out('Timed out after ' + Math.round(WAIT_LIMIT_MS / 1000) + ' seconds waiting for /start.');
235
+ userId = await tty.askUserId('Enter your user id manually (yours from @userinfobot): ');
236
+ }
237
+ const cfg = config.load();
238
+ cfg.mode = 'bot';
239
+ cfg.bot_token = token;
240
+ cfg.user_id = userId;
241
+ config.save(cfg);
242
+ out('Saved.');
243
+ try {
244
+ await telegram.sendMessage(token, userId, 'visend is set up! Everything you pipe will arrive here.');
245
+ out('Test message sent to your Telegram. Setup complete.');
246
+ } catch (err) {
247
+ warn('settings saved, but the test message failed: ' + send.describeTelegramError(err));
248
+ }
249
+ }
250
+
251
+ async function run(args, flags) {
252
+ const cfg = config.load();
253
+ const serverUrl = config.effectiveServerUrl(cfg);
254
+ out('visend setup');
255
+ out('');
256
+ const choice = await chooseMode(serverUrl);
257
+ out('');
258
+ if (choice.mode === 'server') {
259
+ await setupServer(serverUrl, choice.status, choice.config);
260
+ } else {
261
+ await setupBot(flags.yes);
262
+ }
263
+ }
264
+
265
+ module.exports = { run: run };
@@ -0,0 +1,95 @@
1
+ 'use strict';
2
+
3
+ const binary = require('../binary');
4
+ const send = require('../send');
5
+ const stdin = require('../stdin');
6
+ const tty = require('../tty');
7
+ const { VisendError } = require('../errors');
8
+
9
+ const TELEGRAM_TEXT_LIMIT = 4096;
10
+
11
+ // Truncate to the Telegram limit in UTF-16 code units without splitting a
12
+ // surrogate pair: a lone high surrogate would re-encode as U+FFFD and leave
13
+ // a mangled character at the end of the message.
14
+ function truncateToLimit(buf, limit) {
15
+ const text = buf.toString('utf8');
16
+ let cut = text.slice(0, limit);
17
+ const tail = cut.charCodeAt(limit - 1);
18
+ if (tail >= 0xd800 && tail <= 0xdbff) cut = cut.slice(0, limit - 1);
19
+ return Buffer.from(cut, 'utf8');
20
+ }
21
+
22
+ async function run(args, flags) {
23
+ const hasTextArg = args.length > 0;
24
+ const textArg = args.join(' ');
25
+ const hasStdin = stdin.isPiped();
26
+ let buf = null;
27
+
28
+ if (hasTextArg && !textArg.trim()) {
29
+ throw new VisendError(
30
+ 'The text argument is empty. Pass the text to send: `visend text hello world`.'
31
+ );
32
+ }
33
+ if (hasTextArg && hasStdin) {
34
+ process.stderr.write('Warning: stdin ignored - the text argument takes priority.\n');
35
+ }
36
+ if (hasTextArg) {
37
+ buf = Buffer.from(textArg, 'utf8');
38
+ } else if (hasStdin) {
39
+ buf = await stdin.readAll();
40
+ if (!buf.length) {
41
+ throw new VisendError(
42
+ 'Nothing to send - stdin is empty. Pipe something in (`cat notes.txt | visend text`)' +
43
+ ' or pass the text as an argument (`visend text hello world`).'
44
+ );
45
+ }
46
+ } else {
47
+ throw new VisendError(
48
+ 'Nothing to send. Pipe something in (`cat notes.txt | visend text`)' +
49
+ ' or pass the text as an argument (`visend text hello world`).'
50
+ );
51
+ }
52
+
53
+ // Binary check runs before the length check.
54
+ const detected = binary.inspect(buf);
55
+ if (detected.binary) {
56
+ process.stderr.write(
57
+ 'Warning: the input looks like binary data (' + detected.reason + ').\n' +
58
+ 'First bytes: ' + binary.preview(buf) + '\n'
59
+ );
60
+ const ok = await tty.confirm('Send it as text anyway?', flags.yes);
61
+ if (!ok) {
62
+ throw new VisendError('Aborted. Use `visend file` to send binary data as a file.');
63
+ }
64
+ }
65
+
66
+ const charCount = buf.toString('utf8').length;
67
+
68
+ if (flags.forceAsText) {
69
+ if (charCount > TELEGRAM_TEXT_LIMIT) {
70
+ process.stderr.write(
71
+ 'Warning: the input is ' + charCount + ' characters; Telegram cuts messages at ' +
72
+ TELEGRAM_TEXT_LIMIT + ' characters. Sending the first ' + TELEGRAM_TEXT_LIMIT + ' (--force-as-text).\n'
73
+ );
74
+ const cut = truncateToLimit(buf, TELEGRAM_TEXT_LIMIT);
75
+ process.stdout.write(await send.deliverText(send.requireConfig(), cut) + '\n');
76
+ return;
77
+ }
78
+ process.stdout.write(await send.deliverText(send.requireConfig(), buf) + '\n');
79
+ return;
80
+ }
81
+
82
+ if (charCount > TELEGRAM_TEXT_LIMIT) {
83
+ process.stderr.write(
84
+ 'Warning: the input is ' + charCount + ' characters, but Telegram messages are capped at ' +
85
+ TELEGRAM_TEXT_LIMIT + ' characters. Sending it as a file "visend.txt" instead.' +
86
+ ' Use --force-as-text to send it as text anyway (it will be cut).\n'
87
+ );
88
+ process.stdout.write(await send.deliverFile(send.requireConfig(), buf, 'visend.txt') + '\n');
89
+ return;
90
+ }
91
+
92
+ process.stdout.write(await send.deliverText(send.requireConfig(), buf) + '\n');
93
+ }
94
+
95
+ module.exports = { run: run };
package/lib/config.js ADDED
@@ -0,0 +1,186 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const crypto = require('crypto');
7
+ const { execFileSync } = require('child_process');
8
+ const { VisendError } = require('./errors');
9
+
10
+ const DEFAULT_SERVER_URL = 'https://visend.vishota.com';
11
+
12
+ // Keys of config.json. Shared with the bash and powershell implementations.
13
+ const KEYS = ['mode', 'bot_token', 'user_id', 'server_url', 'server_token', 'server_refresh_token'];
14
+
15
+ function configDir() {
16
+ return path.join(os.homedir(), '.config', 'visend');
17
+ }
18
+
19
+ function configPath() {
20
+ return path.join(configDir(), 'config.json');
21
+ }
22
+
23
+ function load() {
24
+ let raw;
25
+ try {
26
+ raw = fs.readFileSync(configPath(), 'utf8');
27
+ } catch (err) {
28
+ if (err.code === 'ENOENT') return {};
29
+ throw new VisendError('Cannot read ' + configPath() + ': ' + err.message);
30
+ }
31
+ // A UTF-8 BOM (e.g. from a legacy Notepad edit) would break JSON.parse.
32
+ raw = raw.replace(/^\uFEFF/, '');
33
+ let parsed;
34
+ try {
35
+ parsed = JSON.parse(raw);
36
+ } catch (err) {
37
+ throw new VisendError(
38
+ 'Settings file is corrupted (' + configPath() + '). ' +
39
+ 'Fix it manually or remove it, then run `visend setup` again.'
40
+ );
41
+ }
42
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
43
+ throw new VisendError(
44
+ 'Settings file is corrupted (' + configPath() + '): expected a JSON object. ' +
45
+ 'Fix it manually or remove it, then run `visend setup` again.'
46
+ );
47
+ }
48
+ const cfg = {};
49
+ for (let i = 0; i < KEYS.length; i++) {
50
+ const key = KEYS[i];
51
+ if (Object.prototype.hasOwnProperty.call(parsed, key) && parsed[key] !== null && parsed[key] !== '') {
52
+ cfg[key] = parsed[key];
53
+ }
54
+ }
55
+ if (cfg.mode && cfg.mode !== 'bot' && cfg.mode !== 'server') delete cfg.mode;
56
+ // A hand-edited or restored config may be world-readable; tighten it.
57
+ if (process.platform !== 'win32') {
58
+ try {
59
+ const st = fs.statSync(configPath());
60
+ if (st.mode & 0o077) {
61
+ process.stderr.write(
62
+ 'Warning: ' + configPath() + ' was readable by other users; permissions tightened to 0600.\n'
63
+ );
64
+ try { fs.chmodSync(configPath(), 0o600); } catch (e) { /* best effort */ }
65
+ }
66
+ } catch (err) { /* unreadable - load() already surfaced the real error */ }
67
+ }
68
+ return cfg;
69
+ }
70
+
71
+ // Restrict permissions to the current user: chmod 600 on POSIX,
72
+ // ACL inheritance removal + explicit grant on Windows. Synchronous on
73
+ // purpose - it must win the race with the atomic rename in save().
74
+ function secure(p, isDir) {
75
+ if (process.platform === 'win32') {
76
+ let user = process.env.USERNAME || '';
77
+ if (process.env.USERDOMAIN) user = process.env.USERDOMAIN + '\\' + user;
78
+ if (!user) {
79
+ process.stderr.write('Warning: could not restrict permissions on ' + p + ' (no USERNAME in the environment)\n');
80
+ return;
81
+ }
82
+ const args = [p, '/inheritance:r', '/grant:r', user + ':' + (isDir ? '(OI)(CI)F' : 'F')];
83
+ try {
84
+ execFileSync('icacls.exe', args, { stdio: 'ignore' });
85
+ } catch (err) {
86
+ process.stderr.write('Warning: could not restrict permissions on ' + p + ' (' + err.message.split('\n')[0] + ')\n');
87
+ }
88
+ } else {
89
+ try {
90
+ fs.chmodSync(p, isDir ? 0o700 : 0o600);
91
+ } catch (err) {
92
+ process.stderr.write(
93
+ 'Warning: could not restrict permissions on ' + p + ' (' + err.message + ')\n'
94
+ );
95
+ }
96
+ }
97
+ }
98
+
99
+ // Block for a few ms without spinning the CPU (Atomics.wait on the main
100
+ // thread is the only synchronous sleep available on Node 10).
101
+ function sleepMs(ms) {
102
+ try {
103
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
104
+ } catch (err) { /* no SharedArrayBuffer: skip the delay */ }
105
+ }
106
+
107
+ // renameSync over an existing file can fail transiently on Windows when an
108
+ // antivirus/indexer briefly holds the target; one short retry removes the
109
+ // most common flakiness.
110
+ function renameWithRetry(from, to) {
111
+ try {
112
+ fs.renameSync(from, to);
113
+ } catch (err) {
114
+ if (process.platform === 'win32' && (err.code === 'EPERM' || err.code === 'EACCES')) {
115
+ sleepMs(100);
116
+ fs.renameSync(from, to);
117
+ } else {
118
+ throw err;
119
+ }
120
+ }
121
+ }
122
+
123
+ // Atomic write: temp file in the same directory, then rename over the target.
124
+ function save(cfg) {
125
+ const dir = configDir();
126
+ const target = configPath();
127
+ const clean = {};
128
+ for (let i = 0; i < KEYS.length; i++) {
129
+ const key = KEYS[i];
130
+ if (cfg[key] !== undefined && cfg[key] !== null && cfg[key] !== '') clean[key] = cfg[key];
131
+ }
132
+ try {
133
+ fs.mkdirSync(dir, { recursive: true });
134
+ } catch (err) {
135
+ if (err.code !== 'EEXIST') throw new VisendError('Cannot create ' + dir + ': ' + err.message);
136
+ }
137
+ secure(dir, true);
138
+ if (Object.keys(clean).length === 0) {
139
+ // This is the `forget` path: only "already gone" may be swallowed. A
140
+ // held-open file (antivirus/indexer on Windows) must surface, or the
141
+ // user believes the token was deleted while it is still on disk.
142
+ try {
143
+ fs.unlinkSync(target);
144
+ } catch (err) {
145
+ if (err.code !== 'ENOENT') {
146
+ throw new VisendError(
147
+ 'Cannot delete ' + target + ': ' + err.message +
148
+ ' - remove the file manually to finish forgetting.'
149
+ );
150
+ }
151
+ }
152
+ return;
153
+ }
154
+ const tmp = path.join(dir, '.config-' + crypto.randomBytes(4).toString('hex') + '.tmp');
155
+ try {
156
+ fs.writeFileSync(tmp, JSON.stringify(clean, null, 2) + '\n', { mode: 0o600 });
157
+ renameWithRetry(tmp, target);
158
+ } catch (err) {
159
+ // Never leave a token-bearing temp file behind on a failed save.
160
+ try { fs.unlinkSync(tmp); } catch (e) { /* already gone */ }
161
+ throw new VisendError('Cannot save settings to ' + target + ': ' + err.message);
162
+ }
163
+ secure(target, false);
164
+ // Sweep leftovers from earlier crashed saves (best effort).
165
+ try {
166
+ const stale = fs.readdirSync(dir).filter(function (f) {
167
+ return f.indexOf('.config-') === 0 && f.slice(-4) === '.tmp';
168
+ });
169
+ for (let i = 0; i < stale.length; i++) {
170
+ try { fs.unlinkSync(path.join(dir, stale[i])); } catch (e) { /* race with a parallel save */ }
171
+ }
172
+ } catch (err) { /* directory unreadable - nothing to sweep */ }
173
+ }
174
+
175
+ function effectiveServerUrl(cfg) {
176
+ return (cfg && cfg.server_url) || DEFAULT_SERVER_URL;
177
+ }
178
+
179
+ module.exports = {
180
+ DEFAULT_SERVER_URL: DEFAULT_SERVER_URL,
181
+ configDir: configDir,
182
+ configPath: configPath,
183
+ load: load,
184
+ save: save,
185
+ effectiveServerUrl: effectiveServerUrl,
186
+ };
package/lib/errors.js ADDED
@@ -0,0 +1,14 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * User-facing error. `main()` catches it, prints the message to stderr
5
+ * and exits with code 1.
6
+ */
7
+ class VisendError extends Error {
8
+ constructor(message) {
9
+ super(message);
10
+ this.name = 'VisendError';
11
+ }
12
+ }
13
+
14
+ module.exports = { VisendError };
package/lib/httpx.js ADDED
@@ -0,0 +1,134 @@
1
+ 'use strict';
2
+
3
+ const http = require('http');
4
+ const https = require('https');
5
+
6
+ const MAX_RESPONSE_BYTES = 64 * 1024 * 1024;
7
+
8
+ // Hard ceiling on the WHOLE request (connect + upload + response). The idle
9
+ // socket timeout covers stalls, but a server dribbling one byte every few
10
+ // seconds would otherwise reset the idle timer forever and hang the CLI.
11
+ function totalDeadlineMs(timeoutMs) {
12
+ return Math.max((timeoutMs || 0) + 60000, 120000);
13
+ }
14
+
15
+ /**
16
+ * Promise-based request on top of node core http/https modules.
17
+ *
18
+ * opts: {
19
+ * method string
20
+ * headers object
21
+ * body Buffer | string
22
+ * parts Buffer[] written sequentially instead of one concat'ed body
23
+ * (halves the memory peak for large multipart uploads)
24
+ * timeoutMs number idle socket timeout (uploads/long polls keep the
25
+ * connection alive, so this must not be an overall cap)
26
+ * }
27
+ * Resolves { status, headers, body: Buffer }.
28
+ */
29
+ function request(target, opts) {
30
+ opts = opts || {};
31
+ const deadline = Date.now() + totalDeadlineMs(opts.timeoutMs);
32
+ return new Promise(function (resolve, reject) {
33
+ let u;
34
+ try {
35
+ u = new URL(target);
36
+ } catch (err) {
37
+ // The URL may embed the bot token (/bot<token>/...) - never echo it.
38
+ reject(new Error('Invalid URL: ' + target.replace(/\/bot[^/]+/g, '/bot***')));
39
+ return;
40
+ }
41
+ const lib = u.protocol === 'https:' ? https : http;
42
+ const headers = Object.assign({}, opts.headers);
43
+ let body = opts.body;
44
+ if (body && !Buffer.isBuffer(body)) body = Buffer.from(body);
45
+ if (opts.parts && body) {
46
+ reject(new Error('opts.body and opts.parts are mutually exclusive'));
47
+ return;
48
+ }
49
+ let length;
50
+ if (opts.parts) {
51
+ length = 0;
52
+ for (let i = 0; i < opts.parts.length; i++) length += opts.parts[i].length;
53
+ } else if (body) {
54
+ length = body.length;
55
+ }
56
+ if (length !== undefined && headers['Content-Length'] === undefined) {
57
+ headers['Content-Length'] = length;
58
+ }
59
+ const req = lib.request(
60
+ {
61
+ protocol: u.protocol,
62
+ hostname: u.hostname,
63
+ port: u.port || (u.protocol === 'https:' ? 443 : 80),
64
+ path: u.pathname + u.search,
65
+ method: opts.method || 'GET',
66
+ headers: headers,
67
+ },
68
+ function (res) {
69
+ const chunks = [];
70
+ let size = 0;
71
+ let aborted = false;
72
+ res.on('data', function (c) {
73
+ size += c.length;
74
+ if (size > MAX_RESPONSE_BYTES && !aborted) {
75
+ aborted = true;
76
+ res.destroy(new Error('Response exceeds ' + MAX_RESPONSE_BYTES + ' bytes'));
77
+ return;
78
+ }
79
+ if (Date.now() > deadline && !aborted) {
80
+ aborted = true;
81
+ res.destroy(new Error('Request exceeded the overall time limit (' + Math.round(totalDeadlineMs(opts.timeoutMs) / 1000) + ' s)'));
82
+ return;
83
+ }
84
+ chunks.push(c);
85
+ });
86
+ res.on('error', reject);
87
+ res.on('end', function () {
88
+ if (aborted) return;
89
+ resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks) });
90
+ });
91
+ }
92
+ );
93
+ req.on('error', reject);
94
+ if (opts.timeoutMs) {
95
+ req.setTimeout(opts.timeoutMs, function () {
96
+ req.destroy(new Error('Request timed out after ' + opts.timeoutMs + ' ms'));
97
+ });
98
+ }
99
+ // Honor write backpressure: waiting for 'drain' is what actually caps
100
+ // the in-memory peak for large uploads (the parts array alone would
101
+ // otherwise all be queued into the socket write buffer at once).
102
+ (async function () {
103
+ if (opts.parts) {
104
+ for (let i = 0; i < opts.parts.length; i++) {
105
+ if (!req.write(opts.parts[i])) {
106
+ await new Promise(function (r) { req.once('drain', r); });
107
+ }
108
+ }
109
+ } else if (body) {
110
+ if (!req.write(body)) {
111
+ await new Promise(function (r) { req.once('drain', r); });
112
+ }
113
+ }
114
+ req.end();
115
+ })().catch(reject);
116
+ });
117
+ }
118
+
119
+ function parseJsonBody(res) {
120
+ let text;
121
+ try {
122
+ text = res.body.toString('utf8');
123
+ return JSON.parse(text);
124
+ } catch (err) {
125
+ const snippet = (text || '').slice(0, 200).replace(/\s+/g, ' ');
126
+ const e = new Error(
127
+ 'Expected JSON response, got HTTP ' + res.status + (snippet ? ': ' + snippet : ' (empty body)')
128
+ );
129
+ e.status = res.status;
130
+ throw e;
131
+ }
132
+ }
133
+
134
+ module.exports = { request: request, parseJsonBody: parseJsonBody };