-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell.ts
More file actions
590 lines (532 loc) · 19.6 KB
/
shell.ts
File metadata and controls
590 lines (532 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
import { Terminal } from "@xterm/xterm";
import { commands, aliases } from "./cli";
import { getConfig } from "./cli/config";
import { WebLinksAddon } from "@xterm/addon-web-links";
import git from "fullstacked/git";
import { githubDeviceFlow } from "./utils/githubDeviceFlow";
import { handleAutocomplete } from "./utils/autocomplete";
import { setupUtilityButtons } from "./utils/utilityButtons";
import { splitShellArgs } from "./utils/args";
import fs from "fs";
import path from "path";
const HISTORY_FILE = path.join(path.sep, "user_data", ".history");
const GIT_CREDENTIALS_FILE = path.join(
path.sep,
"user_data",
".git-credentials"
);
const td = new TextDecoder();
export class Shell {
terminal: Terminal;
command: string = "";
cursorPos: number = 0;
history: string[] = [];
historyIndex: number = 0;
gitAuthManager: Awaited<ReturnType<typeof git.createGitAuthManager>>;
private inputHandler: ((e: string) => void) | null = null;
private _lastDrawnCursorPos = 0;
constructor(terminal: Terminal) {
this.terminal = terminal;
this.terminal.loadAddon(new WebLinksAddon());
this.loadHistory();
this.runInitScript();
git.createGitAuthManager().then((m) => {
this.gitAuthManager = m;
this.gitAuthManager.on("auth", async (host: string) => {
let auth = await this.getGitCredentials(host);
if (!auth) {
if (host === "github.com") {
this.writeln(
`Authenticating with ${host} using Device Flow...`
);
// pass a writer function bound to this instance
auth = await githubDeviceFlow((s) => this.write(s));
}
if (!auth) {
auth = await this.requestUsernamePassword(host);
}
}
if (auth) {
this.gitAuthManager.writeEvent("authResponse", host, auth);
await this.saveGitCredentials(
host,
auth.username,
auth.password
);
} else {
this.writeln("Authentication failed or cancelled.");
this.gitAuthManager.writeEvent("authResponse", host, {
username: "",
password: ""
}); // Cancel/fail
}
});
});
this.setupTouchToolbar();
}
private setupTouchToolbar() {
setupUtilityButtons((char: string) => this.handleInput(char));
}
prompt() {
if (this.terminal.buffer.active.cursorX > 0) {
this.terminal.write("\r\n");
}
this.terminal.write(`${process.cwd()} $ `);
this._lastDrawnCursorPos = 0;
}
write(data: string | Uint8Array) {
if (typeof data === "string") {
this.terminal.write(data);
} else this.terminal.write(td.decode(data));
}
writeln(data?: string) {
if (data) this.terminal.writeln(data);
}
clear() {
this.terminal.clear();
}
redrawInput() {
const promptStr = `${process.cwd()} $ `;
const cols = this.terminal.cols;
// Calculate old cursor physical row relative to prompt start
const oldAbsPos = promptStr.length + (this._lastDrawnCursorPos || 0);
const oldRow = Math.floor(oldAbsPos / cols);
let seq = "\r"; // Go to col 0
if (oldRow > 0) {
seq += `\x1b[${oldRow}A`; // Move up
}
seq += "\x1b[J"; // Clear screen down from here
seq += promptStr + this.command; // Redraw entire command
// Calculate new actual end position and where we need to move the cursor to
const endAbsPos = promptStr.length + this.command.length;
const targetAbsPos = promptStr.length + this.cursorPos;
const endRow = Math.floor(endAbsPos / cols);
const targetRow = Math.floor(targetAbsPos / cols);
const targetCol = targetAbsPos % cols;
const rowsUp = endRow - targetRow;
seq += "\r";
if (rowsUp > 0) {
seq += `\x1b[${rowsUp}A`;
}
if (targetCol > 0) {
seq += `\x1b[${targetCol}C`;
}
this.terminal.write(seq);
this._lastDrawnCursorPos = this.cursorPos;
}
private currentCancelHandler: (() => void) | null = null;
private capturedInputHandler: ((data: string) => void) | null = null;
captureInput(handler: (data: string) => void) {
this.capturedInputHandler = handler;
}
releaseInput() {
this.capturedInputHandler = null;
}
handleInput(e: string) {
if (this.capturedInputHandler) {
this.capturedInputHandler(e);
return;
}
if (this.inputHandler) {
this.inputHandler(e);
return;
}
switch (e) {
case "\r": // Enter
this.terminal.write("\r\n");
if (this.command.trim()) {
this.history.push(this.command);
this.historyIndex = this.history.length;
this.saveHistory();
}
this.executeCommand(this.command);
this.command = "";
this.cursorPos = 0;
break;
case "\u0003": // Ctrl+C
if (this.currentCancelHandler) {
this.currentCancelHandler();
this.currentCancelHandler = null;
return;
}
this.terminal.write("^C");
this.prompt();
this.command = "";
this.cursorPos = 0;
this.historyIndex = this.history.length;
break;
case "\u007F": // Backspace
if (this.cursorPos > 0) {
this.command =
this.command.slice(0, this.cursorPos - 1) +
this.command.slice(this.cursorPos);
this.cursorPos--;
this.redrawInput();
}
break;
case "\x1b[A": // Up Arrow
if (this.historyIndex > 0) {
this.historyIndex--;
this.command = this.history[this.historyIndex];
this.cursorPos = this.command.length;
this.redrawInput();
}
break;
case "\x1b[B": // Down Arrow
if (this.historyIndex < this.history.length) {
this.historyIndex++;
if (this.historyIndex === this.history.length) {
this.command = "";
} else {
this.command = this.history[this.historyIndex];
}
this.cursorPos = this.command.length;
this.redrawInput();
}
break;
case "\t": // Tab
this.handleAutocomplete();
break;
case "\x1b[D": // Left Arrow
if (this.cursorPos > 0) {
this.cursorPos--;
this.terminal.write(e);
}
break;
case "\x1b[C": // Right Arrow
if (this.cursorPos < this.command.length) {
this.cursorPos++;
this.terminal.write(e);
}
break;
case "\x1b[1;3D": // Alt+Left
case "\x1bb":
if (this.cursorPos > 0) {
let p = this.cursorPos;
while (p > 0 && this.command[p - 1] === " ") p--;
while (p > 0 && this.command[p - 1] !== " ") p--;
const dist = this.cursorPos - p;
this.cursorPos = p;
if (dist > 0) this.terminal.write(`\x1b[${dist}D`);
}
break;
case "\x1b[1;3C": // Alt+Right
case "\x1bf":
if (this.cursorPos < this.command.length) {
let p = this.cursorPos;
while (p < this.command.length && this.command[p] !== " ")
p++;
while (p < this.command.length && this.command[p] === " ")
p++;
const dist = p - this.cursorPos;
this.cursorPos = p;
if (dist > 0) this.terminal.write(`\x1b[${dist}C`);
}
break;
default:
if (
(e >= String.fromCharCode(0x20) &&
e <= String.fromCharCode(0x7e)) ||
e >= "\u00a0"
) {
this.command =
this.command.slice(0, this.cursorPos) +
e +
this.command.slice(this.cursorPos);
this.cursorPos += e.length;
this.redrawInput();
}
}
}
private async runInitScript() {
try {
const initScript = await getConfig("initScript");
if (initScript && typeof initScript === "string") {
await this.executeCommand(initScript);
}
} catch (e) {
// Silently fail if initScript cannot be run
}
}
private async loadHistory() {
try {
if (fs.existsSync(HISTORY_FILE)) {
const content = await fs.promises.readFile(
HISTORY_FILE,
"utf-8"
);
this.history = content
.split("\n")
.filter((line) => line.trim() !== "");
this.historyIndex = this.history.length;
}
} catch (e) {
// Silently fail if history cannot be loaded
}
}
private async saveHistory() {
try {
await fs.promises.mkdir(`${path.sep}user_data`, {
recursive: true
});
const content = this.history.join("\n");
await fs.promises.writeFile(HISTORY_FILE, content, "utf-8");
} catch (e) {
// Silently fail if history cannot be saved
}
}
private async getGitCredentials(
host: string
): Promise<{ username: string; password: string } | null> {
try {
if (!fs.existsSync(GIT_CREDENTIALS_FILE)) return null;
const content = await fs.promises.readFile(
GIT_CREDENTIALS_FILE,
"utf-8"
);
const lines = content.split("\n");
for (const line of lines) {
if (!line.trim()) continue;
try {
const url = new URL(line.trim());
if (url.hostname === host) {
return {
username: decodeURIComponent(url.username),
password: decodeURIComponent(url.password)
};
}
} catch (e) {
// Ignore malformed lines
}
}
} catch (e) {
// Silently fail
}
return null;
}
public async saveGitCredentials(
host: string,
username: string,
password: string
) {
if (!username || !password) return;
try {
let credentials: string[] = [];
if (fs.existsSync(GIT_CREDENTIALS_FILE)) {
const content = await fs.promises.readFile(
GIT_CREDENTIALS_FILE,
"utf-8"
);
credentials = content
.split("\n")
.filter((line) => line.trim() !== "");
}
const newCredential = `https://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}`;
// Check if we already have a credential for this host and update it
let updated = false;
for (let i = 0; i < credentials.length; i++) {
try {
const url = new URL(credentials[i]);
if (url.hostname === host) {
credentials[i] = newCredential;
updated = true;
break;
}
} catch (e) {
// Ignore malformed lines
}
}
if (!updated) {
credentials.push(newCredential);
}
try {
await fs.promises.mkdir("/user_data", { recursive: true });
} catch (e) {}
await fs.promises.writeFile(
GIT_CREDENTIALS_FILE,
credentials.join("\n") + "\n",
"utf-8"
);
} catch (e) {
// Silently fail
}
}
async executeCommand(cmdStr: string) {
await this.executeLine(cmdStr);
this.prompt();
}
async executeLine(cmdStr: string): Promise<number> {
// Split by && but respect quotes if possible?
// For now simple split as requested, ensuring we don't break string literals if we can avoid it.
// But a simple split("&&") is the requested task.
const commandsToRun = this.splitCommands(cmdStr);
let lastExitCode = 0;
for (let cmd of commandsToRun) {
cmd = cmd.trim();
if (!cmd) continue;
const sortedAliases = Object.keys(aliases).sort(
(a, b) => b.length - a.length
);
let aliased = false;
for (const alias of sortedAliases) {
if (cmd === alias || cmd.startsWith(alias + " ")) {
const expandedCmd =
aliases[alias] + cmd.slice(alias.length);
// Check if expansion results in multiple commands
const expandedCommands = this.splitCommands(expandedCmd);
if (expandedCommands.length > 1) {
lastExitCode = await this.executeLine(expandedCmd);
aliased = true;
} else {
cmd = expandedCmd;
}
break;
}
}
if (aliased) {
if (lastExitCode !== 0) break;
continue;
}
const args = splitShellArgs(cmd);
const commandName = args.shift();
if (!commandName) {
continue;
}
const command = commands[commandName];
if (command) {
const exitCode = await command.execute(
args,
this,
(handler) => {
this.currentCancelHandler = handler;
}
);
this.currentCancelHandler = null;
if (typeof exitCode === "number" && exitCode !== 0) {
lastExitCode = exitCode;
break;
}
} else {
this.writeln(`command not found: ${commandName}`);
lastExitCode = 1;
break; // Stop execution on error
}
}
return lastExitCode;
}
async handleAutocomplete() {
await handleAutocomplete(
this.command,
this.terminal,
(newCommand, cursorPos) => {
this.command = newCommand;
this.cursorPos = cursorPos;
}
);
}
private readInput(
prompt: string,
hidden: boolean = false
): Promise<string> {
return new Promise((resolve, reject) => {
this.terminal.write(prompt);
let input = "";
let cursor = 0;
this.inputHandler = (e: string) => {
switch (e) {
case "\r": // Enter
this.terminal.write("\r\n");
this.inputHandler = null;
resolve(input);
break;
case "\u0003": // Ctrl+C
this.terminal.write("^C\r\n");
this.inputHandler = null;
reject(new Error("CANCELED"));
break;
case "\u007F": // Backspace
if (cursor > 0) {
input =
input.slice(0, cursor - 1) +
input.slice(cursor);
cursor--;
if (!hidden) this.terminal.write("\b \b");
}
break;
case "\x1b[A": // Up Arrow
case "\x1b[B": // Down Arrow
// Ignore for now in password/input prompt
break;
case "\x1b[D": // Left Arrow
case "\x1b[C": // Right Arrow
// Ignore for now
break;
default:
if (e >= " " && e <= "~") {
input =
input.slice(0, cursor) +
e +
input.slice(cursor);
cursor += e.length;
if (hidden) {
// For password, we don't show characters or show *
// Standard unix login doesn't show anything
} else {
this.terminal.write(e);
}
}
}
};
});
}
async requestUsernamePassword(
resource?: string,
username?: string
): Promise<{ username: string; password: string } | null> {
try {
const usernamePrompt = resource
? `Username for '${resource}': `
: "Username: ";
const passwordPrompt = resource
? `Password for '${resource}': `
: "Password: ";
if (!username) {
username = await this.readInput(usernamePrompt);
}
const password = await this.readInput(passwordPrompt, true);
return { username, password };
} catch (e) {
return null;
}
}
private splitCommands(cmdStr: string): string[] {
const commands: string[] = [];
let currentCommand = "";
let inQuote: string | null = null;
for (let i = 0; i < cmdStr.length; i++) {
const char = cmdStr[i];
if (inQuote) {
if (char === inQuote) {
inQuote = null;
}
currentCommand += char;
} else {
if (char === '"' || char === "'") {
inQuote = char;
currentCommand += char;
} else if (char === "&" && cmdStr[i + 1] === "&") {
// Start of && operator
commands.push(currentCommand);
currentCommand = "";
i++; // Skip the second &
} else {
currentCommand += char;
}
}
}
if (currentCommand) {
commands.push(currentCommand);
}
return commands;
}
}