tring-chat 0.1.4 → 0.1.6

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 CHANGED
@@ -98,7 +98,8 @@ npm i -g ./packages/server # install this checkout as `tring`
98
98
  ```
99
99
 
100
100
  Flags: `--port` (7331), `--host` (127.0.0.1), `--token`, `--scrollback` (5000),
101
- `--idle-ms` (3000), `--shell`, `--no-open`, `--no-update-check`, `--version`.
101
+ `--idle-ms` (3000), `--shell`, `--fs-root`, `--allow-origin`, `--insecure-no-token`,
102
+ `--no-open`, `--no-update-check`, `--version`.
102
103
 
103
104
  ## On a phone
104
105
 
@@ -111,11 +112,45 @@ The daemon only listens on `127.0.0.1` by default. To reach it from a phone, bin
111
112
  the network and require a token:
112
113
 
113
114
  ```
114
- tring --host 0.0.0.0 --token some-long-secret
115
+ tring --host 0.0.0.0 --token "$(openssl rand -hex 32)"
115
116
  ```
116
117
 
117
118
  then open `http://<your-machine>:7331/?token=some-long-secret` on the phone. A private
118
119
  network such as Tailscale is the safer way to do this than opening the port on a LAN.
120
+
121
+ Binding off localhost without a token is refused at startup rather than warned about: the
122
+ daemon spawns shells, and off loopback the token is the only thing in front of them.
123
+ `--insecure-no-token` overrides that if the network is already trusted that far.
124
+
125
+ The token is remembered on that first visit and then taken back off the address bar, but
126
+ a secret that has travelled in a URL is only as private as the URL: it has already been
127
+ through your history, any proxy log on the way, and whatever chat app you sent the link
128
+ in. Treat the link as the secret, and rotate with a new `--token` rather than assuming an
129
+ old link has expired.
130
+
131
+ ## Who can reach the daemon
132
+
133
+ The daemon spawns shells, so it only answers requests from the page it serves itself.
134
+ That check matters more than the bind address: the same-origin policy does not cover
135
+ WebSockets, so without it any website you happened to have open could open a socket to
136
+ `ws://127.0.0.1:7331` and type into your terminals. Binding to loopback keeps other
137
+ machines out, not other websites.
138
+
139
+ - A browser page from another origin is refused at the handshake. So is a domain rebound
140
+ to 127.0.0.1, while the daemon is on loopback.
141
+ - Non-browser clients send no `Origin` and are unaffected — the Claude Code hooks, curl
142
+ and `/api/sessions` scripts keep working exactly as before.
143
+ - `--allow-origin <origin>` adds one, for a front end you serve yourself. `npm run dev`
144
+ sets it for the Vite server on :5173.
145
+ - `--token` is what gates access once you bind past loopback, and is compared in constant
146
+ time. The origin check cannot cover for it there: the hostname is then your own and
147
+ unguessable to the daemon, so `Host` goes unpinned and a rebound name matches it. That
148
+ is why a token is required rather than recommended off loopback.
149
+ - The directory picker (`/api/fs`) browses your home directory and the roots of projects
150
+ you have already created. `--fs-root <path>` adds another — useful if your projects
151
+ live somewhere like `D:\work`. Paths are resolved through symlinks before the check, so
152
+ a link inside a root is not a way back out of it.
153
+
119
154
  ## Install it as an app
120
155
 
121
156
  tring is a progressive web app. Once it is open in a browser, install it and it gets its
package/dist/tring.js CHANGED
@@ -12,10 +12,10 @@ var DEFAULT_PORT = 7331;
12
12
  var DEFAULT_HOST = "127.0.0.1";
13
13
  var DEFAULT_SCROLLBACK = 5e3;
14
14
  function encodeOutput(id, data) {
15
- const head = new TextEncoder().encode(id + "\0");
16
- const out = new Uint8Array(head.length + data.length);
17
- out.set(head, 0);
18
- out.set(data, head.length);
15
+ const head2 = new TextEncoder().encode(id + "\0");
16
+ const out = new Uint8Array(head2.length + data.length);
17
+ out.set(head2, 0);
18
+ out.set(data, head2.length);
19
19
  return out;
20
20
  }
