tring-chat 0.1.6 → 0.1.8

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 path5 from "node:path";
6
+ import { createServer as createSecureServer } from "node:https";
7
+ import path8 from "node:path";
7
8
  import { fileURLToPath } from "node:url";
8
9
  import { WebSocketServer } from "ws";
9
10
 
@@ -24,6 +25,7 @@ var SUSTAINED_MS = 1500;
24
25
  var SUSTAINED_BYTES = 2048;
25
26
  var BURST_GAP_MS = SUSTAINED_MS;
26
27
  var DEFAULT_IDLE_MS = 3e3;
28
+ var ECHO_MS = 300;
27
29
  var NOTABLE_BUSY_MS = 1e4;
28
30
  var ActivityTracker = class {
29
31
  status = "idle";
@@ -40,6 +42,7 @@ var ActivityTracker = class {
40
42
  burstStart = null;
41
43
  burstBytes = 0;
42
44
  lastOutput = null;
45
+ lastNavigation = null;
43
46
  constructor(now, idleMs = DEFAULT_IDLE_MS) {
44
47
  this.since = now;
45
48
  this.idleMs = idleMs;
@@ -52,15 +55,23 @@ var ActivityTracker = class {
52
55
  }
53
56
  this.lastOutput = now;
54
57
  if (this.status !== "idle") return;
58
+ if (this.lastNavigation !== null && now - this.lastNavigation <= ECHO_MS) {
59
+ this.resetBurst();
60
+ return;
61
+ }
55
62
  if (this.burstStart === null) this.burstStart = now;
56
63
  this.burstBytes += bytes;
57
64
  if (now - this.burstStart >= SUSTAINED_MS || this.burstBytes >= SUSTAINED_BYTES) {
58
65
  this.transition("busy", now);
59
66
  }
60
67
  }
61
- /** User typed into this session. Only the focused session receives input. */
62
- input(now) {
68
+ /**
69
+ * The user drove this session: a keystroke, a paste, a mouse report from a
70
+ * wheel. Only the focused session receives input.
71
+ */
72
+ input(now, kind = "command") {
63
73
  this.resetBurst();
74
+ this.lastNavigation = kind === "navigation" ? now : null;
64
75
  if (this.status === "done") this.transition("idle", now);
65
76
  }
66
77
  /** OSC 133;C — a command started. */
@@ -121,20 +132,302 @@ var ActivityTracker = class {
121
132
  }
122
133
  };
123
134
 
124
- // src/project-manager.ts
125
- import { randomUUID as randomUUID2 } from "node:crypto";
126
- import { mkdir, readFile, writeFile } from "node:fs/promises";
135
+ // src/token.ts
136
+ import { randomBytes } from "node:crypto";
137
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
127
138
  import os from "node:os";
128
139
  import path from "node:path";
140
+ var MIN_TOKEN_LENGTH = 16;
141
+ function defaultTokenPath() {
142
+ const base2 = process.env["XDG_CONFIG_HOME"] ?? path.join(os.homedir(), ".config");
143
+ return path.join(base2, "tring", "token");
144
+ }
145
+ function generateToken() {
146
+ return randomBytes(32).toString("hex");
147
+ }
148
+ function tokenProblem(token) {
149
+ if (token.trim() !== token) return "a token cannot start or end with whitespace";
150
+ if (token.length < MIN_TOKEN_LENGTH) {
151
+ return `a token must be at least ${MIN_TOKEN_LENGTH} characters \u2014 generate one with \`openssl rand -hex 32\``;
152
+ }
153
+ return null;
154
+ }
155
+ function lockDown(file) {
156
+ try {
157
+ chmodSync(file, 384);
158
+ } catch {
159
+ }
160
+ }
161
+ function loadOrCreateToken(file = defaultTokenPath()) {
162
+ try {
163
+ const existing = readFileSync(file, "utf8").trim();
164
+ if (tokenProblem(existing) === null) {
165
+ lockDown(file);
166
+ return existing;
167
+ }
168
+ } catch {
169
+ }
170
+ const token = generateToken();
171
+ mkdirSync(path.dirname(file), { recursive: true });
172
+ writeFileSync(file, `${token}
173
+ `, { mode: 384 });
174
+ lockDown(file);
175
+ return token;
176
+ }
177
+
178
+ // src/update-check.ts
179
+ import { createRequire } from "node:module";
180
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
181
+ import path2 from "node:path";
182
+ var require2 = createRequire(import.meta.url);
183
+ function currentVersion() {
184
+ try {
185
+ return require2("../package.json").version;
186
+ } catch {
187
+ return "0.0.0";
188
+ }
189
+ }
190
+ function isNewer(latest, current) {
191
+ if (latest.includes("-")) return false;
192
+ const parse = (v) => v.split("-")[0].split(".").map((n) => Number(n) || 0);
193
+ const a = parse(latest);
194
+ const b = parse(current);
195
+ for (let i = 0; i < 3; i++) {
196
+ const x = a[i] ?? 0;
197
+ const y = b[i] ?? 0;
198
+ if (x !== y) return x > y;
199
+ }
200
+ return false;
201
+ }
202
+ var DAY_MS = 24 * 60 * 60 * 1e3;
203
+ async function checkForUpdate(cachePath) {
204
+ const current = currentVersion();
205
+ let cache = null;
206
+ try {
207
+ cache = JSON.parse(await readFile(cachePath, "utf8"));
208
+ } catch {
209
+ cache = null;
210
+ }
211
+ if (cache && Date.now() - cache.checkedAt < DAY_MS) {
212
+ return isNewer(cache.latest, current) ? cache.latest : null;
213
+ }
214
+ let latest;
215
+ try {
216
+ const res = await fetch("https://registry.npmjs.org/tring-chat/latest", {
217
+ signal: AbortSignal.timeout(3e3)
218
+ });
219
+ if (!res.ok) return null;
220
+ latest = (await res.json()).version ?? "";
221
+ if (!latest) return null;
222
+ } catch {
223
+ return null;
224
+ }
225
+ try {
226
+ await mkdir(path2.dirname(cachePath), { recursive: true });
227
+ await writeFile(cachePath, JSON.stringify({ checkedAt: Date.now(), latest }), "utf8");
228
+ } catch {
229
+ }
230
+ return isNewer(latest, current) ? latest : null;
231
+ }
232
+
233
+ // src/args.ts
234
+ var listOf = (value) => (value ?? "").split(",").map((s) => s.trim()).filter(Boolean);
235
+ var UsageError = class extends Error {
236
+ };
237
+ var HELP = `tring \u2014 focus-centred terminal deck
238
+
239
+ --port <n> default ${DEFAULT_PORT}
240
+ --host <addr> default ${DEFAULT_HOST}
241
+ --token <secret> bearer token clients must present. One is generated and
242
+ kept at ~/.config/tring/token when this is not given
243
+ --tls-cert <file> PEM certificate; serves https/wss instead of http/ws
244
+ --tls-key <file> PEM private key for --tls-cert
245
+ --scrollback <n> lines kept per session, default ${DEFAULT_SCROLLBACK}
246
+ --idle-ms <n> quiet period before a session is done, default ${DEFAULT_IDLE_MS}
247
+ --shell <path> shell to spawn; default $SHELL, or powershell.exe on
248
+ Windows. Use --shell wsl.exe for WSL shells from Windows
249
+ --fs-root <path> extra directory the project picker may browse; repeatable.
250
+ Home and existing project roots are always browsable
251
+ --allow-origin <o> extra browser origin allowed to reach the daemon;
252
+ repeatable. Only the page the daemon serves is allowed by
253
+ default, which is what stops any website you visit from
254
+ opening a socket to it
255
+ --insecure-no-token
256
+ run with no token at all. The daemon spawns shells, so
257
+ this hands one to every process on this machine, to
258
+ everything that can reach the port when bound off
259
+ localhost, and to any site that can rebind a name to it
260
+ --no-open do not launch a browser window
261
+ --no-update-check do not ask npm whether a newer tring exists
262
+ --version print the version and exit`;
263
+ function parseArgs(argv) {
264
+ const args = {
265
+ port: Number(process.env["TRING_PORT"] ?? DEFAULT_PORT),
266
+ host: process.env["TRING_HOST"] ?? DEFAULT_HOST,
267
+ token: process.env["TRING_TOKEN"] ?? null,
268
+ scrollback: DEFAULT_SCROLLBACK,
269
+ idleMs: DEFAULT_IDLE_MS,
270
+ open: !process.env["TRING_NO_OPEN"],
271
+ shell: process.env["TRING_SHELL"] ?? null,
272
+ updateCheck: !process.env["TRING_NO_UPDATE_CHECK"],
273
+ allowOrigin: listOf(process.env["TRING_ALLOW_ORIGIN"]),
274
+ fsRoot: listOf(process.env["TRING_FS_ROOT"]),
275
+ insecureNoToken: !!process.env["TRING_INSECURE_NO_TOKEN"],
276
+ tlsCert: process.env["TRING_TLS_CERT"] ?? null,
277
+ tlsKey: process.env["TRING_TLS_KEY"] ?? null
278
+ };
279
+ for (let i = 0; i < argv.length; i++) {
280
+ const arg = argv[i];
281
+ const eq = arg.indexOf("=");
282
+ const flag = eq === -1 ? arg : arg.slice(0, eq);
283
+ const inline = eq === -1 ? void 0 : arg.slice(eq + 1);
284
+ const take = () => {
285
+ const separate = inline === void 0;
286
+ const value = separate ? argv[i + 1] : inline;
287
+ if (value === void 0 || value === "") throw new UsageError(`${flag} needs a value`);
288
+ if (separate && value.startsWith("--")) {
289
+ throw new UsageError(`${flag} needs a value, but the next argument is ${value}`);
290
+ }
291
+ if (separate) i++;
292
+ return value;
293
+ };
294
+ const takeNumber = () => {
295
+ const raw = take();
296
+ const n = Number(raw);
297
+ if (!Number.isFinite(n)) throw new UsageError(`${flag} needs a number, got ${raw}`);
298
+ return n;
299
+ };
300
+ const noValue = () => {
301
+ if (inline !== void 0) throw new UsageError(`${flag} takes no value`);
302
+ };
303
+ switch (flag) {
304
+ case "--port": {
305
+ const port = takeNumber();
306
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
307
+ throw new UsageError(`--port must be a whole number from 0 to 65535, got ${port}`);
308
+ }
309
+ args.port = port;
310
+ break;
311
+ }
312
+ case "--host":
313
+ args.host = take();
314
+ break;
315
+ case "--token": {
316
+ const token = take();
317
+ const problem = tokenProblem(token);
318
+ if (problem) throw new UsageError(`--token: ${problem}`);
319
+ args.token = token;
320
+ break;
321
+ }
322
+ case "--tls-cert":
323
+ args.tlsCert = take();
324
+ break;
325
+ case "--tls-key":
326
+ args.tlsKey = take();
327
+ break;
328
+ case "--scrollback": {
329
+ const lines = takeNumber();
330
+ if (!Number.isInteger(lines) || lines < 0) {
331
+ throw new UsageError(`--scrollback must be a whole number of lines, got ${lines}`);
332
+ }
333
+ args.scrollback = lines;
334
+ break;
335
+ }
336
+ case "--idle-ms": {
337
+ const ms = takeNumber();
338
+ if (!Number.isInteger(ms) || ms < 0) {
339
+ throw new UsageError(`--idle-ms must be a whole number of milliseconds, got ${ms}`);
340
+ }
341
+ args.idleMs = ms;
342
+ break;
343
+ }
344
+ case "--shell":
345
+ args.shell = take();
346
+ break;
347
+ case "--allow-origin":
348
+ args.allowOrigin.push(...listOf(take()));
349
+ break;
350
+ case "--fs-root":
351
+ args.fsRoot.push(...listOf(take()));
352
+ break;
353
+ case "--insecure-no-token":
354
+ noValue();
355
+ args.insecureNoToken = true;
356
+ break;
357
+ case "--no-open":
358
+ noValue();
359
+ args.open = false;
360
+ break;
361
+ case "--no-update-check":
362
+ noValue();
363
+ args.updateCheck = false;
364
+ break;
365
+ case "--version":
366
+ console.log(currentVersion());
367
+ process.exit(0);
368
+ break;
369
+ case "--help":
370
+ console.log(HELP);
371
+ process.exit(0);
372
+ break;
373
+ // A flag we silently ignored used to mean a `--tokn` typo ran an
374
+ // unauthenticated daemon that looked authenticated.
375
+ default:
376
+ throw new UsageError(`unknown argument ${arg}`);
377
+ }
378
+ }
379
+ if (args.token !== null) {
380
+ const problem = tokenProblem(args.token);
381
+ if (problem) throw new UsageError(`TRING_TOKEN: ${problem}`);
382
+ }
383
+ if (!args.tlsCert !== !args.tlsKey) {
384
+ throw new UsageError("--tls-cert and --tls-key must be given together");
385
+ }
386
+ return args;
387
+ }
388
+
389
+ // src/project-manager.ts
390
+ import { randomUUID as randomUUID2 } from "node:crypto";
391
+ import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
392
+ import os2 from "node:os";
393
+ import path3 from "node:path";
129
394
 
130
395
  // src/session-manager.ts
131
396
  import { randomUUID } from "node:crypto";
132
397
 
133
398
  // src/session.ts
134
399
  import { readlinkSync } from "node:fs";
135
- import { createRequire } from "node:module";
400
+ import { createRequire as createRequire2 } from "node:module";
136
401
  import { spawn } from "node-pty";
137
402
 
403
+ // ../shared/src/input.ts
404
+ var NAVIGATION = new RegExp("^(?:" + [
405
+ "\\x1b\\[<\\d+;\\d+;\\d+[Mm]",
406
+ // SGR, SGR-pixels
407
+ "\\x1b\\[\\d+;\\d+;\\d+M",
408
+ // urxvt
409
+ "\\x1b\\[M[\\s\\S]{3}",
410
+ // X10, UTF-8
411
+ "\\x1b\\[[\\d;]*[ABCDHF]",
412
+ // arrows, home, end — with or without modifiers
413
+ "\\x1bO[ABCDHF]",
414
+ // the same in application cursor mode
415
+ "\\x1b\\[[145678]~",
416
+ // home, end, page up, page down
417
+ "\\x1b\\[[IO]"
418
+ // focus in, focus out — the terminal answering, not the user
419
+ ].join("|") + ")");
420
+ function inputKind(data) {
421
+ if (!data) return "command";
422
+ let rest = data;
423
+ while (rest.length > 0) {
424
+ const match = NAVIGATION.exec(rest);
425
+ if (!match) return "command";
426
+ rest = rest.slice(match[0].length);
427
+ }
428
+ return "navigation";
429
+ }
430
+
138
431
  // src/snapshot.ts
139
432
  function snapshot(term) {
140
433
  const buf = term.buffer.active;
@@ -216,9 +509,9 @@ function interactiveArgs(shell) {
216
509
  }
217
510
 
218
511
  // src/session.ts
219
- var require2 = createRequire(import.meta.url);
220
- var { Terminal } = require2("@xterm/headless");
221
- var { SerializeAddon } = require2("@xterm/addon-serialize");
512
+ var require3 = createRequire2(import.meta.url);
513
+ var { Terminal } = require3("@xterm/headless");
514
+ var { SerializeAddon } = require3("@xterm/addon-serialize");
222
515
  var CWD_POLL_MS = 2e3;
223
516
  var CWD_ENFORCE_MS = 400;
224
517
  var Session = class {
@@ -269,6 +562,8 @@ var Session = class {
269
562
  env["TRING_SLOT"] = String(this.slot);
270
563
  env["TRING_PROJECT"] = opts.projectName;
271
564
  env["TRING_URL"] = opts.url;
565
+ if (opts.token) env["TRING_TOKEN"] = opts.token;
566
+ else delete env["TRING_TOKEN"];
272
567
  const autorun = opts.autorun ?? true;
273
568
  const args = this.command && autorun ? commandArgs(shell, this.command) : interactiveArgs(shell);
274
569
  this.pty = spawn(shell, args, {
@@ -322,7 +617,7 @@ var Session = class {
322
617
  write(data) {
323
618
  if (this.disposed) return;
324
619
  this.hasInput = true;
325
- this.signal((t, now) => t.input(now));
620
+ this.signal((t, now) => t.input(now, inputKind(data)));
326
621
  this.pty.write(data);
327
622
  }
328
623
  resize(cols, rows) {
@@ -442,6 +737,8 @@ var SessionManager = class {
442
737
  }
443
738
  bySlot = /* @__PURE__ */ new Map();
444
739
  byId = /* @__PURE__ */ new Map();
740
+ /** Set while a compound change runs, so listeners are told once, at the end. */
741
+ quiet = false;
445
742
  onSessionData = null;
446
743
  onSessionStatus = null;
447
744
  onSessionExit = null;
@@ -464,6 +761,7 @@ var SessionManager = class {
464
761
  name: spec.name ?? null,
465
762
  color: HEX.test(spec.color ?? "") ? spec.color : null,
466
763
  url: this.opts.url,
764
+ token: this.opts.token ?? null,
467
765
  scrollback: this.opts.scrollback,
468
766
  idleMs: this.opts.idleMs,
469
767
  ...this.opts.shell ? { shell: this.opts.shell } : {},
@@ -472,10 +770,10 @@ var SessionManager = class {
472
770
  session.onData = (data) => this.onSessionData?.(session, data);
473
771
  session.onStatusChange = () => this.onSessionStatus?.(session);
474
772
  session.onExit = (code) => this.onSessionExit?.(session, code);
475
- session.onCwdChange = () => this.onStructureChange?.();
773
+ session.onCwdChange = () => this.structureChanged();
476
774
  this.bySlot.set(slot, session);
477
775
  this.byId.set(session.id, session);
478
- this.onStructureChange?.();
776
+ this.structureChanged();
479
777
  return session;
480
778
  }
481
779
  get(id) {
@@ -491,7 +789,7 @@ var SessionManager = class {
491
789
  const s = this.byId.get(id);
492
790
  if (!s) return;
493
791
  s.name = name;
494
- this.onStructureChange?.();
792
+ this.structureChanged();
495
793
  }
496
794
  /**
497
795
  * The tint ends up in a CSS custom property in the browser, and arrives from
@@ -502,7 +800,7 @@ var SessionManager = class {
502
800
  const s = this.byId.get(id);
503
801
  if (!s) return;
504
802
  s.color = color !== null && HEX.test(color) ? color : null;
505
- this.onStructureChange?.();
803
+ this.structureChanged();
506
804
  }
507
805
  kill(id) {
508
806
  const s = this.byId.get(id);
@@ -510,7 +808,7 @@ var SessionManager = class {
510
808
  s.dispose();
511
809
  this.bySlot.delete(s.slot);
512
810
  this.byId.delete(id);
513
- this.onStructureChange?.();
811
+ this.structureChanged();
514
812
  }
515
813
  /**
516
814
  * Explicit user-initiated respawn of a dead tile. Unlike daemon restore this
@@ -527,7 +825,12 @@ var SessionManager = class {
527
825
  color: old.color,
528
826
  autorun: true
529
827
  };
530
- this.kill(id);
828
+ this.quiet = true;
829
+ try {
830
+ this.kill(id);
831
+ } finally {
832
+ this.quiet = false;
833
+ }
531
834
  return this.create(spec);
532
835
  }
533
836
  tick(now) {
@@ -538,6 +841,9 @@ var SessionManager = class {
538
841
  this.bySlot.clear();
539
842
  this.byId.clear();
540
843
  }
844
+ structureChanged() {
845
+ if (!this.quiet) this.onStructureChange?.();
846
+ }
541
847
  firstEmptySlot() {
542
848
  for (let slot = 1; slot <= SLOT_COUNT; slot++) if (!this.bySlot.has(slot)) return slot;
543
849
  return null;
@@ -546,8 +852,8 @@ var SessionManager = class {
546
852
 
547
853
  // src/project-manager.ts
548
854
  function defaultStatePath() {
549
- const base2 = process.env["XDG_CONFIG_HOME"] ?? path.join(os.homedir(), ".config");
550
- return path.join(base2, "tring", "projects.json");
855
+ const base2 = process.env["XDG_CONFIG_HOME"] ?? path3.join(os2.homedir(), ".config");
856
+ return path3.join(base2, "tring", "projects.json");
551
857
  }
552
858
  var ProjectManager = class _ProjectManager {
553
859
  constructor(opts) {
@@ -660,6 +966,7 @@ var ProjectManager = class _ProjectManager {
660
966
  projectName: e.name,
661
967
  root: e.root,
662
968
  url: this.opts.url,
969
+ token: this.opts.token ?? null,
663
970
  scrollback: this.opts.scrollback,
664
971
  idleMs: this.opts.idleMs,
665
972
  ...this.opts.shell ? { shell: this.opts.shell } : {}
@@ -702,8 +1009,8 @@ var ProjectManager = class _ProjectManager {
702
1009
  save() {
703
1010
  const state = this.snapshotState();
704
1011
  this.writing = this.writing.then(async () => {
705
- await mkdir(path.dirname(this.statePath), { recursive: true });
706
- await writeFile(this.statePath, JSON.stringify(state, null, 2), "utf8");
1012
+ await mkdir2(path3.dirname(this.statePath), { recursive: true });
1013
+ await writeFile2(this.statePath, JSON.stringify(state, null, 2), "utf8");
707
1014
  }).catch(() => {
708
1015
  });
709
1016
  return this.writing;
@@ -711,7 +1018,7 @@ var ProjectManager = class _ProjectManager {
711
1018
  async load() {
712
1019
  let parsed;
713
1020
  try {
714
- parsed = JSON.parse(await readFile(this.statePath, "utf8"));
1021
+ parsed = JSON.parse(await readFile2(this.statePath, "utf8"));
715
1022
  } catch {
716
1023
  return;
717
1024
  }
@@ -732,9 +1039,9 @@ var ProjectManager = class _ProjectManager {
732
1039
 
733
1040
  // src/http.ts
734
1041
  import { createReadStream } from "node:fs";
735
- import { readdir as readdir2, realpath, stat as stat2 } from "node:fs/promises";
736
- import os3 from "node:os";
737
- import path3 from "node:path";
1042
+ import { readdir as readdir3, realpath, stat as stat3 } from "node:fs/promises";
1043
+ import os4 from "node:os";
1044
+ import path6 from "node:path";
738
1045
 
739
1046
  // src/security.ts
740
1047
  import { createHash, timingSafeEqual } from "node:crypto";
@@ -808,9 +1115,9 @@ var SECURITY_HEADERS = Object.freeze({
808
1115
 
809
1116
  // src/usage.ts
810
1117
  import { spawn as spawn2 } from "node:child_process";
811
- import { readdir, readFile as readFile2, stat } from "node:fs/promises";
812
- import os2 from "node:os";
813
- import path2 from "node:path";
1118
+ import { readdir, readFile as readFile3, stat } from "node:fs/promises";
1119
+ import os3 from "node:os";
1120
+ import path4 from "node:path";
814
1121
  var WINDOW_MS = 5 * 36e5;
815
1122
  var WEEK_MS = 7 * 24 * 36e5;
816
1123
  var PRICES = [
@@ -822,8 +1129,8 @@ var PRICES = [
822
1129
  ["claude-haiku-", 1, 5]
823
1130
  ];
824
1131
  function defaultTranscriptDir() {
825
- const base2 = process.env["CLAUDE_CONFIG_DIR"] ?? path2.join(os2.homedir(), ".claude");
826
- return path2.join(base2, "projects");
1132
+ const base2 = process.env["CLAUDE_CONFIG_DIR"] ?? path4.join(os3.homedir(), ".claude");
1133
+ return path4.join(base2, "projects");
827
1134
  }
828
1135
  var empty = () => ({ tokens: 0, cacheReadTokens: 0, cost: 0, messages: 0 });
829
1136
  function add(b, e) {
@@ -843,7 +1150,7 @@ async function scanUsage(dir, now) {
843
1150
  for (const file of await transcripts(dir, weekAgo)) {
844
1151
  let text2;
845
1152
  try {
846
- text2 = await readFile2(file, "utf8");
1153
+ text2 = await readFile3(file, "utf8");
847
1154
  } catch {
848
1155
  continue;
849
1156
  }
@@ -931,7 +1238,7 @@ async function transcripts(dir, since) {
931
1238
  const out = [];
932
1239
  for (const name of names) {
933
1240
  if (!name.endsWith(".jsonl")) continue;
934
- const file = path2.join(dir, name);
1241
+ const file = path4.join(dir, name);
935
1242
  try {
936
1243
  if ((await stat(file)).mtimeMs >= since) out.push(file);
937
1244
  } catch {
@@ -1008,6 +1315,64 @@ function describe(err) {
1008
1315
  return err.message || "could not run `claude -p /usage`";
1009
1316
  }
1010
1317
 
1318
+ // src/uploads.ts
1319
+ import { randomBytes as randomBytes2 } from "node:crypto";
1320
+ import { mkdir as mkdir3, readdir as readdir2, rm, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
1321
+ import path5 from "node:path";
1322
+ var MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
1323
+ var KEEP = 20;
1324
+ function sniffImage(bytes) {
1325
+ const at = (i, sig) => sig.every((b, n) => bytes[i + n] === b);
1326
+ if (at(0, [137, 80, 78, 71, 13, 10, 26, 10])) return ".png";
1327
+ if (at(0, [255, 216, 255])) return ".jpg";
1328
+ if (at(0, [71, 73, 70, 56])) return ".gif";
1329
+ if (at(0, [82, 73, 70, 70]) && at(8, [87, 69, 66, 80])) return ".webp";
1330
+ return null;
1331
+ }
1332
+ var NotAnImage = class extends Error {
1333
+ constructor() {
1334
+ super("only PNG, JPEG, GIF and WebP images can be dropped on a terminal");
1335
+ }
1336
+ };
1337
+ var UploadStore = class {
1338
+ constructor(dir, keep = KEEP) {
1339
+ this.dir = dir;
1340
+ this.keep = keep;
1341
+ }
1342
+ /** Writes the bytes and returns the absolute path to type into the prompt. */
1343
+ async save(bytes) {
1344
+ const ext = sniffImage(bytes);
1345
+ if (!ext) throw new NotAnImage();
1346
+ await mkdir3(this.dir, { recursive: true, mode: 448 });
1347
+ const file = path5.join(this.dir, randomBytes2(8).toString("hex") + ext);
1348
+ await writeFile3(file, bytes, { mode: 384 });
1349
+ await this.prune();
1350
+ return file;
1351
+ }
1352
+ /** Drops are scratch: a daemon that stops has nothing left to point at. */
1353
+ async dispose() {
1354
+ await rm(this.dir, { recursive: true, force: true }).catch(() => {
1355
+ });
1356
+ }
1357
+ /**
1358
+ * Oldest first, newest kept. A deck left open for weeks would otherwise
1359
+ * accumulate every screenshot ever dropped into it.
1360
+ */
1361
+ async prune() {
1362
+ try {
1363
+ const names = await readdir2(this.dir);
1364
+ if (names.length <= this.keep) return;
1365
+ const dated = await Promise.all(names.map(async (name) => {
1366
+ const full = path5.join(this.dir, name);
1367
+ return { full, at: (await stat2(full)).mtimeMs };
1368
+ }));
1369
+ dated.sort((a, b) => b.at - a.at);
1370
+ await Promise.all(dated.slice(this.keep).map((f) => rm(f.full, { force: true })));
1371
+ } catch {
1372
+ }
1373
+ }
1374
+ };
1375
+
1011
1376
  // src/http.ts
1012
1377
  var MIME = {
1013
1378
  ".html": "text/html; charset=utf-8",
@@ -1033,29 +1398,61 @@ var text = (res, code, body) => {
1033
1398
  head(res, code, "text/plain; charset=utf-8");
1034
1399
  res.end(body);
1035
1400
  };
1036
- var readBody = (req) => new Promise((resolve) => {
1037
- let data = "";
1401
+ var DRAIN_GRACE_MS = 2e3;
1402
+ var tooLarge = (req, res, message) => {
1403
+ res.writeHead(413, {
1404
+ ...SECURITY_HEADERS,
1405
+ "content-type": "application/json; charset=utf-8",
1406
+ connection: "close"
1407
+ });
1408
+ res.end(JSON.stringify({ error: message }));
1409
+ const cut = setTimeout(() => req.destroy(), DRAIN_GRACE_MS);
1410
+ cut.unref();
1411
+ req.on("end", () => clearTimeout(cut));
1412
+ req.on("close", () => clearTimeout(cut));
1413
+ req.resume();
1414
+ };
1415
+ var MAX_BODY_BYTES = 1e6;
1416
+ var readBytes = (req, limit) => new Promise((resolve) => {
1417
+ let chunks = [];
1418
+ let size = 0;
1419
+ const settle = (body) => {
1420
+ if (chunks === null) return;
1421
+ chunks = null;
1422
+ resolve(body);
1423
+ };
1038
1424
  req.on("data", (c) => {
1039
- data += c;
1040
- if (data.length > 1e6) req.destroy();
1425
+ if (chunks === null) return;
1426
+ size += c.length;
1427
+ if (size > limit) {
1428
+ settle(null);
1429
+ return;
1430
+ }
1431
+ chunks.push(c);
1041
1432
  });
1042
- req.on("end", () => resolve(data));
1433
+ req.on("end", () => settle(chunks ? Buffer.concat(chunks) : null));
1434
+ req.on("error", () => settle(null));
1435
+ req.on("close", () => settle(null));
1043
1436
  });
1437
+ var readBody = async (req) => {
1438
+ const bytes = await readBytes(req, MAX_BODY_BYTES);
1439
+ return bytes === null ? null : bytes.toString("utf8");
1440
+ };
1044
1441
  var USAGE_CACHE_MS = 3e4;
1045
1442
  function createHandler(opts) {
1046
1443
  const { pm, webRoot, token } = opts;
1047
1444
  const sameOrigin = opts.sameOrigin ?? createOriginCheck();
1048
1445
  let usage = null;
1049
- const homeDir = () => process.env["HOME"] ?? os3.homedir();
1446
+ const homeDir = () => process.env["HOME"] ?? os4.homedir();
1050
1447
  const within = (root, dir) => {
1051
- const rel = path3.relative(path3.resolve(root), dir);
1052
- return rel === "" || !rel.startsWith("..") && !path3.isAbsolute(rel);
1448
+ const rel = path6.relative(path6.resolve(root), dir);
1449
+ return rel === "" || !rel.startsWith("..") && !path6.isAbsolute(rel);
1053
1450
  };
1054
1451
  const real = async (p) => {
1055
1452
  try {
1056
1453
  return await realpath(p);
1057
1454
  } catch {
1058
- return path3.resolve(p);
1455
+ return path6.resolve(p);
1059
1456
  }
1060
1457
  };
1061
1458
  const browsable = async (dir) => {
@@ -1086,9 +1483,11 @@ function createHandler(opts) {
1086
1483
  if (status && req.method === "POST") {
1087
1484
  const s = pm.findSession(decodeURIComponent(status[1]));
1088
1485
  if (!s) return json(res, 404, { error: "no such session" });
1486
+ const raw = await readBody(req);
1487
+ if (raw === null) return tooLarge(req, res, "body too large");
1089
1488
  let body;
1090
1489
  try {
1091
- body = JSON.parse(await readBody(req) || "{}");
1490
+ body = JSON.parse(raw || "{}");
1092
1491
  } catch {
1093
1492
  return json(res, 400, { error: "malformed body" });
1094
1493
  }
@@ -1099,12 +1498,12 @@ function createHandler(opts) {
1099
1498
  }
1100
1499
  if (url.pathname === "/api/fs" && req.method === "GET") {
1101
1500
  const raw = url.searchParams.get("path")?.trim();
1102
- const dir = raw ? path3.resolve(raw) : homeDir();
1501
+ const dir = raw ? path6.resolve(raw) : homeDir();
1103
1502
  if (!await browsable(dir)) return json(res, 403, { error: "outside the browsable roots" });
1104
1503
  try {
1105
- const found = await readdir2(dir, { withFileTypes: true });
1106
- const entries = found.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".")).map((e) => ({ name: e.name, path: path3.join(dir, e.name) })).sort((a, b) => a.name.localeCompare(b.name));
1107
- const parent = path3.dirname(dir);
1504
+ const found = await readdir3(dir, { withFileTypes: true });
1505
+ const entries = found.filter((e) => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith(".")).map((e) => ({ name: e.name, path: path6.join(dir, e.name) })).sort((a, b) => a.name.localeCompare(b.name));
1506
+ const parent = path6.dirname(dir);
1108
1507
  const up = parent !== dir && await browsable(parent) ? parent : null;
1109
1508
  return json(res, 200, { path: dir, parent: up, entries });
1110
1509
  } catch {
@@ -1123,6 +1522,25 @@ function createHandler(opts) {
1123
1522
  return json(res, 500, { error: "cannot read Claude Code transcripts" });
1124
1523
  }
1125
1524
  }
1525
+ if (url.pathname === "/api/upload" && req.method === "POST") {
1526
+ const store = opts.uploads;
1527
+ if (!store) return json(res, 503, { error: "uploads are not configured" });
1528
+ const declared = Number(req.headers["content-length"] ?? "0");
1529
+ if (declared > MAX_UPLOAD_BYTES) {
1530
+ return json(res, 413, { error: `images are limited to ${MAX_UPLOAD_BYTES >> 20}MB` });
1531
+ }
1532
+ const bytes = await readBytes(req, MAX_UPLOAD_BYTES);
1533
+ if (bytes === null) {
1534
+ return tooLarge(req, res, `images are limited to ${MAX_UPLOAD_BYTES >> 20}MB`);
1535
+ }
1536
+ if (bytes.length === 0) return json(res, 400, { error: "empty upload" });
1537
+ try {
1538
+ return json(res, 200, { path: await store.save(bytes) });
1539
+ } catch (err) {
1540
+ if (err instanceof NotAnImage) return json(res, 415, { error: err.message });
1541
+ return json(res, 500, { error: "cannot write the dropped image" });
1542
+ }
1543
+ }
1126
1544
  if (url.pathname === "/api/sessions" && req.method === "GET") {
1127
1545
  const sessions = pm.list().flatMap(
1128
1546
  (p) => p.sessions.map((s) => ({ ...s, project: p.name }))
@@ -1133,15 +1551,15 @@ function createHandler(opts) {
1133
1551
  }
1134
1552
  async function serveStatic(res, pathname) {
1135
1553
  const rel = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
1136
- const file = path3.resolve(webRoot, rel);
1137
- if (file !== webRoot && !file.startsWith(webRoot + path3.sep)) {
1554
+ const file = path6.resolve(webRoot, rel);
1555
+ if (file !== webRoot && !file.startsWith(webRoot + path6.sep)) {
1138
1556
  text(res, 403, "forbidden");
1139
1557
  return;
1140
1558
  }
1141
1559
  try {
1142
- const info = await stat2(file);
1560
+ const info = await stat3(file);
1143
1561
  if (!info.isFile()) throw new Error("not a file");
1144
- head(res, 200, MIME[path3.extname(file)] ?? "application/octet-stream");
1562
+ head(res, 200, MIME[path6.extname(file)] ?? "application/octet-stream");
1145
1563
  createReadStream(file).pipe(res);
1146
1564
  } catch {
1147
1565
  if (rel === "index.html") {
@@ -1356,12 +1774,13 @@ var Hub = class {
1356
1774
 
1357
1775
  // src/open-window.ts
1358
1776
  import { spawn as spawn3 } from "node:child_process";
1359
- import { existsSync, readFileSync } from "node:fs";
1360
- import os4 from "node:os";
1777
+ import { existsSync, readFileSync as readFileSync2 } from "node:fs";
1778
+ import os5 from "node:os";
1779
+ import { setTimeout as delay } from "node:timers/promises";
1361
1780
  function isWsl() {
1362
1781
  if (process.env["WSL_DISTRO_NAME"]) return true;
1363
1782
  try {
1364
- return /microsoft/i.test(readFileSync("/proc/version", "utf8"));
1783
+ return /microsoft/i.test(readFileSync2("/proc/version", "utf8"));
1365
1784
  } catch {
1366
1785
  return false;
1367
1786
  }
@@ -1381,7 +1800,44 @@ function firstExisting(paths) {
1381
1800
  for (const p of paths) if (existsSync(p)) return p;
1382
1801
  return null;
1383
1802
  }
1384
- function openWindow(url) {
1803
+ var WINDOWS_CURL = "/mnt/c/Windows/System32/curl.exe";
1804
+ var RELAY_DEADLINE_MS = 8e3;
1805
+ var RELAY_GAP_MS = 150;
1806
+ function reachableFromWindows(origin) {
1807
+ return new Promise((resolve) => {
1808
+ const probe = spawn3(WINDOWS_CURL, [
1809
+ "-s",
1810
+ "-k",
1811
+ "-o",
1812
+ "NUL",
1813
+ "--max-time",
1814
+ "2",
1815
+ origin
1816
+ ], { stdio: "ignore" });
1817
+ probe.on("close", (code) => resolve(code === 0 ? "reachable" : "refused"));
1818
+ probe.on("error", () => resolve("unusable"));
1819
+ });
1820
+ }
1821
+ async function awaitRelay(probe, opts = {}) {
1822
+ const deadline = Date.now() + (opts.deadlineMs ?? RELAY_DEADLINE_MS);
1823
+ for (; ; ) {
1824
+ const answer = await probe();
1825
+ if (answer !== "refused") return answer;
1826
+ if (Date.now() >= deadline) return "refused";
1827
+ await delay(opts.gapMs ?? RELAY_GAP_MS);
1828
+ }
1829
+ }
1830
+ async function waitForWindowsRelay(url) {
1831
+ if (!existsSync(WINDOWS_CURL)) return;
1832
+ let origin;
1833
+ try {
1834
+ origin = new URL(url).origin;
1835
+ } catch {
1836
+ return;
1837
+ }
1838
+ await awaitRelay(() => reachableFromWindows(origin));
1839
+ }
1840
+ async function openWindow(url) {
1385
1841
  if (process.env["TRING_NO_OPEN"]) return false;
1386
1842
  const appFlag = `--app=${url}`;
1387
1843
  let command;
@@ -1418,6 +1874,7 @@ function openWindow(url) {
1418
1874
  command = exe;
1419
1875
  args = [appFlag];
1420
1876
  }
1877
+ if (isWsl()) await waitForWindowsRelay(url);
1421
1878
  try {
1422
1879
  const child = spawn3(command, args, { detached: true, stdio: "ignore" });
1423
1880
  child.on("error", () => {
@@ -1429,212 +1886,162 @@ function openWindow(url) {
1429
1886
  }
1430
1887
  }
1431
1888
  function describeFallback(url) {
1432
- return isWsl() || os4.platform() === "linux" ? `open ${url} in your browser` : `open ${url}`;
1889
+ return isWsl() || os5.platform() === "linux" ? `open ${url} in your browser` : `open ${url}`;
1433
1890
  }
1434
1891
 
1435
- // src/update-check.ts
1436
- import { createRequire as createRequire2 } from "node:module";
1437
- import { mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "node:fs/promises";
1438
- import path4 from "node:path";
1439
- var require3 = createRequire2(import.meta.url);
1440
- function currentVersion() {
1892
+ // src/spawn-helper.ts
1893
+ import {
1894
+ closeSync,
1895
+ constants,
1896
+ fchmodSync,
1897
+ fstatSync,
1898
+ openSync,
1899
+ readdirSync
1900
+ } from "node:fs";
1901
+ import { createRequire as createRequire3 } from "node:module";
1902
+ import path7 from "node:path";
1903
+ var EXEC = 73;
1904
+ function nodePtyRoot() {
1441
1905
  try {
1442
- return require3("../package.json").version;
1906
+ return path7.dirname(createRequire3(import.meta.url).resolve("node-pty/package.json"));
1443
1907
  } catch {
1444
- return "0.0.0";
1445
- }
1446
- }
1447
- function isNewer(latest, current) {
1448
- if (latest.includes("-")) return false;
1449
- const parse = (v) => v.split("-")[0].split(".").map((n) => Number(n) || 0);
1450
- const a = parse(latest);
1451
- const b = parse(current);
1452
- for (let i = 0; i < 3; i++) {
1453
- const x = a[i] ?? 0;
1454
- const y = b[i] ?? 0;
1455
- if (x !== y) return x > y;
1908
+ return null;
1456
1909
  }
1457
- return false;
1458
1910
  }
1459
- var DAY_MS = 24 * 60 * 60 * 1e3;
1460
- async function checkForUpdate(cachePath) {
1461
- const current = currentVersion();
1462
- let cache = null;
1911
+ function spawnHelperPaths(root) {
1912
+ const found = [path7.join(root, "build", "Release", "spawn-helper")];
1913
+ let prebuilds;
1463
1914
  try {
1464
- cache = JSON.parse(await readFile3(cachePath, "utf8"));
1915
+ prebuilds = readdirSync(path7.join(root, "prebuilds"), { withFileTypes: true });
1465
1916
  } catch {
1466
- cache = null;
1917
+ return found;
1467
1918
  }
1468
- if (cache && Date.now() - cache.checkedAt < DAY_MS) {
1469
- return isNewer(cache.latest, current) ? cache.latest : null;
1470
- }
1471
- let latest;
1472
- try {
1473
- const res = await fetch("https://registry.npmjs.org/tring-chat/latest", {
1474
- signal: AbortSignal.timeout(3e3)
1475
- });
1476
- if (!res.ok) return null;
1477
- latest = (await res.json()).version ?? "";
1478
- if (!latest) return null;
1479
- } catch {
1480
- return null;
1919
+ for (const entry of prebuilds) {
1920
+ if (entry.isDirectory()) found.push(path7.join(root, "prebuilds", entry.name, "spawn-helper"));
1481
1921
  }
1482
- try {
1483
- await mkdir2(path4.dirname(cachePath), { recursive: true });
1484
- await writeFile2(cachePath, JSON.stringify({ checkedAt: Date.now(), latest }), "utf8");
1485
- } catch {
1922
+ return found;
1923
+ }
1924
+ function fixSpawnHelper(root = nodePtyRoot()) {
1925
+ if (process.platform === "win32" || root === null) return [];
1926
+ const fixed = [];
1927
+ for (const file of spawnHelperPaths(root)) {
1928
+ let fd = null;
1929
+ try {
1930
+ fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
1931
+ const info = fstatSync(fd);
1932
+ if (!info.isFile()) continue;
1933
+ const mode = info.mode & 511;
1934
+ if (mode & EXEC) continue;
1935
+ fchmodSync(fd, mode | EXEC);
1936
+ fixed.push(file);
1937
+ } catch {
1938
+ } finally {
1939
+ if (fd !== null) closeSync(fd);
1940
+ }
1486
1941
  }
1487
- return isNewer(latest, current) ? latest : null;
1942
+ return fixed;
1488
1943
  }
1489
1944
 
1490
1945
  // src/index.ts
1491
- var listOf = (value) => (value ?? "").split(",").map((s) => s.trim()).filter(Boolean);
1492
- function parseArgs(argv) {
1493
- const args = {
1494
- port: Number(process.env["TRING_PORT"] ?? DEFAULT_PORT),
1495
- host: process.env["TRING_HOST"] ?? DEFAULT_HOST,
1496
- token: process.env["TRING_TOKEN"] ?? null,
1497
- scrollback: DEFAULT_SCROLLBACK,
1498
- idleMs: DEFAULT_IDLE_MS,
1499
- open: !process.env["TRING_NO_OPEN"],
1500
- shell: process.env["TRING_SHELL"] ?? null,
1501
- updateCheck: !process.env["TRING_NO_UPDATE_CHECK"],
1502
- allowOrigin: listOf(process.env["TRING_ALLOW_ORIGIN"]),
1503
- fsRoot: listOf(process.env["TRING_FS_ROOT"]),
1504
- insecureNoToken: !!process.env["TRING_INSECURE_NO_TOKEN"]
1505
- };
1506
- for (let i = 0; i < argv.length; i++) {
1507
- const [flag, inline] = argv[i].split("=", 2);
1508
- const value = inline ?? argv[++i];
1509
- switch (flag) {
1510
- case "--port":
1511
- args.port = Number(value);
1512
- break;
1513
- case "--host":
1514
- args.host = String(value);
1515
- break;
1516
- case "--token":
1517
- args.token = String(value);
1518
- break;
1519
- case "--scrollback":
1520
- args.scrollback = Number(value);
1521
- break;
1522
- case "--idle-ms":
1523
- args.idleMs = Number(value);
1524
- break;
1525
- case "--shell":
1526
- args.shell = String(value);
1527
- break;
1528
- case "--allow-origin":
1529
- args.allowOrigin.push(...listOf(String(value)));
1530
- break;
1531
- case "--fs-root":
1532
- args.fsRoot.push(...listOf(String(value)));
1533
- break;
1534
- case "--insecure-no-token":
1535
- args.insecureNoToken = true;
1536
- i--;
1537
- break;
1538
- case "--no-open":
1539
- args.open = false;
1540
- i--;
1541
- break;
1542
- case "--no-update-check":
1543
- args.updateCheck = false;
1544
- i--;
1545
- break;
1546
- case "--version":
1547
- console.log(currentVersion());
1548
- process.exit(0);
1549
- case "--help":
1550
- console.log(`tring \u2014 focus-centred terminal deck
1551
-
1552
- --port <n> default ${DEFAULT_PORT}
1553
- --host <addr> default ${DEFAULT_HOST}
1554
- --token <secret> require bearer auth (use when binding off localhost)
1555
- --scrollback <n> lines kept per session, default ${DEFAULT_SCROLLBACK}
1556
- --idle-ms <n> quiet period before a session is done, default ${DEFAULT_IDLE_MS}
1557
- --shell <path> shell to spawn; default $SHELL, or powershell.exe on
1558
- Windows. Use --shell wsl.exe for WSL shells from Windows
1559
- --fs-root <path> extra directory the project picker may browse; repeatable.
1560
- Home and existing project roots are always browsable
1561
- --allow-origin <o> extra browser origin allowed to reach the daemon;
1562
- repeatable. Only the page the daemon serves is allowed by
1563
- default, which is what stops any website you visit from
1564
- opening a socket to it
1565
- --insecure-no-token
1566
- bind off localhost with no --token anyway. The daemon
1567
- spawns shells, so this hands one to everything that can
1568
- reach the port, and to any site that can rebind a name
1569
- to it. Only for a network you already trust that far
1570
- --no-open do not launch a browser window
1571
- --no-update-check do not ask npm whether a newer tring exists
1572
- --version print the version and exit`);
1573
- process.exit(0);
1946
+ function resolveAuth(args) {
1947
+ if (args.insecureNoToken) return { token: null, persisted: false };
1948
+ if (args.token) return { token: args.token, persisted: false };
1949
+ return { token: loadOrCreateToken(), persisted: true };
1950
+ }
1951
+ function loadTls(certFile, keyFile) {
1952
+ const read = (file, what) => {
1953
+ try {
1954
+ return readFileSync3(file);
1955
+ } catch (err) {
1956
+ throw new UsageError(`cannot read the TLS ${what} at ${file}: ${err.message}`);
1574
1957
  }
1575
- }
1576
- return args;
1958
+ };
1959
+ return { cert: read(certFile, "certificate"), key: read(keyFile, "key") };
1577
1960
  }
1578
1961
  async function main() {
1579
1962
  const args = parseArgs(process.argv.slice(2));
1580
- if (bindNeedsToken(args.host, args.token) && !args.insecureNoToken) {
1581
- console.error(`refusing to bind ${args.host} without --token.
1963
+ let auth;
1964
+ try {
1965
+ auth = resolveAuth(args);
1966
+ } catch (err) {
1967
+ throw new UsageError(`cannot read or create ${defaultTokenPath()}: ${err.message}
1968
+ Fix the permissions on that path, pass --token, or accept an unauthenticated
1969
+ daemon on purpose with --insecure-no-token.`);
1970
+ }
1971
+ const { token } = auth;
1972
+ if (bindNeedsToken(args.host, token) && !args.insecureNoToken) {
1973
+ throw new UsageError(`refusing to bind ${args.host} without a token.
1582
1974
 
1583
1975
  The daemon spawns shells, so off localhost the token is the only thing
1584
1976
  between the port and a shell on this machine.
1585
1977
 
1586
- tring --host ${args.host} --token "$(openssl rand -hex 32)"
1587
-
1588
- Pass --insecure-no-token if the network is already trusted that far.`);
1589
- process.exit(1);
1978
+ tring --host ${args.host} --token "$(openssl rand -hex 32)"`);
1590
1979
  }
1591
- const url = `http://${args.host}:${args.port}`;
1592
- const here = path5.dirname(fileURLToPath(import.meta.url));
1980
+ const tls = args.tlsCert && args.tlsKey ? loadTls(args.tlsCert, args.tlsKey) : null;
1981
+ const url = `${tls ? "https" : "http"}://${args.host}:${args.port}`;
1982
+ const cleartextOffBox = !tls && !isLoopbackBind(args.host);
1983
+ const here = path8.dirname(fileURLToPath(import.meta.url));
1593
1984
  const webRoot = [
1594
- path5.resolve(here, "web"),
1595
- path5.resolve(here, "../../web/dist")
1596
- ].find((p) => existsSync2(p)) ?? path5.resolve(here, "web");
1985
+ path8.resolve(here, "web"),
1986
+ path8.resolve(here, "../../web/dist")
1987
+ ].find((p) => existsSync2(p)) ?? path8.resolve(here, "web");
1988
+ for (const file of fixSpawnHelper()) console.log(`made ${file} executable`);
1597
1989
  const pm = await ProjectManager.open({
1598
1990
  url,
1991
+ // Reaches each session as $TRING_TOKEN, so the documented Stop hook can
1992
+ // authenticate itself without the user copying a secret into settings.json.
1993
+ token,
1599
1994
  scrollback: args.scrollback,
1600
1995
  idleMs: args.idleMs,
1601
1996
  ...args.shell ? { shell: args.shell } : {}
1602
1997
  });
1603
1998
  const sameOrigin = createOriginCheck({ host: args.host, allow: args.allowOrigin });
1999
+ const uploads = new UploadStore(path8.join(path8.dirname(pm.statePath), "uploads"));
1604
2000
  const handle = createHandler({
1605
2001
  pm,
1606
2002
  webRoot,
1607
- token: args.token,
2003
+ token,
1608
2004
  sameOrigin,
1609
- fsRoots: args.fsRoot
2005
+ fsRoots: args.fsRoot,
2006
+ uploads
1610
2007
  });
1611
- const server = createServer((req, res) => {
2008
+ const listener = (req, res) => {
1612
2009
  void handle(req, res).catch(() => {
1613
2010
  if (!res.headersSent) res.writeHead(500, SECURITY_HEADERS).end("internal error");
1614
2011
  });
1615
- });
2012
+ };
2013
+ const server = tls ? createSecureServer(tls, listener) : createServer(listener);
1616
2014
  const wss = new WebSocketServer({ server, verifyClient: upgradeGuard(sameOrigin) });
1617
- const hub = new Hub({ pm, token: args.token });
2015
+ const hub = new Hub({ pm, token });
1618
2016
  hub.attach(wss);
2017
+ const authUrl = token ? `${url}/?token=${encodeURIComponent(token)}` : url;
1619
2018
  server.listen(args.port, args.host, () => {
1620
2019
  console.log(`tring listening on ${url}`);
1621
- if (bindNeedsToken(args.host, args.token)) {
1622
- console.warn(`warning: bound off localhost with no token \u2014 anything that can reach ${args.host}:${args.port} can open a shell here`);
2020
+ if (auth.persisted) console.log(` token: ${defaultTokenPath()}`);
2021
+ if (!token) {
2022
+ 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}`));
2023
+ }
2024
+ if (cleartextOffBox) {
2025
+ 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.`);
1623
2026
  }
1624
2027
  if (args.updateCheck) {
1625
- void checkForUpdate(path5.join(path5.dirname(pm.statePath), "update-check.json")).then((latest) => {
2028
+ void checkForUpdate(path8.join(path8.dirname(pm.statePath), "update-check.json")).then((latest) => {
1626
2029
  if (!latest) return;
1627
2030
  hub.setUpdate({ current: currentVersion(), latest });
1628
2031
  console.log(`update available: ${currentVersion()} -> ${latest} (npm i -g tring-chat)`);
1629
2032
  });
1630
2033
  }
1631
2034
  if (args.open) {
1632
- const opened = openWindow(url);
1633
- if (!opened) console.log(`no browser found \u2014 ${describeFallback(url)}`);
2035
+ void openWindow(authUrl).then((opened) => {
2036
+ if (!opened) console.log(`no browser found \u2014 ${describeFallback(authUrl)}`);
2037
+ });
2038
+ } else if (token) {
2039
+ console.log(`open ${authUrl}`);
1634
2040
  }
1635
2041
  });
1636
2042
  const shutdown = async () => {
1637
2043
  hub.dispose();
2044
+ await uploads.dispose();
1638
2045
  await pm.dispose();
1639
2046
  server.close(() => process.exit(0));
1640
2047
  setTimeout(() => process.exit(0), 1e3).unref();
@@ -1642,4 +2049,10 @@ async function main() {
1642
2049
  process.on("SIGINT", () => void shutdown());
1643
2050
  process.on("SIGTERM", () => void shutdown());
1644
2051
  }
1645
- void main();
2052
+ void main().catch((err) => {
2053
+ if (err instanceof UsageError) {
2054
+ console.error(err.message);
2055
+ process.exit(1);
2056
+ }
2057
+ throw err;
2058
+ });