longtable 0.1.49 → 0.1.51

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "longtable",
3
- "version": "0.1.49",
3
+ "version": "0.1.51",
4
4
  "description": "Brings your own Claude Code or Codex to your team's table on longtable.chat, quietly, on your own plan.",
5
5
  "homepage": "https://longtable.chat",
6
6
  "repository": {
@@ -0,0 +1,340 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ // The person's browser at the table, like the one in Claude's own app: one Chrome (or Edge, Brave, Chromium) the
6
+ // connection runs with no window, its profile kept in ~/.longtable/browser so sign-ins stay. Their own page watches it
7
+ // live and passes their clicks and keys in (local.mjs); their AI drives the same one when "Let it open pages" is on, so
8
+ // they can watch it and take over. Frames go only to their own page on this computer, never to Longtable.
9
+ // It is spoken to through Chrome's DevTools pipe (no WebSocket needed on Node 20), and also listens on a DevTools port
10
+ // on 127.0.0.1 only, which is how their AI's browser tools attach to it.
11
+
12
+ export function findBrowser(platform = process.platform, env = process.env, exists = existsSync) {
13
+ const win = (base, ...rest) => (base ? join(base, ...rest) : null);
14
+ const list = platform === "win32" ? [
15
+ win(env.PROGRAMFILES, "Google", "Chrome", "Application", "chrome.exe"),
16
+ win(env["PROGRAMFILES(X86)"], "Google", "Chrome", "Application", "chrome.exe"),
17
+ win(env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe"),
18
+ win(env.PROGRAMFILES, "BraveSoftware", "Brave-Browser", "Application", "brave.exe"),
19
+ win(env.LOCALAPPDATA, "BraveSoftware", "Brave-Browser", "Application", "brave.exe"),
20
+ win(env["PROGRAMFILES(X86)"], "Microsoft", "Edge", "Application", "msedge.exe"),
21
+ win(env.PROGRAMFILES, "Microsoft", "Edge", "Application", "msedge.exe"),
22
+ ] : platform === "darwin" ? [
23
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
24
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
25
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
26
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
27
+ ] : ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser", "brave-browser", "microsoft-edge"].map((n) => {
28
+ const r = spawnSync("sh", ["-c", `command -v ${n}`], { encoding: "utf8" });
29
+ return r.status === 0 ? r.stdout.trim() : null;
30
+ });
31
+ return list.find((p) => p && exists(p)) || null;
32
+ }
33
+
34
+ // Only addresses a browser should be sent to from a typed bar: the web, and pages on this computer.
35
+ export function addressFor(typed) {
36
+ const t = String(typed ?? "").trim();
37
+ if (!t) return null;
38
+ if (/^about:blank$/i.test(t)) return "about:blank";
39
+ const local = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(t);
40
+ let url;
41
+ try { url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(t) ? t : `${local ? "http" : "https"}://${t}`); } catch { return null; }
42
+ return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
43
+ }
44
+
45
+ // Keys that are not text: their DevTools name, key code and the text they make.
46
+ const KEYS = { Enter: [13, "\r"], Backspace: [8], Tab: [9], Escape: [27], Delete: [46], ArrowLeft: [37], ArrowUp: [38], ArrowRight: [39], ArrowDown: [40], Home: [36], End: [35], PageUp: [33], PageDown: [34] };
47
+ const EDITS = { a: "selectAll", c: "copy", x: "cut", v: "paste", z: "undo", y: "redo" };
48
+ const IDLE_MS = 30 * 60 * 1000;
49
+
50
+ export class Browser {
51
+ constructor(home, log) {
52
+ this.profile = join(home, "browser");
53
+ this.log = log;
54
+ this.viewers = new Set();
55
+ this.users = 0;
56
+ this.page = null; // the tab shown: { targetId, sessionId, url, title }
57
+ this.tabs = new Map(); // every tab, by id: { id, url, title }; as many as they or their AI open
58
+ this.sessions = new Map(); // tab id -> the session it is spoken to on
59
+ this.size = { w: 1280, h: 800 };
60
+ this.fit = null; // the size of the picture on their screen, while someone watches
61
+ this.starting = null;
62
+ this.proc = null;
63
+ }
64
+
65
+ // Started on first use; a browser nobody watched or used for half an hour is closed.
66
+ start() {
67
+ if (this.ready) return Promise.resolve(this.port);
68
+ this.starting ??= this.launch().finally(() => { this.starting = null; });
69
+ return this.starting;
70
+ }
71
+
72
+ async launch() {
73
+ const exe = findBrowser();
74
+ if (!exe) throw new Error("No Chrome, Edge or Brave was found on this computer");
75
+ mkdirSync(this.profile, { recursive: true });
76
+ const portFile = join(this.profile, "DevToolsActivePort");
77
+ rmSync(portFile, { force: true });
78
+ const proc = spawn(exe, ["--headless=new", "--remote-debugging-pipe", "--remote-debugging-port=0", "--remote-debugging-address=127.0.0.1",
79
+ `--user-data-dir=${this.profile}`, "--no-first-run", "--no-default-browser-check", `--window-size=${this.size.w},${this.size.h}`, "about:blank"],
80
+ { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"], windowsHide: true });
81
+ this.proc = proc;
82
+ this.calls = new Map();
83
+ this.next = 1;
84
+ let buf = "";
85
+ proc.stdio[4].setEncoding("utf8");
86
+ proc.stdio[4].on("data", (d) => {
87
+ buf += d;
88
+ let at;
89
+ while ((at = buf.indexOf("\0")) >= 0) {
90
+ const msg = buf.slice(0, at);
91
+ buf = buf.slice(at + 1);
92
+ try { this.got(JSON.parse(msg)); } catch (e) { this.log(`browser: a message could not be read: ${e.message}`); }
93
+ }
94
+ });
95
+ proc.stdio[3].on("error", () => {});
96
+ proc.on("exit", () => {
97
+ if (this.proc !== proc) return;
98
+ clearInterval(this.idle);
99
+ this.proc = null;
100
+ this.ready = false;
101
+ this.port = 0;
102
+ this.page = null;
103
+ this.tabs.clear();
104
+ this.sessions.clear();
105
+ for (const { fail } of this.calls.values()) fail(new Error("the browser closed"));
106
+ this.calls.clear();
107
+ this.tell({ closed: true });
108
+ });
109
+ try {
110
+ // Chrome writes the port it took once it listens.
111
+ for (let i = 0; i < 150 && !this.port; i++) {
112
+ await new Promise((r) => setTimeout(r, 100));
113
+ if (!this.proc) throw new Error("the browser did not start (is its profile open in another window?)");
114
+ try { this.port = Number(readFileSync(portFile, "utf8").split("\n")[0]) || 0; } catch {}
115
+ }
116
+ if (!this.port) throw new Error("the browser did not say where it listens");
117
+ await this.call("Target.setDiscoverTargets", { discover: true });
118
+ const { targetInfos } = await this.call("Target.getTargets");
119
+ for (const t of targetInfos) this.note(t);
120
+ const page = targetInfos.find((t) => this.tabs.has(t.targetId));
121
+ await this.show(page ? page.targetId : (await this.call("Target.createTarget", { url: "about:blank" })).targetId);
122
+ } catch (e) {
123
+ this.close();
124
+ throw e;
125
+ }
126
+ this.ready = true;
127
+ this.idle = setInterval(() => {
128
+ if (!this.viewers.size && !this.users && Date.now() - this.used > IDLE_MS) this.close();
129
+ }, 60 * 1000);
130
+ this.idle.unref?.();
131
+ this.used = Date.now();
132
+ this.log("browser: started");
133
+ return this.port;
134
+ }
135
+
136
+ close() {
137
+ clearInterval(this.idle);
138
+ this.ready = false;
139
+ const p = this.proc;
140
+ this.proc = null;
141
+ this.port = 0;
142
+ this.page = null;
143
+ this.tabs.clear();
144
+ this.sessions.clear();
145
+ if (p) { try { p.kill(); } catch {} }
146
+ }
147
+
148
+ call(method, params = {}, sessionId) {
149
+ if (!this.proc) return Promise.reject(new Error("the browser is not running"));
150
+ const id = this.next++;
151
+ return new Promise((ok, fail) => {
152
+ this.calls.set(id, { ok, fail });
153
+ this.proc.stdio[3].write(`${JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) })}\0`);
154
+ });
155
+ }
156
+
157
+ got(msg) {
158
+ if (msg.id) {
159
+ const c = this.calls.get(msg.id);
160
+ if (!c) return;
161
+ this.calls.delete(msg.id);
162
+ return msg.error ? c.fail(new Error(msg.error.message)) : c.ok(msg.result || {});
163
+ }
164
+ const p = msg.params || {};
165
+ if (msg.method === "Page.screencastFrame") {
166
+ this.call("Page.screencastFrameAck", { sessionId: p.sessionId }, msg.sessionId).catch(() => {});
167
+ if (msg.sessionId !== this.page?.sessionId) return;
168
+ this.size = { w: p.metadata.deviceWidth, h: p.metadata.deviceHeight };
169
+ return this.tell({ frame: p.data });
170
+ }
171
+ // A new tab, theirs or their AI's, is the one shown, as it would be in front of them.
172
+ if (msg.method === "Target.targetCreated" && this.note(p.targetInfo)) {
173
+ this.tellTabs();
174
+ if (this.ready) this.show(p.targetInfo.targetId).catch((e) => this.log(`browser: could not show a new tab: ${e.message}`));
175
+ return;
176
+ }
177
+ if (msg.method === "Target.targetInfoChanged" && this.note(p.targetInfo)) {
178
+ this.tellTabs();
179
+ if (p.targetInfo.targetId === this.page?.targetId) {
180
+ this.page.url = p.targetInfo.url;
181
+ this.page.title = p.targetInfo.title;
182
+ this.tell({ url: this.page.url, title: this.page.title });
183
+ }
184
+ return;
185
+ }
186
+ if (msg.method === "Target.targetDestroyed" && this.tabs.delete(p.targetId)) {
187
+ this.sessions.delete(p.targetId);
188
+ this.tellTabs();
189
+ if (p.targetId !== this.page?.targetId) return;
190
+ this.page = null;
191
+ this.casting = null;
192
+ // The last tab closed: a blank one takes its place, as a browser window would keep one open.
193
+ const next = [...this.tabs.keys()].pop();
194
+ return (next ? this.show(next) : this.call("Target.createTarget", { url: "about:blank" }))
195
+ .catch((e) => this.log(`browser: no tab left to show: ${e.message}`));
196
+ }
197
+ }
198
+
199
+ // A page target is a tab (never the browser's own pages, such as DevTools). Kept with its address and title.
200
+ note(t) {
201
+ if (!t || t.type !== "page" || /^(devtools|chrome-extension):/.test(t.url || "")) return false;
202
+ this.tabs.set(t.targetId, { id: t.targetId, url: t.url || "", title: t.title || "" });
203
+ return true;
204
+ }
205
+
206
+ tellTabs() { this.tell({ tabs: [...this.tabs.values()], active: this.page?.targetId || null }); }
207
+
208
+ // One switch at a time, in the order asked: a tab picked just after others opened is the one left showing.
209
+ show(targetId) {
210
+ this.showing = (this.showing || Promise.resolve()).catch(() => {}).then(() => this.showNow(targetId));
211
+ return this.showing;
212
+ }
213
+
214
+ async showNow(targetId) {
215
+ if (this.page?.targetId === targetId || !this.proc) return;
216
+ // The tab shown before stops sending pictures.
217
+ if (this.page && this.casting) { this.call("Page.stopScreencast", {}, this.page.sessionId).catch(() => {}); this.casting = null; }
218
+ let sessionId = this.sessions.get(targetId);
219
+ if (!sessionId) {
220
+ ({ sessionId } = await this.call("Target.attachToTarget", { targetId, flatten: true }));
221
+ this.sessions.set(targetId, sessionId);
222
+ await this.call("Page.enable", {}, sessionId);
223
+ }
224
+ const { targetInfo } = await this.call("Target.getTargetInfo", { targetId });
225
+ this.page = { targetId, sessionId, url: targetInfo?.url || "", title: targetInfo?.title || "" };
226
+ this.tell({ url: this.page.url, title: this.page.title });
227
+ this.tellTabs();
228
+ if (this.viewers.size) {
229
+ await this.fitTo();
230
+ await this.cast();
231
+ const { data } = await this.call("Page.captureScreenshot", { format: "jpeg", quality: 70 }, sessionId);
232
+ this.tell({ frame: data });
233
+ }
234
+ }
235
+
236
+ // The page laid out at the size it is shown at, sharp on their screen, as in Claude's own browser. With nobody
237
+ // watching it goes back to the browser's own window size, which is what their AI then sees.
238
+ async fitTo() {
239
+ const s = this.page?.sessionId;
240
+ if (!s) return;
241
+ if (this.fit && this.viewers.size) await this.call("Emulation.setDeviceMetricsOverride", { width: this.fit.w, height: this.fit.h, deviceScaleFactor: this.fit.dpr, mobile: false }, s);
242
+ else await this.call("Emulation.clearDeviceMetricsOverride", {}, s);
243
+ }
244
+
245
+ // Frames from the tab shown, once (a second start is refused by the browser).
246
+ async cast() {
247
+ const s = this.page?.sessionId;
248
+ if (!s || this.casting === s) return;
249
+ this.casting = s;
250
+ try { await this.call("Page.startScreencast", { format: "jpeg", quality: 70, maxWidth: 4000, maxHeight: 4000 }, s); }
251
+ catch (e) { this.casting = null; throw e; }
252
+ }
253
+
254
+ tell(event) { for (const v of this.viewers) v(event); }
255
+
256
+ // Someone's page watching. It hears where the browser is at once, then every frame.
257
+ async watch(viewer) {
258
+ this.viewers.add(viewer);
259
+ this.used = Date.now();
260
+ await this.start();
261
+ viewer({ url: this.page?.url || "", title: this.page?.title || "" });
262
+ viewer({ tabs: [...this.tabs.values()], active: this.page?.targetId || null });
263
+ await this.fitTo();
264
+ await this.cast();
265
+ // A still page sends no new frame, so the one on screen is asked for.
266
+ const { data } = await this.call("Page.captureScreenshot", { format: "jpeg", quality: 70 }, this.page.sessionId);
267
+ viewer({ frame: data });
268
+ }
269
+
270
+ unwatch(viewer) {
271
+ this.viewers.delete(viewer);
272
+ this.used = Date.now();
273
+ if (!this.viewers.size && this.page) {
274
+ this.casting = null;
275
+ this.fit = null;
276
+ this.call("Page.stopScreencast", {}, this.page.sessionId).catch(() => {});
277
+ this.fitTo().catch(() => {});
278
+ }
279
+ }
280
+
281
+ // Their AI's run uses it: it is started for that, and kept open until the run is done.
282
+ async hold() { this.users++; this.used = Date.now(); try { return await this.start(); } catch (e) { this.users--; throw e; } }
283
+ release() { this.users = Math.max(0, this.users - 1); this.used = Date.now(); }
284
+
285
+ // What their page asks of it. Points are given as fractions of the picture, so any size of screen lands right.
286
+ async act(a) {
287
+ this.used = Date.now();
288
+ // The size it is shown at, which may come before the browser has finished starting: kept, and used when it has.
289
+ if (a.do === "size") {
290
+ const n = (v) => Math.round(Math.max(200, Math.min(3000, Number(v) || 200)));
291
+ this.fit = { w: n(a.w), h: n(a.h), dpr: Math.max(1, Math.min(3, Number(a.dpr) || 1)) };
292
+ if (!this.page || !this.viewers.size) return null;
293
+ // Frames at the new size: the old ones are stopped and started again.
294
+ this.casting = null;
295
+ await this.call("Page.stopScreencast", {}, this.page.sessionId).catch(() => {});
296
+ await this.fitTo();
297
+ return this.cast();
298
+ }
299
+ if (!this.page) throw new Error("the browser is not open");
300
+ const s = this.page.sessionId;
301
+ const at = (n, size) => Math.max(0, Math.min(size, Number(n) * size));
302
+ switch (a.do) {
303
+ case "go": {
304
+ const url = addressFor(a.url);
305
+ if (!url) throw new Error("that is not a web address");
306
+ return this.call("Page.navigate", { url }, s);
307
+ }
308
+ case "back": case "forward": {
309
+ const { currentIndex, entries } = await this.call("Page.getNavigationHistory", {}, s);
310
+ const e = entries[currentIndex + (a.do === "back" ? -1 : 1)];
311
+ return e ? this.call("Page.navigateToHistoryEntry", { entryId: e.id }, s) : null;
312
+ }
313
+ case "reload": return this.call("Page.reload", {}, s);
314
+ // Tabs, with no limit: their page warns past a sensible number, nothing here refuses one.
315
+ case "tab": return this.tabs.has(a.id) ? this.show(a.id) : null;
316
+ case "newtab": return this.call("Target.createTarget", { url: addressFor(a.url) || "about:blank" });
317
+ case "closetab": return this.tabs.has(a.id) ? this.call("Target.closeTarget", { targetId: a.id }) : null;
318
+ case "click": {
319
+ const x = at(a.x, this.size.w), y = at(a.y, this.size.h);
320
+ await this.call("Input.dispatchMouseEvent", { type: "mouseMoved", x, y }, s);
321
+ await this.call("Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "left", clickCount: 1 }, s);
322
+ return this.call("Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "left", clickCount: 1 }, s);
323
+ }
324
+ case "scroll":
325
+ return this.call("Input.dispatchMouseEvent", { type: "mouseWheel", x: at(a.x, this.size.w), y: at(a.y, this.size.h), deltaX: 0, deltaY: Math.max(-2000, Math.min(2000, Number(a.dy) || 0)) }, s);
326
+ case "type": return this.call("Input.insertText", { text: String(a.text ?? "").slice(0, 8000) }, s);
327
+ case "key": {
328
+ const mods = (a.ctrl ? 2 : 0) | (a.meta ? 4 : 0) | (a.shift ? 8 : 0) | (a.alt ? 1 : 0);
329
+ const k = String(a.key ?? "");
330
+ const edit = (a.ctrl || a.meta) && EDITS[k.toLowerCase()];
331
+ const named = KEYS[k];
332
+ if (!named && !edit) return null;
333
+ const base = { key: k, code: named ? k : `Key${k.toUpperCase()}`, windowsVirtualKeyCode: named ? named[0] : k.toUpperCase().charCodeAt(0), modifiers: mods };
334
+ await this.call("Input.dispatchKeyEvent", { type: "keyDown", ...base, ...(named?.[1] && !mods ? { text: named[1] } : {}), ...(edit ? { commands: [edit] } : {}) }, s);
335
+ return this.call("Input.dispatchKeyEvent", { type: "keyUp", ...base }, s);
336
+ }
337
+ default: throw new Error("unknown browser step");
338
+ }
339
+ }
340
+ }
package/src/claude.mjs CHANGED
@@ -171,11 +171,11 @@ export const EFFORTS = new Set(["low", "medium", "high", "xhigh", "max"]);
171
171
  // through the approval server (`full.mcp`, the MCP config that starts it), where the person allows or denies each one.
172
172
  // Their "always allow" answers come back as `full.allow`. On Mac and Linux, commands also run in Claude Code's sandbox.
173
173
  // A job that only reads may not change files (`edit` false).
174
- // A run asked for in Auto on an account that cannot use it goes again in Accept edits, rather than failing.
174
+ // A run asked for in Auto or Bypass on an account that cannot use it goes again in Accept edits, rather than failing.
175
175
  export function ask(opts) {
176
176
  return askOnce(opts).catch((e) => {
177
177
  if (!e.noAuto) throw e;
178
- log("Auto mode is not available to this Claude Code; running in Accept edits");
178
+ log(`${opts.full?.mode} mode is not available to this Claude Code; running in Accept edits`);
179
179
  return askOnce({ ...opts, full: { ...opts.full, mode: "acceptEdits" } });
180
180
  });
181
181
  }
@@ -193,7 +193,7 @@ function askOnce({ claude, cwd, prompt, system, schema, model, tools = "Read,Gre
193
193
  const args = full
194
194
  ? ["-p", "--output-format", "stream-json", "--verbose", "--no-session-persistence",
195
195
  // Their own choice of how it asks (manual, accept edits, auto, plan), else as before: edits go ahead in work.
196
- "--permission-mode", full.mode === "plan" ? "plan" : full.mode === "auto" ? "auto" : full.mode === "manual" ? "default" : full.mode === "acceptEdits" || edit ? "acceptEdits" : "default",
196
+ "--permission-mode", full.mode === "plan" ? "plan" : full.mode === "auto" ? "auto" : full.mode === "bypass" ? "bypassPermissions" : full.mode === "manual" ? "default" : full.mode === "acceptEdits" || edit ? "acceptEdits" : "default",
197
197
  "--permission-prompt-tool", "mcp__longtable__approve",
198
198
  "--mcp-config", full.mcp, "--max-turns", edit && !long ? "200" : "10000"]
199
199
  : ["-p", "--output-format", "stream-json", "--verbose", "--no-session-persistence", "--restricted", "--permission-mode", edit ? "acceptEdits" : "dontAsk",
@@ -326,11 +326,12 @@ function askOnce({ claude, cwd, prompt, system, schema, model, tools = "Read,Gre
326
326
  lines.end();
327
327
  const procs = [...seen.values()];
328
328
  if (ended) return reject(Object.assign(new Error(ended), { procs }));
329
- // Asked for Auto on an account or model that cannot use it: said so, so the run is tried again without it.
330
- const noAuto = full?.mode === "auto" && /auto/i.test(`${err} ${result?.is_error ? result.result || "" : ""}`)
329
+ // Asked for Auto or Bypass on an account or model that cannot use it (an organisation can turn Bypass off): said
330
+ // so, so the run is tried again without it.
331
+ const noAuto = (full?.mode === "auto" || full?.mode === "bypass") && (full.mode === "auto" ? /auto/i : /bypass/i).test(`${err} ${result?.is_error ? result.result || "" : ""}`)
331
332
  && /not (available|supported|enabled)|unavailable|unsupported|requires|disabled/i.test(`${err} ${result?.result || ""}`)
332
333
  && (!result || result.is_error);
333
- if (noAuto) return reject(Object.assign(new Error("Auto mode is not available here"), { noAuto: true }));
334
+ if (noAuto) return reject(Object.assign(new Error(`${full.mode} mode is not available here`), { noAuto: true }));
334
335
  // A session that is gone (deleted, or never written) cannot be picked up: said so, so the request starts a new one.
335
336
  if (session?.resume && (!result || result.is_error) && /no conversation found with session id/i.test(`${err} ${result?.result || ""}`)) {
336
337
  return reject(Object.assign(new Error("that session could not be picked up"), { noSession: true }));
package/src/local.mjs ADDED
@@ -0,0 +1,96 @@
1
+ import { createServer } from "node:http";
2
+ import { randomBytes, timingSafeEqual } from "node:crypto";
3
+ import { Terminal } from "./terminal.mjs";
4
+
5
+ // The bridge: a small server on this computer only (127.0.0.1), which the person's own Longtable page reaches
6
+ // directly, for their terminal and their browser. Nothing sent through it passes through Longtable, so a password typed
7
+ // into the terminal or a sign-in in the browser stays on this computer.
8
+ // Who may use it: a page on Longtable's own address (the browser says which site a request comes from, and no site can
9
+ // pretend), sent to this computer by name (so a web address made to point here cannot reach it), carrying the key of a
10
+ // table whose Longtable says this connection may serve it (runner_local: only their own full Claude Code, which can
11
+ // already run commands here with their approval). Each table has its own key, handed only to its own person.
12
+
13
+ export function bridgeKey() { return randomBytes(24).toString("base64url"); }
14
+
15
+ const same = (a, b) => typeof a === "string" && typeof b === "string" && a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
16
+
17
+ // A request from Longtable's own page, sent to this computer by name.
18
+ export function fromPage({ host, origin }, { port, app }) {
19
+ return (host === `127.0.0.1:${port}` || host === `localhost:${port}`) && !!origin && origin === app;
20
+ }
21
+ // And carrying the table's key.
22
+ export const keyOk = (auth, key) => !!key && same(String(auth || "").replace(/^Bearer /, ""), key);
23
+
24
+ export function startBridge({ app, seats, home, browser, log }) {
25
+ const origin = new URL(app).origin;
26
+ const terms = new Map(); // table id -> { term, listeners }
27
+ const termFor = (seat) => {
28
+ let t = terms.get(seat.table_id);
29
+ if (!t) {
30
+ const listeners = new Set();
31
+ t = { listeners, term: new Terminal(seat.terminalFolder || home, (e) => { for (const l of listeners) l(e); }) };
32
+ terms.set(seat.table_id, t);
33
+ }
34
+ return t;
35
+ };
36
+ const cors = { "Access-Control-Allow-Origin": origin, Vary: "Origin", "Access-Control-Allow-Headers": "authorization, content-type",
37
+ "Access-Control-Allow-Methods": "GET, POST", "Access-Control-Allow-Private-Network": "true", "Access-Control-Max-Age": "600" };
38
+ const send = (res, status, body) => { res.writeHead(status, { ...cors, "Content-Type": "application/json", "Cache-Control": "no-store" }); res.end(JSON.stringify(body)); };
39
+ const body = (req) => new Promise((ok, fail) => {
40
+ let s = "";
41
+ req.setEncoding("utf8");
42
+ req.on("data", (d) => { s += d; if (s.length > 64 * 1024) { fail(new Error("too much")); req.destroy(); } });
43
+ req.on("end", () => { try { ok(s ? JSON.parse(s) : {}); } catch { fail(new Error("not JSON")); } });
44
+ req.on("error", fail);
45
+ });
46
+ // A stream of lines of JSON, kept open with a blank line now and then.
47
+ const stream = (req, res, first, add, remove) => {
48
+ res.writeHead(200, { ...cors, "Content-Type": "application/x-ndjson", "Cache-Control": "no-store" });
49
+ const write = (e) => { res.write(`${JSON.stringify(e)}\n`); };
50
+ const beat = setInterval(() => res.write("\n"), 15000);
51
+ if (first) write(first);
52
+ const done = () => { clearInterval(beat); remove(write); };
53
+ req.on("close", done);
54
+ return Promise.resolve(add(write)).catch((e) => { write({ error: e.message }); res.end(); });
55
+ };
56
+
57
+ const server = createServer(async (req, res) => {
58
+ try {
59
+ const url = new URL(req.url, "http://127.0.0.1");
60
+ const port = server.address().port;
61
+ const seat = seats.find((s) => s.table_id === url.searchParams.get("t") && !s.gone && s.local?.allowed);
62
+ if (!fromPage(req.headers, { port, app: origin })) { res.writeHead(403); return res.end(); }
63
+ if (req.method === "OPTIONS") { res.writeHead(204, cors); return res.end(); }
64
+ if (!seat || !keyOk(req.headers.authorization, seat.local.key)) {
65
+ return send(res, 401, { error: "not yours" });
66
+ }
67
+ const path = url.pathname;
68
+ // The terminal: what it printed so far, then everything it prints. Opening it starts the shell at the page's size.
69
+ if (req.method === "GET" && path === "/term") {
70
+ const t = termFor(seat);
71
+ return stream(req, res, { data: t.term.text, all: true }, async (w) => { t.listeners.add(w); await t.term.open(url.searchParams.get("cols"), url.searchParams.get("rows")); },
72
+ (w) => t.listeners.delete(w));
73
+ }
74
+ if (req.method === "GET" && path === "/browser") {
75
+ return stream(req, res, null, (w) => browser.watch(w), (w) => browser.unwatch(w));
76
+ }
77
+ if (req.method !== "POST") return send(res, 404, { error: "nothing here" });
78
+ const b = await body(req);
79
+ // Keys as typed, or a whole command from the chat's "!".
80
+ if (path === "/term") { const t = termFor(seat).term; await (typeof b.line === "string" ? t.run(b.line) : t.write(b.data)); return send(res, 200, { ok: true }); }
81
+ if (path === "/term/size") { termFor(seat).term.resize(b.cols, b.rows); return send(res, 200, { ok: true }); }
82
+ // Closed from the page: the shell goes, and so does what it printed.
83
+ if (path === "/term/stop") { const t = termFor(seat); t.term.stop(); terms.delete(seat.table_id); return send(res, 200, { ok: true }); }
84
+ if (path === "/browser") { await browser.act(b); return send(res, 200, { ok: true }); }
85
+ return send(res, 404, { error: "nothing here" });
86
+ } catch (e) {
87
+ log(`bridge: ${e.message}`);
88
+ if (!res.headersSent) send(res, 500, { error: e.message });
89
+ else res.end();
90
+ }
91
+ });
92
+ return new Promise((ok, fail) => {
93
+ server.once("error", fail);
94
+ server.listen(0, "127.0.0.1", () => ok({ port: server.address().port, close: () => { for (const t of terms.values()) t.term.stop(); server.close(); } }));
95
+ });
96
+ }
package/src/pty.mjs ADDED
@@ -0,0 +1,60 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, join, normalize, sep } from "node:path";
4
+ import { home, log } from "./store.mjs";
5
+ import { fetchChecked, ownDir } from "./update.mjs";
6
+
7
+ // A real terminal needs a pseudo-terminal, which only a small native library can give (ConPTY on Windows, forkpty on
8
+ // Mac and Linux). The connection keeps itself up to date with plain files only, so the library is not inside it: it
9
+ // is loaded from the package's own install when there is one (connecting through npm, or this repository), else
10
+ // fetched once from the npm registry for this computer, at the exact version the connection names, checked against
11
+ // the registry's fingerprint, and kept in ~/.longtable/pty/<version>. Only the one package for this system and
12
+ // processor is fetched: the prebuilt library itself, no install scripts.
13
+
14
+ const NAME = "@lydell/node-pty";
15
+ export const ptyVersion = () => JSON.parse(readFileSync(join(ownDir(), "package.json"), "utf8")).dependencies?.[NAME] || null;
16
+ export const platformPackage = (platform = process.platform, arch = process.arch) => `${NAME}-${platform}-${arch}`;
17
+
18
+ // Only plain paths inside the package.
19
+ function rel(name) {
20
+ if (!name.startsWith("package/")) return null;
21
+ const r = name.slice("package/".length);
22
+ if (!r || r.includes("\\") || r.includes("\0") || r.split("/").some((p) => p === ".." || p === "." || p === "")) return null;
23
+ return r;
24
+ }
25
+
26
+ export async function installPty(version, dir) {
27
+ const files = await fetchChecked(platformPackage(), version, 40 * 1024 * 1024);
28
+ const next = `${dir}-next`;
29
+ rmSync(next, { recursive: true, force: true });
30
+ for (const f of files) {
31
+ const r = rel(f.name);
32
+ if (!r) continue;
33
+ const to = normalize(join(next, ...r.split("/")));
34
+ if (!to.startsWith(next + sep)) throw new Error("a file would land outside its folder");
35
+ mkdirSync(dirname(to), { recursive: true });
36
+ writeFileSync(to, f.data);
37
+ // The helper programs it starts must stay runnable on Mac and Linux.
38
+ if (f.exec && process.platform !== "win32") chmodSync(to, 0o755);
39
+ }
40
+ if (!existsSync(join(next, "package.json"))) throw new Error("the terminal library came without its package");
41
+ rmSync(dir, { recursive: true, force: true });
42
+ renameSync(next, dir);
43
+ }
44
+
45
+ let loading = null;
46
+ // The library, once: from the package's own install, else from the copy kept for this computer, fetched if missing.
47
+ export function loadPty() {
48
+ loading ??= (async () => {
49
+ try { return createRequire(import.meta.url)(NAME); } catch {}
50
+ const version = ptyVersion();
51
+ if (!/^[0-9A-Za-z.-]+$/.test(version || "")) throw new Error("the connection names no terminal library");
52
+ const dir = join(home, "pty", version, platformPackage().split("/")[1]);
53
+ if (!existsSync(join(dir, "package.json"))) {
54
+ log(`terminal: fetching ${platformPackage()} ${version} for this computer`);
55
+ await installPty(version, dir);
56
+ }
57
+ return createRequire(join(dir, "package.json"))(join(dir, "lib", "index.js"));
58
+ })().catch((e) => { loading = null; throw e; });
59
+ return loading;
60
+ }
package/src/repo.mjs CHANGED
@@ -335,7 +335,7 @@ const LONGTABLE = { ...quiet, GIT_AUTHOR_NAME: "Longtable", GIT_AUTHOR_EMAIL: "l
335
335
  // Who a copy's own commits (its start, a clean copy, catching up, a take-back) are signed by: the person whose
336
336
  // computer makes them, as git already knows them, the same way landWork signs a change. Vercel's free plan refuses
337
337
  // to build a private repository's commit whose author is not the account's own, so a copy signed "Longtable" was
338
- // never put up (found on SAMS's preview, 26 Oct 2026). "Longtable" only when this computer has no git identity.
338
+ // never put up (found on a real team's preview hosting, 26 Oct 2026). "Longtable" only when this computer has no git identity.
339
339
  function signer(G) {
340
340
  let name = "";
341
341
  let email = "";
package/src/run.mjs CHANGED
@@ -23,6 +23,8 @@ import { askCodex, codexLimits, findCodex } from "./codex.mjs";
23
23
  import { packCode } from "./pack.mjs";
24
24
  import { changedSoFar, closeTree, fileFolder, folderChanges, folderState, freshCopy, isAddress, pushPlan, sourceFor, trustedRepo, landTree, landWork, neverCommit, openBranch, openTree, openWork, ownFolder, layTree, tidyTrees, patchOf, realRepo, refreshBranch, safeTable, treeChanges, undoCommit, workBranch } from "./repo.mjs";
25
25
  import { alwaysRules } from "./approve-server.mjs";
26
+ import { Browser } from "./browser.mjs";
27
+ import { bridgeKey, startBridge } from "./local.mjs";
26
28
  import { fileURLToPath } from "node:url";
27
29
  import { cut, hideSecrets, home, loadSecret, log, readConfig, writeWhole } from "./store.mjs";
28
30
 
@@ -532,6 +534,9 @@ export function cleanSources(dir, sources) {
532
534
  return out.slice(0, 6);
533
535
  }
534
536
 
537
+ // The person's browser at the table: their page shows it and their AI uses it (browser.mjs). Started when first used.
538
+ const sharedBrowser = new Browser(home, log);
539
+
535
540
  // Whether longtable:// on this computer starts the connection (keepWakeLink, at start).
536
541
  let wakeLink = false;
537
542
 
@@ -1411,7 +1416,7 @@ async function work(rpc, seat, engines, raw) {
1411
1416
  } finally {
1412
1417
  if (beat) clearInterval(beat);
1413
1418
  if (pending) clearTimeout(pending);
1414
- if (fullRun) { try { rmSync(fullRun.mcp, { force: true }); if (fullRun.browserDir) rmSync(fullRun.browserDir, { recursive: true, force: true }); } catch {} }
1419
+ if (fullRun) { try { rmSync(fullRun.mcp, { force: true }); if (fullRun.browserDir) rmSync(fullRun.browserDir, { recursive: true, force: true }); } catch {} if (fullRun.shared) sharedBrowser.release(); }
1415
1420
  if (tree) closeTree(tree);
1416
1421
  if (side) { try { rmSync(side, { recursive: true, force: true }); } catch {} }
1417
1422
  if (inbox) await inbox.close();
@@ -1429,10 +1434,12 @@ const PLANNING = "Your person has you in plan mode: read what you need, then ans
1429
1434
  // own browser profile) and its screenshots kept in a folder of the connection's. Run through npm's own npx beside this
1430
1435
  // Node when it is there (a .cmd cannot be started directly on Windows), else npx on the PATH.
1431
1436
  export const PLAYWRIGHT_MCP = "@playwright/mcp@0.0.83";
1432
- export function browserServer(out) {
1437
+ // With `cdp`, it drives the person's browser at the table (browser.mjs), the one their page shows them, instead of a
1438
+ // fresh one of its own.
1439
+ export function browserServer(out, cdp = null) {
1433
1440
  // Beside node.exe on Windows; under lib/ beside the node binary on Mac and Linux.
1434
1441
  const npxCli = [join(dirname(process.execPath), "node_modules", "npm", "bin", "npx-cli.js"), join(dirname(process.execPath), "..", "lib", "node_modules", "npm", "bin", "npx-cli.js")].find((p) => existsSync(p));
1435
- const args = ["-y", PLAYWRIGHT_MCP, "--headless", "--isolated", "--output-dir", out];
1442
+ const args = ["-y", PLAYWRIGHT_MCP, ...(cdp ? ["--cdp-endpoint", cdp] : ["--headless", "--isolated"]), "--output-dir", out];
1436
1443
  return npxCli ? { command: process.execPath, args: [npxCli, ...args] } : { command: "npx", args };
1437
1444
  }
1438
1445
 
@@ -1445,13 +1452,20 @@ async function fullSetup(rpc, seat, job, inFolder = false, workDir = null) {
1445
1452
  const server = fileURLToPath(new URL("./approve-server.mjs", import.meta.url));
1446
1453
  // Screenshots go outside ~/.longtable, which is never shared, so the person's Claude can put one on its answer.
1447
1454
  const browserDir = join(tmpdir(), `longtable-browser-${String(job.job_id).replace(/[^a-f0-9-]/gi, "")}`);
1448
- const browser = job.browser === true ? browserServer(browserDir) : null;
1455
+ // Their browser at the table when it can be started, so they can watch it and take over; else one of its own.
1456
+ let shared = false;
1457
+ let browser = null;
1458
+ if (job.browser === true) {
1459
+ let port = 0;
1460
+ try { port = await sharedBrowser.hold(); shared = true; } catch (e) { log(`job ${job.job_id}: their browser could not be used, so it gets one of its own: ${e.message}`); }
1461
+ browser = browserServer(browserDir, port ? `http://127.0.0.1:${port}` : null);
1462
+ }
1449
1463
  writeWhole(mcp, JSON.stringify({ mcpServers: { longtable: { command: process.execPath, args: [server],
1450
1464
  // What it may put on its answer: files in the folder it works in, and its own screenshots. Nothing else.
1451
1465
  env: { LT_SUPABASE_URL: rpc.base, LT_KEY: rpc.key, LT_JOB_KEY: key, LT_ALWAYS: always, LT_SHARE_ROOTS: [workDir, browser ? browserDir : null].filter(Boolean).join(delimiter) } }, ...(browser ? { playwright: browser } : {}) } }));
1452
1466
  // In their own folder Claude Code reads the project's settings itself, as at home. With their browser on, its tools
1453
1467
  // are theirs to use without asking each time, as they turned it on.
1454
- return { mcp, browserDir: browser ? browserDir : null, allow: [...alwaysRules(always), ...(browser ? ["mcp__playwright"] : [])], project: inFolder ? {} : projectSettings(seat) };
1468
+ return { mcp, shared, browserDir: browser ? browserDir : null, allow: [...alwaysRules(always), ...(browser ? ["mcp__playwright"] : [])], project: inFolder ? {} : projectSettings(seat) };
1455
1469
  }
1456
1470
 
1457
1471
  // Their project's own Claude Code settings, from their own folder (shared, then their local ones on top): what their
@@ -1520,6 +1534,29 @@ async function tellCommands(rpc, seat) {
1520
1534
  } catch (e) { log(`commands not sent: ${e.message}`); }
1521
1535
  }
1522
1536
 
1537
+ // The bridge for each person's own terminal and browser (local.mjs). Longtable hears where it listens, with a key for
1538
+ // each table, at start and every minute, and says for each whether this connection may serve it there (their own full
1539
+ // Claude Code only). A bridge that cannot open is written down; everything else goes on as before.
1540
+ async function openBridge(rpc, config, seats) {
1541
+ const mine = seats.filter((s) => s.kind === "claude" && !s.gone);
1542
+ if (!mine.length || !config.app) return;
1543
+ for (const s of mine) s.local = { key: bridgeKey(), allowed: false };
1544
+ for (const s of mine) s.terminalFolder = ownFolder(s) || homedir();
1545
+ let bridge;
1546
+ try { bridge = await startBridge({ app: config.app, seats: mine, home: homedir(), browser: sharedBrowser, log }); }
1547
+ catch (e) { return log(`the terminal and browser bridge did not open: ${e.message}`); }
1548
+ process.on("exit", () => bridge.close());
1549
+ const tell = async () => {
1550
+ for (const s of mine) {
1551
+ if (s.gone) continue;
1552
+ try { s.local.allowed = await rpc("runner_local", { token: s.token, port: bridge.port, key: s.local.key }) === true; }
1553
+ catch (e) { log(`bridge not reported: ${e.message}`); }
1554
+ }
1555
+ };
1556
+ await tell();
1557
+ setInterval(tell, 60 * 1000).unref?.();
1558
+ }
1559
+
1523
1560
  export async function runLoop({ pollMs = 1000, backup = false } = {}) {
1524
1561
  const config = readConfig();
1525
1562
  if (!config.connections?.length) throw new Error("Not connected to any table yet.");
@@ -1538,7 +1575,7 @@ export async function runLoop({ pollMs = 1000, backup = false } = {}) {
1538
1575
  if (old && old !== process.pid) { endConnection(old); log(`ended the connection that was already running (${old})`); }
1539
1576
  writeFileSync(lock, `${process.pid} ${Date.now()}`);
1540
1577
  const unlock = () => { try { if (runningConnection() === process.pid) rmSync(lock, { force: true }); } catch {} };
1541
- process.on("exit", () => { stopAll(); endAllSessions("the connection stopped"); unlock(); });
1578
+ process.on("exit", () => { stopAll(); sharedBrowser.close(); endAllSessions("the connection stopped"); unlock(); });
1542
1579
  // Which common tools its Claude will find here, looked for once at start and shown in its AI window.
1543
1580
  setTimeout(() => { lookForTools().catch((e) => log(`could not look for tools: ${e.message}`)); }, 2000).unref?.();
1544
1581
  // What an earlier connection's sessions left running is stopped, and a session nobody uses for a while ends.
@@ -1572,6 +1609,7 @@ export async function runLoop({ pollMs = 1000, backup = false } = {}) {
1572
1609
  }
1573
1610
  }
1574
1611
  if (seats.every((s) => s.gone)) throw new Error("Every table has taken this connection off. Connect again from Longtable.");
1612
+ openBridge(rpc, config, seats);
1575
1613
  // Each minute: nothing is sent unless the list changed (a new command written, or Claude Code's own list learned).
1576
1614
  setInterval(() => { for (const s of seats) if (!s.gone) tellCommands(rpc, s); }, 60 * 1000).unref?.();
1577
1615
  // Keeping itself up to date: Longtable says which version to run. When it is newer, the connection keeps working and
@@ -0,0 +1,85 @@
1
+ import { homedir } from "node:os";
2
+ import { loadPty } from "./pty.mjs";
3
+
4
+ // A terminal on the person's own computer, reached only from their own page through the bridge (local.mjs): their
5
+ // own shell in a real pseudo-terminal (pty.mjs), as in any terminal app. Colours, prompts, arrow keys, Tab completion,
6
+ // Ctrl+C and full-screen programs all work, because the page runs a real terminal (xterm.js) and every key goes
7
+ // straight to the shell. It starts in the folder they connected from and lives until it exits or they close it; what it
8
+ // printed is kept, so a page opened later sees the screen as it was.
9
+
10
+ const KEEP = 400_000; // characters of output kept for a page that opens later
11
+
12
+ export function shellFor(platform = process.platform, env = process.env) {
13
+ if (platform === "win32") return { cmd: "powershell.exe", args: ["-NoLogo"] };
14
+ return { cmd: env.SHELL || "/bin/bash", args: ["-l"] };
15
+ }
16
+
17
+ // What the shell runs with: the person's own environment, minus the connection's own settings, as a colour terminal.
18
+ export function termEnv(env = process.env) {
19
+ const out = {};
20
+ for (const [k, v] of Object.entries(env)) if (!/^(LONGTABLE_|LT_)/i.test(k) && k !== "NO_COLOR" && k !== "FORCE_COLOR") out[k] = v;
21
+ return { ...out, TERM: "xterm-256color", COLORTERM: "truecolor" };
22
+ }
23
+
24
+ const size = (n, lo, hi, d) => Math.max(lo, Math.min(hi, Math.round(Number(n)) || d));
25
+
26
+ export class Terminal {
27
+ constructor(cwd, emit, load = loadPty) {
28
+ this.cwd = cwd || homedir();
29
+ this.emit = emit;
30
+ this.load = load;
31
+ this.text = "";
32
+ this.proc = null;
33
+ this.starting = null;
34
+ this.cols = 100;
35
+ this.rows = 30;
36
+ }
37
+
38
+ // The shell, started when first needed (and again after it exited).
39
+ open(cols, rows) {
40
+ if (cols) this.resize(cols, rows);
41
+ if (this.proc) return Promise.resolve();
42
+ this.starting ??= (async () => {
43
+ const pty = await this.load();
44
+ const { cmd, args } = shellFor();
45
+ const proc = pty.spawn(cmd, args, { name: "xterm-256color", cols: this.cols, rows: this.rows, cwd: this.cwd, env: termEnv() });
46
+ this.proc = proc;
47
+ proc.onData((d) => {
48
+ this.text = (this.text + d).slice(-KEEP);
49
+ this.emit({ data: d });
50
+ });
51
+ proc.onExit(({ exitCode }) => {
52
+ if (this.proc !== proc) return;
53
+ this.proc = null;
54
+ const line = `\r\n[the shell ended${exitCode ? ` with ${exitCode}` : ""}; press a key to start a new one]\r\n`;
55
+ this.text = (this.text + line).slice(-KEEP);
56
+ this.emit({ data: line, exited: true });
57
+ });
58
+ })().finally(() => { this.starting = null; });
59
+ return this.starting;
60
+ }
61
+
62
+ // Keys, exactly as typed (a shell that ended starts again on the next key).
63
+ async write(data) {
64
+ const s = String(data ?? "");
65
+ if (!s) return;
66
+ if (!this.proc) await this.open();
67
+ this.proc.write(s.slice(0, 64 * 1024));
68
+ }
69
+
70
+ // A command from the chat's "!": typed in and run, as if it were typed here.
71
+ run(line) { return this.write(`${String(line ?? "").replace(/[\r\n]+/g, " ").slice(0, 8000)}\r`); }
72
+
73
+ resize(cols, rows) {
74
+ this.cols = size(cols, 20, 500, this.cols);
75
+ this.rows = size(rows, 5, 200, this.rows);
76
+ try { this.proc?.resize(this.cols, this.rows); } catch {}
77
+ }
78
+
79
+ // Closed for good from the page, or when the connection stops: the shell and everything it started.
80
+ stop() {
81
+ const p = this.proc;
82
+ this.proc = null;
83
+ try { p?.kill(); } catch {}
84
+ }
85
+ }
package/src/update.mjs CHANGED
@@ -49,6 +49,7 @@ export function untar(gz) {
49
49
  const head = buf.subarray(pos, pos + 512);
50
50
  if (head.every((b) => b === 0)) break;
51
51
  const size = parseInt(str(head.subarray(124, 136)).trim() || "0", 8);
52
+ const mode = parseInt(str(head.subarray(100, 108)).trim() || "644", 8);
52
53
  if (!Number.isFinite(size) || size < 0) throw new Error("a broken tar header");
53
54
  const type = String.fromCharCode(head[156] || 48);
54
55
  const prefix = str(head.subarray(345, 500));
@@ -59,7 +60,7 @@ export function untar(gz) {
59
60
  longName = null;
60
61
  if (type === "x") { const m = body.toString("utf8").match(/(?:^|\n)\d+ path=([^\n]*)\n/); if (m) longName = m[1]; continue; }
61
62
  if (type === "L") { longName = str(body); continue; }
62
- if (type === "0" || type === "\0" || type === "7") files.push({ name, data: Buffer.from(body) });
63
+ if (type === "0" || type === "\0" || type === "7") files.push({ name, data: Buffer.from(body), exec: (mode & 0o111) !== 0 });
63
64
  }
64
65
  return files;
65
66
  }
@@ -73,25 +74,31 @@ export function keepFile(name) {
73
74
  return null;
74
75
  }
75
76
 
76
- // Fetch that exact version from the registry, checked against the registry's fingerprint. Returns its files.
77
- export async function fetchRelease(version) {
78
- if (!/^\d+\.\d+\.\d+$/.test(version)) throw new Error(`not a version: ${version}`);
79
- const metaRes = await fetch(`${REGISTRY}/${NAME}/${version}`, { headers: { accept: "application/json" } });
80
- if (!metaRes.ok) throw new Error(`the registry has no ${NAME} ${version} yet (${metaRes.status})`);
77
+ // One exact version of one package from the registry, checked against the registry's own sha512 fingerprint and
78
+ // found where the registry keeps that package. Returns the files of its tarball.
79
+ export async function fetchChecked(name, version, max = MAX_TARBALL) {
80
+ const metaRes = await fetch(`${REGISTRY}/${name.replace("/", "%2f")}/${version}`, { headers: { accept: "application/json" } });
81
+ if (!metaRes.ok) throw new Error(`the registry has no ${name} ${version} yet (${metaRes.status})`);
81
82
  const meta = await metaRes.json();
82
83
  const tarball = meta?.dist?.tarball;
83
84
  const integrity = String(meta?.dist?.integrity || "");
84
- if (meta?.name !== NAME || meta?.version !== version) throw new Error("the registry answered for something else");
85
- if (typeof tarball !== "string" || !tarball.startsWith(`${REGISTRY}/${NAME}/-/`)) throw new Error("the package is not where the registry keeps it");
85
+ if (meta?.name !== name || meta?.version !== version) throw new Error("the registry answered for something else");
86
+ if (typeof tarball !== "string" || !tarball.startsWith(`${REGISTRY}/${name}/-/`)) throw new Error("the package is not where the registry keeps it");
86
87
  const want = integrity.match(/^sha512-([A-Za-z0-9+/=]+)$/)?.[1];
87
88
  if (!want) throw new Error("the registry gave no sha512 fingerprint");
88
89
  const res = await fetch(tarball);
89
- if (!res.ok) throw new Error(`could not download ${version} (${res.status})`);
90
+ if (!res.ok) throw new Error(`could not download ${name} ${version} (${res.status})`);
90
91
  const gz = Buffer.from(await res.arrayBuffer());
91
- if (gz.length > MAX_TARBALL) throw new Error("the package is far bigger than it should be");
92
+ if (gz.length > max) throw new Error("the package is far bigger than it should be");
92
93
  if (createHash("sha512").update(gz).digest("base64") !== want) throw new Error("the download does not match the registry's fingerprint");
94
+ return untar(gz);
95
+ }
96
+
97
+ // Fetch that exact version of the connection, keeping only its own parts. Returns its files.
98
+ export async function fetchRelease(version) {
99
+ if (!/^\d+\.\d+\.\d+$/.test(version)) throw new Error(`not a version: ${version}`);
93
100
  const files = [];
94
- for (const f of untar(gz)) { const rel = keepFile(f.name); if (rel) files.push({ rel, data: f.data }); }
101
+ for (const f of await fetchChecked(NAME, version)) { const rel = keepFile(f.name); if (rel) files.push({ rel, data: f.data }); }
95
102
  const pkg = files.find((f) => f.rel === "package.json");
96
103
  if (!pkg || JSON.parse(pkg.data.toString("utf8")).version !== version) throw new Error("the package says it is another version");
97
104
  if (!files.some((f) => f.rel === "bin/longtable.mjs")) throw new Error("the package has no connection in it");