@bom0792/herdgate 0.9.18 → 0.9.20
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/package.json +1 -1
- package/plugin/server/common.mjs +27 -0
- package/plugin/server/index.mjs +36 -2
- package/src/cloud/gateway.ts +43 -2
- package/src/cloud/stores.ts +10 -0
- package/src/host/herdr.ts +66 -0
- package/src/web/app.css +19 -0
- package/src/web/app.js +265 -2
- package/src/web/herdgate-host.zip +0 -0
- package/src/web/sw.js +1 -1
package/package.json
CHANGED
package/plugin/server/common.mjs
CHANGED
|
@@ -64,6 +64,33 @@ export async function herdrSnapshot(bin, timeoutMs = 8_000) {
|
|
|
64
64
|
return parsed?.result?.snapshot ?? parsed?.snapshot ?? parsed;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
/** Live panes — the PWA's terminal picker. One row per pane, grouped by workspace there. */
|
|
68
|
+
export async function herdrPanes(bin, timeoutMs = 8_000) {
|
|
69
|
+
const { stdout } = await run(bin, ["pane", "list"], { timeout: timeoutMs, maxBuffer: 8 << 20 });
|
|
70
|
+
const parsed = JSON.parse(stdout);
|
|
71
|
+
const panes = parsed?.result?.panes ?? parsed?.panes ?? [];
|
|
72
|
+
return panes
|
|
73
|
+
.filter((p) => p && typeof p.pane_id === "string")
|
|
74
|
+
.map((p) => ({
|
|
75
|
+
id: p.pane_id,
|
|
76
|
+
workspace: typeof p.workspace_id === "string" ? p.workspace_id : "",
|
|
77
|
+
agent: typeof p.agent === "string" ? p.agent : null,
|
|
78
|
+
status: typeof p.agent_status === "string" ? p.agent_status : "unknown",
|
|
79
|
+
cwd: typeof p.cwd === "string" ? p.cwd : "",
|
|
80
|
+
title: typeof p.terminal_title_stripped === "string" ? p.terminal_title_stripped : typeof p.terminal_title === "string" ? p.terminal_title : "",
|
|
81
|
+
}));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** One pane's screen as ANSI text — the PWA renders the colors itself. */
|
|
85
|
+
export async function herdrRead(bin, target, lines = 40, timeoutMs = 8_000) {
|
|
86
|
+
const { stdout } = await run(
|
|
87
|
+
bin,
|
|
88
|
+
["agent", "read", String(target), "--source", "visible", "--lines", String(lines), "--format", "ansi"],
|
|
89
|
+
{ timeout: timeoutMs, maxBuffer: 8 << 20 },
|
|
90
|
+
);
|
|
91
|
+
return stdout;
|
|
92
|
+
}
|
|
93
|
+
|
|
67
94
|
export function summarize(snap) {
|
|
68
95
|
const ws = Array.isArray(snap?.workspaces) ? snap.workspaces : [];
|
|
69
96
|
const agents = Array.isArray(snap?.agents) ? snap.agents : [];
|
package/plugin/server/index.mjs
CHANGED
|
@@ -10,7 +10,7 @@ import { spawn } from "node:child_process";
|
|
|
10
10
|
import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync } from "node:fs";
|
|
11
11
|
import { join, dirname } from "node:path";
|
|
12
12
|
import { hostname, homedir } from "node:os";
|
|
13
|
-
import { dirs, readConfig, writeConfig, readState, writeState, herdrSnapshot, summarize } from "./common.mjs";
|
|
13
|
+
import { dirs, readConfig, writeConfig, readState, writeState, herdrSnapshot, summarize, herdrPanes, herdrRead } from "./common.mjs";
|
|
14
14
|
import { createSshBridge } from "./ssh.mjs";
|
|
15
15
|
import { HostChannel, b64d, b64e, fingerprint, generateKeyPair } from "./e2e.mjs";
|
|
16
16
|
|
|
@@ -198,7 +198,9 @@ async function publisherLoop() {
|
|
|
198
198
|
}
|
|
199
199
|
return e2eSelf;
|
|
200
200
|
};
|
|
201
|
-
const e2eSessions = new Map();
|
|
201
|
+
const e2eSessions = new Map();
|
|
202
|
+
/** Per-device last-call times for the subprocess-backed term.* ops (1/s each). */
|
|
203
|
+
const termThrottle = new Map();
|
|
202
204
|
/** null = not an e2e payload; {reply} = handshake answer to send; {inner} = decrypted device payload. */
|
|
203
205
|
const e2eOnDevice = async (device, payload) => {
|
|
204
206
|
if (payload && typeof payload === "object" && typeof payload.op === "string" && payload.op.startsWith("e2e")) log(`e2e: op ${payload.op} from ${device}`);
|
|
@@ -333,6 +335,38 @@ async function publisherLoop() {
|
|
|
333
335
|
lastSig = "";
|
|
334
336
|
return void publish(ws);
|
|
335
337
|
}
|
|
338
|
+
// Live terminal access, read-only: the panes list and one pane's ANSI screen.
|
|
339
|
+
// Subprocess-backed, so both ops are throttled per device (a phone's poll must
|
|
340
|
+
// not fork `herdr` in a tight loop) and the target string is whitelisted hard.
|
|
341
|
+
if (op === "term.list") {
|
|
342
|
+
const now = Date.now();
|
|
343
|
+
const last = termThrottle.get(`list:${m.device}`) ?? 0;
|
|
344
|
+
if (now - last < 1_000) return void replyTo({ op: "error", code: "busy", message: "term.list is throttled (1/s)" });
|
|
345
|
+
termThrottle.set(`list:${m.device}`, now);
|
|
346
|
+
try {
|
|
347
|
+
const panes = await herdrPanes(D.herdrBin);
|
|
348
|
+
return void replyTo({ op: "term.list", panes });
|
|
349
|
+
} catch (e) {
|
|
350
|
+
return void replyTo({ op: "error", code: "herdr", message: `pane list failed: ${e instanceof Error ? e.message : String(e)}` });
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
if (op === "term.read") {
|
|
354
|
+
const target = typeof payload.target === "string" ? payload.target : "";
|
|
355
|
+
const lines = Math.max(10, Math.min(120, Number(payload.lines) || 40));
|
|
356
|
+
if (!/^[A-Za-z0-9_:.-]{1,64}$/.test(target)) {
|
|
357
|
+
return void replyTo({ op: "error", code: "bad-target", message: "term.read needs a pane id" });
|
|
358
|
+
}
|
|
359
|
+
const now = Date.now();
|
|
360
|
+
const last = termThrottle.get(`read:${m.device}`) ?? 0;
|
|
361
|
+
if (now - last < 1_000) return void replyTo({ op: "error", code: "busy", message: "term.read is throttled (1/s)" });
|
|
362
|
+
termThrottle.set(`read:${m.device}`, now);
|
|
363
|
+
try {
|
|
364
|
+
const ansi = await herdrRead(D.herdrBin, target, lines);
|
|
365
|
+
return void replyTo({ op: "term.read", target, ansi });
|
|
366
|
+
} catch (e) {
|
|
367
|
+
return void replyTo({ op: "error", code: "herdr", message: `read failed: ${e instanceof Error ? e.message : String(e)}` });
|
|
368
|
+
}
|
|
369
|
+
}
|
|
336
370
|
return void replyTo({ op: "error", code: "read-only", message: `dev.herdgate.host has no op ${String(op)}` });
|
|
337
371
|
}
|
|
338
372
|
if (m.t === "pair.request") {
|
package/src/cloud/gateway.ts
CHANGED
|
@@ -576,11 +576,11 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
|
|
|
576
576
|
});
|
|
577
577
|
ws.on("error", () => { /* onclose follows */ });
|
|
578
578
|
sock.on("tobytes", (chunk: Buffer) => {
|
|
579
|
-
if (ws.readyState ===
|
|
579
|
+
if (ws.readyState === 1) ws.send(chunk); // 1 = OPEN, instance-safe
|
|
580
580
|
});
|
|
581
581
|
sock.on("close", () => {
|
|
582
582
|
bye();
|
|
583
|
-
if (ws.readyState ===
|
|
583
|
+
if (ws.readyState === 1) {
|
|
584
584
|
try { ws.close(1000); } catch { /* undici: some codes throw */ }
|
|
585
585
|
}
|
|
586
586
|
});
|
|
@@ -880,6 +880,47 @@ export function startCloud(cfg: CloudConfig): Promise<Cloud> {
|
|
|
880
880
|
});
|
|
881
881
|
}
|
|
882
882
|
|
|
883
|
+
// The owner's device roster (per room) and un-pairing. Account-token auth —
|
|
884
|
+
// the same identity that approved the machine.
|
|
885
|
+
if (path === "/v1/devices") {
|
|
886
|
+
if (blocked(ipOf(req))) return json(res, 429, { error: "rate limited" });
|
|
887
|
+
if (req.method !== "GET") return json(res, 405, { error: "method not allowed" });
|
|
888
|
+
const account = accountByAuth(req);
|
|
889
|
+
if (!account) return json(res, 401, { error: "account token required" });
|
|
890
|
+
const q = new URL(req.url ?? "/", "http://x").searchParams;
|
|
891
|
+
const room = state.rooms.find((r) => r.id === (q.get("room") ?? ""));
|
|
892
|
+
if (!room || room.accountId !== account.id) return json(res, 403, { error: "not one of this account's rooms" });
|
|
893
|
+
const live = new Set<string>();
|
|
894
|
+
for (const c of deviceConns) if (c.device) live.add(c.device.id);
|
|
895
|
+
return json(res, 200, {
|
|
896
|
+
devices: state.devices
|
|
897
|
+
.filter((d) => d.roomId === room.id)
|
|
898
|
+
.map((d) => ({ id: d.id, name: d.name, scope: d.scope, connected: live.has(d.id), keys: (d.sshKeys ?? []).length, created: d.created })),
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
if (path === "/v1/device/revoke") {
|
|
902
|
+
if (blocked(ipOf(req))) return json(res, 429, { error: "rate limited" });
|
|
903
|
+
if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
|
|
904
|
+
const account = accountByAuth(req);
|
|
905
|
+
if (!account) return json(res, 401, { error: "account token required" });
|
|
906
|
+
return void readJsonBody(req).then((body) => {
|
|
907
|
+
const deviceId = typeof body?.device === "string" ? body.device : "";
|
|
908
|
+
const device = deviceId ? state.deviceById(deviceId) : null;
|
|
909
|
+
if (!device || device.accountId !== account.id) return json(res, 404, { error: "no such device" });
|
|
910
|
+
const gone = state.removeDevice(device.id);
|
|
911
|
+
if (!gone) return json(res, 404, { error: "no such device" });
|
|
912
|
+
for (const c of deviceConns) {
|
|
913
|
+
if (c.device?.id === device.id) {
|
|
914
|
+
deviceConns.delete(c);
|
|
915
|
+
try { c.ws.close(4001, "revoked"); } catch { /* already gone */ }
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
pushRoomUpdate(device.roomId);
|
|
919
|
+
log(`device ${device.id} (${device.name}) revoked by ${account.name}`);
|
|
920
|
+
return json(res, 200, { ok: true });
|
|
921
|
+
});
|
|
922
|
+
}
|
|
923
|
+
|
|
883
924
|
// Device SSH public keys: register the key of the machine that will `hc machine
|
|
884
925
|
// add` this device, so system ssh logs in without a password prompt. Same two
|
|
885
926
|
// identities as /v1/device/push (the device's own secret, or the owner's token).
|
package/src/cloud/stores.ts
CHANGED
|
@@ -157,6 +157,16 @@ export class State {
|
|
|
157
157
|
return true;
|
|
158
158
|
}
|
|
159
159
|
|
|
160
|
+
/** Un-pair: the owner revoked a device. Its secret dies with it (hash gone),
|
|
161
|
+
* its websocket is kicked by the gateway, its push subscription with it. */
|
|
162
|
+
removeDevice(id: string): DeviceRecord | null {
|
|
163
|
+
const i = this.devices.findIndex((d) => d.id === id);
|
|
164
|
+
if (i < 0) return null;
|
|
165
|
+
const [gone] = this.devices.splice(i, 1);
|
|
166
|
+
this.#save();
|
|
167
|
+
return gone;
|
|
168
|
+
}
|
|
169
|
+
|
|
160
170
|
accountById(id: string): Account | null {
|
|
161
171
|
return this.accounts.find((a) => a.id === id) ?? null;
|
|
162
172
|
}
|
package/src/host/herdr.ts
CHANGED
|
@@ -155,6 +155,46 @@ export async function readHerdrView(o: HerdrReadOptions = {}): Promise<HerdrView
|
|
|
155
155
|
return mapSnapshot(parsed);
|
|
156
156
|
}
|
|
157
157
|
|
|
158
|
+
export interface HerdrPane {
|
|
159
|
+
id: string;
|
|
160
|
+
workspace: string;
|
|
161
|
+
agent: string | null;
|
|
162
|
+
status: string;
|
|
163
|
+
cwd: string;
|
|
164
|
+
title: string;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Live panes (`herdr pane list`), mapped for the term.list op. */
|
|
168
|
+
export async function readHerdrPanes(o: HerdrReadOptions = {}): Promise<HerdrPane[]> {
|
|
169
|
+
const bin = o.bin ?? process.env.HERDGATE_HERDR_BIN ?? "herdr";
|
|
170
|
+
const { stdout } = await run(bin, ["pane", "list"], { timeout: o.timeoutMs ?? 5_000, maxBuffer: MAX_SNAPSHOT_BYTES, env: o.env ?? process.env });
|
|
171
|
+
const parsed = JSON.parse(stdout) as { result?: { panes?: unknown[] }; panes?: unknown[] };
|
|
172
|
+
const panes = parsed?.result?.panes ?? parsed?.panes ?? [];
|
|
173
|
+
return panes
|
|
174
|
+
.filter((p): p is Record<string, unknown> => Boolean(p) && typeof (p as Record<string, unknown>).pane_id === "string")
|
|
175
|
+
.map((p) => ({
|
|
176
|
+
id: String(p.pane_id),
|
|
177
|
+
workspace: typeof p.workspace_id === "string" ? p.workspace_id : "",
|
|
178
|
+
agent: typeof p.agent === "string" ? p.agent : null,
|
|
179
|
+
status: typeof p.agent_status === "string" ? p.agent_status : "unknown",
|
|
180
|
+
cwd: typeof p.cwd === "string" ? p.cwd : "",
|
|
181
|
+
title: typeof p.terminal_title_stripped === "string" ? p.terminal_title_stripped : typeof p.terminal_title === "string" ? p.terminal_title : "",
|
|
182
|
+
}));
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** One pane's visible screen as ANSI (`herdr agent read --format ansi`). */
|
|
186
|
+
export async function readHerdrTerm(target: string, lines = 40, o: HerdrReadOptions = {}): Promise<string> {
|
|
187
|
+
const bin = o.bin ?? process.env.HERDGATE_HERDR_BIN ?? "herdr";
|
|
188
|
+
if (!/^[A-Za-z0-9_:.-]{1,64}$/.test(target)) throw new Error("bad pane id");
|
|
189
|
+
const n = Math.max(10, Math.min(120, Math.trunc(lines) || 40));
|
|
190
|
+
const { stdout } = await run(bin, ["agent", "read", target, "--source", "visible", "--lines", String(n), "--format", "ansi"], {
|
|
191
|
+
timeout: o.timeoutMs ?? 5_000,
|
|
192
|
+
maxBuffer: MAX_SNAPSHOT_BYTES,
|
|
193
|
+
env: o.env ?? process.env,
|
|
194
|
+
});
|
|
195
|
+
return stdout;
|
|
196
|
+
}
|
|
197
|
+
|
|
158
198
|
/** What the host can push/drive; the agent supplies it (see `HerdrAdapter.attach`). */
|
|
159
199
|
export interface HostLink {
|
|
160
200
|
send(device: string, payload: unknown): void;
|
|
@@ -191,6 +231,8 @@ export class HerdrAdapter implements AgentAdapter {
|
|
|
191
231
|
readonly #log: (line: string) => void;
|
|
192
232
|
#link: HostLink | null = null;
|
|
193
233
|
#view: HerdrView | null = null;
|
|
234
|
+
/** Per-device last-call times for the subprocess-backed term.* ops (1/s each). */
|
|
235
|
+
#termThrottle = new Map<string, number>();
|
|
194
236
|
#sig = "";
|
|
195
237
|
#lastError: string | null = null;
|
|
196
238
|
#timer: NodeJS.Timeout | null = null;
|
|
@@ -257,6 +299,30 @@ export class HerdrAdapter implements AgentAdapter {
|
|
|
257
299
|
}
|
|
258
300
|
case "ping":
|
|
259
301
|
return link.send(device, { op: "pong", n: (payload as { n?: unknown }).n ?? null, at: (this.#o.now?.() ?? new Date()).toISOString() });
|
|
302
|
+
case "term.list": {
|
|
303
|
+
// Subprocess-backed: throttle per device so a poll loop cannot fork herdr hot.
|
|
304
|
+
const now = this.#o.now?.() ?? new Date();
|
|
305
|
+
const last = this.#termThrottle.get(`list:${device}`) ?? 0;
|
|
306
|
+
if (now.getTime() - last < 1_000) return link.send(device, { op: "error", code: "busy", message: "term.list is throttled (1/s)" });
|
|
307
|
+
this.#termThrottle.set(`list:${device}`, now.getTime());
|
|
308
|
+
readHerdrPanes()
|
|
309
|
+
.then((panes) => link.send(device, { op: "term.list", panes }))
|
|
310
|
+
.catch((e: unknown) => link.send(device, { op: "error", code: "herdr", message: `pane list failed: ${e instanceof Error ? e.message : String(e)}` }));
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
case "term.read": {
|
|
314
|
+
const target = typeof (payload as { target?: unknown }).target === "string" ? (payload as { target: string }).target : "";
|
|
315
|
+
if (!/^[A-Za-z0-9_:.-]{1,64}$/.test(target)) return link.send(device, { op: "error", code: "bad-target", message: "term.read needs a pane id" });
|
|
316
|
+
const lines = Math.max(10, Math.min(120, Number((payload as { lines?: unknown }).lines) || 40));
|
|
317
|
+
const nowT = this.#o.now?.() ?? new Date();
|
|
318
|
+
const lastT = this.#termThrottle.get(`read:${device}`) ?? 0;
|
|
319
|
+
if (nowT.getTime() - lastT < 1_000) return link.send(device, { op: "error", code: "busy", message: "term.read is throttled (1/s)" });
|
|
320
|
+
this.#termThrottle.set(`read:${device}`, nowT.getTime());
|
|
321
|
+
readHerdrTerm(target, lines)
|
|
322
|
+
.then((ansi) => link.send(device, { op: "term.read", target, ansi }))
|
|
323
|
+
.catch((e: unknown) => link.send(device, { op: "error", code: "herdr", message: `read failed: ${e instanceof Error ? e.message : String(e)}` }));
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
260
326
|
default:
|
|
261
327
|
// The read-only invariant lives HERE: the cloud cannot inspect payloads, so the
|
|
262
328
|
// host is the last trusted decision point for "this device may not do that".
|
package/src/web/app.css
CHANGED
|
@@ -310,3 +310,22 @@ dialog::backdrop {
|
|
|
310
310
|
border-radius: 6px;
|
|
311
311
|
}
|
|
312
312
|
.sshkeys .keyrow { margin-top: 8px; }
|
|
313
|
+
|
|
314
|
+
/* Live terminals (read-only) */
|
|
315
|
+
.termbody { display: flex; flex-direction: column; gap: 8px; }
|
|
316
|
+
.termlist .termname { text-align: left; }
|
|
317
|
+
.termrow { padding: 2px 0; }
|
|
318
|
+
.termbar { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
|
|
319
|
+
.termscreen {
|
|
320
|
+
max-height: 60vh;
|
|
321
|
+
overflow: auto;
|
|
322
|
+
background: #14161a; /* a terminal is dark: keep it dark in light mode too */
|
|
323
|
+
color: #cfd3da;
|
|
324
|
+
border: 1px solid #2a2d33;
|
|
325
|
+
border-radius: 8px;
|
|
326
|
+
padding: 10px 12px;
|
|
327
|
+
font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
328
|
+
white-space: pre-wrap;
|
|
329
|
+
word-break: break-word;
|
|
330
|
+
margin: 0;
|
|
331
|
+
}
|
package/src/web/app.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// - the token lives in localStorage on this device and is never sent anywhere but the
|
|
12
12
|
// cloud's own WS endpoint.
|
|
13
13
|
|
|
14
|
-
const BUILD = "v0.9.
|
|
14
|
+
const BUILD = "v0.9.20";
|
|
15
15
|
|
|
16
16
|
const $ = (id) => document.getElementById(id);
|
|
17
17
|
const TOKEN_KEY = "herdgate.token";
|
|
@@ -107,6 +107,12 @@ const state = {
|
|
|
107
107
|
roomId: null,
|
|
108
108
|
view: null,
|
|
109
109
|
viewError: null,
|
|
110
|
+
terms: null,
|
|
111
|
+
termTarget: null,
|
|
112
|
+
termAnsi: null,
|
|
113
|
+
termTimer: null,
|
|
114
|
+
termBody: null,
|
|
115
|
+
termPre: null,
|
|
110
116
|
retry: 0,
|
|
111
117
|
closedByUs: false,
|
|
112
118
|
};
|
|
@@ -267,6 +273,30 @@ function renderRoom() {
|
|
|
267
273
|
box.append(p);
|
|
268
274
|
}
|
|
269
275
|
|
|
276
|
+
// Live terminals (read-only): the host's own panes — pick one and watch its
|
|
277
|
+
// ANSI screen. Everything rides the same frames (E2E when paired), no new trust.
|
|
278
|
+
if (room?.online) {
|
|
279
|
+
const tblock = document.createElement("details");
|
|
280
|
+
tblock.className = "terms";
|
|
281
|
+
const ts = document.createElement("summary");
|
|
282
|
+
ts.textContent = "Live terminals — this machine's panes, read-only";
|
|
283
|
+
tblock.append(ts);
|
|
284
|
+
const tbody = document.createElement("div");
|
|
285
|
+
tbody.className = "termbody";
|
|
286
|
+
tblock.append(tbody);
|
|
287
|
+
tblock.addEventListener("toggle", () => {
|
|
288
|
+
if (tblock.open && !state.terms) send({ t: "frame", payload: { op: "term.list" } });
|
|
289
|
+
});
|
|
290
|
+
box.append(tblock);
|
|
291
|
+
state.termBody = tbody;
|
|
292
|
+
renderTerms();
|
|
293
|
+
if (state.termTarget) {
|
|
294
|
+
// The view rebuilds this node; keep the live pane ticking without a new poll.
|
|
295
|
+
paintTerm();
|
|
296
|
+
if (!state.termTimer) startTerm(state.termTarget);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
270
300
|
// The SSH leg: this device's own key dials the gate. In the Herdr phone app, add a
|
|
271
301
|
// machine with this host/port and the key shown once at pair time.
|
|
272
302
|
if (state.deviceSecret && state.deviceId) {
|
|
@@ -405,8 +435,229 @@ function renderRoom() {
|
|
|
405
435
|
loadKeys();
|
|
406
436
|
});
|
|
407
437
|
loadKeys();
|
|
408
|
-
|
|
438
|
+
details.append(keysBlock);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// The owner's roster for this machine: every paired device, its scope, live dot,
|
|
442
|
+
// public-key count — and the two things the owner always needs: pairing one more
|
|
443
|
+
// device (e.g. an `act` one) and un-pairing (revoke). Works with the account
|
|
444
|
+
// token, so it is here even when this browser itself is only a read device.
|
|
445
|
+
if (state.token && state.roomId) {
|
|
446
|
+
const block = document.createElement("details");
|
|
447
|
+
block.className = "devices";
|
|
448
|
+
const summaryEl = document.createElement("summary");
|
|
449
|
+
summaryEl.textContent = "Devices — paired phones, browsers and machines";
|
|
450
|
+
block.append(summaryEl);
|
|
451
|
+
const roster = document.createElement("div");
|
|
452
|
+
block.append(roster);
|
|
453
|
+
const pairMore = document.createElement("button");
|
|
454
|
+
pairMore.type = "button";
|
|
455
|
+
pairMore.className = "primary";
|
|
456
|
+
pairMore.textContent = "Pair another device (pick act for full control)";
|
|
457
|
+
pairMore.addEventListener("click", () => openPair(state.roomId));
|
|
458
|
+
block.append(pairMore);
|
|
459
|
+
box.append(block);
|
|
460
|
+
|
|
461
|
+
const loadDevices = async () => {
|
|
462
|
+
try {
|
|
463
|
+
const r = await fetch(`${cloudBase()}/v1/devices?room=${encodeURIComponent(state.roomId)}`, {
|
|
464
|
+
headers: { authorization: `Bearer ${state.token}` },
|
|
465
|
+
});
|
|
466
|
+
if (!r.ok) return;
|
|
467
|
+
const { devices = [] } = await r.json();
|
|
468
|
+
roster.replaceChildren();
|
|
469
|
+
for (const d of devices) {
|
|
470
|
+
const row = document.createElement("div");
|
|
471
|
+
row.className = "keyrow";
|
|
472
|
+
const pre = document.createElement("pre");
|
|
473
|
+
pre.textContent = `${d.name} · ${d.scope}${d.connected ? " · live" : ""} · ${d.keys} key(s) · ${d.id}${d.id === state.deviceId ? " (this browser)" : ""}`;
|
|
474
|
+
row.append(pre);
|
|
475
|
+
const rm = document.createElement("button");
|
|
476
|
+
rm.type = "button";
|
|
477
|
+
rm.className = "link danger";
|
|
478
|
+
rm.textContent = "revoke";
|
|
479
|
+
rm.addEventListener("click", async () => {
|
|
480
|
+
if (!confirm(`Revoke ${d.name}? Its key and access die immediately.`)) return;
|
|
481
|
+
await fetch(`${cloudBase()}/v1/device/revoke`, {
|
|
482
|
+
method: "POST",
|
|
483
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${state.token}` },
|
|
484
|
+
body: JSON.stringify({ device: d.id }),
|
|
485
|
+
});
|
|
486
|
+
if (d.id === state.deviceId) {
|
|
487
|
+
// This browser just un-paired itself: back to the machine list.
|
|
488
|
+
state.deviceId = null;
|
|
489
|
+
state.deviceSecret = null;
|
|
490
|
+
localStorage.removeItem(DEVICE_KEY);
|
|
491
|
+
localStorage.removeItem(DEVICE_SECRET_KEY);
|
|
492
|
+
}
|
|
493
|
+
loadDevices();
|
|
494
|
+
});
|
|
495
|
+
row.append(rm);
|
|
496
|
+
roster.append(row);
|
|
497
|
+
}
|
|
498
|
+
if (!devices.length) roster.append(note("none yet — pair a device below", "muted"));
|
|
499
|
+
} catch {
|
|
500
|
+
/* offline: the section stays as-is */
|
|
501
|
+
}
|
|
502
|
+
};
|
|
503
|
+
loadDevices();
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// ---- live terminals (read-only) ---------------------------------------------
|
|
508
|
+
|
|
509
|
+
function startTerm(target) {
|
|
510
|
+
stopTerm(false);
|
|
511
|
+
state.termTarget = target;
|
|
512
|
+
state.termAnsi = null;
|
|
513
|
+
send({ t: "frame", payload: { op: "term.read", target, lines: 40 } });
|
|
514
|
+
state.termTimer = setInterval(() => {
|
|
515
|
+
if (!state.termTarget || !state.roomId) return stopTerm();
|
|
516
|
+
send({ t: "frame", payload: { op: "term.read", target: state.termTarget, lines: 40 } });
|
|
517
|
+
}, 2_000);
|
|
518
|
+
renderTerms();
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function stopTerm(rerender = true) {
|
|
522
|
+
if (state.termTimer) clearInterval(state.termTimer);
|
|
523
|
+
state.termTimer = null;
|
|
524
|
+
state.termTarget = null;
|
|
525
|
+
state.termAnsi = null;
|
|
526
|
+
if (rerender) renderTerms();
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** The panes list + the live pane, inside the details' body (survives view re-renders). */
|
|
530
|
+
function renderTerms() {
|
|
531
|
+
const body = state.termBody;
|
|
532
|
+
if (!body) return;
|
|
533
|
+
body.replaceChildren();
|
|
534
|
+
if (state.termTarget) {
|
|
535
|
+
const bar = document.createElement("div");
|
|
536
|
+
bar.className = "termbar";
|
|
537
|
+
const name = document.createElement("span");
|
|
538
|
+
name.className = "muted small";
|
|
539
|
+
name.textContent = `${state.termTarget} — live, refreshes every 2s`;
|
|
540
|
+
const stop = document.createElement("button");
|
|
541
|
+
stop.type = "button";
|
|
542
|
+
stop.className = "link";
|
|
543
|
+
stop.textContent = "close";
|
|
544
|
+
stop.addEventListener("click", () => stopTerm());
|
|
545
|
+
bar.append(name, stop);
|
|
546
|
+
body.append(bar);
|
|
547
|
+
const pre = document.createElement("pre");
|
|
548
|
+
pre.className = "termscreen";
|
|
549
|
+
pre.textContent = state.termAnsi ?? "waiting for the pane…";
|
|
550
|
+
body.append(pre);
|
|
551
|
+
state.termPre = pre;
|
|
552
|
+
paintTerm();
|
|
553
|
+
return;
|
|
409
554
|
}
|
|
555
|
+
const list = document.createElement("div");
|
|
556
|
+
list.className = "termlist";
|
|
557
|
+
const btn = document.createElement("button");
|
|
558
|
+
btn.type = "button";
|
|
559
|
+
btn.className = "link";
|
|
560
|
+
btn.textContent = "refresh the pane list";
|
|
561
|
+
btn.addEventListener("click", () => send({ t: "frame", payload: { op: "term.list" } }));
|
|
562
|
+
list.append(btn);
|
|
563
|
+
const panes = state.terms ?? null;
|
|
564
|
+
if (panes === null) {
|
|
565
|
+
list.append(note("loading…", "muted"));
|
|
566
|
+
} else if (!panes.length) {
|
|
567
|
+
list.append(note("no panes — is a workspace open on the machine?", "muted"));
|
|
568
|
+
} else {
|
|
569
|
+
const labels = new Map((state.view?.workspaces ?? []).map((w) => [w.id, w.label]));
|
|
570
|
+
for (const p of panes) {
|
|
571
|
+
const row = document.createElement("div");
|
|
572
|
+
row.className = "keyrow termrow";
|
|
573
|
+
const label = document.createElement("button");
|
|
574
|
+
label.type = "button";
|
|
575
|
+
label.className = "link termname";
|
|
576
|
+
const ws = labels.get(p.workspace) || p.workspace;
|
|
577
|
+
label.textContent = `${ws} · ${p.agent ? `${p.agent} (${p.status})` : p.title || "terminal"}`;
|
|
578
|
+
label.title = `${p.cwd} — ${p.id}`;
|
|
579
|
+
label.addEventListener("click", () => startTerm(p.id));
|
|
580
|
+
row.append(label);
|
|
581
|
+
list.append(row);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
body.append(list);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
function paintTerm() {
|
|
588
|
+
const pre = state.termPre;
|
|
589
|
+
if (!pre || !state.termAnsi) return;
|
|
590
|
+
pre.replaceChildren(...ansiToNodes(state.termAnsi));
|
|
591
|
+
pre.scrollTop = pre.scrollHeight;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** SGR-only ANSI → DOM nodes: colors (palette + truecolor), bold. Cursor and other
|
|
595
|
+
* sequences are dropped — this is a reading view, not an emulator. No innerHTML:
|
|
596
|
+
* every byte from the wire becomes text nodes, never markup. */
|
|
597
|
+
function ansiToNodes(s) {
|
|
598
|
+
const pal = ["#5b5b5b", "#d54e53", "#5db542", "#e5c07b", "#61afef", "#c678dd", "#56b6c2", "#acacac", "#8a8a8a", "#ff6f6f", "#8ce07d", "#ffe08a", "#93c5fd", "#e2a2ff", "#8be9fd", "#ffffff"];
|
|
599
|
+
const out = [];
|
|
600
|
+
let fg = null;
|
|
601
|
+
let bg = null;
|
|
602
|
+
let bold = false;
|
|
603
|
+
let i = 0;
|
|
604
|
+
s = String(s).replace(/\r\n?/g, "\n");
|
|
605
|
+
const flush = (text) => {
|
|
606
|
+
if (!text) return;
|
|
607
|
+
if (fg === null && bg === null && !bold) {
|
|
608
|
+
out.push(document.createTextNode(text));
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
const span = document.createElement("span");
|
|
612
|
+
if (fg) span.style.color = bold ? `color-mix(in srgb, ${fg} 70%, white)` : fg;
|
|
613
|
+
if (bg) span.style.background = bg;
|
|
614
|
+
if (bold && !fg) span.style.fontWeight = "600";
|
|
615
|
+
span.textContent = text;
|
|
616
|
+
out.push(span);
|
|
617
|
+
};
|
|
618
|
+
while (i < s.length) {
|
|
619
|
+
if (s.charCodeAt(i) === 27) {
|
|
620
|
+
const rest = s.slice(i);
|
|
621
|
+
let m = /^\x1b\[([0-9;]*)([A-Za-z])/.exec(rest);
|
|
622
|
+
if (m) {
|
|
623
|
+
if (m[2] === "m") {
|
|
624
|
+
const parts = m[1] === "" ? [0] : m[1].split(";").map((x) => (x === "" ? 0 : Number(x)));
|
|
625
|
+
for (let k = 0; k < parts.length; k += 1) {
|
|
626
|
+
const p = parts[k];
|
|
627
|
+
if (p === 0) { fg = bg = null; bold = false; }
|
|
628
|
+
else if (p === 1) bold = true;
|
|
629
|
+
else if (p === 22) bold = false;
|
|
630
|
+
else if (p === 39) fg = null;
|
|
631
|
+
else if (p === 49) bg = null;
|
|
632
|
+
else if (p >= 30 && p <= 37) fg = pal[p - 30];
|
|
633
|
+
else if (p >= 90 && p <= 97) fg = pal[p - 90 + 8];
|
|
634
|
+
else if (p >= 40 && p <= 47) bg = pal[p - 40];
|
|
635
|
+
else if (p >= 100 && p <= 107) bg = pal[p - 100 + 8];
|
|
636
|
+
else if ((p === 38 || p === 48) && parts[k + 1] === 2) {
|
|
637
|
+
const c = `rgb(${parts[k + 2] || 0},${parts[k + 3] || 0},${parts[k + 4] || 0})`;
|
|
638
|
+
if (p === 38) fg = c; else bg = c;
|
|
639
|
+
k += 4;
|
|
640
|
+
} else if ((p === 38 || p === 48) && parts[k + 1] === 5) {
|
|
641
|
+
const n8 = parts[k + 2] || 0;
|
|
642
|
+
const c = pal[n8 % 16];
|
|
643
|
+
if (p === 38) fg = c; else bg = c;
|
|
644
|
+
k += 2;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
i += m[0].length;
|
|
649
|
+
continue;
|
|
650
|
+
}
|
|
651
|
+
m = /^\x1b\][^\x07]*(?:\x07|\x1b\\)/.exec(rest) || /^\x1b./.exec(rest);
|
|
652
|
+
i += m ? m[0].length : 1;
|
|
653
|
+
continue;
|
|
654
|
+
}
|
|
655
|
+
let j = s.indexOf("\x1b", i);
|
|
656
|
+
if (j < 0) j = s.length;
|
|
657
|
+
flush(s.slice(i, j));
|
|
658
|
+
i = j;
|
|
659
|
+
}
|
|
660
|
+
return out;
|
|
410
661
|
}
|
|
411
662
|
|
|
412
663
|
function note(message, kind) {
|
|
@@ -623,6 +874,18 @@ function applyPayload(payload) {
|
|
|
623
874
|
if (payload && typeof payload === "object" && payload.op === "view") {
|
|
624
875
|
state.view = payload.view;
|
|
625
876
|
state.viewError = null;
|
|
877
|
+
} else if (payload && typeof payload === "object" && payload.op === "term.list") {
|
|
878
|
+
state.terms = Array.isArray(payload.panes) ? payload.panes : [];
|
|
879
|
+
renderTerms();
|
|
880
|
+
return;
|
|
881
|
+
} else if (payload && typeof payload === "object" && payload.op === "term.read") {
|
|
882
|
+
if (payload.target === state.termTarget && typeof payload.ansi === "string") {
|
|
883
|
+
state.termAnsi = payload.ansi;
|
|
884
|
+
paintTerm();
|
|
885
|
+
}
|
|
886
|
+
return;
|
|
887
|
+
} else if (payload && typeof payload === "object" && payload.op === "error" && payload.code === "busy") {
|
|
888
|
+
return; // our poll raced the host's 1/s throttle — the next tick catches up
|
|
626
889
|
} else if (payload && typeof payload === "object" && payload.op === "error") {
|
|
627
890
|
// The host refused or could not answer: an op we may not use, or its Herdr is down.
|
|
628
891
|
state.viewError = payload.message ?? payload.code ?? "the host refused";
|
|
Binary file
|
package/src/web/sw.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
//
|
|
4
4
|
// Bump VERSION when a shell file changes; old caches are dropped on activate.
|
|
5
5
|
|
|
6
|
-
const VERSION = "herdgate-
|
|
6
|
+
const VERSION = "herdgate-v11";
|
|
7
7
|
const SHELL = ["/", "/app.css", "/e2e.js", "/app.js", "/app.webmanifest", "/icons/icon.svg"];
|
|
8
8
|
|
|
9
9
|
self.addEventListener("install", (event) => {
|