tring-chat 0.1.5 → 0.1.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.
package/dist/tring.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
// src/index.ts
|
|
4
|
-
import { existsSync as existsSync2 } from "node:fs";
|
|
4
|
+
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
|
|
5
5
|
import { createServer } from "node:http";
|
|
6
|
-
import
|
|
6
|
+
import { createServer as createSecureServer } from "node:https";
|
|
7
|
+
import path6 from "node:path";
|
|
7
8
|
import { fileURLToPath } from "node:url";
|
|
8
9
|
import { WebSocketServer } from "ws";
|
|
9
10
|
|
|
@@ -12,10 +13,10 @@ var DEFAULT_PORT = 7331;
|
|
|
12
13
|
var DEFAULT_HOST = "127.0.0.1";
|
|
13
14
|
var DEFAULT_SCROLLBACK = 5e3;
|
|
14
15
|
function encodeOutput(id, data) {
|
|
15
|
-
const
|
|
16
|
-
const out = new Uint8Array(
|
|
17
|
-
out.set(
|
|
18
|
-
out.set(data,
|
|
16
|
+
const head2 = new TextEncoder().encode(id + "\0");
|
|
17
|
+
const out = new Uint8Array(head2.length + data.length);
|
|
18
|
+
out.set(head2, 0);
|
|
19
|
+
out.set(data, head2.length);
|
|
19
20
|
return out;
|
|
20
21
|
}
|
|
21
22
|
|
|
@@ -121,18 +122,272 @@ var ActivityTracker = class {
|
|
|
121
122
|
}
|
|
122
123
|
};
|
|
123
124
|
|
|
124
|
-
// src/
|
|
125
|
-
import {
|
|
126
|
-
import {
|
|
125
|
+
// src/token.ts
|
|
126
|
+
import { randomBytes } from "node:crypto";
|
|
127
|
+
import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
127
128
|
import os from "node:os";
|
|
128
129
|
import path from "node:path";
|
|
130
|
+
var MIN_TOKEN_LENGTH = 16;
|
|
131
|
+
function defaultTokenPath() {
|
|
132
|
+
const base2 = process.env["XDG_CONFIG_HOME"] ?? path.join(os.homedir(), ".config");
|
|
133
|
+
return path.join(base2, "tring", "token");
|
|
134
|
+
}
|
|
135
|
+
function generateToken() {
|
|
136
|
+
return randomBytes(32).toString("hex");
|
|
137
|
+
}
|
|
138
|
+
function tokenProblem(token) {
|
|
139
|
+
if (token.trim() !== token) return "a token cannot start or end with whitespace";
|
|
140
|
+
if (token.length < MIN_TOKEN_LENGTH) {
|
|
141
|
+
return `a token must be at least ${MIN_TOKEN_LENGTH} characters \u2014 generate one with \`openssl rand -hex 32\``;
|
|
142
|
+
}
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
function lockDown(file) {
|
|
146
|
+
try {
|
|
147
|
+
chmodSync(file, 384);
|
|
148
|
+
} catch {
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function loadOrCreateToken(file = defaultTokenPath()) {
|
|
152
|
+
try {
|
|
153
|
+
const existing = readFileSync(file, "utf8").trim();
|
|
154
|
+
if (tokenProblem(existing) === null) {
|
|
155
|
+
lockDown(file);
|
|
156
|
+
return existing;
|
|
157
|
+
}
|
|
158
|
+
} catch {
|
|
159
|
+
}
|
|
160
|
+
const token = generateToken();
|
|
161
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
162
|
+
writeFileSync(file, `${token}
|
|
163
|
+
`, { mode: 384 });
|
|
164
|
+
lockDown(file);
|
|
165
|
+
return token;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// src/update-check.ts
|
|
169
|
+
import { createRequire } from "node:module";
|
|
170
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
171
|
+
import path2 from "node:path";
|
|
172
|
+
var require2 = createRequire(import.meta.url);
|
|
173
|
+
function currentVersion() {
|
|
174
|
+
try {
|
|
175
|
+
return require2("../package.json").version;
|
|
176
|
+
} catch {
|
|
177
|
+
return "0.0.0";
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function isNewer(latest, current) {
|
|
181
|
+
if (latest.includes("-")) return false;
|
|
182
|
+
const parse = (v) => v.split("-")[0].split(".").map((n) => Number(n) || 0);
|
|
183
|
+
const a = parse(latest);
|
|
184
|
+
const b = parse(current);
|
|
185
|
+
for (let i = 0; i < 3; i++) {
|
|
186
|
+
const x = a[i] ?? 0;
|
|
187
|
+
const y = b[i] ?? 0;
|
|
188
|
+
if (x !== y) return x > y;
|
|
189
|
+
}
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
193
|
+
async function checkForUpdate(cachePath) {
|
|
194
|
+
const current = currentVersion();
|
|
195
|
+
let cache = null;
|
|
196
|
+
try {
|
|
197
|
+
cache = JSON.parse(await readFile(cachePath, "utf8"));
|
|
198
|
+
} catch {
|
|
199
|
+
cache = null;
|
|
200
|
+
}
|
|
201
|
+
if (cache && Date.now() - cache.checkedAt < DAY_MS) {
|
|
202
|
+
return isNewer(cache.latest, current) ? cache.latest : null;
|
|
203
|
+
}
|
|
204
|
+
let latest;
|
|
205
|
+
try {
|
|
206
|
+
const res = await fetch("https://registry.npmjs.org/tring-chat/latest", {
|
|
207
|
+
signal: AbortSignal.timeout(3e3)
|
|
208
|
+
});
|
|
209
|
+
if (!res.ok) return null;
|
|
210
|
+
latest = (await res.json()).version ?? "";
|
|
211
|
+
if (!latest) return null;
|
|
212
|
+
} catch {
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
try {
|
|
216
|
+
await mkdir(path2.dirname(cachePath), { recursive: true });
|
|
217
|
+
await writeFile(cachePath, JSON.stringify({ checkedAt: Date.now(), latest }), "utf8");
|
|
218
|
+
} catch {
|
|
219
|
+
}
|
|
220
|
+
return isNewer(latest, current) ? latest : null;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// src/args.ts
|
|
224
|
+
var listOf = (value) => (value ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
225
|
+
var UsageError = class extends Error {
|
|
226
|
+
};
|
|
227
|
+
var HELP = `tring \u2014 focus-centred terminal deck
|
|
228
|
+
|
|
229
|
+
--port <n> default ${DEFAULT_PORT}
|
|
230
|
+
--host <addr> default ${DEFAULT_HOST}
|
|
231
|
+
--token <secret> bearer token clients must present. One is generated and
|
|
232
|
+
kept at ~/.config/tring/token when this is not given
|
|
233
|
+
--tls-cert <file> PEM certificate; serves https/wss instead of http/ws
|
|
234
|
+
--tls-key <file> PEM private key for --tls-cert
|
|
235
|
+
--scrollback <n> lines kept per session, default ${DEFAULT_SCROLLBACK}
|
|
236
|
+
--idle-ms <n> quiet period before a session is done, default ${DEFAULT_IDLE_MS}
|
|
237
|
+
--shell <path> shell to spawn; default $SHELL, or powershell.exe on
|
|
238
|
+
Windows. Use --shell wsl.exe for WSL shells from Windows
|
|
239
|
+
--fs-root <path> extra directory the project picker may browse; repeatable.
|
|
240
|
+
Home and existing project roots are always browsable
|
|
241
|
+
--allow-origin <o> extra browser origin allowed to reach the daemon;
|
|
242
|
+
repeatable. Only the page the daemon serves is allowed by
|
|
243
|
+
default, which is what stops any website you visit from
|
|
244
|
+
opening a socket to it
|
|
245
|
+
--insecure-no-token
|
|
246
|
+
run with no token at all. The daemon spawns shells, so
|
|
247
|
+
this hands one to every process on this machine, to
|
|
248
|
+
everything that can reach the port when bound off
|
|
249
|
+
localhost, and to any site that can rebind a name to it
|
|
250
|
+
--no-open do not launch a browser window
|
|
251
|
+
--no-update-check do not ask npm whether a newer tring exists
|
|
252
|
+
--version print the version and exit`;
|
|
253
|
+
function parseArgs(argv) {
|
|
254
|
+
const args = {
|
|
255
|
+
port: Number(process.env["TRING_PORT"] ?? DEFAULT_PORT),
|
|
256
|
+
host: process.env["TRING_HOST"] ?? DEFAULT_HOST,
|
|
257
|
+
token: process.env["TRING_TOKEN"] ?? null,
|
|
258
|
+
scrollback: DEFAULT_SCROLLBACK,
|
|
259
|
+
idleMs: DEFAULT_IDLE_MS,
|
|
260
|
+
open: !process.env["TRING_NO_OPEN"],
|
|
261
|
+
shell: process.env["TRING_SHELL"] ?? null,
|
|
262
|
+
updateCheck: !process.env["TRING_NO_UPDATE_CHECK"],
|
|
263
|
+
allowOrigin: listOf(process.env["TRING_ALLOW_ORIGIN"]),
|
|
264
|
+
fsRoot: listOf(process.env["TRING_FS_ROOT"]),
|
|
265
|
+
insecureNoToken: !!process.env["TRING_INSECURE_NO_TOKEN"],
|
|
266
|
+
tlsCert: process.env["TRING_TLS_CERT"] ?? null,
|
|
267
|
+
tlsKey: process.env["TRING_TLS_KEY"] ?? null
|
|
268
|
+
};
|
|
269
|
+
for (let i = 0; i < argv.length; i++) {
|
|
270
|
+
const arg = argv[i];
|
|
271
|
+
const eq = arg.indexOf("=");
|
|
272
|
+
const flag = eq === -1 ? arg : arg.slice(0, eq);
|
|
273
|
+
const inline = eq === -1 ? void 0 : arg.slice(eq + 1);
|
|
274
|
+
const take = () => {
|
|
275
|
+
const separate = inline === void 0;
|
|
276
|
+
const value = separate ? argv[i + 1] : inline;
|
|
277
|
+
if (value === void 0 || value === "") throw new UsageError(`${flag} needs a value`);
|
|
278
|
+
if (separate && value.startsWith("--")) {
|
|
279
|
+
throw new UsageError(`${flag} needs a value, but the next argument is ${value}`);
|
|
280
|
+
}
|
|
281
|
+
if (separate) i++;
|
|
282
|
+
return value;
|
|
283
|
+
};
|
|
284
|
+
const takeNumber = () => {
|
|
285
|
+
const raw = take();
|
|
286
|
+
const n = Number(raw);
|
|
287
|
+
if (!Number.isFinite(n)) throw new UsageError(`${flag} needs a number, got ${raw}`);
|
|
288
|
+
return n;
|
|
289
|
+
};
|
|
290
|
+
const noValue = () => {
|
|
291
|
+
if (inline !== void 0) throw new UsageError(`${flag} takes no value`);
|
|
292
|
+
};
|
|
293
|
+
switch (flag) {
|
|
294
|
+
case "--port": {
|
|
295
|
+
const port = takeNumber();
|
|
296
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
|
297
|
+
throw new UsageError(`--port must be a whole number from 0 to 65535, got ${port}`);
|
|
298
|
+
}
|
|
299
|
+
args.port = port;
|
|
300
|
+
break;
|
|
301
|
+
}
|
|
302
|
+
case "--host":
|
|
303
|
+
args.host = take();
|
|
304
|
+
break;
|
|
305
|
+
case "--token": {
|
|
306
|
+
const token = take();
|
|
307
|
+
const problem = tokenProblem(token);
|
|
308
|
+
if (problem) throw new UsageError(`--token: ${problem}`);
|
|
309
|
+
args.token = token;
|
|
310
|
+
break;
|
|
311
|
+
}
|
|
312
|
+
case "--tls-cert":
|
|
313
|
+
args.tlsCert = take();
|
|
314
|
+
break;
|
|
315
|
+
case "--tls-key":
|
|
316
|
+
args.tlsKey = take();
|
|
317
|
+
break;
|
|
318
|
+
case "--scrollback": {
|
|
319
|
+
const lines = takeNumber();
|
|
320
|
+
if (!Number.isInteger(lines) || lines < 0) {
|
|
321
|
+
throw new UsageError(`--scrollback must be a whole number of lines, got ${lines}`);
|
|
322
|
+
}
|
|
323
|
+
args.scrollback = lines;
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
case "--idle-ms": {
|
|
327
|
+
const ms = takeNumber();
|
|
328
|
+
if (!Number.isInteger(ms) || ms < 0) {
|
|
329
|
+
throw new UsageError(`--idle-ms must be a whole number of milliseconds, got ${ms}`);
|
|
330
|
+
}
|
|
331
|
+
args.idleMs = ms;
|
|
332
|
+
break;
|
|
333
|
+
}
|
|
334
|
+
case "--shell":
|
|
335
|
+
args.shell = take();
|
|
336
|
+
break;
|
|
337
|
+
case "--allow-origin":
|
|
338
|
+
args.allowOrigin.push(...listOf(take()));
|
|
339
|
+
break;
|
|
340
|
+
case "--fs-root":
|
|
341
|
+
args.fsRoot.push(...listOf(take()));
|
|
342
|
+
break;
|
|
343
|
+
case "--insecure-no-token":
|
|
344
|
+
noValue();
|
|
345
|
+
args.insecureNoToken = true;
|
|
346
|
+
break;
|
|
347
|
+
case "--no-open":
|
|
348
|
+
noValue();
|
|
349
|
+
args.open = false;
|
|
350
|
+
break;
|
|
351
|
+
case "--no-update-check":
|
|
352
|
+
noValue();
|
|
353
|
+
args.updateCheck = false;
|
|
354
|
+
break;
|
|
355
|
+
case "--version":
|
|
356
|
+
console.log(currentVersion());
|
|
357
|
+
process.exit(0);
|
|
358
|
+
break;
|
|
359
|
+
case "--help":
|
|
360
|
+
console.log(HELP);
|
|
361
|
+
process.exit(0);
|
|
362
|
+
break;
|
|
363
|
+
// A flag we silently ignored used to mean a `--tokn` typo ran an
|
|
364
|
+
// unauthenticated daemon that looked authenticated.
|
|
365
|
+
default:
|
|
366
|
+
throw new UsageError(`unknown argument ${arg}`);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
if (args.token !== null) {
|
|
370
|
+
const problem = tokenProblem(args.token);
|
|
371
|
+
if (problem) throw new UsageError(`TRING_TOKEN: ${problem}`);
|
|
372
|
+
}
|
|
373
|
+
if (!args.tlsCert !== !args.tlsKey) {
|
|
374
|
+
throw new UsageError("--tls-cert and --tls-key must be given together");
|
|
375
|
+
}
|
|
376
|
+
return args;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// src/project-manager.ts
|
|
380
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
381
|
+
import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
|
|
382
|
+
import os2 from "node:os";
|
|
383
|
+
import path3 from "node:path";
|
|
129
384
|
|
|
130
385
|
// src/session-manager.ts
|
|
131
386
|
import { randomUUID } from "node:crypto";
|
|
132
387
|
|
|
133
388
|
// src/session.ts
|
|
134
389
|
import { readlinkSync } from "node:fs";
|
|
135
|
-
import { createRequire } from "node:module";
|
|
390
|
+
import { createRequire as createRequire2 } from "node:module";
|
|
136
391
|
import { spawn } from "node-pty";
|
|
137
392
|
|
|
138
393
|
// src/snapshot.ts
|
|
@@ -148,14 +403,14 @@ function snapshot(term) {
|
|
|
148
403
|
const cell = line.getCell(x);
|
|
149
404
|
if (!cell) break;
|
|
150
405
|
if (cell.getWidth() === 0) continue;
|
|
151
|
-
const
|
|
406
|
+
const text2 = cell.getChars() || " ";
|
|
152
407
|
const fg = cell.isFgDefault() ? -1 : cell.getFgColor();
|
|
153
408
|
const bg = cell.isBgDefault() ? -1 : cell.getBgColor();
|
|
154
409
|
const bold = cell.isBold() !== 0;
|
|
155
410
|
if (run && run.fg === fg && run.bg === bg && run.bold === bold) {
|
|
156
|
-
run.text +=
|
|
411
|
+
run.text += text2;
|
|
157
412
|
} else {
|
|
158
|
-
run = { text, fg, bg, bold };
|
|
413
|
+
run = { text: text2, fg, bg, bold };
|
|
159
414
|
out.push(run);
|
|
160
415
|
}
|
|
161
416
|
}
|
|
@@ -216,9 +471,9 @@ function interactiveArgs(shell) {
|
|
|
216
471
|
}
|
|
217
472
|
|
|
218
473
|
// src/session.ts
|
|
219
|
-
var
|
|
220
|
-
var { Terminal } =
|
|
221
|
-
var { SerializeAddon } =
|
|
474
|
+
var require3 = createRequire2(import.meta.url);
|
|
475
|
+
var { Terminal } = require3("@xterm/headless");
|
|
476
|
+
var { SerializeAddon } = require3("@xterm/addon-serialize");
|
|
222
477
|
var CWD_POLL_MS = 2e3;
|
|
223
478
|
var CWD_ENFORCE_MS = 400;
|
|
224
479
|
var Session = class {
|
|
@@ -269,6 +524,8 @@ var Session = class {
|
|
|
269
524
|
env["TRING_SLOT"] = String(this.slot);
|
|
270
525
|
env["TRING_PROJECT"] = opts.projectName;
|
|
271
526
|
env["TRING_URL"] = opts.url;
|
|
527
|
+
if (opts.token) env["TRING_TOKEN"] = opts.token;
|
|
528
|
+
else delete env["TRING_TOKEN"];
|
|
272
529
|
const autorun = opts.autorun ?? true;
|
|
273
530
|
const args = this.command && autorun ? commandArgs(shell, this.command) : interactiveArgs(shell);
|
|
274
531
|
this.pty = spawn(shell, args, {
|
|
@@ -464,6 +721,7 @@ var SessionManager = class {
|
|
|
464
721
|
name: spec.name ?? null,
|
|
465
722
|
color: HEX.test(spec.color ?? "") ? spec.color : null,
|
|
466
723
|
url: this.opts.url,
|
|
724
|
+
token: this.opts.token ?? null,
|
|
467
725
|
scrollback: this.opts.scrollback,
|
|
468
726
|
idleMs: this.opts.idleMs,
|
|
469
727
|
...this.opts.shell ? { shell: this.opts.shell } : {},
|
|
@@ -546,8 +804,8 @@ var SessionManager = class {
|
|
|
546
804
|
|
|
547
805
|
// src/project-manager.ts
|
|
548
806
|
function defaultStatePath() {
|
|
549
|
-
const base2 = process.env["XDG_CONFIG_HOME"] ??
|
|
550
|
-
return
|
|
807
|
+
const base2 = process.env["XDG_CONFIG_HOME"] ?? path3.join(os2.homedir(), ".config");
|
|
808
|
+
return path3.join(base2, "tring", "projects.json");
|
|
551
809
|
}
|
|
552
810
|
var ProjectManager = class _ProjectManager {
|
|
553
811
|
constructor(opts) {
|
|
@@ -660,6 +918,7 @@ var ProjectManager = class _ProjectManager {
|
|
|
660
918
|
projectName: e.name,
|
|
661
919
|
root: e.root,
|
|
662
920
|
url: this.opts.url,
|
|
921
|
+
token: this.opts.token ?? null,
|
|
663
922
|
scrollback: this.opts.scrollback,
|
|
664
923
|
idleMs: this.opts.idleMs,
|
|
665
924
|
...this.opts.shell ? { shell: this.opts.shell } : {}
|
|
@@ -702,8 +961,8 @@ var ProjectManager = class _ProjectManager {
|
|
|
702
961
|
save() {
|
|
703
962
|
const state = this.snapshotState();
|
|
704
963
|
this.writing = this.writing.then(async () => {
|
|
705
|
-
await
|
|
706
|
-
await
|
|
964
|
+
await mkdir2(path3.dirname(this.statePath), { recursive: true });
|
|
965
|
+
await writeFile2(this.statePath, JSON.stringify(state, null, 2), "utf8");
|
|
707
966
|
}).catch(() => {
|
|
708
967
|
});
|
|
709
968
|
return this.writing;
|
|
@@ -711,7 +970,7 @@ var ProjectManager = class _ProjectManager {
|
|
|
711
970
|
async load() {
|
|
712
971
|
let parsed;
|
|
713
972
|
try {
|
|
714
|
-
parsed = JSON.parse(await
|
|
973
|
+
parsed = JSON.parse(await readFile2(this.statePath, "utf8"));
|
|
715
974
|
} catch {
|
|
716
975
|
return;
|
|
717
976
|
}
|
|
@@ -732,15 +991,85 @@ var ProjectManager = class _ProjectManager {
|
|
|
732
991
|
|
|
733
992
|
// src/http.ts
|
|
734
993
|
import { createReadStream } from "node:fs";
|
|
735
|
-
import {
|
|
736
|
-
import
|
|
737
|
-
import
|
|
994
|
+
import { readdir as readdir2, realpath, stat as stat2 } from "node:fs/promises";
|
|
995
|
+
import os4 from "node:os";
|
|
996
|
+
import path5 from "node:path";
|
|
997
|
+
|
|
998
|
+
// src/security.ts
|
|
999
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
1000
|
+
var LOOPBACK = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\]|::1)$/i;
|
|
1001
|
+
function hostname(host) {
|
|
1002
|
+
return (/^(\[[^\]]*\]|[^:]*)/.exec(host)?.[1] ?? host).toLowerCase();
|
|
1003
|
+
}
|
|
1004
|
+
function isLoopbackBind(host) {
|
|
1005
|
+
return !host || LOOPBACK.test(host);
|
|
1006
|
+
}
|
|
1007
|
+
function bindNeedsToken(host, token) {
|
|
1008
|
+
return !isLoopbackBind(host) && !token;
|
|
1009
|
+
}
|
|
1010
|
+
function originHost(origin) {
|
|
1011
|
+
try {
|
|
1012
|
+
const u = new URL(origin);
|
|
1013
|
+
return u.protocol === "http:" || u.protocol === "https:" ? u.host.toLowerCase() : null;
|
|
1014
|
+
} catch {
|
|
1015
|
+
return null;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
function createOriginCheck(opts = {}) {
|
|
1019
|
+
const allow = new Set(
|
|
1020
|
+
(opts.allow ?? []).map((o) => originHost(o.trim())).filter((o) => o !== null)
|
|
1021
|
+
);
|
|
1022
|
+
const pinned = isLoopbackBind(opts.host);
|
|
1023
|
+
return function sameOrigin(req) {
|
|
1024
|
+
const host = req.headers.host?.toLowerCase();
|
|
1025
|
+
if (pinned && (!host || !LOOPBACK.test(hostname(host)))) return false;
|
|
1026
|
+
const origin = req.headers.origin;
|
|
1027
|
+
if (!origin) return true;
|
|
1028
|
+
const from = originHost(origin);
|
|
1029
|
+
return from !== null && (from === host || allow.has(from));
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
var upgradeGuard = (check) => ({ req }) => check(req);
|
|
1033
|
+
function secretEquals(a, b) {
|
|
1034
|
+
if (typeof a !== "string" || typeof b !== "string") return false;
|
|
1035
|
+
const digest = (s) => createHash("sha256").update(s, "utf8").digest();
|
|
1036
|
+
return timingSafeEqual(digest(a), digest(b));
|
|
1037
|
+
}
|
|
1038
|
+
function bearerEquals(token, header) {
|
|
1039
|
+
const match = header ? /^bearer +(.*)$/i.exec(header) : null;
|
|
1040
|
+
return secretEquals(token, match?.[1] ?? null);
|
|
1041
|
+
}
|
|
1042
|
+
var SECURITY_HEADERS = Object.freeze({
|
|
1043
|
+
"content-security-policy": [
|
|
1044
|
+
"default-src 'self'",
|
|
1045
|
+
"script-src 'self'",
|
|
1046
|
+
// xterm writes a <style> element of its own for terminal metrics.
|
|
1047
|
+
"style-src 'self' 'unsafe-inline'",
|
|
1048
|
+
"img-src 'self' data:",
|
|
1049
|
+
// the favicon is an inline SVG
|
|
1050
|
+
"font-src 'self'",
|
|
1051
|
+
"connect-src 'self'",
|
|
1052
|
+
// ws:// to this same host is 'self' under CSP 3
|
|
1053
|
+
"worker-src 'self'",
|
|
1054
|
+
// the PWA service worker
|
|
1055
|
+
"manifest-src 'self'",
|
|
1056
|
+
"base-uri 'none'",
|
|
1057
|
+
"object-src 'none'",
|
|
1058
|
+
"form-action 'none'",
|
|
1059
|
+
"frame-ancestors 'none'"
|
|
1060
|
+
].join("; "),
|
|
1061
|
+
"x-content-type-options": "nosniff",
|
|
1062
|
+
"x-frame-options": "DENY",
|
|
1063
|
+
"referrer-policy": "no-referrer",
|
|
1064
|
+
"cross-origin-opener-policy": "same-origin",
|
|
1065
|
+
"cross-origin-resource-policy": "same-origin"
|
|
1066
|
+
});
|
|
738
1067
|
|
|
739
1068
|
// src/usage.ts
|
|
740
1069
|
import { spawn as spawn2 } from "node:child_process";
|
|
741
|
-
import { readdir, readFile as
|
|
742
|
-
import
|
|
743
|
-
import
|
|
1070
|
+
import { readdir, readFile as readFile3, stat } from "node:fs/promises";
|
|
1071
|
+
import os3 from "node:os";
|
|
1072
|
+
import path4 from "node:path";
|
|
744
1073
|
var WINDOW_MS = 5 * 36e5;
|
|
745
1074
|
var WEEK_MS = 7 * 24 * 36e5;
|
|
746
1075
|
var PRICES = [
|
|
@@ -752,8 +1081,8 @@ var PRICES = [
|
|
|
752
1081
|
["claude-haiku-", 1, 5]
|
|
753
1082
|
];
|
|
754
1083
|
function defaultTranscriptDir() {
|
|
755
|
-
const base2 = process.env["CLAUDE_CONFIG_DIR"] ??
|
|
756
|
-
return
|
|
1084
|
+
const base2 = process.env["CLAUDE_CONFIG_DIR"] ?? path4.join(os3.homedir(), ".claude");
|
|
1085
|
+
return path4.join(base2, "projects");
|
|
757
1086
|
}
|
|
758
1087
|
var empty = () => ({ tokens: 0, cacheReadTokens: 0, cost: 0, messages: 0 });
|
|
759
1088
|
function add(b, e) {
|
|
@@ -771,13 +1100,13 @@ async function scanUsage(dir, now) {
|
|
|
771
1100
|
const entries = [];
|
|
772
1101
|
const weekAgo = now - WEEK_MS;
|
|
773
1102
|
for (const file of await transcripts(dir, weekAgo)) {
|
|
774
|
-
let
|
|
1103
|
+
let text2;
|
|
775
1104
|
try {
|
|
776
|
-
|
|
1105
|
+
text2 = await readFile3(file, "utf8");
|
|
777
1106
|
} catch {
|
|
778
1107
|
continue;
|
|
779
1108
|
}
|
|
780
|
-
for (const line of
|
|
1109
|
+
for (const line of text2.split("\n")) {
|
|
781
1110
|
if (!line.includes('"usage"')) continue;
|
|
782
1111
|
let rec;
|
|
783
1112
|
try {
|
|
@@ -861,7 +1190,7 @@ async function transcripts(dir, since) {
|
|
|
861
1190
|
const out = [];
|
|
862
1191
|
for (const name of names) {
|
|
863
1192
|
if (!name.endsWith(".jsonl")) continue;
|
|
864
|
-
const file =
|
|
1193
|
+
const file = path4.join(dir, name);
|
|
865
1194
|
try {
|
|
866
1195
|
if ((await stat(file)).mtimeMs >= since) out.push(file);
|
|
867
1196
|
} catch {
|
|
@@ -870,9 +1199,9 @@ async function transcripts(dir, since) {
|
|
|
870
1199
|
return out;
|
|
871
1200
|
}
|
|
872
1201
|
var LIMIT_LINE = /^Current ([^:]+):\s*(\d+)%\s*used(?:\s*·\s*resets\s*(.+?))?\s*$/;
|
|
873
|
-
function parseLimits(
|
|
1202
|
+
function parseLimits(text2) {
|
|
874
1203
|
const out = [];
|
|
875
|
-
for (const line of
|
|
1204
|
+
for (const line of text2.split("\n")) {
|
|
876
1205
|
const m = LIMIT_LINE.exec(line.trim());
|
|
877
1206
|
if (!m) continue;
|
|
878
1207
|
const label = m[1].trim();
|
|
@@ -952,10 +1281,16 @@ var MIME = {
|
|
|
952
1281
|
// Browsers refuse to install a PWA whose manifest is served as anything else.
|
|
953
1282
|
".webmanifest": "application/manifest+json"
|
|
954
1283
|
};
|
|
1284
|
+
var head = (res, code, type) => {
|
|
1285
|
+
res.writeHead(code, { ...SECURITY_HEADERS, "content-type": type });
|
|
1286
|
+
};
|
|
955
1287
|
var json = (res, code, body) => {
|
|
956
|
-
|
|
957
|
-
res.
|
|
958
|
-
|
|
1288
|
+
head(res, code, "application/json; charset=utf-8");
|
|
1289
|
+
res.end(JSON.stringify(body));
|
|
1290
|
+
};
|
|
1291
|
+
var text = (res, code, body) => {
|
|
1292
|
+
head(res, code, "text/plain; charset=utf-8");
|
|
1293
|
+
res.end(body);
|
|
959
1294
|
};
|
|
960
1295
|
var readBody = (req) => new Promise((resolve) => {
|
|
961
1296
|
let data = "";
|
|
@@ -965,30 +1300,33 @@ var readBody = (req) => new Promise((resolve) => {
|
|
|
965
1300
|
});
|
|
966
1301
|
req.on("end", () => resolve(data));
|
|
967
1302
|
});
|
|
968
|
-
var DROP_MAX = 25e6;
|
|
969
|
-
var readRaw = (req, cap) => new Promise((resolve, reject) => {
|
|
970
|
-
const parts = [];
|
|
971
|
-
let size = 0;
|
|
972
|
-
req.on("data", (c) => {
|
|
973
|
-
size += c.length;
|
|
974
|
-
if (size > cap) {
|
|
975
|
-
req.destroy();
|
|
976
|
-
reject(new Error("too large"));
|
|
977
|
-
return;
|
|
978
|
-
}
|
|
979
|
-
parts.push(c);
|
|
980
|
-
});
|
|
981
|
-
req.on("end", () => resolve(Buffer.concat(parts)));
|
|
982
|
-
req.on("error", reject);
|
|
983
|
-
});
|
|
984
1303
|
var USAGE_CACHE_MS = 3e4;
|
|
985
1304
|
function createHandler(opts) {
|
|
986
1305
|
const { pm, webRoot, token } = opts;
|
|
1306
|
+
const sameOrigin = opts.sameOrigin ?? createOriginCheck();
|
|
987
1307
|
let usage = null;
|
|
1308
|
+
const homeDir = () => process.env["HOME"] ?? os4.homedir();
|
|
1309
|
+
const within = (root, dir) => {
|
|
1310
|
+
const rel = path5.relative(path5.resolve(root), dir);
|
|
1311
|
+
return rel === "" || !rel.startsWith("..") && !path5.isAbsolute(rel);
|
|
1312
|
+
};
|
|
1313
|
+
const real = async (p) => {
|
|
1314
|
+
try {
|
|
1315
|
+
return await realpath(p);
|
|
1316
|
+
} catch {
|
|
1317
|
+
return path5.resolve(p);
|
|
1318
|
+
}
|
|
1319
|
+
};
|
|
1320
|
+
const browsable = async (dir) => {
|
|
1321
|
+
const roots = [homeDir(), ...pm.list().map((p) => p.root), ...opts.fsRoots ?? []];
|
|
1322
|
+
const [target, ...resolved] = await Promise.all([dir, ...roots].map(real));
|
|
1323
|
+
return resolved.some((root) => within(root, target));
|
|
1324
|
+
};
|
|
988
1325
|
return async function handle(req, res) {
|
|
989
1326
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
1327
|
+
if (!sameOrigin(req)) return text(res, 403, "forbidden origin");
|
|
990
1328
|
if (url.pathname.startsWith("/api/")) {
|
|
991
|
-
if (token && req.headers.authorization
|
|
1329
|
+
if (token && !bearerEquals(token, req.headers.authorization)) {
|
|
992
1330
|
return json(res, 401, { error: "unauthorized" });
|
|
993
1331
|
}
|
|
994
1332
|
return await api(req, res, url);
|
|
@@ -1020,12 +1358,14 @@ function createHandler(opts) {
|
|
|
1020
1358
|
}
|
|
1021
1359
|
if (url.pathname === "/api/fs" && req.method === "GET") {
|
|
1022
1360
|
const raw = url.searchParams.get("path")?.trim();
|
|
1023
|
-
const dir = raw ?
|
|
1361
|
+
const dir = raw ? path5.resolve(raw) : homeDir();
|
|
1362
|
+
if (!await browsable(dir)) return json(res, 403, { error: "outside the browsable roots" });
|
|
1024
1363
|
try {
|
|
1025
1364
|
const found = await readdir2(dir, { withFileTypes: true });
|
|
1026
|
-
const entries = found.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".")).map((e) => ({ name: e.name, path:
|
|
1027
|
-
const parent =
|
|
1028
|
-
|
|
1365
|
+
const entries = found.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".")).map((e) => ({ name: e.name, path: path5.join(dir, e.name) })).sort((a, b) => a.name.localeCompare(b.name));
|
|
1366
|
+
const parent = path5.dirname(dir);
|
|
1367
|
+
const up = parent !== dir && await browsable(parent) ? parent : null;
|
|
1368
|
+
return json(res, 200, { path: dir, parent: up, entries });
|
|
1029
1369
|
} catch {
|
|
1030
1370
|
return json(res, 400, { error: `cannot read ${dir}` });
|
|
1031
1371
|
}
|
|
@@ -1042,24 +1382,6 @@ function createHandler(opts) {
|
|
|
1042
1382
|
return json(res, 500, { error: "cannot read Claude Code transcripts" });
|
|
1043
1383
|
}
|
|
1044
1384
|
}
|
|
1045
|
-
if (url.pathname === "/api/drop" && req.method === "POST") {
|
|
1046
|
-
const safe = (url.searchParams.get("name") ?? "").replace(/[^\w.-]+/g, "_").slice(0, 80);
|
|
1047
|
-
const dir = path3.join(os3.tmpdir(), "tring-drops");
|
|
1048
|
-
if (Number(req.headers["content-length"] ?? 0) > DROP_MAX) {
|
|
1049
|
-
json(res, 413, { error: `file is bigger than ${DROP_MAX / 1e6}MB` });
|
|
1050
|
-
req.resume();
|
|
1051
|
-
return;
|
|
1052
|
-
}
|
|
1053
|
-
try {
|
|
1054
|
-
const bytes = await readRaw(req, DROP_MAX);
|
|
1055
|
-
await mkdir2(dir, { recursive: true });
|
|
1056
|
-
const file = path3.join(dir, `${Date.now().toString(36)}-${safe || "file"}`);
|
|
1057
|
-
await writeFile2(file, bytes);
|
|
1058
|
-
return json(res, 200, { path: file });
|
|
1059
|
-
} catch {
|
|
1060
|
-
return json(res, 413, { error: `file is bigger than ${DROP_MAX / 1e6}MB` });
|
|
1061
|
-
}
|
|
1062
|
-
}
|
|
1063
1385
|
if (url.pathname === "/api/sessions" && req.method === "GET") {
|
|
1064
1386
|
const sessions = pm.list().flatMap(
|
|
1065
1387
|
(p) => p.sessions.map((s) => ({ ...s, project: p.name }))
|
|
@@ -1070,23 +1392,23 @@ function createHandler(opts) {
|
|
|
1070
1392
|
}
|
|
1071
1393
|
async function serveStatic(res, pathname) {
|
|
1072
1394
|
const rel = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
|
|
1073
|
-
const file =
|
|
1074
|
-
if (file !== webRoot && !file.startsWith(webRoot +
|
|
1075
|
-
res
|
|
1395
|
+
const file = path5.resolve(webRoot, rel);
|
|
1396
|
+
if (file !== webRoot && !file.startsWith(webRoot + path5.sep)) {
|
|
1397
|
+
text(res, 403, "forbidden");
|
|
1076
1398
|
return;
|
|
1077
1399
|
}
|
|
1078
1400
|
try {
|
|
1079
1401
|
const info = await stat2(file);
|
|
1080
1402
|
if (!info.isFile()) throw new Error("not a file");
|
|
1081
|
-
res
|
|
1403
|
+
head(res, 200, MIME[path5.extname(file)] ?? "application/octet-stream");
|
|
1082
1404
|
createReadStream(file).pipe(res);
|
|
1083
1405
|
} catch {
|
|
1084
1406
|
if (rel === "index.html") {
|
|
1085
|
-
res
|
|
1407
|
+
head(res, 200, MIME[".html"]);
|
|
1086
1408
|
res.end('<!doctype html><meta charset="utf-8"><title>tring</title><body style="font:14px ui-monospace,monospace;background:#040c0a;color:#dceee7;padding:2rem"><p>Daemon is running. The web bundle is not built yet.</p><p style="color:#8aa79d">Run <code>npm run build -w @tring/web</code>.</p>');
|
|
1087
1409
|
return;
|
|
1088
1410
|
}
|
|
1089
|
-
res
|
|
1411
|
+
text(res, 404, "not found");
|
|
1090
1412
|
}
|
|
1091
1413
|
}
|
|
1092
1414
|
}
|
|
@@ -1145,7 +1467,7 @@ var Hub = class {
|
|
|
1145
1467
|
handle(c, msg) {
|
|
1146
1468
|
const pm = this.opts.pm;
|
|
1147
1469
|
if (msg.type === "hello") {
|
|
1148
|
-
if (this.opts.token &&
|
|
1470
|
+
if (this.opts.token && !secretEquals(this.opts.token, msg.token)) {
|
|
1149
1471
|
this.send(c, { type: "error", message: "unauthorized" });
|
|
1150
1472
|
c.ws.close();
|
|
1151
1473
|
return;
|
|
@@ -1293,12 +1615,12 @@ var Hub = class {
|
|
|
1293
1615
|
|
|
1294
1616
|
// src/open-window.ts
|
|
1295
1617
|
import { spawn as spawn3 } from "node:child_process";
|
|
1296
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
1297
|
-
import
|
|
1618
|
+
import { existsSync, readFileSync as readFileSync2 } from "node:fs";
|
|
1619
|
+
import os5 from "node:os";
|
|
1298
1620
|
function isWsl() {
|
|
1299
1621
|
if (process.env["WSL_DISTRO_NAME"]) return true;
|
|
1300
1622
|
try {
|
|
1301
|
-
return /microsoft/i.test(
|
|
1623
|
+
return /microsoft/i.test(readFileSync2("/proc/version", "utf8"));
|
|
1302
1624
|
} catch {
|
|
1303
1625
|
return false;
|
|
1304
1626
|
}
|
|
@@ -1366,165 +1688,100 @@ function openWindow(url) {
|
|
|
1366
1688
|
}
|
|
1367
1689
|
}
|
|
1368
1690
|
function describeFallback(url) {
|
|
1369
|
-
return isWsl() ||
|
|
1691
|
+
return isWsl() || os5.platform() === "linux" ? `open ${url} in your browser` : `open ${url}`;
|
|
1370
1692
|
}
|
|
1371
1693
|
|
|
1372
|
-
// src/
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
function currentVersion() {
|
|
1378
|
-
try {
|
|
1379
|
-
return require3("../package.json").version;
|
|
1380
|
-
} catch {
|
|
1381
|
-
return "0.0.0";
|
|
1382
|
-
}
|
|
1694
|
+
// src/index.ts
|
|
1695
|
+
function resolveAuth(args) {
|
|
1696
|
+
if (args.insecureNoToken) return { token: null, persisted: false };
|
|
1697
|
+
if (args.token) return { token: args.token, persisted: false };
|
|
1698
|
+
return { token: loadOrCreateToken(), persisted: true };
|
|
1383
1699
|
}
|
|
1384
|
-
function
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
}
|
|
1394
|
-
return false;
|
|
1700
|
+
function loadTls(certFile, keyFile) {
|
|
1701
|
+
const read = (file, what) => {
|
|
1702
|
+
try {
|
|
1703
|
+
return readFileSync3(file);
|
|
1704
|
+
} catch (err) {
|
|
1705
|
+
throw new UsageError(`cannot read the TLS ${what} at ${file}: ${err.message}`);
|
|
1706
|
+
}
|
|
1707
|
+
};
|
|
1708
|
+
return { cert: read(certFile, "certificate"), key: read(keyFile, "key") };
|
|
1395
1709
|
}
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
let cache = null;
|
|
1400
|
-
try {
|
|
1401
|
-
cache = JSON.parse(await readFile3(cachePath, "utf8"));
|
|
1402
|
-
} catch {
|
|
1403
|
-
cache = null;
|
|
1404
|
-
}
|
|
1405
|
-
if (cache && Date.now() - cache.checkedAt < DAY_MS) {
|
|
1406
|
-
return isNewer(cache.latest, current) ? cache.latest : null;
|
|
1407
|
-
}
|
|
1408
|
-
let latest;
|
|
1409
|
-
try {
|
|
1410
|
-
const res = await fetch("https://registry.npmjs.org/tring-chat/latest", {
|
|
1411
|
-
signal: AbortSignal.timeout(3e3)
|
|
1412
|
-
});
|
|
1413
|
-
if (!res.ok) return null;
|
|
1414
|
-
latest = (await res.json()).version ?? "";
|
|
1415
|
-
if (!latest) return null;
|
|
1416
|
-
} catch {
|
|
1417
|
-
return null;
|
|
1418
|
-
}
|
|
1710
|
+
async function main() {
|
|
1711
|
+
const args = parseArgs(process.argv.slice(2));
|
|
1712
|
+
let auth;
|
|
1419
1713
|
try {
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
}
|
|
1714
|
+
auth = resolveAuth(args);
|
|
1715
|
+
} catch (err) {
|
|
1716
|
+
throw new UsageError(`cannot read or create ${defaultTokenPath()}: ${err.message}
|
|
1717
|
+
Fix the permissions on that path, pass --token, or accept an unauthenticated
|
|
1718
|
+
daemon on purpose with --insecure-no-token.`);
|
|
1719
|
+
}
|
|
1720
|
+
const { token } = auth;
|
|
1721
|
+
if (bindNeedsToken(args.host, token) && !args.insecureNoToken) {
|
|
1722
|
+
throw new UsageError(`refusing to bind ${args.host} without a token.
|
|
1426
1723
|
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
const args = {
|
|
1430
|
-
port: Number(process.env["TRING_PORT"] ?? DEFAULT_PORT),
|
|
1431
|
-
host: process.env["TRING_HOST"] ?? DEFAULT_HOST,
|
|
1432
|
-
token: process.env["TRING_TOKEN"] ?? null,
|
|
1433
|
-
scrollback: DEFAULT_SCROLLBACK,
|
|
1434
|
-
idleMs: DEFAULT_IDLE_MS,
|
|
1435
|
-
open: !process.env["TRING_NO_OPEN"],
|
|
1436
|
-
shell: process.env["TRING_SHELL"] ?? null,
|
|
1437
|
-
updateCheck: !process.env["TRING_NO_UPDATE_CHECK"]
|
|
1438
|
-
};
|
|
1439
|
-
for (let i = 0; i < argv.length; i++) {
|
|
1440
|
-
const [flag, inline] = argv[i].split("=", 2);
|
|
1441
|
-
const value = inline ?? argv[++i];
|
|
1442
|
-
switch (flag) {
|
|
1443
|
-
case "--port":
|
|
1444
|
-
args.port = Number(value);
|
|
1445
|
-
break;
|
|
1446
|
-
case "--host":
|
|
1447
|
-
args.host = String(value);
|
|
1448
|
-
break;
|
|
1449
|
-
case "--token":
|
|
1450
|
-
args.token = String(value);
|
|
1451
|
-
break;
|
|
1452
|
-
case "--scrollback":
|
|
1453
|
-
args.scrollback = Number(value);
|
|
1454
|
-
break;
|
|
1455
|
-
case "--idle-ms":
|
|
1456
|
-
args.idleMs = Number(value);
|
|
1457
|
-
break;
|
|
1458
|
-
case "--shell":
|
|
1459
|
-
args.shell = String(value);
|
|
1460
|
-
break;
|
|
1461
|
-
case "--no-open":
|
|
1462
|
-
args.open = false;
|
|
1463
|
-
i--;
|
|
1464
|
-
break;
|
|
1465
|
-
case "--no-update-check":
|
|
1466
|
-
args.updateCheck = false;
|
|
1467
|
-
i--;
|
|
1468
|
-
break;
|
|
1469
|
-
case "--version":
|
|
1470
|
-
console.log(currentVersion());
|
|
1471
|
-
process.exit(0);
|
|
1472
|
-
case "--help":
|
|
1473
|
-
console.log(`tring \u2014 focus-centred terminal deck
|
|
1724
|
+
The daemon spawns shells, so off localhost the token is the only thing
|
|
1725
|
+
between the port and a shell on this machine.
|
|
1474
1726
|
|
|
1475
|
-
|
|
1476
|
-
--host <addr> default ${DEFAULT_HOST}
|
|
1477
|
-
--token <secret> require bearer auth (use when binding off localhost)
|
|
1478
|
-
--scrollback <n> lines kept per session, default ${DEFAULT_SCROLLBACK}
|
|
1479
|
-
--idle-ms <n> quiet period before a session is done, default ${DEFAULT_IDLE_MS}
|
|
1480
|
-
--shell <path> shell to spawn; default $SHELL, or powershell.exe on
|
|
1481
|
-
Windows. Use --shell wsl.exe for WSL shells from Windows
|
|
1482
|
-
--no-open do not launch a browser window
|
|
1483
|
-
--no-update-check do not ask npm whether a newer tring exists
|
|
1484
|
-
--version print the version and exit`);
|
|
1485
|
-
process.exit(0);
|
|
1486
|
-
}
|
|
1727
|
+
tring --host ${args.host} --token "$(openssl rand -hex 32)"`);
|
|
1487
1728
|
}
|
|
1488
|
-
|
|
1489
|
-
}
|
|
1490
|
-
|
|
1491
|
-
const
|
|
1492
|
-
const url = `http://${args.host}:${args.port}`;
|
|
1493
|
-
const here = path5.dirname(fileURLToPath(import.meta.url));
|
|
1729
|
+
const tls = args.tlsCert && args.tlsKey ? loadTls(args.tlsCert, args.tlsKey) : null;
|
|
1730
|
+
const url = `${tls ? "https" : "http"}://${args.host}:${args.port}`;
|
|
1731
|
+
const cleartextOffBox = !tls && !isLoopbackBind(args.host);
|
|
1732
|
+
const here = path6.dirname(fileURLToPath(import.meta.url));
|
|
1494
1733
|
const webRoot = [
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
].find((p) => existsSync2(p)) ??
|
|
1734
|
+
path6.resolve(here, "web"),
|
|
1735
|
+
path6.resolve(here, "../../web/dist")
|
|
1736
|
+
].find((p) => existsSync2(p)) ?? path6.resolve(here, "web");
|
|
1498
1737
|
const pm = await ProjectManager.open({
|
|
1499
1738
|
url,
|
|
1739
|
+
// Reaches each session as $TRING_TOKEN, so the documented Stop hook can
|
|
1740
|
+
// authenticate itself without the user copying a secret into settings.json.
|
|
1741
|
+
token,
|
|
1500
1742
|
scrollback: args.scrollback,
|
|
1501
1743
|
idleMs: args.idleMs,
|
|
1502
1744
|
...args.shell ? { shell: args.shell } : {}
|
|
1503
1745
|
});
|
|
1504
|
-
const
|
|
1505
|
-
const
|
|
1746
|
+
const sameOrigin = createOriginCheck({ host: args.host, allow: args.allowOrigin });
|
|
1747
|
+
const handle = createHandler({
|
|
1748
|
+
pm,
|
|
1749
|
+
webRoot,
|
|
1750
|
+
token,
|
|
1751
|
+
sameOrigin,
|
|
1752
|
+
fsRoots: args.fsRoot
|
|
1753
|
+
});
|
|
1754
|
+
const listener = (req, res) => {
|
|
1506
1755
|
void handle(req, res).catch(() => {
|
|
1507
|
-
if (!res.headersSent) res.writeHead(500).end("internal error");
|
|
1756
|
+
if (!res.headersSent) res.writeHead(500, SECURITY_HEADERS).end("internal error");
|
|
1508
1757
|
});
|
|
1509
|
-
}
|
|
1510
|
-
const
|
|
1511
|
-
const
|
|
1758
|
+
};
|
|
1759
|
+
const server = tls ? createSecureServer(tls, listener) : createServer(listener);
|
|
1760
|
+
const wss = new WebSocketServer({ server, verifyClient: upgradeGuard(sameOrigin) });
|
|
1761
|
+
const hub = new Hub({ pm, token });
|
|
1512
1762
|
hub.attach(wss);
|
|
1763
|
+
const authUrl = token ? `${url}/?token=${encodeURIComponent(token)}` : url;
|
|
1513
1764
|
server.listen(args.port, args.host, () => {
|
|
1514
1765
|
console.log(`tring listening on ${url}`);
|
|
1515
|
-
if (
|
|
1516
|
-
|
|
1766
|
+
if (auth.persisted) console.log(` token: ${defaultTokenPath()}`);
|
|
1767
|
+
if (!token) {
|
|
1768
|
+
console.warn("warning: running with no token \u2014 every process on this machine can open a shell here" + (isLoopbackBind(args.host) ? "" : `, as can anything that reaches ${args.host}:${args.port}`));
|
|
1769
|
+
}
|
|
1770
|
+
if (cleartextOffBox) {
|
|
1771
|
+
console.warn(`warning: ${url} is plain http \u2014 the token, every keystroke and all terminal output cross the network in clear. Use an encrypted overlay (Tailscale, WireGuard) or pass --tls-cert/--tls-key.`);
|
|
1517
1772
|
}
|
|
1518
1773
|
if (args.updateCheck) {
|
|
1519
|
-
void checkForUpdate(
|
|
1774
|
+
void checkForUpdate(path6.join(path6.dirname(pm.statePath), "update-check.json")).then((latest) => {
|
|
1520
1775
|
if (!latest) return;
|
|
1521
1776
|
hub.setUpdate({ current: currentVersion(), latest });
|
|
1522
1777
|
console.log(`update available: ${currentVersion()} -> ${latest} (npm i -g tring-chat)`);
|
|
1523
1778
|
});
|
|
1524
1779
|
}
|
|
1525
1780
|
if (args.open) {
|
|
1526
|
-
const opened = openWindow(
|
|
1527
|
-
if (!opened) console.log(`no browser found \u2014 ${describeFallback(
|
|
1781
|
+
const opened = openWindow(authUrl);
|
|
1782
|
+
if (!opened) console.log(`no browser found \u2014 ${describeFallback(authUrl)}`);
|
|
1783
|
+
} else if (token) {
|
|
1784
|
+
console.log(`open ${authUrl}`);
|
|
1528
1785
|
}
|
|
1529
1786
|
});
|
|
1530
1787
|
const shutdown = async () => {
|
|
@@ -1536,4 +1793,10 @@ async function main() {
|
|
|
1536
1793
|
process.on("SIGINT", () => void shutdown());
|
|
1537
1794
|
process.on("SIGTERM", () => void shutdown());
|
|
1538
1795
|
}
|
|
1539
|
-
void main()
|
|
1796
|
+
void main().catch((err) => {
|
|
1797
|
+
if (err instanceof UsageError) {
|
|
1798
|
+
console.error(err.message);
|
|
1799
|
+
process.exit(1);
|
|
1800
|
+
}
|
|
1801
|
+
throw err;
|
|
1802
|
+
});
|