@saws/cli 1.0.11 → 2.0.0-beta.11
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/README.md +131 -4
- package/dist/.tsbuildinfo +1 -0
- package/dist/bin/saws.js +39 -32
- package/dist/commands/app/deploy.d.ts +4 -0
- package/dist/commands/app/deploy.js +20 -0
- package/dist/commands/app/index.js +16 -0
- package/dist/commands/app/install.d.ts +5 -0
- package/dist/commands/app/install.js +41 -0
- package/dist/commands/app/paths.d.ts +1 -0
- package/dist/commands/app/paths.js +8 -0
- package/dist/commands/app/process.d.ts +2 -0
- package/dist/commands/app/process.js +28 -0
- package/dist/commands/deploy/command.js +15 -0
- package/dist/commands/deploy/index.js +6 -0
- package/dist/commands/dev/command.js +61 -0
- package/dist/commands/dev/index.js +3 -0
- package/dist/commands/dev/tui/dev-tui.d.ts +33 -0
- package/dist/commands/dev/tui/dev-tui.js +380 -0
- package/dist/commands/host/command.d.ts +9 -0
- package/dist/commands/host/command.js +129 -0
- package/dist/commands/host/create.d.ts +9 -0
- package/dist/commands/host/create.js +30 -0
- package/dist/commands/host/deployment-key.d.ts +2 -0
- package/dist/commands/host/deployment-key.js +40 -0
- package/dist/commands/host/import-key.d.ts +5 -0
- package/dist/commands/host/import-key.js +40 -0
- package/dist/commands/host/index.js +32 -0
- package/dist/commands/init/command.d.ts +1 -0
- package/dist/commands/init/command.js +24 -0
- package/dist/commands/init/index.d.ts +2 -0
- package/dist/commands/init/index.js +6 -0
- package/dist/commands/init/templates/gitignore.template.js +4 -0
- package/dist/commands/init/templates/saws-ts.template.d.ts +3 -0
- package/dist/commands/init/templates/saws-ts.template.js +7 -0
- package/dist/commands/init/templates/tsconfig-json.template.js +4 -0
- package/dist/commands/logs/command.d.ts +5 -0
- package/dist/commands/logs/command.js +19 -0
- package/dist/commands/logs/index.d.ts +2 -0
- package/dist/commands/logs/index.js +7 -0
- package/dist/commands/secrets/command.d.ts +8 -0
- package/dist/commands/secrets/command.js +28 -0
- package/dist/commands/secrets/index.d.ts +2 -0
- package/dist/commands/secrets/index.js +11 -0
- package/dist/hosts.d.ts +2 -0
- package/dist/hosts.js +18 -0
- package/package.json +11 -15
- package/dist/src/commands/deploy/command.js +0 -16
- package/dist/src/commands/deploy/index.js +0 -11
- package/dist/src/commands/dev/command.js +0 -22
- package/dist/src/commands/dev/index.js +0 -10
- package/dist/src/commands/execute/command.d.ts +0 -3
- package/dist/src/commands/execute/command.js +0 -41
- package/dist/src/commands/execute/index.js +0 -12
- package/dist/src/commands/init/command.d.ts +0 -1
- package/dist/src/commands/init/command.js +0 -23
- package/dist/src/commands/init/index.js +0 -9
- package/dist/src/commands/init/templates/gitignore.template.js +0 -13
- package/dist/src/commands/init/templates/saws-js.template.d.ts +0 -3
- package/dist/src/commands/init/templates/saws-js.template.js +0 -12
- package/dist/src/commands/init/templates/tsconfig-json.template.js +0 -25
- package/dist/tsconfig.tsbuildinfo +0 -1
- /package/dist/{src/commands/deploy → commands/app}/index.d.ts +0 -0
- /package/dist/{src/commands → commands}/deploy/command.d.ts +0 -0
- /package/dist/{src/commands/dev → commands/deploy}/index.d.ts +0 -0
- /package/dist/{src/commands → commands}/dev/command.d.ts +0 -0
- /package/dist/{src/commands/execute → commands/dev}/index.d.ts +0 -0
- /package/dist/{src/commands/init → commands/host}/index.d.ts +0 -0
- /package/dist/{src/commands → commands}/init/templates/gitignore.template.d.ts +0 -0
- /package/dist/{src/commands → commands}/init/templates/tsconfig-json.template.d.ts +0 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export interface RuntimeLogEntry {
|
|
2
|
+
serviceName: string;
|
|
3
|
+
stream: "stdout" | "stderr";
|
|
4
|
+
chunk: string;
|
|
5
|
+
timestamp: Date;
|
|
6
|
+
}
|
|
7
|
+
export type RuntimeLogSink = (entry: RuntimeLogEntry) => void;
|
|
8
|
+
export declare class DevTui {
|
|
9
|
+
readonly logSink: RuntimeLogSink;
|
|
10
|
+
private readonly services;
|
|
11
|
+
private readonly logs;
|
|
12
|
+
private readonly logScrollOffsets;
|
|
13
|
+
private selectedIndex;
|
|
14
|
+
private isStarted;
|
|
15
|
+
private isSelectionMode;
|
|
16
|
+
private previousRawMode;
|
|
17
|
+
private readonly maxLines;
|
|
18
|
+
constructor(services: string[]);
|
|
19
|
+
start(): void;
|
|
20
|
+
stop(): void;
|
|
21
|
+
private handleKeypress;
|
|
22
|
+
private handleInput;
|
|
23
|
+
private addLog;
|
|
24
|
+
private render;
|
|
25
|
+
private enterSelectionMode;
|
|
26
|
+
private exitSelectionMode;
|
|
27
|
+
private getHelpText;
|
|
28
|
+
private getSelectedService;
|
|
29
|
+
private getBodyHeight;
|
|
30
|
+
private scrollSelectedLog;
|
|
31
|
+
private selectServiceAt;
|
|
32
|
+
private clampLogScrollOffset;
|
|
33
|
+
}
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import readline from "node:readline";
|
|
2
|
+
const CLEAR_SCREEN = "\x1b[2J";
|
|
3
|
+
const CLEAR_LINE = "\x1b[2K";
|
|
4
|
+
const CURSOR_HOME = "\x1b[H";
|
|
5
|
+
const HIDE_CURSOR = "\x1b[?25l";
|
|
6
|
+
const SHOW_CURSOR = "\x1b[?25h";
|
|
7
|
+
const ENTER_ALT_SCREEN = "\x1b[?1049h";
|
|
8
|
+
const EXIT_ALT_SCREEN = "\x1b[?1049l";
|
|
9
|
+
const ENABLE_MOUSE = "\x1b[?1000h\x1b[?1006h";
|
|
10
|
+
const DISABLE_MOUSE = "\x1b[?1000l\x1b[?1006l";
|
|
11
|
+
const RESET = "\x1b[0m";
|
|
12
|
+
const INVERSE = "\x1b[7m";
|
|
13
|
+
const DIM = "\x1b[2m";
|
|
14
|
+
const CYAN = "\x1b[36m";
|
|
15
|
+
const WHEEL_SCROLL_LINES = 3;
|
|
16
|
+
export class DevTui {
|
|
17
|
+
logSink = (entry) => this.addLog(entry);
|
|
18
|
+
services;
|
|
19
|
+
logs = new Map();
|
|
20
|
+
logScrollOffsets = new Map();
|
|
21
|
+
selectedIndex = 0;
|
|
22
|
+
isStarted = false;
|
|
23
|
+
isSelectionMode = false;
|
|
24
|
+
previousRawMode = false;
|
|
25
|
+
maxLines = 2000;
|
|
26
|
+
constructor(services) {
|
|
27
|
+
this.services = [...new Set(services)];
|
|
28
|
+
for (const service of this.services) {
|
|
29
|
+
this.logs.set(service, { lines: [], partial: "" });
|
|
30
|
+
this.logScrollOffsets.set(service, 0);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
start() {
|
|
34
|
+
if (this.isStarted || !process.stdout.isTTY || !process.stdin.isTTY) {
|
|
35
|
+
this.isStarted = process.stdout.isTTY && process.stdin.isTTY;
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
this.isStarted = true;
|
|
39
|
+
this.previousRawMode = process.stdin.isRaw;
|
|
40
|
+
process.stdout.write(`${ENTER_ALT_SCREEN}${HIDE_CURSOR}${ENABLE_MOUSE}`);
|
|
41
|
+
readline.emitKeypressEvents(process.stdin);
|
|
42
|
+
process.stdin.setRawMode(true);
|
|
43
|
+
process.stdin.resume();
|
|
44
|
+
process.stdin.on("data", this.handleInput);
|
|
45
|
+
process.stdin.on("keypress", this.handleKeypress);
|
|
46
|
+
process.stdout.on("resize", this.render);
|
|
47
|
+
this.render();
|
|
48
|
+
}
|
|
49
|
+
stop() {
|
|
50
|
+
if (!this.isStarted)
|
|
51
|
+
return;
|
|
52
|
+
process.stdin.off("data", this.handleInput);
|
|
53
|
+
process.stdin.off("keypress", this.handleKeypress);
|
|
54
|
+
process.stdout.off("resize", this.render);
|
|
55
|
+
this.isSelectionMode = false;
|
|
56
|
+
process.stdin.setRawMode(this.previousRawMode);
|
|
57
|
+
process.stdout.write(`${DISABLE_MOUSE}${SHOW_CURSOR}${EXIT_ALT_SCREEN}${RESET}`);
|
|
58
|
+
this.isStarted = false;
|
|
59
|
+
}
|
|
60
|
+
handleKeypress = (_input, key) => {
|
|
61
|
+
if (key.ctrl && key.name === "c") {
|
|
62
|
+
process.kill(process.pid, "SIGINT");
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (this.isSelectionMode) {
|
|
66
|
+
if (key.name === "escape" || key.name === "c") {
|
|
67
|
+
this.exitSelectionMode();
|
|
68
|
+
}
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (key.name === "c") {
|
|
72
|
+
this.enterSelectionMode();
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (key.name === "up" || key.name === "k") {
|
|
76
|
+
this.selectedIndex = Math.max(0, this.selectedIndex - 1);
|
|
77
|
+
this.render();
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (key.name === "down" || key.name === "j") {
|
|
81
|
+
this.selectedIndex = Math.min(this.services.length - 1, this.selectedIndex + 1);
|
|
82
|
+
this.render();
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
if (key.name === "pageup" || key.name === "u") {
|
|
86
|
+
this.scrollSelectedLog(this.getBodyHeight());
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (key.name === "pagedown" || key.name === "d") {
|
|
90
|
+
this.scrollSelectedLog(-this.getBodyHeight());
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
if (key.name === "home" || key.name === "g") {
|
|
94
|
+
this.scrollSelectedLog(Number.POSITIVE_INFINITY);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (key.name === "end" || (key.shift && key.name === "g")) {
|
|
98
|
+
this.logScrollOffsets.set(this.getSelectedService(), 0);
|
|
99
|
+
this.render();
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (key.name === "q") {
|
|
103
|
+
process.kill(process.pid, "SIGTERM");
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
handleInput = (chunk) => {
|
|
107
|
+
if (this.isSelectionMode)
|
|
108
|
+
return;
|
|
109
|
+
const input = chunk.toString();
|
|
110
|
+
for (const event of parseMouseEvents(input)) {
|
|
111
|
+
if (event.type === "wheel-up") {
|
|
112
|
+
this.scrollSelectedLog(WHEEL_SCROLL_LINES);
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (event.type === "wheel-down") {
|
|
116
|
+
this.scrollSelectedLog(-WHEEL_SCROLL_LINES);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (event.type === "press") {
|
|
120
|
+
this.selectServiceAt(event.x, event.y);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
addLog(entry) {
|
|
125
|
+
if (entry.serviceName === "system")
|
|
126
|
+
return;
|
|
127
|
+
const serviceName = entry.serviceName;
|
|
128
|
+
if (!this.logs.has(serviceName)) {
|
|
129
|
+
this.services.push(serviceName);
|
|
130
|
+
this.logs.set(serviceName, { lines: [], partial: "" });
|
|
131
|
+
this.logScrollOffsets.set(serviceName, 0);
|
|
132
|
+
this.selectedIndex = this.services.length - 1;
|
|
133
|
+
}
|
|
134
|
+
const log = this.logs.get(serviceName) ?? { lines: [], partial: "" };
|
|
135
|
+
const pieces = `${log.partial}${sanitizeLogChunk(entry.chunk)}`.split("\n");
|
|
136
|
+
log.partial = pieces.pop() ?? "";
|
|
137
|
+
for (const piece of pieces) {
|
|
138
|
+
log.lines.push(`${timestamp(entry.timestamp)} ${entry.stream === "stderr" ? "[err] " : ""}${piece}`);
|
|
139
|
+
}
|
|
140
|
+
if (log.lines.length > this.maxLines) {
|
|
141
|
+
log.lines.splice(0, log.lines.length - this.maxLines);
|
|
142
|
+
}
|
|
143
|
+
this.logs.set(serviceName, log);
|
|
144
|
+
this.clampLogScrollOffset(serviceName);
|
|
145
|
+
this.render();
|
|
146
|
+
}
|
|
147
|
+
render = (force = false) => {
|
|
148
|
+
if (!this.isStarted || !process.stdout.isTTY || (this.isSelectionMode && !force))
|
|
149
|
+
return;
|
|
150
|
+
const width = process.stdout.columns ?? 80;
|
|
151
|
+
const navWidth = getNavWidth(width);
|
|
152
|
+
const logWidth = Math.max(10, width - navWidth - 1);
|
|
153
|
+
const bodyHeight = this.getBodyHeight();
|
|
154
|
+
const selectedService = this.getSelectedService();
|
|
155
|
+
const log = this.logs.get(selectedService) ?? { lines: [], partial: "" };
|
|
156
|
+
const visibleLines = [...log.lines, log.partial].filter(Boolean);
|
|
157
|
+
const wrappedLogLines = visibleLines.flatMap((line) => wrapLine(line, logWidth));
|
|
158
|
+
const logScrollOffset = this.clampLogScrollOffset(selectedService, wrappedLogLines.length);
|
|
159
|
+
const logEnd = Math.max(bodyHeight, wrappedLogLines.length - logScrollOffset);
|
|
160
|
+
const logStart = Math.max(0, logEnd - bodyHeight);
|
|
161
|
+
const logLines = wrappedLogLines.slice(logStart, logEnd);
|
|
162
|
+
const rows = [];
|
|
163
|
+
rows.push(`${CYAN}SAWS dev${RESET}${DIM} ${this.getHelpText()}${RESET}`.padEnd(width));
|
|
164
|
+
rows.push(`${"Services".padEnd(navWidth)} ${logHeading(selectedService, logScrollOffset).padEnd(logWidth)}`);
|
|
165
|
+
for (let index = 0; index < bodyHeight; index += 1) {
|
|
166
|
+
const service = this.services[index] ?? "";
|
|
167
|
+
const isSelected = index === this.selectedIndex;
|
|
168
|
+
const serviceLabel = service === "" ? "" : ` ${service}`;
|
|
169
|
+
const nav = truncate(serviceLabel, navWidth).padEnd(navWidth);
|
|
170
|
+
const logLine = truncate(logLines[index] ?? "", logWidth).padEnd(logWidth);
|
|
171
|
+
rows.push(`${isSelected ? `${INVERSE}${nav}${RESET}` : nav} ${logLine}`);
|
|
172
|
+
}
|
|
173
|
+
process.stdout.write(renderRows(rows, width, process.stdout.rows ?? 24));
|
|
174
|
+
};
|
|
175
|
+
enterSelectionMode() {
|
|
176
|
+
this.isSelectionMode = true;
|
|
177
|
+
process.stdout.write(`${DISABLE_MOUSE}${SHOW_CURSOR}`);
|
|
178
|
+
this.render(true);
|
|
179
|
+
}
|
|
180
|
+
exitSelectionMode() {
|
|
181
|
+
this.isSelectionMode = false;
|
|
182
|
+
process.stdout.write(`${HIDE_CURSOR}${ENABLE_MOUSE}`);
|
|
183
|
+
this.render(true);
|
|
184
|
+
}
|
|
185
|
+
getHelpText() {
|
|
186
|
+
if (this.isSelectionMode)
|
|
187
|
+
return "select/copy text with terminal, esc resume";
|
|
188
|
+
return "up/down select, pgup/pgdn scroll, c copy/select, q quit";
|
|
189
|
+
}
|
|
190
|
+
getSelectedService() {
|
|
191
|
+
return this.services[this.selectedIndex] ?? "";
|
|
192
|
+
}
|
|
193
|
+
getBodyHeight() {
|
|
194
|
+
return Math.max(1, (process.stdout.rows ?? 24) - 3);
|
|
195
|
+
}
|
|
196
|
+
scrollSelectedLog(delta) {
|
|
197
|
+
const selectedService = this.getSelectedService();
|
|
198
|
+
const current = this.logScrollOffsets.get(selectedService) ?? 0;
|
|
199
|
+
this.logScrollOffsets.set(selectedService, current + delta);
|
|
200
|
+
this.render();
|
|
201
|
+
}
|
|
202
|
+
selectServiceAt(x, y) {
|
|
203
|
+
const navWidth = getNavWidth(process.stdout.columns ?? 80);
|
|
204
|
+
if (x > navWidth || y < 3)
|
|
205
|
+
return;
|
|
206
|
+
const serviceIndex = y - 3;
|
|
207
|
+
if (serviceIndex < 0 || serviceIndex >= this.services.length)
|
|
208
|
+
return;
|
|
209
|
+
this.selectedIndex = serviceIndex;
|
|
210
|
+
this.render();
|
|
211
|
+
}
|
|
212
|
+
clampLogScrollOffset(serviceName, wrappedLineCount) {
|
|
213
|
+
const width = process.stdout.columns ?? 80;
|
|
214
|
+
const navWidth = getNavWidth(width);
|
|
215
|
+
const logWidth = Math.max(10, width - navWidth - 1);
|
|
216
|
+
const log = this.logs.get(serviceName) ?? { lines: [], partial: "" };
|
|
217
|
+
const lineCount = wrappedLineCount ??
|
|
218
|
+
[...log.lines, log.partial].filter(Boolean).flatMap((line) => wrapLine(line, logWidth))
|
|
219
|
+
.length;
|
|
220
|
+
const maxOffset = Math.max(0, lineCount - this.getBodyHeight());
|
|
221
|
+
const nextOffset = Math.min(maxOffset, Math.max(0, this.logScrollOffsets.get(serviceName) ?? 0));
|
|
222
|
+
this.logScrollOffsets.set(serviceName, nextOffset);
|
|
223
|
+
return nextOffset;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
function logHeading(serviceName, scrollOffset) {
|
|
227
|
+
if (scrollOffset === 0)
|
|
228
|
+
return `Logs: ${serviceName}`;
|
|
229
|
+
return `Logs: ${serviceName} (${scrollOffset} lines from bottom)`;
|
|
230
|
+
}
|
|
231
|
+
function renderRows(rows, width, height) {
|
|
232
|
+
const output = [CURSOR_HOME, CLEAR_SCREEN];
|
|
233
|
+
for (let index = 0; index < height; index += 1) {
|
|
234
|
+
output.push(cursorPosition(index + 1, 1));
|
|
235
|
+
output.push(CLEAR_LINE);
|
|
236
|
+
output.push(truncate(rows[index] ?? "", width).padEnd(width));
|
|
237
|
+
}
|
|
238
|
+
return output.join("");
|
|
239
|
+
}
|
|
240
|
+
function cursorPosition(row, column) {
|
|
241
|
+
return `\x1b[${row};${column}H`;
|
|
242
|
+
}
|
|
243
|
+
function getNavWidth(terminalWidth) {
|
|
244
|
+
return Math.min(30, Math.max(18, Math.floor(terminalWidth * 0.28)));
|
|
245
|
+
}
|
|
246
|
+
function parseMouseEvents(input) {
|
|
247
|
+
const events = [];
|
|
248
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
249
|
+
if (input.charCodeAt(index) !== 27 || input[index + 1] !== "[" || input[index + 2] !== "<") {
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
const codeResult = readUnsignedNumber(input, index + 3);
|
|
253
|
+
if (codeResult == null || input[codeResult.nextIndex] !== ";")
|
|
254
|
+
continue;
|
|
255
|
+
const xResult = readUnsignedNumber(input, codeResult.nextIndex + 1);
|
|
256
|
+
if (xResult == null || input[xResult.nextIndex] !== ";")
|
|
257
|
+
continue;
|
|
258
|
+
const yResult = readUnsignedNumber(input, xResult.nextIndex + 1);
|
|
259
|
+
if (yResult == null)
|
|
260
|
+
continue;
|
|
261
|
+
const action = input[yResult.nextIndex];
|
|
262
|
+
index = yResult.nextIndex;
|
|
263
|
+
if (action !== "M")
|
|
264
|
+
continue;
|
|
265
|
+
if (codeResult.value >= 64 && codeResult.value <= 95) {
|
|
266
|
+
const wheelDirection = codeResult.value & 3;
|
|
267
|
+
if (wheelDirection === 0) {
|
|
268
|
+
events.push({ type: "wheel-up", x: xResult.value, y: yResult.value });
|
|
269
|
+
}
|
|
270
|
+
else if (wheelDirection === 1) {
|
|
271
|
+
events.push({ type: "wheel-down", x: xResult.value, y: yResult.value });
|
|
272
|
+
}
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
if ((codeResult.value & 3) === 0) {
|
|
276
|
+
events.push({ type: "press", x: xResult.value, y: yResult.value });
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return events;
|
|
280
|
+
}
|
|
281
|
+
function readUnsignedNumber(value, startIndex) {
|
|
282
|
+
let index = startIndex;
|
|
283
|
+
while (index < value.length && value[index] >= "0" && value[index] <= "9") {
|
|
284
|
+
index += 1;
|
|
285
|
+
}
|
|
286
|
+
if (index === startIndex)
|
|
287
|
+
return null;
|
|
288
|
+
return {
|
|
289
|
+
value: Number(value.slice(startIndex, index)),
|
|
290
|
+
nextIndex: index,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
function timestamp(date) {
|
|
294
|
+
return date.toLocaleTimeString(undefined, {
|
|
295
|
+
hour12: false,
|
|
296
|
+
hour: "2-digit",
|
|
297
|
+
minute: "2-digit",
|
|
298
|
+
second: "2-digit",
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
function wrapLine(line, width) {
|
|
302
|
+
const chunks = [];
|
|
303
|
+
let remaining = line;
|
|
304
|
+
while (visibleLength(remaining) > width) {
|
|
305
|
+
chunks.push(remaining.slice(0, width));
|
|
306
|
+
remaining = remaining.slice(width);
|
|
307
|
+
}
|
|
308
|
+
chunks.push(remaining);
|
|
309
|
+
return chunks;
|
|
310
|
+
}
|
|
311
|
+
function truncate(value, width) {
|
|
312
|
+
if (visibleLength(value) <= width)
|
|
313
|
+
return value;
|
|
314
|
+
if (width <= 3)
|
|
315
|
+
return value.slice(0, width);
|
|
316
|
+
return `${value.slice(0, width - 3)}...`;
|
|
317
|
+
}
|
|
318
|
+
function visibleLength(value) {
|
|
319
|
+
return stripAnsiColor(value).length;
|
|
320
|
+
}
|
|
321
|
+
function sanitizeLogChunk(value) {
|
|
322
|
+
return stripAnsiControlSequences(value.replaceAll("\r\n", "\n").replaceAll("\r", "\n"));
|
|
323
|
+
}
|
|
324
|
+
function stripAnsiControlSequences(value) {
|
|
325
|
+
let stripped = "";
|
|
326
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
327
|
+
const code = value.charCodeAt(index);
|
|
328
|
+
if (code === 27) {
|
|
329
|
+
index = skipEscapeSequence(value, index);
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
if ((code >= 0 && code < 9) || (code > 13 && code < 32) || code === 127) {
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
stripped += value[index];
|
|
336
|
+
}
|
|
337
|
+
return stripped;
|
|
338
|
+
}
|
|
339
|
+
function skipEscapeSequence(value, startIndex) {
|
|
340
|
+
const next = value[startIndex + 1];
|
|
341
|
+
if (next === "[") {
|
|
342
|
+
let index = startIndex + 2;
|
|
343
|
+
while (index < value.length) {
|
|
344
|
+
const code = value.charCodeAt(index);
|
|
345
|
+
if (code >= 64 && code <= 126)
|
|
346
|
+
return index;
|
|
347
|
+
index += 1;
|
|
348
|
+
}
|
|
349
|
+
return value.length - 1;
|
|
350
|
+
}
|
|
351
|
+
if (next === "]") {
|
|
352
|
+
let index = startIndex + 2;
|
|
353
|
+
while (index < value.length) {
|
|
354
|
+
if (value.charCodeAt(index) === 7)
|
|
355
|
+
return index;
|
|
356
|
+
if (value.charCodeAt(index) === 27 && value[index + 1] === "\\")
|
|
357
|
+
return index + 1;
|
|
358
|
+
index += 1;
|
|
359
|
+
}
|
|
360
|
+
return value.length - 1;
|
|
361
|
+
}
|
|
362
|
+
return Math.min(startIndex + 1, value.length - 1);
|
|
363
|
+
}
|
|
364
|
+
function stripAnsiColor(value) {
|
|
365
|
+
let stripped = "";
|
|
366
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
367
|
+
if (value.charCodeAt(index) !== 27) {
|
|
368
|
+
stripped += value[index];
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
if (value[index + 1] !== "[") {
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
index += 2;
|
|
375
|
+
while (index < value.length && /[0-9;]/.test(value[index] ?? "")) {
|
|
376
|
+
index += 1;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return stripped;
|
|
380
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Host } from "@saws/core";
|
|
2
|
+
export interface ConfigureHostCommandOptions {
|
|
3
|
+
config?: string;
|
|
4
|
+
dryRun?: boolean;
|
|
5
|
+
global?: boolean;
|
|
6
|
+
user: string;
|
|
7
|
+
}
|
|
8
|
+
export declare function configureHostCommand(name: string | undefined, options: ConfigureHostCommandOptions): Promise<void>;
|
|
9
|
+
export declare function selectHost(hosts: Host[], name?: string): Host;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { chmod, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { ParameterNotFoundError, SecretsManager, ServiceDefinition, getGlobalHost, getGlobalHostSecretsManager, getSawsConfigModule, hostSshPublicKeyEnvName, } from "@saws/core";
|
|
4
|
+
import { findConfiguredHosts } from "../../hosts.js";
|
|
5
|
+
import { derivePublicKey, generatePrivateKey } from "./deployment-key.js";
|
|
6
|
+
export async function configureHostCommand(name, options) {
|
|
7
|
+
if (options.global) {
|
|
8
|
+
if (options.config != null) {
|
|
9
|
+
throw new Error("host configure accepts only one of --global or --config <path>");
|
|
10
|
+
}
|
|
11
|
+
if (name == null) {
|
|
12
|
+
throw new Error("host configure --global requires a host name");
|
|
13
|
+
}
|
|
14
|
+
await configureSelectedHost(getGlobalHost(name), getGlobalHostSecretsManager(), options);
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
const config = await getSawsConfigModule(options.config);
|
|
18
|
+
if (!(config.secrets instanceof SecretsManager)) {
|
|
19
|
+
throw new Error('saws.ts must export a SecretsManager instance named "secrets"');
|
|
20
|
+
}
|
|
21
|
+
if (!(config.default instanceof ServiceDefinition)) {
|
|
22
|
+
throw new Error("saws.ts must default-export a ServiceDefinition");
|
|
23
|
+
}
|
|
24
|
+
const host = selectHost(findConfiguredHosts(config.default), name);
|
|
25
|
+
await configureSelectedHost(host, config.secrets, options);
|
|
26
|
+
}
|
|
27
|
+
async function configureSelectedHost(host, manager, options) {
|
|
28
|
+
validatePrivateKeyReference(host, manager);
|
|
29
|
+
if (options.dryRun) {
|
|
30
|
+
await host.configure({
|
|
31
|
+
bootstrapUser: options.user,
|
|
32
|
+
deploymentPublicKey: "[redacted deployment public key]",
|
|
33
|
+
dryRun: true,
|
|
34
|
+
});
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const { privateKey, created } = await getOrCreateDeploymentKey(manager, host);
|
|
38
|
+
const publicKey = await derivePublicKey(privateKey);
|
|
39
|
+
if (created) {
|
|
40
|
+
await manager.global.set(host.sshPrivateKey.name, privateKey);
|
|
41
|
+
}
|
|
42
|
+
await updatePublicKeyEnvironment(manager.rootDir, hostSshPublicKeyEnvName(host.name), publicKey);
|
|
43
|
+
await host.configure({
|
|
44
|
+
bootstrapUser: options.user,
|
|
45
|
+
deploymentPublicKey: publicKey,
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
export function selectHost(hosts, name) {
|
|
49
|
+
if (hosts.length === 0) {
|
|
50
|
+
throw new Error("No hosts are configured");
|
|
51
|
+
}
|
|
52
|
+
const host = name == null
|
|
53
|
+
? hosts.length === 1
|
|
54
|
+
? hosts[0]
|
|
55
|
+
: undefined
|
|
56
|
+
: hosts.find((candidate) => candidate.name === name);
|
|
57
|
+
if (host != null)
|
|
58
|
+
return host;
|
|
59
|
+
const available = hosts
|
|
60
|
+
.map((candidate) => candidate.name)
|
|
61
|
+
.sort()
|
|
62
|
+
.join(", ");
|
|
63
|
+
throw new Error(name == null
|
|
64
|
+
? `Host name is required. Available hosts: ${available}`
|
|
65
|
+
: `Host "${name}" was not found. Available hosts: ${available}`);
|
|
66
|
+
}
|
|
67
|
+
function validatePrivateKeyReference(host, manager) {
|
|
68
|
+
if (host.sshPrivateKey == null || host.sshPrivateKey.scope !== "global") {
|
|
69
|
+
throw new Error(`Host "${host.name}" must configure sshPrivateKey with secrets.global.reference(...)`);
|
|
70
|
+
}
|
|
71
|
+
if (!host.sshPrivateKey.isManagedBy(manager)) {
|
|
72
|
+
throw new Error(`Host "${host.name}" sshPrivateKey must use the SecretsManager exported as "secrets"`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async function getOrCreateDeploymentKey(manager, host) {
|
|
76
|
+
try {
|
|
77
|
+
return {
|
|
78
|
+
privateKey: await manager.global.get(host.sshPrivateKey.name),
|
|
79
|
+
created: false,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (!(error instanceof ParameterNotFoundError))
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
privateKey: await generatePrivateKey(),
|
|
88
|
+
created: true,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
async function updatePublicKeyEnvironment(rootDir, variableName, publicKey) {
|
|
92
|
+
const envPath = path.resolve(rootDir, ".env");
|
|
93
|
+
let contents = "";
|
|
94
|
+
try {
|
|
95
|
+
contents = await readFile(envPath, "utf8");
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (error.code !== "ENOENT")
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
const matcher = new RegExp(`^(?:export\\s+)?${escapeRegExp(variableName)}\\s*=`);
|
|
102
|
+
const lines = contents.split(/\r?\n/);
|
|
103
|
+
const replacement = `${variableName}=${publicKey}`;
|
|
104
|
+
let replaced = false;
|
|
105
|
+
const updated = lines.flatMap((line) => {
|
|
106
|
+
if (!matcher.test(line))
|
|
107
|
+
return [line];
|
|
108
|
+
if (replaced)
|
|
109
|
+
return [];
|
|
110
|
+
replaced = true;
|
|
111
|
+
return [replacement];
|
|
112
|
+
});
|
|
113
|
+
while (updated.at(-1) === "")
|
|
114
|
+
updated.pop();
|
|
115
|
+
if (!replaced)
|
|
116
|
+
updated.push(replacement);
|
|
117
|
+
const temporaryPath = `${envPath}.${process.pid}.tmp`;
|
|
118
|
+
try {
|
|
119
|
+
await writeFile(temporaryPath, `${updated.join("\n")}\n`, { mode: 0o600 });
|
|
120
|
+
await rename(temporaryPath, envPath);
|
|
121
|
+
await chmod(envPath, 0o600);
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
await rm(temporaryPath, { force: true });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function escapeRegExp(value) {
|
|
128
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
129
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface CreateHostCommandOptions {
|
|
2
|
+
address: string;
|
|
3
|
+
user: string;
|
|
4
|
+
sshPort?: string;
|
|
5
|
+
exposure?: string;
|
|
6
|
+
platform?: string;
|
|
7
|
+
allowedTcpPort?: string[];
|
|
8
|
+
}
|
|
9
|
+
export declare function createHostCommand(name: string, options: CreateHostCommandOptions): Promise<void>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { createGlobalHost } from "@saws/core";
|
|
2
|
+
export async function createHostCommand(name, options) {
|
|
3
|
+
const host = await createGlobalHost({
|
|
4
|
+
name,
|
|
5
|
+
address: options.address,
|
|
6
|
+
user: options.user,
|
|
7
|
+
...(options.sshPort == null ? {} : { sshPort: parsePort(options.sshPort, "SSH port") }),
|
|
8
|
+
...(options.exposure == null ? {} : { exposure: parseExposure(options.exposure) }),
|
|
9
|
+
...(options.platform == null ? {} : { platform: options.platform }),
|
|
10
|
+
...(options.allowedTcpPort == null
|
|
11
|
+
? {}
|
|
12
|
+
: {
|
|
13
|
+
allowedTcpPorts: options.allowedTcpPort.map((port) => parsePort(port, "Allowed TCP port")),
|
|
14
|
+
}),
|
|
15
|
+
});
|
|
16
|
+
console.log(`Created global host "${host.name}" at ${host.address}`);
|
|
17
|
+
}
|
|
18
|
+
function parsePort(value, label) {
|
|
19
|
+
const port = Number(value);
|
|
20
|
+
if (!Number.isInteger(port) || port < 1 || port > 65_535) {
|
|
21
|
+
throw new Error(`${label} must be a valid TCP port`);
|
|
22
|
+
}
|
|
23
|
+
return port;
|
|
24
|
+
}
|
|
25
|
+
function parseExposure(value) {
|
|
26
|
+
if (value !== "tunnel" && value !== "public") {
|
|
27
|
+
throw new Error('Host exposure must be either "tunnel" or "public"');
|
|
28
|
+
}
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
export async function generatePrivateKey() {
|
|
7
|
+
return withTemporaryDirectory(async (directory) => {
|
|
8
|
+
const keyPath = path.join(directory, "id_ed25519");
|
|
9
|
+
await execFileAsync("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-f", keyPath]);
|
|
10
|
+
return readFile(keyPath, "utf8");
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
export async function derivePublicKey(privateKey) {
|
|
14
|
+
return withTemporaryDirectory(async (directory) => {
|
|
15
|
+
const keyPath = path.join(directory, "id_private");
|
|
16
|
+
await writeFile(keyPath, privateKey, { mode: 0o600 });
|
|
17
|
+
let stdout;
|
|
18
|
+
try {
|
|
19
|
+
({ stdout } = await execFileAsync("ssh-keygen", ["-y", "-P", "", "-f", keyPath]));
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
throw new Error("SSH private key is invalid or passphrase-protected; SAWS host keys must not require a passphrase");
|
|
23
|
+
}
|
|
24
|
+
const publicKey = stdout.trim();
|
|
25
|
+
if (publicKey.length === 0) {
|
|
26
|
+
throw new Error("Could not derive the deployment public key");
|
|
27
|
+
}
|
|
28
|
+
return publicKey;
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
async function withTemporaryDirectory(callback) {
|
|
32
|
+
const directory = await mkdtemp(path.join(tmpdir(), "saws-key-"));
|
|
33
|
+
try {
|
|
34
|
+
return await callback(directory);
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
await rm(directory, { recursive: true, force: true });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const execFileAsync = promisify(execFile);
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { ParameterNotFoundError, getGlobalHost, getGlobalHostSecretsManager } from "@saws/core";
|
|
4
|
+
import { derivePublicKey } from "./deployment-key.js";
|
|
5
|
+
export async function importHostKeyCommand(name, options) {
|
|
6
|
+
const host = getGlobalHost(name);
|
|
7
|
+
const keyPath = path.resolve(options.file);
|
|
8
|
+
let privateKey;
|
|
9
|
+
try {
|
|
10
|
+
privateKey = await readFile(keyPath, "utf8");
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
if (error.code === "ENOENT") {
|
|
14
|
+
throw new Error(`SSH private key file does not exist: ${keyPath}`);
|
|
15
|
+
}
|
|
16
|
+
throw error;
|
|
17
|
+
}
|
|
18
|
+
if (privateKey.trim().length === 0) {
|
|
19
|
+
throw new Error(`SSH private key file is empty: ${keyPath}`);
|
|
20
|
+
}
|
|
21
|
+
await derivePublicKey(privateKey);
|
|
22
|
+
const manager = getGlobalHostSecretsManager();
|
|
23
|
+
const secretName = host.sshPrivateKey.name;
|
|
24
|
+
if (!options.force && (await secretExists(manager, secretName))) {
|
|
25
|
+
throw new Error(`Global host "${host.name}" already has a deployment key; pass --force to replace it`);
|
|
26
|
+
}
|
|
27
|
+
await manager.global.set(secretName, privateKey);
|
|
28
|
+
console.log(`Imported deployment key for global host "${host.name}"`);
|
|
29
|
+
}
|
|
30
|
+
async function secretExists(manager, secretName) {
|
|
31
|
+
try {
|
|
32
|
+
await manager.global.get(secretName);
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (error instanceof ParameterNotFoundError)
|
|
37
|
+
return false;
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
}
|