tring-chat 0.1.6 → 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/README.md +77 -32
- package/dist/tring.js +355 -198
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -97,9 +97,9 @@ npm test # vitest
|
|
|
97
97
|
npm i -g ./packages/server # install this checkout as `tring`
|
|
98
98
|
```
|
|
99
99
|
|
|
100
|
-
Flags: `--port` (7331), `--host` (127.0.0.1), `--token`, `--
|
|
101
|
-
`--idle-ms` (3000), `--shell`, `--fs-root`, `--allow-origin`,
|
|
102
|
-
`--no-open`, `--no-update-check`, `--version`.
|
|
100
|
+
Flags: `--port` (7331), `--host` (127.0.0.1), `--token`, `--tls-cert`, `--tls-key`,
|
|
101
|
+
`--scrollback` (5000), `--idle-ms` (3000), `--shell`, `--fs-root`, `--allow-origin`,
|
|
102
|
+
`--insecure-no-token`, `--no-open`, `--no-update-check`, `--version`.
|
|
103
103
|
|
|
104
104
|
## On a phone
|
|
105
105
|
|
|
@@ -108,49 +108,89 @@ bar under the project tabs shows which session you are in. Tap it to get the sam
|
|
|
108
108
|
`Ctrl+Space` opens on desktop, as a sheet you can thumb through; the button beside it jumps
|
|
109
109
|
to the next finished session and counts how many are waiting.
|
|
110
110
|
|
|
111
|
-
The daemon only listens on `127.0.0.1` by default.
|
|
112
|
-
the network and
|
|
111
|
+
The daemon only listens on `127.0.0.1` by default. Reaching it from a phone means binding
|
|
112
|
+
it to the network, and that traffic has to be encrypted — it carries the token, every
|
|
113
|
+
keystroke you type into a shell and everything the shell prints back, which is exactly
|
|
114
|
+
where SSH passphrases, API keys and `.env` contents live.
|
|
115
|
+
|
|
116
|
+
**Use an encrypted overlay network.** Tailscale or WireGuard, with the daemon still on the
|
|
117
|
+
address that network gives you. This is the supported way, not the cautious one:
|
|
118
|
+
|
|
119
|
+
```
|
|
120
|
+
tring --host 100.x.y.z # the Tailscale address of this machine
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
If you must serve the LAN directly, terminate TLS yourself:
|
|
113
124
|
|
|
114
125
|
```
|
|
115
|
-
tring --host 0.0.0.0 --
|
|
126
|
+
tring --host 0.0.0.0 --tls-cert cert.pem --tls-key key.pem
|
|
116
127
|
```
|
|
117
128
|
|
|
118
|
-
|
|
119
|
-
|
|
129
|
+
Then open the link the daemon prints on the phone. `--tls-cert`/`--tls-key` switch the
|
|
130
|
+
daemon to `https` and `wss`; the page follows automatically. Bound off localhost over
|
|
131
|
+
plain `http`, the daemon warns at startup, because anyone on that network segment can read
|
|
132
|
+
the token off the wire and then has a shell.
|
|
120
133
|
|
|
121
|
-
Binding off localhost
|
|
122
|
-
daemon spawns shells, and off loopback the token is the only thing in front of
|
|
123
|
-
|
|
134
|
+
Binding off localhost with `--insecure-no-token` is refused at startup rather than warned
|
|
135
|
+
about: the daemon spawns shells, and off loopback the token is the only thing in front of
|
|
136
|
+
them.
|
|
124
137
|
|
|
125
138
|
The token is remembered on that first visit and then taken back off the address bar, but
|
|
126
139
|
a secret that has travelled in a URL is only as private as the URL: it has already been
|
|
127
140
|
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
|
|
129
|
-
old link has expired.
|
|
141
|
+
in. Treat the link as the secret, and rotate it by deleting `~/.config/tring/token` (or
|
|
142
|
+
passing a new `--token`) rather than assuming an old link has expired.
|
|
130
143
|
|
|
131
144
|
## Who can reach the daemon
|
|
132
145
|
|
|
133
|
-
The daemon spawns shells, so it
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
146
|
+
The daemon spawns shells, so **it requires a bearer token by default, on loopback as much
|
|
147
|
+
as off it.** Binding to `127.0.0.1` is not an authentication boundary: every process on
|
|
148
|
+
the machine can reach it — a postinstall script in some dependency of some project, a
|
|
149
|
+
second user account, a container sharing the host network namespace — and "can run code
|
|
150
|
+
on this box as any user" is not a boundary worth having in front of a shell.
|
|
151
|
+
|
|
152
|
+
If you do not pass `--token`, one is generated on first run and kept at
|
|
153
|
+
`~/.config/tring/token` with mode `0600`. It is stable across restarts, and the daemon
|
|
154
|
+
hands it to the browser window it opens, so there is nothing to copy by hand.
|
|
155
|
+
|
|
156
|
+
- **Scripts on the same machine** read the token back out of that file, which is what
|
|
157
|
+
keeps curl and `/api/sessions` working while other users on the box stay out:
|
|
158
|
+
|
|
159
|
+
```
|
|
160
|
+
curl -s -H "Authorization: Bearer $(cat ~/.config/tring/token)" \
|
|
161
|
+
http://127.0.0.1:7331/api/sessions
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Inside a tring session there is nothing to read: `$TRING_TOKEN` is already set.
|
|
165
|
+
- **Another browser** needs the link once — `http://127.0.0.1:7331/?token=<secret>`. The
|
|
166
|
+
page stores it and scrubs it from the address bar, so installed PWAs start without it.
|
|
167
|
+
- `--insecure-no-token` turns authentication off entirely, and says so at startup. It is
|
|
168
|
+
the only way to get the old unauthenticated behaviour back.
|
|
169
|
+
|
|
170
|
+
On top of the token, the daemon only answers requests from the page it serves itself. The
|
|
171
|
+
same-origin policy does not cover WebSockets, so without that check any website you
|
|
172
|
+
happened to have open could open a socket to `ws://127.0.0.1:7331` and type into your
|
|
173
|
+
terminals.
|
|
138
174
|
|
|
139
175
|
- A browser page from another origin is refused at the handshake. So is a domain rebound
|
|
140
176
|
to 127.0.0.1, while the daemon is on loopback.
|
|
141
|
-
- Non-browser clients send no `Origin` and are unaffected
|
|
142
|
-
|
|
177
|
+
- Non-browser clients send no `Origin` and are unaffected by *that* check — they need the
|
|
178
|
+
token instead.
|
|
143
179
|
- `--allow-origin <origin>` adds one, for a front end you serve yourself. `npm run dev`
|
|
144
180
|
sets it for the Vite server on :5173.
|
|
145
|
-
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
is why a token is required rather than recommended off loopback.
|
|
181
|
+
- The token is compared in constant time. Off loopback the origin check cannot cover for
|
|
182
|
+
it: the hostname is then your own and unguessable to the daemon, so `Host` goes unpinned
|
|
183
|
+
and a rebound name matches it.
|
|
149
184
|
- The directory picker (`/api/fs`) browses your home directory and the roots of projects
|
|
150
185
|
you have already created. `--fs-root <path>` adds another — useful if your projects
|
|
151
186
|
live somewhere like `D:\work`. Paths are resolved through symlinks before the check, so
|
|
152
187
|
a link inside a root is not a way back out of it.
|
|
153
188
|
|
|
189
|
+
What this does **not** protect against: the browser window the daemon opens is launched
|
|
190
|
+
with the token on its command line, so on a shared machine another user who can read
|
|
191
|
+
`/proc/<pid>/cmdline` can read it there. The same is true of `--token` on your own command
|
|
192
|
+
line. If that matters, start with `--no-open` and open the printed link by hand.
|
|
193
|
+
|
|
154
194
|
## Install it as an app
|
|
155
195
|
|
|
156
196
|
tring is a progressive web app. Once it is open in a browser, install it and it gets its
|
|
@@ -160,9 +200,10 @@ own icon and window with no address bar:
|
|
|
160
200
|
- **iPhone and iPad (Safari):** the share button, then *Add to Home Screen*.
|
|
161
201
|
- **Desktop (Chrome, Edge):** the install icon at the right of the address bar.
|
|
162
202
|
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
203
|
+
Open it once with `?token=<secret>` on the URL before installing — the window the daemon
|
|
204
|
+
opens for you already carries it, and `~/.config/tring/token` holds it otherwise. The
|
|
205
|
+
token is remembered in the browser, so the installed app starts without it. Opening a link
|
|
206
|
+
with a new token replaces the remembered one.
|
|
166
207
|
|
|
167
208
|
## Projects
|
|
168
209
|
|
|
@@ -361,7 +402,7 @@ instant Claude ends its turn instead of after the idle timeout:
|
|
|
361
402
|
"hooks": {
|
|
362
403
|
"Stop": [
|
|
363
404
|
{ "hooks": [ { "type": "command",
|
|
364
|
-
"command": "curl -s -X POST \"$TRING_URL/api/sessions/$TRING_SESSION_ID/done\"" } ] }
|
|
405
|
+
"command": "curl -s -X POST -H \"Authorization: Bearer $TRING_TOKEN\" \"$TRING_URL/api/sessions/$TRING_SESSION_ID/done\"" } ] }
|
|
365
406
|
]
|
|
366
407
|
}
|
|
367
408
|
}
|
|
@@ -370,14 +411,18 @@ instant Claude ends its turn instead of after the idle timeout:
|
|
|
370
411
|
In a PowerShell session the same hook is:
|
|
371
412
|
|
|
372
413
|
```powershell
|
|
373
|
-
curl.exe -s -X POST "$env:TRING_URL/api/sessions/$env:TRING_SESSION_ID/done"
|
|
414
|
+
curl.exe -s -X POST -H "Authorization: Bearer $env:TRING_TOKEN" "$env:TRING_URL/api/sessions/$env:TRING_SESSION_ID/done"
|
|
374
415
|
```
|
|
375
416
|
|
|
376
417
|
`curl.exe` rather than `curl`, which PowerShell aliases to `Invoke-WebRequest`.
|
|
377
418
|
|
|
378
|
-
`TRING_URL`, `TRING_SESSION_ID`, `TRING_SLOT` and `TRING_PROJECT` are set
|
|
379
|
-
session's environment. Session ids are globally unique, so this one snippet is
|
|
380
|
-
in every session of every project and does not change as projects come and go.
|
|
419
|
+
`TRING_URL`, `TRING_TOKEN`, `TRING_SESSION_ID`, `TRING_SLOT` and `TRING_PROJECT` are set
|
|
420
|
+
in every session's environment. Session ids are globally unique, so this one snippet is
|
|
421
|
+
correct in every session of every project and does not change as projects come and go.
|
|
422
|
+
|
|
423
|
+
The `Authorization` header is what changed when the daemon started requiring a token by
|
|
424
|
+
default. A hook written against an older tring still runs, but the request now comes back
|
|
425
|
+
`401` and the tile waits for the idle timeout instead of turning green immediately.
|
|
381
426
|
|
|
382
427
|
## Stack
|
|
383
428
|
|
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
|
|
|
@@ -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
|
|
@@ -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
|
}
|
|
@@ -733,8 +992,8 @@ var ProjectManager = class _ProjectManager {
|
|
|
733
992
|
// src/http.ts
|
|
734
993
|
import { createReadStream } from "node:fs";
|
|
735
994
|
import { readdir as readdir2, realpath, stat as stat2 } from "node:fs/promises";
|
|
736
|
-
import
|
|
737
|
-
import
|
|
995
|
+
import os4 from "node:os";
|
|
996
|
+
import path5 from "node:path";
|
|
738
997
|
|
|
739
998
|
// src/security.ts
|
|
740
999
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
@@ -808,9 +1067,9 @@ var SECURITY_HEADERS = Object.freeze({
|
|
|
808
1067
|
|
|
809
1068
|
// src/usage.ts
|
|
810
1069
|
import { spawn as spawn2 } from "node:child_process";
|
|
811
|
-
import { readdir, readFile as
|
|
812
|
-
import
|
|
813
|
-
import
|
|
1070
|
+
import { readdir, readFile as readFile3, stat } from "node:fs/promises";
|
|
1071
|
+
import os3 from "node:os";
|
|
1072
|
+
import path4 from "node:path";
|
|
814
1073
|
var WINDOW_MS = 5 * 36e5;
|
|
815
1074
|
var WEEK_MS = 7 * 24 * 36e5;
|
|
816
1075
|
var PRICES = [
|
|
@@ -822,8 +1081,8 @@ var PRICES = [
|
|
|
822
1081
|
["claude-haiku-", 1, 5]
|
|
823
1082
|
];
|
|
824
1083
|
function defaultTranscriptDir() {
|
|
825
|
-
const base2 = process.env["CLAUDE_CONFIG_DIR"] ??
|
|
826
|
-
return
|
|
1084
|
+
const base2 = process.env["CLAUDE_CONFIG_DIR"] ?? path4.join(os3.homedir(), ".claude");
|
|
1085
|
+
return path4.join(base2, "projects");
|
|
827
1086
|
}
|
|
828
1087
|
var empty = () => ({ tokens: 0, cacheReadTokens: 0, cost: 0, messages: 0 });
|
|
829
1088
|
function add(b, e) {
|
|
@@ -843,7 +1102,7 @@ async function scanUsage(dir, now) {
|
|
|
843
1102
|
for (const file of await transcripts(dir, weekAgo)) {
|
|
844
1103
|
let text2;
|
|
845
1104
|
try {
|
|
846
|
-
text2 = await
|
|
1105
|
+
text2 = await readFile3(file, "utf8");
|
|
847
1106
|
} catch {
|
|
848
1107
|
continue;
|
|
849
1108
|
}
|
|
@@ -931,7 +1190,7 @@ async function transcripts(dir, since) {
|
|
|
931
1190
|
const out = [];
|
|
932
1191
|
for (const name of names) {
|
|
933
1192
|
if (!name.endsWith(".jsonl")) continue;
|
|
934
|
-
const file =
|
|
1193
|
+
const file = path4.join(dir, name);
|
|
935
1194
|
try {
|
|
936
1195
|
if ((await stat(file)).mtimeMs >= since) out.push(file);
|
|
937
1196
|
} catch {
|
|
@@ -1046,16 +1305,16 @@ function createHandler(opts) {
|
|
|
1046
1305
|
const { pm, webRoot, token } = opts;
|
|
1047
1306
|
const sameOrigin = opts.sameOrigin ?? createOriginCheck();
|
|
1048
1307
|
let usage = null;
|
|
1049
|
-
const homeDir = () => process.env["HOME"] ??
|
|
1308
|
+
const homeDir = () => process.env["HOME"] ?? os4.homedir();
|
|
1050
1309
|
const within = (root, dir) => {
|
|
1051
|
-
const rel =
|
|
1052
|
-
return rel === "" || !rel.startsWith("..") && !
|
|
1310
|
+
const rel = path5.relative(path5.resolve(root), dir);
|
|
1311
|
+
return rel === "" || !rel.startsWith("..") && !path5.isAbsolute(rel);
|
|
1053
1312
|
};
|
|
1054
1313
|
const real = async (p) => {
|
|
1055
1314
|
try {
|
|
1056
1315
|
return await realpath(p);
|
|
1057
1316
|
} catch {
|
|
1058
|
-
return
|
|
1317
|
+
return path5.resolve(p);
|
|
1059
1318
|
}
|
|
1060
1319
|
};
|
|
1061
1320
|
const browsable = async (dir) => {
|
|
@@ -1099,12 +1358,12 @@ function createHandler(opts) {
|
|
|
1099
1358
|
}
|
|
1100
1359
|
if (url.pathname === "/api/fs" && req.method === "GET") {
|
|
1101
1360
|
const raw = url.searchParams.get("path")?.trim();
|
|
1102
|
-
const dir = raw ?
|
|
1361
|
+
const dir = raw ? path5.resolve(raw) : homeDir();
|
|
1103
1362
|
if (!await browsable(dir)) return json(res, 403, { error: "outside the browsable roots" });
|
|
1104
1363
|
try {
|
|
1105
1364
|
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:
|
|
1107
|
-
const parent =
|
|
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);
|
|
1108
1367
|
const up = parent !== dir && await browsable(parent) ? parent : null;
|
|
1109
1368
|
return json(res, 200, { path: dir, parent: up, entries });
|
|
1110
1369
|
} catch {
|
|
@@ -1133,15 +1392,15 @@ function createHandler(opts) {
|
|
|
1133
1392
|
}
|
|
1134
1393
|
async function serveStatic(res, pathname) {
|
|
1135
1394
|
const rel = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
|
|
1136
|
-
const file =
|
|
1137
|
-
if (file !== webRoot && !file.startsWith(webRoot +
|
|
1395
|
+
const file = path5.resolve(webRoot, rel);
|
|
1396
|
+
if (file !== webRoot && !file.startsWith(webRoot + path5.sep)) {
|
|
1138
1397
|
text(res, 403, "forbidden");
|
|
1139
1398
|
return;
|
|
1140
1399
|
}
|
|
1141
1400
|
try {
|
|
1142
1401
|
const info = await stat2(file);
|
|
1143
1402
|
if (!info.isFile()) throw new Error("not a file");
|
|
1144
|
-
head(res, 200, MIME[
|
|
1403
|
+
head(res, 200, MIME[path5.extname(file)] ?? "application/octet-stream");
|
|
1145
1404
|
createReadStream(file).pipe(res);
|
|
1146
1405
|
} catch {
|
|
1147
1406
|
if (rel === "index.html") {
|
|
@@ -1356,12 +1615,12 @@ var Hub = class {
|
|
|
1356
1615
|
|
|
1357
1616
|
// src/open-window.ts
|
|
1358
1617
|
import { spawn as spawn3 } from "node:child_process";
|
|
1359
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
1360
|
-
import
|
|
1618
|
+
import { existsSync, readFileSync as readFileSync2 } from "node:fs";
|
|
1619
|
+
import os5 from "node:os";
|
|
1361
1620
|
function isWsl() {
|
|
1362
1621
|
if (process.env["WSL_DISTRO_NAME"]) return true;
|
|
1363
1622
|
try {
|
|
1364
|
-
return /microsoft/i.test(
|
|
1623
|
+
return /microsoft/i.test(readFileSync2("/proc/version", "utf8"));
|
|
1365
1624
|
} catch {
|
|
1366
1625
|
return false;
|
|
1367
1626
|
}
|
|
@@ -1429,173 +1688,57 @@ function openWindow(url) {
|
|
|
1429
1688
|
}
|
|
1430
1689
|
}
|
|
1431
1690
|
function describeFallback(url) {
|
|
1432
|
-
return isWsl() ||
|
|
1433
|
-
}
|
|
1434
|
-
|
|
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() {
|
|
1441
|
-
try {
|
|
1442
|
-
return require3("../package.json").version;
|
|
1443
|
-
} 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;
|
|
1456
|
-
}
|
|
1457
|
-
return false;
|
|
1458
|
-
}
|
|
1459
|
-
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
1460
|
-
async function checkForUpdate(cachePath) {
|
|
1461
|
-
const current = currentVersion();
|
|
1462
|
-
let cache = null;
|
|
1463
|
-
try {
|
|
1464
|
-
cache = JSON.parse(await readFile3(cachePath, "utf8"));
|
|
1465
|
-
} catch {
|
|
1466
|
-
cache = null;
|
|
1467
|
-
}
|
|
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;
|
|
1481
|
-
}
|
|
1482
|
-
try {
|
|
1483
|
-
await mkdir2(path4.dirname(cachePath), { recursive: true });
|
|
1484
|
-
await writeFile2(cachePath, JSON.stringify({ checkedAt: Date.now(), latest }), "utf8");
|
|
1485
|
-
} catch {
|
|
1486
|
-
}
|
|
1487
|
-
return isNewer(latest, current) ? latest : null;
|
|
1691
|
+
return isWsl() || os5.platform() === "linux" ? `open ${url} in your browser` : `open ${url}`;
|
|
1488
1692
|
}
|
|
1489
1693
|
|
|
1490
1694
|
// src/index.ts
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
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);
|
|
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 };
|
|
1699
|
+
}
|
|
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}`);
|
|
1574
1706
|
}
|
|
1575
|
-
}
|
|
1576
|
-
return
|
|
1707
|
+
};
|
|
1708
|
+
return { cert: read(certFile, "certificate"), key: read(keyFile, "key") };
|
|
1577
1709
|
}
|
|
1578
1710
|
async function main() {
|
|
1579
1711
|
const args = parseArgs(process.argv.slice(2));
|
|
1580
|
-
|
|
1581
|
-
|
|
1712
|
+
let auth;
|
|
1713
|
+
try {
|
|
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.
|
|
1582
1723
|
|
|
1583
1724
|
The daemon spawns shells, so off localhost the token is the only thing
|
|
1584
1725
|
between the port and a shell on this machine.
|
|
1585
1726
|
|
|
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);
|
|
1727
|
+
tring --host ${args.host} --token "$(openssl rand -hex 32)"`);
|
|
1590
1728
|
}
|
|
1591
|
-
const
|
|
1592
|
-
const
|
|
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));
|
|
1593
1733
|
const webRoot = [
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
].find((p) => existsSync2(p)) ??
|
|
1734
|
+
path6.resolve(here, "web"),
|
|
1735
|
+
path6.resolve(here, "../../web/dist")
|
|
1736
|
+
].find((p) => existsSync2(p)) ?? path6.resolve(here, "web");
|
|
1597
1737
|
const pm = await ProjectManager.open({
|
|
1598
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,
|
|
1599
1742
|
scrollback: args.scrollback,
|
|
1600
1743
|
idleMs: args.idleMs,
|
|
1601
1744
|
...args.shell ? { shell: args.shell } : {}
|
|
@@ -1604,33 +1747,41 @@ async function main() {
|
|
|
1604
1747
|
const handle = createHandler({
|
|
1605
1748
|
pm,
|
|
1606
1749
|
webRoot,
|
|
1607
|
-
token
|
|
1750
|
+
token,
|
|
1608
1751
|
sameOrigin,
|
|
1609
1752
|
fsRoots: args.fsRoot
|
|
1610
1753
|
});
|
|
1611
|
-
const
|
|
1754
|
+
const listener = (req, res) => {
|
|
1612
1755
|
void handle(req, res).catch(() => {
|
|
1613
1756
|
if (!res.headersSent) res.writeHead(500, SECURITY_HEADERS).end("internal error");
|
|
1614
1757
|
});
|
|
1615
|
-
}
|
|
1758
|
+
};
|
|
1759
|
+
const server = tls ? createSecureServer(tls, listener) : createServer(listener);
|
|
1616
1760
|
const wss = new WebSocketServer({ server, verifyClient: upgradeGuard(sameOrigin) });
|
|
1617
|
-
const hub = new Hub({ pm, token
|
|
1761
|
+
const hub = new Hub({ pm, token });
|
|
1618
1762
|
hub.attach(wss);
|
|
1763
|
+
const authUrl = token ? `${url}/?token=${encodeURIComponent(token)}` : url;
|
|
1619
1764
|
server.listen(args.port, args.host, () => {
|
|
1620
1765
|
console.log(`tring listening on ${url}`);
|
|
1621
|
-
if (
|
|
1622
|
-
|
|
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.`);
|
|
1623
1772
|
}
|
|
1624
1773
|
if (args.updateCheck) {
|
|
1625
|
-
void checkForUpdate(
|
|
1774
|
+
void checkForUpdate(path6.join(path6.dirname(pm.statePath), "update-check.json")).then((latest) => {
|
|
1626
1775
|
if (!latest) return;
|
|
1627
1776
|
hub.setUpdate({ current: currentVersion(), latest });
|
|
1628
1777
|
console.log(`update available: ${currentVersion()} -> ${latest} (npm i -g tring-chat)`);
|
|
1629
1778
|
});
|
|
1630
1779
|
}
|
|
1631
1780
|
if (args.open) {
|
|
1632
|
-
const opened = openWindow(
|
|
1633
|
-
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}`);
|
|
1634
1785
|
}
|
|
1635
1786
|
});
|
|
1636
1787
|
const shutdown = async () => {
|
|
@@ -1642,4 +1793,10 @@ async function main() {
|
|
|
1642
1793
|
process.on("SIGINT", () => void shutdown());
|
|
1643
1794
|
process.on("SIGTERM", () => void shutdown());
|
|
1644
1795
|
}
|
|
1645
|
-
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
|
+
});
|