21
21
 
@@ -148,14 +148,14 @@ function snapshot(term) {
148
148
  const cell = line.getCell(x);
149
149
  if (!cell) break;
150
150
  if (cell.getWidth() === 0) continue;
151
- const text = cell.getChars() || " ";
151
+ const text2 = cell.getChars() || " ";
152
152
  const fg = cell.isFgDefault() ? -1 : cell.getFgColor();
153
153
  const bg = cell.isBgDefault() ? -1 : cell.getBgColor();
154
154
  const bold = cell.isBold() !== 0;
155
155
  if (run && run.fg === fg && run.bg === bg && run.bold === bold) {
156
- run.text += text;
156
+ run.text += text2;
157
157
  } else {
158
- run = { text, fg, bg, bold };
158
+ run = { text: text2, fg, bg, bold };
159
159
  out.push(run);
160
160
  }
161
161
  }
@@ -732,10 +732,80 @@ var ProjectManager = class _ProjectManager {
732
732
 
733
733
  // src/http.ts
734
734
  import { createReadStream } from "node:fs";
735
- import { readdir as readdir2, stat as stat2 } from "node:fs/promises";
735
+ import { readdir as readdir2, realpath, stat as stat2 } from "node:fs/promises";
736
736
  import os3 from "node:os";
737
737
  import path3 from "node:path";
738
738
 
739
+ // src/security.ts
740
+ import { createHash, timingSafeEqual } from "node:crypto";
741
+ var LOOPBACK = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\]|::1)$/i;
742
+ function hostname(host) {
743
+ return (/^(\[[^\]]*\]|[^:]*)/.exec(host)?.[1] ?? host).toLowerCase();
744
+ }
745
+ function isLoopbackBind(host) {
746
+ return !host || LOOPBACK.test(host);
747
+ }
748
+ function bindNeedsToken(host, token) {
749
+ return !isLoopbackBind(host) && !token;
750
+ }
751
+ function originHost(origin) {
752
+ try {
753
+ const u = new URL(origin);
754
+ return u.protocol === "http:" || u.protocol === "https:" ? u.host.toLowerCase() : null;
755
+ } catch {
756
+ return null;
757
+ }
758
+ }
759
+ function createOriginCheck(opts = {}) {
760
+ const allow = new Set(
761
+ (opts.allow ?? []).map((o) => originHost(o.trim())).filter((o) => o !== null)
762
+ );
763
+ const pinned = isLoopbackBind(opts.host);
764
+ return function sameOrigin(req) {
765
+ const host = req.headers.host?.toLowerCase();
766
+ if (pinned && (!host || !LOOPBACK.test(hostname(host)))) return false;
767
+ const origin = req.headers.origin;
768
+ if (!origin) return true;
769
+ const from = originHost(origin);
770
+ return from !== null && (from === host || allow.has(from));
771
+ };
772
+ }
773
+ var upgradeGuard = (check) => ({ req }) => check(req);
774
+ function secretEquals(a, b) {
775
+ if (typeof a !== "string" || typeof b !== "string") return false;
776
+ const digest = (s) => createHash("sha256").update(s, "utf8").digest();
777
+ return timingSafeEqual(digest(a), digest(b));
778
+ }
779
+ function bearerEquals(token, header) {
780
+ const match = header ? /^bearer +(.*)$/i.exec(header) : null;
781
+ return secretEquals(token, match?.[1] ?? null);
782
+ }
783
+ var SECURITY_HEADERS = Object.freeze({
784
+ "content-security-policy": [
785
+ "default-src 'self'",
786
+ "script-src 'self'",
787
+ // xterm writes a <style> element of its own for terminal metrics.
788
+ "style-src 'self' 'unsafe-inline'",
789
+ "img-src 'self' data:",
790
+ // the favicon is an inline SVG
791
+ "font-src 'self'",
792
+ "connect-src 'self'",
793
+ // ws:// to this same host is 'self' under CSP 3
794
+ "worker-src 'self'",
795
+ // the PWA service worker
796
+ "manifest-src 'self'",
797
+ "base-uri 'none'",
798
+ "object-src 'none'",
799
+ "form-action 'none'",
800
+ "frame-ancestors 'none'"
801
+ ].join("; "),
802
+ "x-content-type-options": "nosniff",
803
+ "x-frame-options": "DENY",
804
+ "referrer-policy": "no-referrer",
805
+ "cross-origin-opener-policy": "same-origin",
806
+ "cross-origin-resource-policy": "same-origin"
807
+ });
808
+
739
809
  // src/usage.ts
