korveniq 1.0.6 → 1.0.7

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,27 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * lib/net-forward.js: Linux only. Runs inside the private network namespace of one package installation and passes
5
+ * connections made to 127.0.0.1:<port> there to the CLI's registry proxy (a unix socket). It forwards bytes only; the
6
+ * proxy decides what is allowed. Usage: node net-forward.js <socket path> <port>
7
+ */
8
+
9
+ const net = require('net');
10
+
11
+ function forward(socketPath, port) {
12
+ net
13
+ .createServer((client) => {
14
+ const upstream = net.connect(socketPath);
15
+ client.on('error', () => upstream.destroy());
16
+ upstream.on('error', () => client.destroy());
17
+ client.pipe(upstream);
18
+ upstream.pipe(client);
19
+ })
20
+ .listen(port, '127.0.0.1', () => process.stdout.write('ready\n'));
21
+ // ends with the CLI: its input closes
22
+ process.stdin.on('end', () => process.exit(0));
23
+ process.stdin.resume();
24
+ }
25
+
26
+ if (require.main === module) forward(process.argv[2], Number(process.argv[3]));
27
+ else module.exports = { forward };
@@ -0,0 +1,165 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * lib/net-proxy.js
5
+ * -----------------------------------------------------------------------------
6
+ * The only way to the internet an approved package installation gets: an HTTPS tunnel (CONNECT) through the CLI, to a
7
+ * fixed list of package registry hosts. It exists only while that installation runs.
8
+ *
9
+ * - CONNECT to <allowed host>:443 only; every other method, host or port is refused. A redirect to another host
10
+ * needs a new CONNECT, so it is checked the same way.
11
+ * - The CLI resolves the name itself, refuses the answer if any address is private, loopback, link-local or otherwise
12
+ * special, and connects to the address it checked (no second lookup an attacker could answer differently).
13
+ * - The TLS handshake must name the same host (SNI), so the tunnel cannot be pointed at another site on a shared
14
+ * server. TLS itself is end to end: the CLI sees no content and cannot see requests or paths inside it.
15
+ * - Callers must present a random password that only the installation's environment holds.
16
+ */
17
+
18
+ const net = require('net');
19
+ const dns = require('dns');
20
+ const http = require('http');
21
+ const crypto = require('crypto');
22
+
23
+ const IDLE_MS = 60_000;
24
+ const MAX_TUNNELS = 64;
25
+
26
+ /** Addresses an installation must never reach, whatever a name resolves to. */
27
+ const SPECIAL = (() => {
28
+ const list = new net.BlockList();
29
+ for (const [address, bits] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12], ['192.0.0.0', 24], ['192.0.2.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15], ['198.51.100.0', 24], ['203.0.113.0', 24], ['224.0.0.0', 4], ['240.0.0.0', 4]]) list.addSubnet(address, bits, 'ipv4');
30
+ // IPv6: only global unicast (2000::/3) is accepted at all; these parts of it are special as well.
31
+ for (const [address, bits] of [['2001:db8::', 32], ['2001::', 23], ['2002::', 16]]) list.addSubnet(address, bits, 'ipv6');
32
+ return list;
33
+ })();
34
+ const GLOBAL_V6 = (() => {
35
+ const list = new net.BlockList();
36
+ list.addSubnet('2000::', 3, 'ipv6');
37
+ return list;
38
+ })();
39
+
40
+ function isPublicAddress(address) {
41
+ const family = net.isIP(address);
42
+ if (family === 4) return !SPECIAL.check(address, 'ipv4');
43
+ if (family === 6) return GLOBAL_V6.check(address, 'ipv6') && !SPECIAL.check(address, 'ipv6');
44
+ return false;
45
+ }
46
+
47
+ /** The server name in a TLS ClientHello. null: not a ClientHello, or none. undefined: more bytes are needed. */
48
+ function sniOf(buf) {
49
+ if (buf.length < 5) return undefined;
50
+ if (buf[0] !== 22) return null;
51
+ const length = buf.readUInt16BE(3);
52
+ if (buf.length < 5 + length) return length > 16 * 1024 ? null : undefined;
53
+ try {
54
+ let p = 5;
55
+ if (buf[p] !== 1) return null;
56
+ p += 4 + 2 + 32;
57
+ p += 1 + buf[p];
58
+ p += 2 + buf.readUInt16BE(p);
59
+ p += 1 + buf[p];
60
+ const end = p + 2 + buf.readUInt16BE(p);
61
+ for (p += 2; p + 4 <= end; ) {
62
+ const type = buf.readUInt16BE(p);
63
+ const size = buf.readUInt16BE(p + 2);
64
+ if (type === 0) {
65
+ const nameLength = buf.readUInt16BE(p + 7);
66
+ return buf.toString('ascii', p + 9, p + 9 + nameLength).toLowerCase();
67
+ }
68
+ p += 4 + size;
69
+ }
70
+ } catch {
71
+ /* truncated or damaged */
72
+ }
73
+ return null;
74
+ }
75
+
76
+ /**
77
+ * @param {object} opts
78
+ * @param {string[]} opts.hosts the allowed host names
79
+ * @param {string} [opts.socketPath] listen on this unix socket instead of a loopback port
80
+ * @param {Function} [opts.lookup] dns.lookup (tests)
81
+ * @param {Function} [opts.connect] net.connect (tests)
82
+ */
83
+ async function startProxy({ hosts, socketPath = null, lookup = dns.lookup, connect = net.connect }) {
84
+ const allowed = new Set(hosts.map((h) => h.toLowerCase()));
85
+ const password = crypto.randomBytes(24).toString('hex');
86
+ const expected = Buffer.from(`Basic ${Buffer.from(`kq:${password}`).toString('base64')}`);
87
+ const sockets = new Set();
88
+ const log = { allowed: new Set(), refused: [] };
89
+ const track = (s) => {
90
+ sockets.add(s);
91
+ s.on('close', () => sockets.delete(s));
92
+ s.on('error', () => s.destroy());
93
+ s.setTimeout(IDLE_MS, () => s.destroy());
94
+ };
95
+
96
+ const server = http.createServer((req, res) => {
97
+ log.refused.push(`${req.method} ${String(req.url).slice(0, 80)} (only HTTPS tunnels)`);
98
+ res.writeHead(403, { Connection: 'close' }).end();
99
+ });
100
+ server.on('connection', track);
101
+ server.on('connect', (req, client, head) => {
102
+ const refuse = (status, why) => {
103
+ if (why) log.refused.push(`${String(req.url).slice(0, 80)} (${why})`);
104
+ client.end(`HTTP/1.1 ${status}\r\nConnection: close\r\n${status.startsWith('407') ? 'Proxy-Authenticate: Basic realm="korveniq"\r\n' : ''}\r\n`);
105
+ };
106
+ const auth = Buffer.from(String(req.headers['proxy-authorization'] || ''));
107
+ if (auth.length !== expected.length || !crypto.timingSafeEqual(auth, expected)) return refuse('407 Proxy Authentication Required');
108
+ const m = /^([A-Za-z0-9.-]{1,253}):(\d{1,5})$/.exec(String(req.url));
109
+ const host = m && m[1].toLowerCase();
110
+ if (!m || Number(m[2]) !== 443 || !allowed.has(host)) return refuse('403 Forbidden', 'not an allowed registry');
111
+ if (sockets.size > MAX_TUNNELS * 2) return refuse('503 Service Unavailable', 'too many connections');
112
+ lookup(host, { all: true, verbatim: true }, (err, addresses) => {
113
+ if (client.destroyed) return;
114
+ if (err || !addresses || !addresses.length) return refuse('502 Bad Gateway', 'the name cannot be resolved');
115
+ if (!addresses.every((a) => isPublicAddress(a.address))) return refuse('403 Forbidden', 'the name resolves to a private or special address');
116
+ // The client speaks first (TLS): check the name it asks for before anything reaches the server.
117
+ client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
118
+ let hello = head && head.length ? head : Buffer.alloc(0);
119
+ const onData = (chunk) => {
120
+ if (chunk) hello = Buffer.concat([hello, chunk]);
121
+ const sni = sniOf(hello);
122
+ if (sni === undefined && hello.length <= 20 * 1024) return;
123
+ client.removeListener('data', onData);
124
+ if (sni !== host) {
125
+ log.refused.push(`${host}:443 (the TLS handshake names ${sni ? `"${sni.slice(0, 80)}"` : 'no server'})`);
126
+ return client.destroy();
127
+ }
128
+ client.pause();
129
+ const upstream = connect({ host: addresses[0].address, port: 443 });
130
+ track(upstream);
131
+ upstream.once('connect', () => {
132
+ log.allowed.add(host);
133
+ upstream.write(hello);
134
+ client.pipe(upstream);
135
+ upstream.pipe(client);
136
+ client.resume();
137
+ });
138
+ upstream.on('close', () => client.destroy());
139
+ client.on('close', () => upstream.destroy());
140
+ };
141
+ client.on('data', onData);
142
+ if (hello.length) onData(null);
143
+ });
144
+ });
145
+
146
+ await new Promise((resolve, reject) => {
147
+ server.once('error', reject);
148
+ if (socketPath) server.listen(socketPath, resolve);
149
+ else server.listen(0, '127.0.0.1', resolve);
150
+ });
151
+ server.unref();
152
+ return {
153
+ port: socketPath ? null : server.address().port,
154
+ /** The proxy address with its password, for a client that reaches it on `port`. */
155
+ url: (port) => `http://kq:${password}@127.0.0.1:${port}`,
156
+ log,
157
+ close: () =>
158
+ new Promise((resolve) => {
159
+ for (const s of sockets) s.destroy();
160
+ server.close(() => resolve());
161
+ }),
162
+ };
163
+ }
164
+
165
+ module.exports = { startProxy, isPublicAddress, sniOf };
package/lib/paste.js ADDED
@@ -0,0 +1,330 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * lib/paste.js
5
+ * -----------------------------------------------------------------------------
6
+ * Pasting into the chat input, with the terminal's bracketed paste mode: pasted
7
+ * text arrives between ESC[200~ and ESC[201~, so its line breaks are text and
8
+ * never the Enter that sends the message.
9
+ *
10
+ * Node's readline treats every CR / LF it receives as Enter, and its handling of
11
+ * a line that holds line breaks differs between Node versions. So readline never
12
+ * sees a pasted key: this sits in front of its 'keypress' listeners, collects the
13
+ * paste and puts it into the input line at the cursor. While you edit, the line
14
+ * holds real line breaks. At the moment readline takes it (Enter, history) they
15
+ * are stand-ins, so that readline always keeps a single line.
16
+ *
17
+ * A confirmation (the Yes/No menus and their typed form) is never answered by a paste: see deliberate() and
18
+ * confirmEnter() below.
19
+ *
20
+ * A paste too tall for the screen (readline cannot redraw that) is shown as
21
+ * "[Pasted text #1: 80 lines]" and sent in full. The marker is edited as one unit.
22
+ */
23
+
24
+ const START = '\x1b[200~';
25
+ const END = '\x1b[201~';
26
+ const ENABLE = '\x1b[?2004h';
27
+ const DISABLE = '\x1b[?2004l';
28
+
29
+ const NEWLINE = ''; // stands for a line break inside readline's line and history
30
+ const TAB = '⇥'; // a pasted tab as shown (a real one would break readline's cursor arithmetic)
31
+ const MARKER_RE = /\[Pasted text #\d+: \d+ (?:lines|characters)\]/g;
32
+ const MAX_SHOWN_CHARS = 4_000;
33
+ const MAX_BLOCKS = 100;
34
+ /** A paste whose end marker never comes is taken as finished after this much silence. */
35
+ const IDLE_END_MS = 5_000;
36
+ /** An Enter that confirms something arrives on its own: no other input this long before it, or this long after. */
37
+ const QUIET_BEFORE_MS = 15;
38
+ const QUIET_AFTER_MS = 40;
39
+ /** One chunk of input that can be one key press: a character, an escape sequence, or a held arrow key / Tab. */
40
+ const ONE_KEY_RE = /^(?:\r\n|\x1b(?:\[[\d;]*[ -/]*[@-~]|O.|.)?|(?:\x1b[[O][ABZ])+|.)$/su;
41
+ const ENTER_RE = /^(?:\r\n|\r|\n)$/;
42
+ // Node 18 reads only two digits of "ESC [ 200 ~": the "~" comes as a character of its own.
43
+ const SPLIT_MARKER_RE = /^\x1b+\[20[01]$/;
44
+
45
+ const blocks = new Map(); // marker -> pasted text (kept for the history of this run)
46
+ let counter = 0;
47
+
48
+ // ---------------------------------------------------------------------------
49
+ // The terminal mode
50
+ // ---------------------------------------------------------------------------
51
+
52
+ let enabled = null; // the output the mode was switched on for
53
+ const tracked = new WeakMap(); // input -> what is known about its input (see track)
54
+
55
+ const isStart = (key) => Boolean(key && key.sequence === START);
56
+ // (an ESC at the very end of the pasted text joins the end marker's own)
57
+ const isEnd = (key) => Boolean(key && typeof key.sequence === 'string' && key.sequence.endsWith(END.slice(1)) && key.sequence.startsWith('\x1b'));
58
+
59
+ /**
60
+ * Follow an input stream, also while nobody is asking anything: whether a paste is under way (it may end in the next
61
+ * prompt), and how the latest keys arrived. It also repairs the paste markers on Node 18, before any listener sees them.
62
+ * @returns {{ pasting: boolean, chunk: string, at: number, before: number, count: number }}
63
+ */
64
+ function track(input) {
65
+ let state = tracked.get(input);
66
+ if (state) return state;
67
+ state = { pasting: false, chunk: '', at: -Infinity, before: Infinity, count: 0 };
68
+ tracked.set(input, state);
69
+ // In front of the key decoder, so every key is seen together with the chunk it came in.
70
+ input.prependListener('data', (data) => {
71
+ const now = performance.now();
72
+ if (state.pasting && now - state.at > IDLE_END_MS) state.pasting = false;
73
+ state.before = now - state.at;
74
+ state.at = now;
75
+ state.chunk = String(data);
76
+ state.count++;
77
+ });
78
+ const emit = input.emit;
79
+ let held = null; // Node 18: a marker still missing its "~"
80
+ input.emit = function (event, ...args) {
81
+ if (event !== 'keypress') return emit.call(this, event, ...args);
82
+ let [text, key] = args;
83
+ if (held) {
84
+ const first = held;
85
+ held = null;
86
+ if (text === '~') {
87
+ const sequence = `${first[1].sequence}~`;
88
+ text = undefined;
89
+ key = { sequence, name: sequence.endsWith('[200~') ? 'paste-start' : 'paste-end', ctrl: false, meta: false, shift: false };
90
+ } else emit.call(this, event, ...first);
91
+ }
92
+ if (key && typeof key.sequence === 'string' && SPLIT_MARKER_RE.test(key.sequence)) {
93
+ held = [text, key];
94
+ return true;
95
+ }
96
+ if (isStart(key)) state.pasting = true;
97
+ else if (isEnd(key)) state.pasting = false;
98
+ return emit.call(this, event, text, key);
99
+ };
100
+ return state;
101
+ }
102
+
103
+ // ---------------------------------------------------------------------------
104
+ // Confirmations
105
+ // ---------------------------------------------------------------------------
106
+
107
+ /** False for a key that is part of a paste: marked as one, or arriving with other keys (a terminal that marks nothing). */
108
+ function deliberate(input) {
109
+ const state = track(input);
110
+ return !state.pasting && (state.chunk === '' || ONE_KEY_RE.test(state.chunk));
111
+ }
112
+
113
+ /**
114
+ * An Enter key was received for a question that grants something. `confirmed` is called, a moment later, only if it was
115
+ * pressed: not part of a paste, alone in its chunk, with no other input just before or after it.
116
+ */
117
+ function confirmEnter(input, confirmed) {
118
+ const state = track(input);
119
+ if (state.pasting || (state.chunk !== '' && !ENTER_RE.test(state.chunk)) || state.before < QUIET_BEFORE_MS) return;
120
+ const count = state.count;
121
+ setTimeout(() => {
122
+ if (state.count === count && !state.pasting) confirmed();
123
+ }, QUIET_AFTER_MS);
124
+ }
125
+
126
+ // ---------------------------------------------------------------------------
127
+ // The terminal mode, continued
128
+ // ---------------------------------------------------------------------------
129
+
130
+ /** Ask the terminal to mark pastes. It stays on for the whole session and is switched off when the process ends. */
131
+ function enable(output) {
132
+ if (!output.isTTY || process.env.TERM === 'dumb') return;
133
+ if (!enabled) process.once('exit', disable);
134
+ enabled = output;
135
+ output.write(ENABLE);
136
+ }
137
+
138
+ function disable() {
139
+ if (!enabled) return;
140
+ try {
141
+ enabled.write(DISABLE);
142
+ } catch {
143
+ /* the terminal is already gone */
144
+ }
145
+ }
146
+
147
+ // ---------------------------------------------------------------------------
148
+ // Text
149
+ // ---------------------------------------------------------------------------
150
+
151
+ /** Pasted text: one kind of line break, and no control or escape sequences that could drive the terminal. */
152
+ function clean(text) {
153
+ return String(text)
154
+ .replace(/\r\n?/g, '\n')
155
+ .replace(/\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)?|.)?/g, '')
156
+ .replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '');
157
+ }
158
+
159
+ /** Rows a text takes in a terminal `columns` wide (an estimate: every character counted as one column). */
160
+ function rowsOf(text, columns) {
161
+ return text.split('\n').reduce((n, line) => n + Math.max(1, Math.ceil([...line].length / columns)), 0);
162
+ }
163
+
164
+ /** The line as readline may keep it. */
165
+ const encode = (line) => line.replace(/\n/g, NEWLINE);
166
+ /** The line as it is edited and shown. */
167
+ const decode = (line) => line.split(NEWLINE).join('\n');
168
+ /** The line as it is sent: markers replaced by what was pasted, shown tabs by tabs. */
169
+ function expand(line) {
170
+ return decode(line)
171
+ .split(TAB)
172
+ .join('\t')
173
+ .replace(MARKER_RE, (m) => (blocks.has(m) ? blocks.get(m) : m));
174
+ }
175
+
176
+ /** What to put into the line for a paste: the text itself, or a marker for it. */
177
+ function represent(text, { before = '', after = '', columns = 80, rows = 24 } = {}) {
178
+ const shown = text.split('\t').join(TAB);
179
+ const fits = !text.includes(TAB) && before.length + shown.length + after.length <= MAX_SHOWN_CHARS && rowsOf(`> ${before}${shown}${after}`, columns) <= Math.max(3, rows - 4);
180
+ if (fits) return shown;
181
+ const lines = text.replace(/\n$/, '').split('\n').length;
182
+ const marker = `[Pasted text #${++counter}: ${lines > 1 ? `${lines} lines` : `${[...text].length} characters`}]`;
183
+ blocks.set(marker, text);
184
+ if (blocks.size > MAX_BLOCKS) blocks.delete(blocks.keys().next().value);
185
+ return marker;
186
+ }
187
+
188
+ /** Where the markers of known pastes are in a line. */
189
+ function markers(line) {
190
+ return [...line.matchAll(MARKER_RE)].filter((m) => blocks.has(m[0])).map((m) => ({ from: m.index, to: m.index + m[0].length }));
191
+ }
192
+
193
+ /**
194
+ * A marker is one unit: an edit that reaches inside one takes all of it (never leaving half a marker to be sent in place
195
+ * of the text), and the cursor does not stop inside.
196
+ * @returns {{ line: string, cursor: number }|null} what the line should become, or null to leave it
197
+ */
198
+ function keepMarkersWhole(was, now) {
199
+ const found = markers(was.line);
200
+ if (!found.length) return null;
201
+ if (was.line !== now.line) {
202
+ const max = Math.min(was.line.length, now.line.length);
203
+ // The edit replaced was[from, to) by `put`; the cursor says where, when the text alone would allow several places.
204
+ let from = 0;
205
+ while (from < max && from < Math.min(was.cursor, now.cursor) && was.line[from] === now.line[from]) from++;
206
+ let tail = 0;
207
+ while (tail < max - from && was.line[was.line.length - 1 - tail] === now.line[now.line.length - 1 - tail]) tail++;
208
+ const to = was.line.length - tail;
209
+ const hit = found.filter((m) => from < m.to && to > m.from && !(from === to));
210
+ const inside = found.find((m) => from === to && from > m.from && from < m.to);
211
+ if (inside) hit.push(inside);
212
+ if (!hit.length) return null;
213
+ const start = Math.min(from, ...hit.map((m) => m.from));
214
+ const end = Math.max(to, ...hit.map((m) => m.to));
215
+ const put = now.line.slice(from, now.line.length - tail);
216
+ return { line: was.line.slice(0, start) + put + was.line.slice(end), cursor: start + put.length };
217
+ }
218
+ const m = found.find((x) => now.cursor > x.from && now.cursor < x.to);
219
+ return m ? { line: now.line, cursor: now.cursor < was.cursor ? m.from : m.to } : null;
220
+ }
221
+
222
+ // ---------------------------------------------------------------------------
223
+ // One prompt
224
+ // ---------------------------------------------------------------------------
225
+
226
+ /**
227
+ * Put paste handling in front of a readline interface. Attach it after every other 'keypress' listener of the prompt.
228
+ * @param {import('readline').Interface} rl
229
+ * @param {object} opts
230
+ * @param {Set<Function>} opts.keep listeners that were there before the prompt: left alone
231
+ * @param {() => void} [opts.before] a paste is about to change the line
232
+ * @param {() => void} [opts.after] it has
233
+ * @param {() => void} [opts.onKey] the user did something
234
+ * @returns {{ detach: () => void }}
235
+ */
236
+ function attachPaste(rl, { keep = new Set(), before = () => {}, after = () => {}, onKey = () => {} } = {}) {
237
+ const input = rl.input;
238
+ const output = rl.output;
239
+ const state = track(input);
240
+ const inner = input.listeners('keypress').filter((l) => !keep.has(l));
241
+ let buffer = state.pasting ? [] : null; // the keys of the paste under way
242
+ let timer = null;
243
+ let detached = false;
244
+
245
+ const set = (line, cursor) => {
246
+ rl.line = line;
247
+ rl.cursor = cursor;
248
+ rl.prompt(true); // readline redraws the prompt and the line
249
+ };
250
+
251
+ function finishPaste() {
252
+ clearTimeout(timer);
253
+ const text = clean((buffer || []).join(''));
254
+ buffer = null;
255
+ state.pasting = false;
256
+ if (!text) return;
257
+ before();
258
+ const head = rl.line.slice(0, rl.cursor);
259
+ const tail = rl.line.slice(rl.cursor);
260
+ const piece = represent(text, { before: head, after: tail, columns: output.columns || 80, rows: output.rows || 24 });
261
+ set(head + piece + tail, head.length + piece.length);
262
+ after();
263
+ }
264
+
265
+ const wait = () => {
266
+ clearTimeout(timer);
267
+ timer = setTimeout(finishPaste, IDLE_END_MS);
268
+ timer.unref();
269
+ };
270
+
271
+ function onKeypress(s, key = {}) {
272
+ if (isStart(key)) {
273
+ onKey();
274
+ buffer = buffer || [];
275
+ return wait();
276
+ }
277
+ if (isEnd(key)) {
278
+ if (buffer) finishPaste();
279
+ return;
280
+ }
281
+ if (buffer) {
282
+ buffer.push(typeof s === 'string' ? s : key.sequence || '');
283
+ return wait();
284
+ }
285
+ const enter = key.name === 'return' || key.name === 'enter';
286
+ const leaving = enter || (key.ctrl && key.name === 'c');
287
+ // The line is left with the cursor at its end, or what is printed next would overwrite its later rows.
288
+ if (leaving && rl.line.includes('\n') && rl.cursor !== rl.line.length) set(rl.line, rl.line.length);
289
+ const was = { line: rl.line, cursor: rl.cursor };
290
+ if (enter && rl.line.includes('\n')) {
291
+ rl.line = encode(rl.line);
292
+ rl.cursor = rl.line.length;
293
+ }
294
+ for (const listener of inner) {
295
+ listener.call(input, s, key);
296
+ if (detached) return; // that key ended the prompt
297
+ }
298
+ if (rl.line.includes(NEWLINE)) {
299
+ // From the history, or an Enter that did not send (it accepted a suggestion): show the line breaks again.
300
+ before();
301
+ const cursor = rl.cursor;
302
+ set(decode(rl.line), cursor);
303
+ after();
304
+ return;
305
+ }
306
+ if (key.name === 'up' || key.name === 'down') return;
307
+ const fixed = keepMarkersWhole(was, { line: rl.line, cursor: rl.cursor });
308
+ if (fixed) {
309
+ before();
310
+ set(fixed.line, fixed.cursor);
311
+ after();
312
+ }
313
+ }
314
+
315
+ for (const l of inner) input.removeListener('keypress', l);
316
+ input.on('keypress', onKeypress);
317
+ if (buffer) wait();
318
+
319
+ return {
320
+ detach() {
321
+ if (detached) return;
322
+ detached = true;
323
+ clearTimeout(timer);
324
+ input.removeListener('keypress', onKeypress);
325
+ for (const l of inner) input.on('keypress', l); // readline removes its own when it closes
326
+ },
327
+ };
328
+ }
329
+
330
+ module.exports = { attachPaste, enable, disable, track, deliberate, confirmEnter, clean, represent, keepMarkersWhole, encode, decode, expand, START, END, ENABLE, DISABLE, NEWLINE, TAB };