740
810
  import { spawn as spawn2 } from "node:child_process";
741
811
  import { readdir, readFile as readFile2, stat } from "node:fs/promises";
@@ -771,13 +841,13 @@ async function scanUsage(dir, now) {
771
841
  const entries = [];
772
842
  const weekAgo = now - WEEK_MS;
773
843
  for (const file of await transcripts(dir, weekAgo)) {
774
- let text;
844
+ let text2;
775
845
  try {
776
- text = await readFile2(file, "utf8");
846
+ text2 = await readFile2(file, "utf8");
777
847
  } catch {
778
848
  continue;
779
849
  }
780
- for (const line of text.split("\n")) {
850
+ for (const line of text2.split("\n")) {
781
851
  if (!line.includes('"usage"')) continue;
782
852
  let rec;
783
853
  try {
@@ -870,9 +940,9 @@ async function transcripts(dir, since) {
870
940
  return out;
871
941
  }
872
942
  var LIMIT_LINE = /^Current ([^:]+):\s*(\d+)%\s*used(?:\s*·\s*resets\s*(.+?))?\s*$/;
873
- function parseLimits(text) {
943
+ function parseLimits(text2) {
874
944
  const out = [];
875
- for (const line of text.split("\n")) {
945
+ for (const line of text2.split("\n")) {
876
946
  const m = LIMIT_LINE.exec(line.trim());
877
947
  if (!m) continue;
878
948
  const label = m[1].trim();
@@ -952,10 +1022,16 @@ var MIME = {
952
1022
  // Browsers refuse to install a PWA whose manifest is served as anything else.
953
1023
  ".webmanifest": "application/manifest+json"
954
1024
  };
1025
+ var head = (res, code, type) => {
1026
+ res.writeHead(code, { ...SECURITY_HEADERS, "content-type": type });
1027
+ };
955
1028
  var json = (res, code, body) => {
956
- const payload = JSON.stringify(body);
957
- res.writeHead(code, { "content-type": "application/json; charset=utf-8" });
958
- res.end(payload);
1029
+ head(res, code, "application/json; charset=utf-8");
1030
+ res.end(JSON.stringify(body));
1031
+ };
1032
+ var text = (res, code, body) => {
1033
+ head(res, code, "text/plain; charset=utf-8");
1034
+ res.end(body);
959
1035
  };
960
1036
  var readBody = (req) => new Promise((resolve) => {
961
1037
  let data = "";
@@ -968,11 +1044,30 @@ var readBody = (req) => new Promise((resolve) => {
968
1044
  var USAGE_CACHE_MS = 3e4;
969
1045
  function createHandler(opts) {
970
1046
  const { pm, webRoot, token } = opts;
1047
+ const sameOrigin = opts.sameOrigin ?? createOriginCheck();
971
1048
  let usage = null;
1049
+ const homeDir = () => process.env["HOME"] ?? os3.homedir();
1050
+ const within = (root, dir) => {
1051
+ const rel = path3.relative(path3.resolve(root), dir);
1052
+ return rel === "" || !rel.startsWith("..") && !path3.isAbsolute(rel);
1053
+ };
1054
+ const real = async (p) => {
1055
+ try {
1056
+ return await realpath(p);
1057
+ } catch {
1058
+ return path3.resolve(p);
1059
+ }
1060
+ };
1061
+ const browsable = async (dir) => {
1062
+ const roots = [homeDir(), ...pm.list().map((p) => p.root), ...opts.fsRoots ?? []];
1063
+ const [target, ...resolved] = await Promise.all([dir, ...roots].map(real));
1064
+ return resolved.some((root) => within(root, target));
1065
+ };
972
1066
  return async function handle(req, res) {
973
1067
  const url = new URL(req.url ?? "/", "http://localhost");
1068
+ if (!sameOrigin(req)) return text(res, 403, "forbidden origin");
974
1069
  if (url.pathname.startsWith("/api/")) {
975
- if (token && req.headers.authorization !== `Bearer ${token}`) {
1070
+ if (token && !bearerEquals(token, req.headers.authorization)) {
976
1071
  return json(res, 401, { error: "unauthorized" });
977
1072
  }
978
1073
  return await api(req, res, url);
@@ -1004,12 +1099,14 @@ function createHandler(opts) {
1004
1099
  }
1005
1100
  if (url.pathname === "/api/fs" && req.method === "GET") {
1006
1101
  const raw = url.searchParams.get("path")?.trim();
1007
- const dir = raw ? path3.resolve(raw) : process.env["HOME"] ?? os3.homedir();
1102
+ const dir = raw ? path3.resolve(raw) : homeDir();
1103
+ if (!await browsable(dir)) return json(res, 403, { error: "outside the browsable roots" });
1008
1104
  try {
1009
1105
  const found = await readdir2(dir, { withFileTypes: true });
1010
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));
1011
1107
  const parent = path3.dirname(dir);
1012
- return json(res, 200, { path: dir, parent: parent === dir ? null : parent, entries });
1108
+ const up = parent !== dir && await browsable(parent) ? parent : null;
1109
+ return json(res, 200, { path: dir, parent: up, entries });
1013
1110
  } catch {
1014
1111
  return json(res, 400, { error: `cannot read ${dir}` });
1015
1112
  }
@@ -1038,21 +1135,21 @@ function createHandler(opts) {
1038
1135
  const rel = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
1039
1136
  const file = path3.resolve(webRoot, rel);
1040
1137
  if (file !== webRoot && !file.startsWith(webRoot + path3.sep)) {
1041
- res.writeHead(403).end("forbidden");
1138
+ text(res, 403, "forbidden");
1042
1139
  return;
1043
1140
  }
1044
1141
  try {
1045
1142
  const info = await stat2(file);
1046
1143
  if (!info.isFile()) throw new Error("not a file");
1047
- res.writeHead(200, { "content-type": MIME[path3.extname(file)] ?? "application/octet-stream" });
1144
+ head(res, 200, MIME[path3.extname(file)] ?? "application/octet-stream");
1048
1145
  createReadStream(file).pipe(res);
1049
1146
  } catch {
1050
1147
  if (rel === "index.html") {
1051
- res.writeHead(200, { "content-type": MIME[".html"] });
1148
+ head(res, 200, MIME[".html"]);
1052
1149
  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>');
1053
1150
  return;
1054
1151
  }
1055
- res.writeHead(404).end("not found");
1152
+ text(res, 404, "not found");
1056
1153
  }
1057
1154
  }
1058
1155
  }
@@ -1111,7 +1208,7 @@ var Hub = class {
1111
1208
  handle(c, msg) {
1112
1209
  const pm = this.opts.pm;
1113
1210
  if (msg.type === "hello") {
1114
- if (this.opts.token && msg.token !== this.opts.token) {
1211
+ if (this.opts.token && !secretEquals(this.opts.token, msg.token)) {
1115
1212
  this.send(c, { type: "error", message: "unauthorized" });
1116
1213
  c.ws.close();
1117
1214
  return;
@@ -1391,6 +1488,7 @@ async function checkForUpdate(cachePath) {
1391
1488
  }
1392
1489
 
1393
1490
  // src/index.ts
1491
+ var listOf = (value) => (value ?? "").split(",").map((s) => s.trim()).filter(Boolean);
1394
1492
  function parseArgs(argv) {
1395
1493
  const args = {
1396
1494
  port: Number(process.env["TRING_PORT"] ?? DEFAULT_PORT),
@@ -1400,7 +1498,10 @@ function parseArgs(argv) {
1400
1498
  idleMs: DEFAULT_IDLE_MS,
1401
1499
  open: !process.env["TRING_NO_OPEN"],
1402
1500
  shell: process.env["TRING_SHELL"] ?? null,
1403
- updateCheck: !process.env["TRING_NO_UPDATE_CHECK"]
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"]
1404
1505
  };
1405
1506
  for (let i = 0; i < argv.length; i++) {
1406
1507
  const [flag, inline] = argv[i].split("=", 2);
@@ -1424,6 +1525,16 @@ function parseArgs(argv) {
1424
1525
  case "--shell":
1425
1526
  args.shell = String(value);
1426
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;
1427
1538
  case "--no-open":
1428
1539
  args.open = false;
1429
1540
  i--;
@@ -1445,6 +1556,17 @@ function parseArgs(argv) {
1445
1556
  --idle-ms <n> quiet period before a session is done, default ${DEFAULT_IDLE_MS}
1446
1557
  --shell <path> shell to spawn; default $SHELL, or powershell.exe on
1447
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
1448
1570
  --no-open do not launch a browser window
1449
1571
  --no-update-check do not ask npm whether a newer tring exists
1450
1572
  --version print the version and exit`);
@@ -1455,6 +1577,17 @@ function parseArgs(argv) {
1455
1577
  }
1456
1578
  async function main() {
1457
1579
  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.
1582
+
1583
+ The daemon spawns shells, so off localhost the token is the only thing
1584
+ between the port and a shell on this machine.
1585
+
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);
1590
+ }
1458
1591
  const url = `http://${args.host}:${args.port}`;
1459
1592
  const here = path5.dirname(fileURLToPath(import.meta.url));
1460
1593
  const webRoot = [
@@ -1467,19 +1600,26 @@ async function main() {
1467
1600
  idleMs: args.idleMs,
1468
1601
  ...args.shell ? { shell: args.shell } : {}
1469
1602
  });
1470
- const handle = createHandler({ pm, webRoot, token: args.token });
1603
+ const sameOrigin = createOriginCheck({ host: args.host, allow: args.allowOrigin });
1604
+ const handle = createHandler({
1605
+ pm,
1606
+ webRoot,
1607
+ token: args.token,
1608
+ sameOrigin,
1609
+ fsRoots: args.fsRoot
1610
+ });
1471
1611
  const server = createServer((req, res) => {
1472
1612
  void handle(req, res).catch(() => {
1473
- if (!res.headersSent) res.writeHead(500).end("internal error");
1613
+ if (!res.headersSent) res.writeHead(500, SECURITY_HEADERS).end("internal error");
1474
1614
  });
1475
1615
  });
1476
- const wss = new WebSocketServer({ server });
1616
+ const wss = new WebSocketServer({ server, verifyClient: upgradeGuard(sameOrigin) });
1477
1617
  const hub = new Hub({ pm, token: args.token });
1478
1618
  hub.attach(wss);
1479
1619
  server.listen(args.port, args.host, () => {
1480
1620
  console.log(`tring listening on ${url}`);
1481
- if (!args.token && args.host !== "127.0.0.1" && args.host !== "localhost") {
1482
- console.warn("warning: bound off localhost without --token");
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`);
1483
1623
  }
1484
1624
  if (args.updateCheck) {
1485
1625
  void checkForUpdate(path5.join(path5.dirname(pm.statePath), "update-check.json")).then((latest) => {