@phren/cli 0.3.75 → 0.3.76
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/browser-recordings.d.ts +19 -0
- package/dist/bridge/browser-recordings.js +75 -15
- package/dist/bridge/browser-registry.d.ts +2 -0
- package/dist/bridge/browser-registry.js +9 -0
- package/dist/bridge/computers.d.ts +6 -0
- package/dist/bridge/computers.js +38 -0
- package/dist/bridge/pair.d.ts +3 -1
- package/dist/bridge/pair.js +16 -6
- package/dist/bridge/push.d.ts +9 -0
- package/dist/bridge/push.js +29 -5
- package/dist/bridge/server-routes.js +9 -0
- package/dist/bridge/unpair.d.ts +49 -0
- package/dist/bridge/unpair.js +185 -0
- package/dist/bridge-hook.mjs +117 -23
- package/dist/cli-registry.js +5 -0
- package/dist/modules/registry.js +2 -2
- package/package.json +1 -1
|
@@ -29,6 +29,21 @@ export interface RecordingMeta {
|
|
|
29
29
|
title: string;
|
|
30
30
|
}[];
|
|
31
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* What a watched page can make the Hook keep. Its URL, title and navigations
|
|
34
|
+
* are the page's to choose, so each is cut to a size and the lists to a length:
|
|
35
|
+
* the metadata file, rewritten whole on every change, stays under about 1 MB.
|
|
36
|
+
*/
|
|
37
|
+
export declare const RECORDING_LIMITS: {
|
|
38
|
+
readonly url: 1024;
|
|
39
|
+
readonly title: 200;
|
|
40
|
+
readonly reason: 1024;
|
|
41
|
+
readonly navigations: 500;
|
|
42
|
+
readonly navigationsPerSecond: 10;
|
|
43
|
+
readonly pages: 100;
|
|
44
|
+
readonly handoffs: 500;
|
|
45
|
+
readonly saveEveryMs: 1000;
|
|
46
|
+
};
|
|
32
47
|
interface IndexFrame {
|
|
33
48
|
t: number;
|
|
34
49
|
pageId: string;
|
|
@@ -44,6 +59,10 @@ export declare class BrowserRecordings {
|
|
|
44
59
|
constructor(root: string);
|
|
45
60
|
private dir;
|
|
46
61
|
private save;
|
|
62
|
+
/** Frames arrive up to four times a second; their counters reach the file at most once a second, and at the end. */
|
|
63
|
+
private saveSoon;
|
|
64
|
+
private saveNow;
|
|
65
|
+
private forget;
|
|
47
66
|
start(hello: Hello, now?: number): void;
|
|
48
67
|
page(page: PageInfo, now?: number): void;
|
|
49
68
|
frame(info: FrameInfo, jpeg: Buffer): void;
|
|
@@ -2,6 +2,12 @@ import * as fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { BridgeError } from "./protocol.js";
|
|
4
4
|
import { BROWSER_ID } from "./browser-protocol.js";
|
|
5
|
+
/**
|
|
6
|
+
* What a watched page can make the Hook keep. Its URL, title and navigations
|
|
7
|
+
* are the page's to choose, so each is cut to a size and the lists to a length:
|
|
8
|
+
* the metadata file, rewritten whole on every change, stays under about 1 MB.
|
|
9
|
+
*/
|
|
10
|
+
export const RECORDING_LIMITS = { url: 1024, title: 200, reason: 1024, navigations: 500, navigationsPerSecond: 10, pages: 100, handoffs: 500, saveEveryMs: 1000 };
|
|
5
11
|
export function browserId(value) {
|
|
6
12
|
if (!value || !BROWSER_ID.test(value))
|
|
7
13
|
throw new BridgeError(400, "Invalid browser identifier.");
|
|
@@ -20,6 +26,30 @@ export class BrowserRecordings {
|
|
|
20
26
|
fs.writeFileSync(path.join(dir, "meta.tmp"), JSON.stringify(meta), { mode: 0o600 });
|
|
21
27
|
fs.renameSync(path.join(dir, "meta.tmp"), path.join(dir, "meta.json"));
|
|
22
28
|
}
|
|
29
|
+
/** Frames arrive up to four times a second; their counters reach the file at most once a second, and at the end. */
|
|
30
|
+
saveSoon(state) {
|
|
31
|
+
const wait = state.savedAt + RECORDING_LIMITS.saveEveryMs - Date.now();
|
|
32
|
+
if (wait <= 0) {
|
|
33
|
+
this.saveNow(state);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
state.timer ??= setTimeout(() => {
|
|
37
|
+
state.timer = undefined;
|
|
38
|
+
// Retention may have removed the recording meanwhile.
|
|
39
|
+
if (this.active.get(state.meta.id) === state)
|
|
40
|
+
try {
|
|
41
|
+
this.saveNow(state);
|
|
42
|
+
}
|
|
43
|
+
catch { /* the folder is gone */ }
|
|
44
|
+
}, wait).unref();
|
|
45
|
+
}
|
|
46
|
+
saveNow(state) {
|
|
47
|
+
clearTimeout(state.timer);
|
|
48
|
+
state.timer = undefined;
|
|
49
|
+
this.save(state.meta);
|
|
50
|
+
state.savedAt = Date.now();
|
|
51
|
+
}
|
|
52
|
+
forget(id) { clearTimeout(this.active.get(id)?.timer); this.active.delete(id); }
|
|
23
53
|
start(hello, now = Date.now()) {
|
|
24
54
|
const dir = this.dir(hello.browserId);
|
|
25
55
|
fs.mkdirSync(dir, { mode: 0o700 }); // never overwrite an earlier recording
|
|
@@ -27,28 +57,42 @@ export class BrowserRecordings {
|
|
|
27
57
|
fs.writeFileSync(path.join(dir, "index.jsonl"), "", { mode: 0o600 });
|
|
28
58
|
const meta = { id: hello.browserId, browserId: hello.browserId, session: hello.session, cwd: hello.cwd, engine: hello.engine, headless: hello.headless, startedAt: now, endedAt: null, frames: 0, bytes: 0, pages: [], navigations: [], handoffs: [] };
|
|
29
59
|
this.save(meta);
|
|
30
|
-
this.active.set(meta.id, { meta, last: new Map() });
|
|
60
|
+
this.active.set(meta.id, { meta, last: new Map(), savedAt: Date.now(), second: 0, inSecond: 0 });
|
|
31
61
|
}
|
|
32
62
|
page(page, now = Date.now()) {
|
|
33
63
|
const state = this.active.get(page.browserId);
|
|
34
64
|
if (!state)
|
|
35
65
|
return;
|
|
36
|
-
const nav = { t: now, pageId: page.pageId, url: page.url, title: page.title };
|
|
66
|
+
const nav = { t: now, pageId: page.pageId, url: page.url.slice(0, RECORDING_LIMITS.url), title: page.title.slice(0, RECORDING_LIMITS.title) };
|
|
37
67
|
const previous = state.meta.navigations.filter(n => n.pageId === page.pageId).at(-1);
|
|
38
|
-
if (previous?.url ===
|
|
68
|
+
if (previous?.url === nav.url && previous.title === nav.title)
|
|
39
69
|
return;
|
|
40
70
|
const existing = state.meta.pages.find(p => p.pageId === page.pageId);
|
|
41
71
|
// A copy: the page entry follows the latest navigation, the timeline keeps each one as it was.
|
|
42
72
|
if (existing)
|
|
43
73
|
Object.assign(existing, { url: nav.url, title: nav.title });
|
|
44
|
-
else
|
|
74
|
+
else if (state.meta.pages.length < RECORDING_LIMITS.pages)
|
|
45
75
|
state.meta.pages.push({ ...nav });
|
|
46
|
-
// The shim announces a navigation before its title loads; the title then completes that entry.
|
|
47
|
-
if (previous?.url === page.url && !previous.title)
|
|
48
|
-
previous.title = page.title;
|
|
49
76
|
else
|
|
77
|
+
return;
|
|
78
|
+
// The shim announces a navigation before its title loads; the title then completes that entry.
|
|
79
|
+
if (previous?.url === nav.url && !previous.title)
|
|
80
|
+
previous.title = nav.title;
|
|
81
|
+
else {
|
|
82
|
+
// A page that navigates in a loop fills neither the timeline nor the disk:
|
|
83
|
+
// past the limits the page entry still follows it, the timeline does not.
|
|
84
|
+
const second = Math.floor(now / 1000);
|
|
85
|
+
if (state.second !== second) {
|
|
86
|
+
state.second = second;
|
|
87
|
+
state.inSecond = 0;
|
|
88
|
+
}
|
|
89
|
+
if (state.meta.navigations.length >= RECORDING_LIMITS.navigations || ++state.inSecond > RECORDING_LIMITS.navigationsPerSecond) {
|
|
90
|
+
this.saveSoon(state);
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
50
93
|
state.meta.navigations.push(nav);
|
|
51
|
-
|
|
94
|
+
}
|
|
95
|
+
this.saveNow(state);
|
|
52
96
|
}
|
|
53
97
|
frame(info, jpeg) {
|
|
54
98
|
const state = this.active.get(info.browserId);
|
|
@@ -67,22 +111,24 @@ export class BrowserRecordings {
|
|
|
67
111
|
state.meta.bytes += jpeg.length;
|
|
68
112
|
state.meta.frames++;
|
|
69
113
|
state.last.set(info.pageId, { t: info.t, jpeg });
|
|
70
|
-
this.
|
|
114
|
+
this.saveSoon(state);
|
|
71
115
|
}
|
|
72
116
|
handoff(id, kind, reason) {
|
|
73
117
|
const state = this.active.get(id);
|
|
74
118
|
if (!state)
|
|
75
119
|
return;
|
|
76
|
-
state.meta.handoffs.
|
|
77
|
-
|
|
120
|
+
if (state.meta.handoffs.length >= RECORDING_LIMITS.handoffs)
|
|
121
|
+
return;
|
|
122
|
+
state.meta.handoffs.push({ t: Date.now(), kind, ...(reason ? { reason: reason.slice(0, RECORDING_LIMITS.reason) } : {}) });
|
|
123
|
+
this.saveNow(state);
|
|
78
124
|
}
|
|
79
125
|
end(id, now = Date.now()) {
|
|
80
126
|
const state = this.active.get(id);
|
|
81
127
|
if (!state)
|
|
82
128
|
return;
|
|
83
129
|
state.meta.endedAt = now;
|
|
84
|
-
this.
|
|
85
|
-
this.
|
|
130
|
+
this.saveNow(state);
|
|
131
|
+
this.forget(id);
|
|
86
132
|
}
|
|
87
133
|
list() {
|
|
88
134
|
return fs.readdirSync(this.root).filter(id => BROWSER_ID.test(id)).flatMap(id => {
|
|
@@ -97,7 +143,14 @@ export class BrowserRecordings {
|
|
|
97
143
|
index(id) {
|
|
98
144
|
const dir = this.dir(id);
|
|
99
145
|
try {
|
|
100
|
-
return { meta: JSON.parse(fs.readFileSync(path.join(dir, "meta.json"), "utf8")),
|
|
146
|
+
return { meta: JSON.parse(fs.readFileSync(path.join(dir, "meta.json"), "utf8")),
|
|
147
|
+
// A crash during an append leaves a torn last line; the complete rows before it still play.
|
|
148
|
+
frames: fs.readFileSync(path.join(dir, "index.jsonl"), "utf8").split("\n").filter(Boolean).flatMap(line => { try {
|
|
149
|
+
return [JSON.parse(line)];
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return [];
|
|
153
|
+
} }) };
|
|
101
154
|
}
|
|
102
155
|
catch {
|
|
103
156
|
throw new BridgeError(404, "Recording not found.");
|
|
@@ -128,6 +181,13 @@ export class BrowserRecordings {
|
|
|
128
181
|
recover(now = Date.now()) {
|
|
129
182
|
for (const meta of this.list())
|
|
130
183
|
if (meta.endedAt === null && !this.active.has(meta.id)) {
|
|
184
|
+
// The counters in the file can trail the frames written in the last second before the crash.
|
|
185
|
+
try {
|
|
186
|
+
const frames = this.index(meta.id).frames, final = frames.at(-1);
|
|
187
|
+
meta.frames = frames.length;
|
|
188
|
+
meta.bytes = final ? final.offset + final.length : 0;
|
|
189
|
+
}
|
|
190
|
+
catch { /* keep what the file says */ }
|
|
131
191
|
meta.endedAt = now;
|
|
132
192
|
this.save(meta);
|
|
133
193
|
}
|
|
@@ -139,7 +199,7 @@ export class BrowserRecordings {
|
|
|
139
199
|
for (const meta of all.reverse()) {
|
|
140
200
|
if (now - meta.startedAt >= 86_400_000 || total > budget) {
|
|
141
201
|
// Retention includes live recordings. Capture continues live after its expired archive is removed.
|
|
142
|
-
this.
|
|
202
|
+
this.forget(meta.id);
|
|
143
203
|
this.remove(meta.id);
|
|
144
204
|
total -= sizes.get(meta.id) ?? 0;
|
|
145
205
|
}
|
|
@@ -5,6 +5,8 @@ import path from "node:path";
|
|
|
5
5
|
import { BrowserMessageReader, browserWire } from "./browser-protocol.js";
|
|
6
6
|
import { browserSocketPath } from "./browser-socket.js";
|
|
7
7
|
import { BrowserRecordings } from "./browser-recordings.js";
|
|
8
|
+
/** Pages one browser lists, open and closed. */
|
|
9
|
+
export const MAX_PAGES = 200;
|
|
8
10
|
const MAX_INPUT_BACKLOG = 1024 * 1024;
|
|
9
11
|
export class BrowserRegistry extends EventEmitter {
|
|
10
12
|
root;
|
|
@@ -49,6 +51,13 @@ export class BrowserRegistry extends EventEmitter {
|
|
|
49
51
|
if (page && !page.live)
|
|
50
52
|
throw new Error("Closed page");
|
|
51
53
|
if (!page) {
|
|
54
|
+
// A page that opens and closes popups in a loop must not grow this list: the oldest closed pages go first.
|
|
55
|
+
while (browser.pages.length >= MAX_PAGES) {
|
|
56
|
+
const closed = browser.pages.findIndex(page => !page.live);
|
|
57
|
+
if (closed < 0)
|
|
58
|
+
throw new Error("Too many pages");
|
|
59
|
+
browser.pages.splice(closed, 1);
|
|
60
|
+
}
|
|
52
61
|
page = { id: p.pageId, url: p.url, title: p.title, width: p.width, height: p.height, live: true };
|
|
53
62
|
browser.pages.push(page);
|
|
54
63
|
}
|
|
@@ -7,6 +7,12 @@ export declare function computerKeyLine(name: string, publicKey: string): string
|
|
|
7
7
|
export declare function enrollComputer(name: string, root?: string): Promise<string>;
|
|
8
8
|
/** Accept a public key, rebuilding the restrictions rather than trusting supplied options. */
|
|
9
9
|
export declare function acceptComputer(name: string, input: string, sshDirectory?: string): Promise<void>;
|
|
10
|
+
/**
|
|
11
|
+
* Remove every authorized_keys line `matches` picks, under the enrollment lock.
|
|
12
|
+
* Returns how many lines went. Every other line, comments and blank lines
|
|
13
|
+
* included, is written back as it was.
|
|
14
|
+
*/
|
|
15
|
+
export declare function removeAuthorizedKeys(matches: (line: string) => boolean, sshDirectory?: string): Promise<number>;
|
|
10
16
|
/**
|
|
11
17
|
* Append one authorized_keys line under a lock, refusing when `conflicts`
|
|
12
18
|
* matches an existing line and leaving an identical line in place.
|
package/dist/bridge/computers.js
CHANGED
|
@@ -79,6 +79,44 @@ export async function acceptComputer(name, input, sshDirectory = path.join(homed
|
|
|
79
79
|
const encoded = publicKey.split(" ")[1];
|
|
80
80
|
await appendAuthorizedKey(line, existing => existing.endsWith(` phren-computer:${name}`) || existing.split(/\s+/).includes(encoded), "This name or key is already enrolled differently. Revoke the old line explicitly first.", sshDirectory);
|
|
81
81
|
}
|
|
82
|
+
/**
|
|
83
|
+
* Remove every authorized_keys line `matches` picks, under the enrollment lock.
|
|
84
|
+
* Returns how many lines went. Every other line, comments and blank lines
|
|
85
|
+
* included, is written back as it was.
|
|
86
|
+
*/
|
|
87
|
+
export async function removeAuthorizedKeys(matches, sshDirectory = path.join(homedir(), ".ssh")) {
|
|
88
|
+
const directory = await lstat(sshDirectory).catch(() => undefined);
|
|
89
|
+
if (!directory)
|
|
90
|
+
return 0;
|
|
91
|
+
if (!directory.isDirectory() || directory.isSymbolicLink())
|
|
92
|
+
throw new BridgeError(409, "Refusing an unexpected SSH directory.");
|
|
93
|
+
const lock = path.join(sshDirectory, ".phren-enroll.lock");
|
|
94
|
+
try {
|
|
95
|
+
await mkdir(lock, { mode: 0o700 });
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
throw new BridgeError(409, "SSH enrollment is already running; inspect .phren-enroll.lock if interrupted.");
|
|
99
|
+
}
|
|
100
|
+
const file = path.join(sshDirectory, "authorized_keys");
|
|
101
|
+
const temporary = path.join(lock, "authorized_keys");
|
|
102
|
+
try {
|
|
103
|
+
if (!await regularFile(file))
|
|
104
|
+
return 0;
|
|
105
|
+
const before = await readFile(file, "utf8");
|
|
106
|
+
const lines = before.split("\n");
|
|
107
|
+
const kept = lines.filter(line => !matches(line));
|
|
108
|
+
if (kept.length === lines.length)
|
|
109
|
+
return 0;
|
|
110
|
+
await writeFile(temporary, kept.join("\n"), { mode: 0o600, flag: "wx" });
|
|
111
|
+
if (await readFile(file, "utf8") !== before)
|
|
112
|
+
throw new BridgeError(409, "authorized_keys changed while removing the key. Try again.");
|
|
113
|
+
await rename(temporary, file);
|
|
114
|
+
return lines.length - kept.length;
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
await rm(lock, { recursive: true, force: true });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
82
120
|
/**
|
|
83
121
|
* Append one authorized_keys line under a lock, refusing when `conflicts`
|
|
84
122
|
* matches an existing line and leaving an identical line in place.
|
package/dist/bridge/pair.d.ts
CHANGED
|
@@ -57,7 +57,7 @@ export interface PairingApproval {
|
|
|
57
57
|
name?: string;
|
|
58
58
|
check: string | null;
|
|
59
59
|
}
|
|
60
|
-
/** Listen for one phone. Resolves once its key is authorized; rejects on timeout
|
|
60
|
+
/** Listen for one phone. Resolves once its key is authorized; rejects on timeout. */
|
|
61
61
|
export declare function startPairing(options: {
|
|
62
62
|
code: string;
|
|
63
63
|
user: string;
|
|
@@ -76,6 +76,8 @@ export declare function startPairing(options: {
|
|
|
76
76
|
* typed pairing is refused.
|
|
77
77
|
*/
|
|
78
78
|
approve?: (phone: PairingApproval) => Promise<boolean>;
|
|
79
|
+
/** Called once, when wrong codes have turned typed pairing off for this session. */
|
|
80
|
+
onTypedOff?: () => void;
|
|
79
81
|
}): Promise<PairingSession>;
|
|
80
82
|
export declare const PAIR_USAGE = "phren pair [--minutes <1-30>] [--port <n>] [--no-install] | phren pair --scope gitboy-read|gitboy-write --key <public-key-file|-> [--no-install]";
|
|
81
83
|
/** The authorized_keys line for a scoped key: no PTY, no forwarding, its own forced command. */
|
package/dist/bridge/pair.js
CHANGED
|
@@ -122,7 +122,7 @@ const request = z.object({
|
|
|
122
122
|
device: z.enum(["ios", "android"]).default("ios"), name: z.string().max(80).optional(),
|
|
123
123
|
typed: z.boolean().optional(),
|
|
124
124
|
});
|
|
125
|
-
/** Listen for one phone. Resolves once its key is authorized; rejects on timeout
|
|
125
|
+
/** Listen for one phone. Resolves once its key is authorized; rejects on timeout. */
|
|
126
126
|
export async function startPairing(options) {
|
|
127
127
|
let failures = 0, finished = false, claimed = false, timer;
|
|
128
128
|
let approvals = Promise.resolve();
|
|
@@ -150,6 +150,10 @@ export async function startPairing(options) {
|
|
|
150
150
|
throw new BridgeError(410, "Pairing is closed. Run phren pair again.");
|
|
151
151
|
if (incoming.method !== "POST" || incoming.url !== "/v1/pair")
|
|
152
152
|
throw new BridgeError(404, "Not found.");
|
|
153
|
+
// The phone apps send neither header; a web page's request always carries
|
|
154
|
+
// one. Refused before it can count as a wrong code.
|
|
155
|
+
if (incoming.headers.origin !== undefined || incoming.headers["sec-fetch-site"] !== undefined)
|
|
156
|
+
throw new BridgeError(403, "Pair from the Phren app.");
|
|
153
157
|
let size = 0;
|
|
154
158
|
const chunks = [];
|
|
155
159
|
for await (const chunk of incoming) {
|
|
@@ -163,12 +167,17 @@ export async function startPairing(options) {
|
|
|
163
167
|
const scanned = options.scanSecret !== undefined
|
|
164
168
|
&& sameProof(scanProof(options.code, options.scanSecret, "phone", publicKey), input.proof);
|
|
165
169
|
if (!scanned && !sameProof(pairingProof(options.code, "phone", publicKey), input.proof)) {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
170
|
+
// Wrong codes bound how often the short code can be guessed. They no
|
|
171
|
+
// longer close the session: anyone who could reach the port could
|
|
172
|
+
// cancel pairing with five requests. They turn typed pairing off, and a
|
|
173
|
+
// phone that scans still pairs, since the scan secret cannot be guessed.
|
|
174
|
+
if (++failures === MAX_FAILURES)
|
|
175
|
+
options.onTypedOff?.();
|
|
169
176
|
throw new BridgeError(403, "That pairing code doesn't match this computer.");
|
|
170
177
|
}
|
|
171
178
|
if (!scanned) {
|
|
179
|
+
if (failures >= MAX_FAILURES)
|
|
180
|
+
throw new BridgeError(403, "Too many wrong codes were tried on this computer. Scan the pairing code, or run phren pair again.");
|
|
172
181
|
// The code alone never authorizes a key, whatever the request says
|
|
173
182
|
// about itself: `typed` only tells a phone that will wait for the
|
|
174
183
|
// answer from an app that scanned before the scan secret existed and
|
|
@@ -392,7 +401,8 @@ export async function runPair(args, version) {
|
|
|
392
401
|
}
|
|
393
402
|
let cancelPairing = () => { };
|
|
394
403
|
const session = await startPairing({ code, user, sshPort, fingerprint, name, port, timeoutMs: minutes * 60_000, scanSecret,
|
|
395
|
-
approve: phone => askToAllow(phone, () => cancelPairing())
|
|
404
|
+
approve: phone => askToAllow(phone, () => cancelPairing()),
|
|
405
|
+
onTypedOff: () => console.log("\n⚠ Five wrong codes were tried, so typing the code is off for this pairing. Scanning still works; run phren pair again to type a code.") });
|
|
396
406
|
cancelPairing = () => session.close();
|
|
397
407
|
const url = pairingURL({ hosts, port: session.port, user, sshPort, fingerprint, code, name, secret: scanSecret });
|
|
398
408
|
const { renderUnicodeCompact } = await import("uqr");
|
|
@@ -414,7 +424,7 @@ export async function runPair(args, version) {
|
|
|
414
424
|
try {
|
|
415
425
|
const paired = await session.done;
|
|
416
426
|
console.log(`\n✓ Paired ${paired.name ?? "your phone"}. It can reach Phren Hook on ${name} as ${user}.`);
|
|
417
|
-
console.log(
|
|
427
|
+
console.log(" To remove it later, run: phren unpair");
|
|
418
428
|
return 0;
|
|
419
429
|
}
|
|
420
430
|
catch (error) {
|
package/dist/bridge/push.d.ts
CHANGED
|
@@ -112,6 +112,11 @@ export declare class ApprovalPushService {
|
|
|
112
112
|
private devices;
|
|
113
113
|
private sender?;
|
|
114
114
|
private readonly devicesFile;
|
|
115
|
+
/** Loading, registering, forgetting and dropping a gone phone each read or
|
|
116
|
+
* write the list and its file; one at a time, so an older write never lands
|
|
117
|
+
* over a newer one and a load never brings back what was just forgotten. */
|
|
118
|
+
private changes;
|
|
119
|
+
private change;
|
|
115
120
|
start(): Promise<void>;
|
|
116
121
|
/** Phones this Hook can reach: through the relay, or direct with its own key. */
|
|
117
122
|
private get reachable();
|
|
@@ -124,6 +129,10 @@ export declare class ApprovalPushService {
|
|
|
124
129
|
relay: number;
|
|
125
130
|
};
|
|
126
131
|
register(value: unknown): Promise<void>;
|
|
132
|
+
/** Drop every registration; returns how many went. Registrations carry no
|
|
133
|
+
* SSH key, so removing a phone cannot pick out its own: all go, and the
|
|
134
|
+
* phones still paired register again the next time Phren renews (hourly, on open). */
|
|
135
|
+
forgetAll(): Promise<number>;
|
|
127
136
|
/** One phone: the relay when it registered through one, otherwise direct. */
|
|
128
137
|
private send;
|
|
129
138
|
/** Until when the owner is at Phren desktop (ms epoch): approval pushes wait for the desk to go quiet. */
|
package/dist/bridge/push.js
CHANGED
|
@@ -214,8 +214,17 @@ export class ApprovalPushService {
|
|
|
214
214
|
devices = [];
|
|
215
215
|
sender;
|
|
216
216
|
devicesFile = path.join(bridgeRoot(), "push-devices.json");
|
|
217
|
+
/** Loading, registering, forgetting and dropping a gone phone each read or
|
|
218
|
+
* write the list and its file; one at a time, so an older write never lands
|
|
219
|
+
* over a newer one and a load never brings back what was just forgotten. */
|
|
220
|
+
changes = Promise.resolve();
|
|
221
|
+
change(work) {
|
|
222
|
+
const next = this.changes.then(work, work);
|
|
223
|
+
this.changes = next.catch(() => { });
|
|
224
|
+
return next;
|
|
225
|
+
}
|
|
217
226
|
async start() {
|
|
218
|
-
this.devices = await secureJSON(this.devicesFile, z.array(deviceSchema).max(16)) ?? [];
|
|
227
|
+
await this.change(async () => { this.devices = await secureJSON(this.devicesFile, z.array(deviceSchema).max(16)) ?? []; });
|
|
219
228
|
const configFile = process.env.PHREN_APNS_CONFIG || path.join(bridgeRoot(), "apns.json");
|
|
220
229
|
const config = await secureJSON(configFile, configSchema);
|
|
221
230
|
if (!config)
|
|
@@ -234,16 +243,31 @@ export class ApprovalPushService {
|
|
|
234
243
|
devices: this.devices.length, relay };
|
|
235
244
|
}
|
|
236
245
|
async register(value) {
|
|
237
|
-
this.
|
|
238
|
-
|
|
246
|
+
await this.change(async () => {
|
|
247
|
+
this.devices = upsertPushDevice(this.devices, value);
|
|
248
|
+
await atomic(this.devicesFile, JSON.stringify(this.devices));
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
/** Drop every registration; returns how many went. Registrations carry no
|
|
252
|
+
* SSH key, so removing a phone cannot pick out its own: all go, and the
|
|
253
|
+
* phones still paired register again the next time Phren renews (hourly, on open). */
|
|
254
|
+
async forgetAll() {
|
|
255
|
+
return this.change(async () => {
|
|
256
|
+
const removed = this.devices.length;
|
|
257
|
+
this.devices = [];
|
|
258
|
+
await atomic(this.devicesFile, JSON.stringify(this.devices));
|
|
259
|
+
return removed;
|
|
260
|
+
});
|
|
239
261
|
}
|
|
240
262
|
/** One phone: the relay when it registered through one, otherwise direct. */
|
|
241
263
|
async send(device, payload, headers) {
|
|
242
264
|
if (device.relay) {
|
|
243
265
|
const result = await sendThroughRelay(device.relay, payload, headers);
|
|
244
266
|
if (result === "gone") {
|
|
245
|
-
|
|
246
|
-
|
|
267
|
+
await this.change(async () => {
|
|
268
|
+
this.devices = this.devices.filter(item => item.deviceID !== device.deviceID);
|
|
269
|
+
await atomic(this.devicesFile, JSON.stringify(this.devices));
|
|
270
|
+
}).catch(() => { });
|
|
247
271
|
}
|
|
248
272
|
return result === "sent";
|
|
249
273
|
}
|
|
@@ -1320,9 +1320,18 @@ export function createRouteHandler(ctx) {
|
|
|
1320
1320
|
}
|
|
1321
1321
|
else if (url.pathname === "/v1/push/register") {
|
|
1322
1322
|
// Registration is kept for when a key is added; the reply says whether push works now.
|
|
1323
|
+
// The owner's phone only: a linked computer or an agent must not add a destination for this computer's alerts.
|
|
1324
|
+
if (!ownerRequest(request, data))
|
|
1325
|
+
throw new BridgeError(403, "Only the owner's phone registers for notifications.");
|
|
1323
1326
|
await agentHooks.push.register(data);
|
|
1324
1327
|
result = { ok: true, configured: agentHooks.push.status.configured };
|
|
1325
1328
|
}
|
|
1329
|
+
else if (url.pathname === "/v1/push/forget") {
|
|
1330
|
+
// `phren unpair` ends a removed phone's notifications with this.
|
|
1331
|
+
if (!ownerRequest(request, data))
|
|
1332
|
+
throw new BridgeError(403, "Only the owner removes notification registrations.");
|
|
1333
|
+
result = { ok: true, removed: await agentHooks.push.forgetAll() };
|
|
1334
|
+
}
|
|
1326
1335
|
else if (url.pathname === "/v1/sudo/answer") {
|
|
1327
1336
|
// The owner answers from the phone; an agent's call names its pane and
|
|
1328
1337
|
// a peer computer's arrives through its key's scope.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export declare const UNPAIR_USAGE = "phren unpair [<number> | SHA256:<fingerprint> | --all | --notifications]";
|
|
2
|
+
export interface PhoneKey {
|
|
3
|
+
line: string;
|
|
4
|
+
device: "ios" | "android";
|
|
5
|
+
fingerprint: string;
|
|
6
|
+
}
|
|
7
|
+
/** The phone keys `phren pair` and the phone's password sign-in wrote, in file order. */
|
|
8
|
+
export declare function phoneKeys(authorizedKeys: string): PhoneKey[];
|
|
9
|
+
export interface ProcessRow {
|
|
10
|
+
pid: number;
|
|
11
|
+
ppid: number;
|
|
12
|
+
uid: number;
|
|
13
|
+
command: string;
|
|
14
|
+
}
|
|
15
|
+
export declare function parseProcessRows(output: string): ProcessRow[];
|
|
16
|
+
/**
|
|
17
|
+
* The SSH connections to end after a key is removed. sshd does not say which
|
|
18
|
+
* key opened a connection, and one that is already open keeps working without
|
|
19
|
+
* its authorized_keys line: it can open the Hook pipe again at any time. So
|
|
20
|
+
* every connection of this user that runs nothing but the Phren gateway, or
|
|
21
|
+
* nothing at all, is ended; the phones and computers still enrolled reconnect.
|
|
22
|
+
* A connection running anything else (a login shell, an editor's server, this
|
|
23
|
+
* command itself) is left alone.
|
|
24
|
+
*/
|
|
25
|
+
export declare function gatewayConnections(rows: ProcessRow[], options: {
|
|
26
|
+
uid: number;
|
|
27
|
+
root: string;
|
|
28
|
+
self: number;
|
|
29
|
+
}): {
|
|
30
|
+
sessions: number[];
|
|
31
|
+
children: number[];
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* End them; returns how many connections were ended. A sign-in that was accepted
|
|
35
|
+
* just before the key went can still be finishing, so the scan runs again after
|
|
36
|
+
* a pause until one pass finds nothing.
|
|
37
|
+
*/
|
|
38
|
+
export declare function endGatewayConnections(root?: string, pauseMs?: number): Promise<number>;
|
|
39
|
+
/**
|
|
40
|
+
* Push registrations are not tied to an SSH key, so the removed phone's cannot
|
|
41
|
+
* be told from the others: the Hook drops them all. With no Hook running, the
|
|
42
|
+
* saved list goes and the next Hook starts without it.
|
|
43
|
+
*/
|
|
44
|
+
export declare function forgetPushRegistrations(root?: string): Promise<number>;
|
|
45
|
+
export declare function runUnpair(args: string[], options?: {
|
|
46
|
+
sshDirectory?: string;
|
|
47
|
+
endConnections?: () => Promise<number>;
|
|
48
|
+
forgetPush?: () => Promise<number>;
|
|
49
|
+
}): Promise<number>;
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { readFile, rm } from "node:fs/promises";
|
|
4
|
+
import { homedir, userInfo } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { hookRequest } from "./client.js";
|
|
8
|
+
import { removeAuthorizedKeys } from "./computers.js";
|
|
9
|
+
import { forcedCommand } from "./install.js";
|
|
10
|
+
import { bridgeRoot } from "./protocol.js";
|
|
11
|
+
const exec = promisify(execFile);
|
|
12
|
+
export const UNPAIR_USAGE = "phren unpair [<number> | SHA256:<fingerprint> | --all | --notifications]";
|
|
13
|
+
const phoneLine = new RegExp(`^restrict,pty,${forcedCommand.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} ssh-ed25519 ([A-Za-z0-9+/]+={0,2}) phren-(iphone|android)\\s*$`);
|
|
14
|
+
/** The phone keys `phren pair` and the phone's password sign-in wrote, in file order. */
|
|
15
|
+
export function phoneKeys(authorizedKeys) {
|
|
16
|
+
const keys = [];
|
|
17
|
+
for (const line of authorizedKeys.split("\n")) {
|
|
18
|
+
const match = phoneLine.exec(line);
|
|
19
|
+
if (!match)
|
|
20
|
+
continue;
|
|
21
|
+
// The fingerprint `ssh-keygen -l` and the phone's key screen show.
|
|
22
|
+
const fingerprint = `SHA256:${createHash("sha256").update(Buffer.from(match[1], "base64")).digest("base64").replace(/=+$/, "")}`;
|
|
23
|
+
keys.push({ line, device: match[2] === "android" ? "android" : "ios", fingerprint });
|
|
24
|
+
}
|
|
25
|
+
return keys;
|
|
26
|
+
}
|
|
27
|
+
export function parseProcessRows(output) {
|
|
28
|
+
const rows = [];
|
|
29
|
+
for (const line of output.split("\n")) {
|
|
30
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/.exec(line);
|
|
31
|
+
if (match)
|
|
32
|
+
rows.push({ pid: Number(match[1]), ppid: Number(match[2]), uid: Number(match[3]), command: match[4] });
|
|
33
|
+
}
|
|
34
|
+
return rows;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The SSH connections to end after a key is removed. sshd does not say which
|
|
38
|
+
* key opened a connection, and one that is already open keeps working without
|
|
39
|
+
* its authorized_keys line: it can open the Hook pipe again at any time. So
|
|
40
|
+
* every connection of this user that runs nothing but the Phren gateway, or
|
|
41
|
+
* nothing at all, is ended; the phones and computers still enrolled reconnect.
|
|
42
|
+
* A connection running anything else (a login shell, an editor's server, this
|
|
43
|
+
* command itself) is left alone.
|
|
44
|
+
*/
|
|
45
|
+
export function gatewayConnections(rows, options) {
|
|
46
|
+
const byPid = new Map(rows.map(row => [row.pid, row]));
|
|
47
|
+
const ancestors = new Set();
|
|
48
|
+
for (let pid = options.self, hops = 0; pid && pid > 1 && hops < 64; pid = byPid.get(pid)?.ppid, hops++)
|
|
49
|
+
ancestors.add(pid);
|
|
50
|
+
const gateway = (command) => command.includes(`${options.root}/`) || command.includes("/.local/share/phren/bridge/dispatch");
|
|
51
|
+
// "sshd: user" before the first channel, "sshd: user@notty" or "@pts/3" after;
|
|
52
|
+
// the root-owned "[priv]" monitor fails the uid check and goes with its child.
|
|
53
|
+
// An internal-sftp child carries the same title and is someone's transfer.
|
|
54
|
+
const session = /^sshd(?:-session)?: [^\s@]+(?:@(?!internal-sftp)\S+)?\s*$/;
|
|
55
|
+
const sessions = [], children = [];
|
|
56
|
+
for (const row of rows) {
|
|
57
|
+
if (row.uid !== options.uid || ancestors.has(row.pid) || !session.test(row.command))
|
|
58
|
+
continue;
|
|
59
|
+
const own = rows.filter(child => child.ppid === row.pid);
|
|
60
|
+
if (!own.every(child => child.uid === options.uid && gateway(child.command)))
|
|
61
|
+
continue;
|
|
62
|
+
sessions.push(row.pid);
|
|
63
|
+
children.push(...own.map(child => child.pid));
|
|
64
|
+
}
|
|
65
|
+
return { sessions, children };
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* End them; returns how many connections were ended. A sign-in that was accepted
|
|
69
|
+
* just before the key went can still be finishing, so the scan runs again after
|
|
70
|
+
* a pause until one pass finds nothing.
|
|
71
|
+
*/
|
|
72
|
+
export async function endGatewayConnections(root = bridgeRoot(), pauseMs = 1500) {
|
|
73
|
+
let ended = 0;
|
|
74
|
+
for (let pass = 0; pass < 4; pass++) {
|
|
75
|
+
if (pass)
|
|
76
|
+
await new Promise(resolve => setTimeout(resolve, pauseMs));
|
|
77
|
+
const { stdout } = await exec("ps", ["-Aww", "-o", "pid=,ppid=,uid=,command="], { timeout: 5000, maxBuffer: 16_777_216 });
|
|
78
|
+
const { sessions, children } = gatewayConnections(parseProcessRows(stdout), { uid: userInfo().uid, root, self: process.pid });
|
|
79
|
+
if (pass && !sessions.length)
|
|
80
|
+
break;
|
|
81
|
+
for (const pid of children) {
|
|
82
|
+
try {
|
|
83
|
+
process.kill(pid, "SIGTERM");
|
|
84
|
+
}
|
|
85
|
+
catch { /* already gone */ }
|
|
86
|
+
}
|
|
87
|
+
for (const pid of sessions) {
|
|
88
|
+
try {
|
|
89
|
+
process.kill(pid, "SIGTERM");
|
|
90
|
+
ended++;
|
|
91
|
+
}
|
|
92
|
+
catch { /* already gone */ }
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return ended;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Push registrations are not tied to an SSH key, so the removed phone's cannot
|
|
99
|
+
* be told from the others: the Hook drops them all. With no Hook running, the
|
|
100
|
+
* saved list goes and the next Hook starts without it.
|
|
101
|
+
*/
|
|
102
|
+
export async function forgetPushRegistrations(root = bridgeRoot()) {
|
|
103
|
+
try {
|
|
104
|
+
const reply = await hookRequest("/v1/push/forget", {}, undefined, 10_000);
|
|
105
|
+
return typeof reply.removed === "number" ? reply.removed : 0;
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
const code = error.code;
|
|
109
|
+
if (code !== "ENOENT" && code !== "ECONNREFUSED")
|
|
110
|
+
throw error;
|
|
111
|
+
const file = path.join(root, "push-devices.json");
|
|
112
|
+
const saved = await readFile(file, "utf8").then(text => JSON.parse(text)).catch(() => []);
|
|
113
|
+
await rm(file, { force: true });
|
|
114
|
+
// A Hook that started in between may have read the list before it went: ask again.
|
|
115
|
+
// One that starts after this finds no file.
|
|
116
|
+
const late = await hookRequest("/v1/push/forget", {}, undefined, 10_000).then(reply => typeof reply.removed === "number" ? reply.removed : 0, () => 0);
|
|
117
|
+
return Math.max(Array.isArray(saved) ? saved.length : 0, late);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const deviceName = (key) => key.device === "android" ? "Android phone" : "iPhone";
|
|
121
|
+
export async function runUnpair(args, options = {}) {
|
|
122
|
+
if (args.length > 1 || args[0] === "--help" || args[0] === "-h") {
|
|
123
|
+
console.error(`Usage: ${UNPAIR_USAGE}`);
|
|
124
|
+
return 1;
|
|
125
|
+
}
|
|
126
|
+
if (!["darwin", "linux"].includes(process.platform)) {
|
|
127
|
+
console.error("phren unpair supports macOS and Linux.");
|
|
128
|
+
return 1;
|
|
129
|
+
}
|
|
130
|
+
const forgetPush = async () => {
|
|
131
|
+
try {
|
|
132
|
+
const removed = await (options.forgetPush ?? forgetPushRegistrations)();
|
|
133
|
+
console.log(removed
|
|
134
|
+
? `Removed ${removed} notification registration${removed === 1 ? "" : "s"}, so a removed phone gets no more alerts from this computer. Phones that are still paired register again within an hour of opening Phren.`
|
|
135
|
+
: "No notification registrations to remove.");
|
|
136
|
+
return 0;
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
console.error(`Could not remove notification registrations (${error.message}). A removed phone may still get alerts from this computer; run phren bridge update, then phren unpair --notifications.`);
|
|
140
|
+
return 1;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
// On its own: after a key was removed by hand, or to finish a removal whose last step failed.
|
|
144
|
+
if (args[0] === "--notifications")
|
|
145
|
+
return forgetPush();
|
|
146
|
+
const sshDirectory = options.sshDirectory ?? path.join(homedir(), ".ssh");
|
|
147
|
+
const keys = phoneKeys(await readFile(path.join(sshDirectory, "authorized_keys"), "utf8").catch(() => ""));
|
|
148
|
+
if (!keys.length) {
|
|
149
|
+
console.log("No phone is paired with this computer.");
|
|
150
|
+
return args.length ? 1 : 0;
|
|
151
|
+
}
|
|
152
|
+
if (!args.length) {
|
|
153
|
+
console.log("Phones paired with this computer:\n");
|
|
154
|
+
keys.forEach((key, index) => console.log(` ${index + 1}. ${deviceName(key)} ${key.fingerprint}`));
|
|
155
|
+
console.log("");
|
|
156
|
+
console.log(`Remove one with: phren unpair <number> (or its fingerprint, or --all)`);
|
|
157
|
+
return 0;
|
|
158
|
+
}
|
|
159
|
+
const target = args[0];
|
|
160
|
+
const chosen = target === "--all" ? keys
|
|
161
|
+
: /^[1-9][0-9]{0,3}$/.test(target) ? keys.slice(Number(target) - 1, Number(target))
|
|
162
|
+
: keys.filter(key => key.fingerprint === target);
|
|
163
|
+
if (!chosen.length) {
|
|
164
|
+
console.error(`No paired phone matches ${target}. Run phren unpair to list them.`);
|
|
165
|
+
return 1;
|
|
166
|
+
}
|
|
167
|
+
const lines = new Set(chosen.map(key => key.line));
|
|
168
|
+
const removed = await removeAuthorizedKeys(line => lines.has(line), sshDirectory);
|
|
169
|
+
if (!removed) {
|
|
170
|
+
console.error("The key was already gone. Run phren unpair to list what is paired now.");
|
|
171
|
+
return 1;
|
|
172
|
+
}
|
|
173
|
+
console.log(`Removed ${removed === 1 ? `the ${deviceName(chosen[0])} key ${chosen[0].fingerprint}` : `${removed} phone keys`}. It can no longer sign in.`);
|
|
174
|
+
try {
|
|
175
|
+
const ended = await (options.endConnections ?? endGatewayConnections)();
|
|
176
|
+
console.log(ended
|
|
177
|
+
? `Ended ${ended} open Phren connection${ended === 1 ? "" : "s"}, so a connection the removed phone still held is closed. Phones and computers that are still paired reconnect on their own.`
|
|
178
|
+
: "No open Phren connections to end.");
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
console.error(`Could not end open connections (${error.message}). A connection the phone already had open may keep working until it drops; restart SSH or this computer to be sure.`);
|
|
182
|
+
return 1;
|
|
183
|
+
}
|
|
184
|
+
return forgetPush();
|
|
185
|
+
}
|
package/dist/bridge-hook.mjs
CHANGED
|
@@ -39521,7 +39521,7 @@ var init_package_metadata = __esm({
|
|
|
39521
39521
|
__dirname = path41.dirname(fileURLToPath3(import.meta.url));
|
|
39522
39522
|
ROOT = path41.join(__dirname, "..");
|
|
39523
39523
|
PACKAGE_JSON_PATH = path41.join(ROOT, "package.json");
|
|
39524
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
39524
|
+
BUNDLED_VERSION = true ? "0.3.76" : "0.0.0";
|
|
39525
39525
|
PACKAGE_JSON = readPackageJson();
|
|
39526
39526
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
39527
39527
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -42184,6 +42184,7 @@ var init_registry = __esm({
|
|
|
42184
42184
|
"bridge serve",
|
|
42185
42185
|
"bridge ssh",
|
|
42186
42186
|
"pair",
|
|
42187
|
+
"unpair",
|
|
42187
42188
|
"bridge fanouts archive",
|
|
42188
42189
|
"bridge accounts",
|
|
42189
42190
|
"bridge askpass",
|
|
@@ -42253,6 +42254,7 @@ var init_registry = __esm({
|
|
|
42253
42254
|
]),
|
|
42254
42255
|
...routes("POST", [
|
|
42255
42256
|
"/v1/push/register",
|
|
42257
|
+
"/v1/push/forget",
|
|
42256
42258
|
"/v1/push/answer",
|
|
42257
42259
|
"/v1/push/target",
|
|
42258
42260
|
"/v1/push/presence",
|
|
@@ -67038,12 +67040,13 @@ function browserId(value2) {
|
|
|
67038
67040
|
if (!value2 || !BROWSER_ID.test(value2)) throw new BridgeError(400, "Invalid browser identifier.");
|
|
67039
67041
|
return value2;
|
|
67040
67042
|
}
|
|
67041
|
-
var BrowserRecordings;
|
|
67043
|
+
var RECORDING_LIMITS, BrowserRecordings;
|
|
67042
67044
|
var init_browser_recordings = __esm({
|
|
67043
67045
|
"src/bridge/browser-recordings.ts"() {
|
|
67044
67046
|
"use strict";
|
|
67045
67047
|
init_protocol();
|
|
67046
67048
|
init_browser_protocol();
|
|
67049
|
+
RECORDING_LIMITS = { url: 1024, title: 200, reason: 1024, navigations: 500, navigationsPerSecond: 10, pages: 100, handoffs: 500, saveEveryMs: 1e3 };
|
|
67047
67050
|
BrowserRecordings = class {
|
|
67048
67051
|
constructor(root) {
|
|
67049
67052
|
this.root = root;
|
|
@@ -67059,6 +67062,31 @@ var init_browser_recordings = __esm({
|
|
|
67059
67062
|
fs47.writeFileSync(path109.join(dir, "meta.tmp"), JSON.stringify(meta3), { mode: 384 });
|
|
67060
67063
|
fs47.renameSync(path109.join(dir, "meta.tmp"), path109.join(dir, "meta.json"));
|
|
67061
67064
|
}
|
|
67065
|
+
/** Frames arrive up to four times a second; their counters reach the file at most once a second, and at the end. */
|
|
67066
|
+
saveSoon(state) {
|
|
67067
|
+
const wait = state.savedAt + RECORDING_LIMITS.saveEveryMs - Date.now();
|
|
67068
|
+
if (wait <= 0) {
|
|
67069
|
+
this.saveNow(state);
|
|
67070
|
+
return;
|
|
67071
|
+
}
|
|
67072
|
+
state.timer ??= setTimeout(() => {
|
|
67073
|
+
state.timer = void 0;
|
|
67074
|
+
if (this.active.get(state.meta.id) === state) try {
|
|
67075
|
+
this.saveNow(state);
|
|
67076
|
+
} catch {
|
|
67077
|
+
}
|
|
67078
|
+
}, wait).unref();
|
|
67079
|
+
}
|
|
67080
|
+
saveNow(state) {
|
|
67081
|
+
clearTimeout(state.timer);
|
|
67082
|
+
state.timer = void 0;
|
|
67083
|
+
this.save(state.meta);
|
|
67084
|
+
state.savedAt = Date.now();
|
|
67085
|
+
}
|
|
67086
|
+
forget(id3) {
|
|
67087
|
+
clearTimeout(this.active.get(id3)?.timer);
|
|
67088
|
+
this.active.delete(id3);
|
|
67089
|
+
}
|
|
67062
67090
|
start(hello, now = Date.now()) {
|
|
67063
67091
|
const dir = this.dir(hello.browserId);
|
|
67064
67092
|
fs47.mkdirSync(dir, { mode: 448 });
|
|
@@ -67066,20 +67094,32 @@ var init_browser_recordings = __esm({
|
|
|
67066
67094
|
fs47.writeFileSync(path109.join(dir, "index.jsonl"), "", { mode: 384 });
|
|
67067
67095
|
const meta3 = { id: hello.browserId, browserId: hello.browserId, session: hello.session, cwd: hello.cwd, engine: hello.engine, headless: hello.headless, startedAt: now, endedAt: null, frames: 0, bytes: 0, pages: [], navigations: [], handoffs: [] };
|
|
67068
67096
|
this.save(meta3);
|
|
67069
|
-
this.active.set(meta3.id, { meta: meta3, last: /* @__PURE__ */ new Map() });
|
|
67097
|
+
this.active.set(meta3.id, { meta: meta3, last: /* @__PURE__ */ new Map(), savedAt: Date.now(), second: 0, inSecond: 0 });
|
|
67070
67098
|
}
|
|
67071
67099
|
page(page, now = Date.now()) {
|
|
67072
67100
|
const state = this.active.get(page.browserId);
|
|
67073
67101
|
if (!state) return;
|
|
67074
|
-
const nav = { t: now, pageId: page.pageId, url: page.url, title: page.title };
|
|
67102
|
+
const nav = { t: now, pageId: page.pageId, url: page.url.slice(0, RECORDING_LIMITS.url), title: page.title.slice(0, RECORDING_LIMITS.title) };
|
|
67075
67103
|
const previous = state.meta.navigations.filter((n) => n.pageId === page.pageId).at(-1);
|
|
67076
|
-
if (previous?.url ===
|
|
67104
|
+
if (previous?.url === nav.url && previous.title === nav.title) return;
|
|
67077
67105
|
const existing = state.meta.pages.find((p) => p.pageId === page.pageId);
|
|
67078
67106
|
if (existing) Object.assign(existing, { url: nav.url, title: nav.title });
|
|
67079
|
-
else state.meta.pages.push({ ...nav });
|
|
67080
|
-
|
|
67081
|
-
|
|
67082
|
-
|
|
67107
|
+
else if (state.meta.pages.length < RECORDING_LIMITS.pages) state.meta.pages.push({ ...nav });
|
|
67108
|
+
else return;
|
|
67109
|
+
if (previous?.url === nav.url && !previous.title) previous.title = nav.title;
|
|
67110
|
+
else {
|
|
67111
|
+
const second = Math.floor(now / 1e3);
|
|
67112
|
+
if (state.second !== second) {
|
|
67113
|
+
state.second = second;
|
|
67114
|
+
state.inSecond = 0;
|
|
67115
|
+
}
|
|
67116
|
+
if (state.meta.navigations.length >= RECORDING_LIMITS.navigations || ++state.inSecond > RECORDING_LIMITS.navigationsPerSecond) {
|
|
67117
|
+
this.saveSoon(state);
|
|
67118
|
+
return;
|
|
67119
|
+
}
|
|
67120
|
+
state.meta.navigations.push(nav);
|
|
67121
|
+
}
|
|
67122
|
+
this.saveNow(state);
|
|
67083
67123
|
}
|
|
67084
67124
|
frame(info, jpeg) {
|
|
67085
67125
|
const state = this.active.get(info.browserId);
|
|
@@ -67094,20 +67134,21 @@ var init_browser_recordings = __esm({
|
|
|
67094
67134
|
state.meta.bytes += jpeg.length;
|
|
67095
67135
|
state.meta.frames++;
|
|
67096
67136
|
state.last.set(info.pageId, { t: info.t, jpeg });
|
|
67097
|
-
this.
|
|
67137
|
+
this.saveSoon(state);
|
|
67098
67138
|
}
|
|
67099
67139
|
handoff(id3, kind, reason3) {
|
|
67100
67140
|
const state = this.active.get(id3);
|
|
67101
67141
|
if (!state) return;
|
|
67102
|
-
state.meta.handoffs.
|
|
67103
|
-
|
|
67142
|
+
if (state.meta.handoffs.length >= RECORDING_LIMITS.handoffs) return;
|
|
67143
|
+
state.meta.handoffs.push({ t: Date.now(), kind, ...reason3 ? { reason: reason3.slice(0, RECORDING_LIMITS.reason) } : {} });
|
|
67144
|
+
this.saveNow(state);
|
|
67104
67145
|
}
|
|
67105
67146
|
end(id3, now = Date.now()) {
|
|
67106
67147
|
const state = this.active.get(id3);
|
|
67107
67148
|
if (!state) return;
|
|
67108
67149
|
state.meta.endedAt = now;
|
|
67109
|
-
this.
|
|
67110
|
-
this.
|
|
67150
|
+
this.saveNow(state);
|
|
67151
|
+
this.forget(id3);
|
|
67111
67152
|
}
|
|
67112
67153
|
list() {
|
|
67113
67154
|
return fs47.readdirSync(this.root).filter((id3) => BROWSER_ID.test(id3)).flatMap((id3) => {
|
|
@@ -67121,7 +67162,17 @@ var init_browser_recordings = __esm({
|
|
|
67121
67162
|
index(id3) {
|
|
67122
67163
|
const dir = this.dir(id3);
|
|
67123
67164
|
try {
|
|
67124
|
-
return {
|
|
67165
|
+
return {
|
|
67166
|
+
meta: JSON.parse(fs47.readFileSync(path109.join(dir, "meta.json"), "utf8")),
|
|
67167
|
+
// A crash during an append leaves a torn last line; the complete rows before it still play.
|
|
67168
|
+
frames: fs47.readFileSync(path109.join(dir, "index.jsonl"), "utf8").split("\n").filter(Boolean).flatMap((line) => {
|
|
67169
|
+
try {
|
|
67170
|
+
return [JSON.parse(line)];
|
|
67171
|
+
} catch {
|
|
67172
|
+
return [];
|
|
67173
|
+
}
|
|
67174
|
+
})
|
|
67175
|
+
};
|
|
67125
67176
|
} catch {
|
|
67126
67177
|
throw new BridgeError(404, "Recording not found.");
|
|
67127
67178
|
}
|
|
@@ -67146,6 +67197,12 @@ var init_browser_recordings = __esm({
|
|
|
67146
67197
|
/** Recover archives left open by a Hook crash before accepting new producers. */
|
|
67147
67198
|
recover(now = Date.now()) {
|
|
67148
67199
|
for (const meta3 of this.list()) if (meta3.endedAt === null && !this.active.has(meta3.id)) {
|
|
67200
|
+
try {
|
|
67201
|
+
const frames = this.index(meta3.id).frames, final = frames.at(-1);
|
|
67202
|
+
meta3.frames = frames.length;
|
|
67203
|
+
meta3.bytes = final ? final.offset + final.length : 0;
|
|
67204
|
+
} catch {
|
|
67205
|
+
}
|
|
67149
67206
|
meta3.endedAt = now;
|
|
67150
67207
|
this.save(meta3);
|
|
67151
67208
|
}
|
|
@@ -67156,7 +67213,7 @@ var init_browser_recordings = __esm({
|
|
|
67156
67213
|
let total = [...sizes.values()].reduce((a, b) => a + b, 0);
|
|
67157
67214
|
for (const meta3 of all.reverse()) {
|
|
67158
67215
|
if (now - meta3.startedAt >= 864e5 || total > budget) {
|
|
67159
|
-
this.
|
|
67216
|
+
this.forget(meta3.id);
|
|
67160
67217
|
this.remove(meta3.id);
|
|
67161
67218
|
total -= sizes.get(meta3.id) ?? 0;
|
|
67162
67219
|
}
|
|
@@ -67171,13 +67228,14 @@ import { EventEmitter as EventEmitter2 } from "node:events";
|
|
|
67171
67228
|
import * as fs48 from "node:fs/promises";
|
|
67172
67229
|
import { createServer as createServer2, connect as connect3 } from "node:net";
|
|
67173
67230
|
import path110 from "node:path";
|
|
67174
|
-
var MAX_INPUT_BACKLOG, BrowserRegistry;
|
|
67231
|
+
var MAX_PAGES, MAX_INPUT_BACKLOG, BrowserRegistry;
|
|
67175
67232
|
var init_browser_registry = __esm({
|
|
67176
67233
|
"src/bridge/browser-registry.ts"() {
|
|
67177
67234
|
"use strict";
|
|
67178
67235
|
init_browser_protocol();
|
|
67179
67236
|
init_browser_socket();
|
|
67180
67237
|
init_browser_recordings();
|
|
67238
|
+
MAX_PAGES = 200;
|
|
67181
67239
|
MAX_INPUT_BACKLOG = 1024 * 1024;
|
|
67182
67240
|
BrowserRegistry = class extends EventEmitter2 {
|
|
67183
67241
|
constructor(root) {
|
|
@@ -67220,6 +67278,11 @@ var init_browser_registry = __esm({
|
|
|
67220
67278
|
let page = browser.pages.find((page2) => page2.id === p.pageId);
|
|
67221
67279
|
if (page && !page.live) throw new Error("Closed page");
|
|
67222
67280
|
if (!page) {
|
|
67281
|
+
while (browser.pages.length >= MAX_PAGES) {
|
|
67282
|
+
const closed = browser.pages.findIndex((page2) => !page2.live);
|
|
67283
|
+
if (closed < 0) throw new Error("Too many pages");
|
|
67284
|
+
browser.pages.splice(closed, 1);
|
|
67285
|
+
}
|
|
67223
67286
|
page = { id: p.pageId, url: p.url, title: p.title, width: p.width, height: p.height, live: true };
|
|
67224
67287
|
browser.pages.push(page);
|
|
67225
67288
|
}
|
|
@@ -72493,8 +72556,20 @@ var init_push = __esm({
|
|
|
72493
72556
|
devices = [];
|
|
72494
72557
|
sender;
|
|
72495
72558
|
devicesFile = path122.join(bridgeRoot(), "push-devices.json");
|
|
72559
|
+
/** Loading, registering, forgetting and dropping a gone phone each read or
|
|
72560
|
+
* write the list and its file; one at a time, so an older write never lands
|
|
72561
|
+
* over a newer one and a load never brings back what was just forgotten. */
|
|
72562
|
+
changes = Promise.resolve();
|
|
72563
|
+
change(work) {
|
|
72564
|
+
const next = this.changes.then(work, work);
|
|
72565
|
+
this.changes = next.catch(() => {
|
|
72566
|
+
});
|
|
72567
|
+
return next;
|
|
72568
|
+
}
|
|
72496
72569
|
async start() {
|
|
72497
|
-
|
|
72570
|
+
await this.change(async () => {
|
|
72571
|
+
this.devices = await secureJSON(this.devicesFile, external_exports.array(deviceSchema).max(16)) ?? [];
|
|
72572
|
+
});
|
|
72498
72573
|
const configFile = process.env.PHREN_APNS_CONFIG || path122.join(bridgeRoot(), "apns.json");
|
|
72499
72574
|
const config4 = await secureJSON(configFile, configSchema3);
|
|
72500
72575
|
if (!config4) return;
|
|
@@ -72520,16 +72595,31 @@ var init_push = __esm({
|
|
|
72520
72595
|
};
|
|
72521
72596
|
}
|
|
72522
72597
|
async register(value2) {
|
|
72523
|
-
this.
|
|
72524
|
-
|
|
72598
|
+
await this.change(async () => {
|
|
72599
|
+
this.devices = upsertPushDevice(this.devices, value2);
|
|
72600
|
+
await atomic(this.devicesFile, JSON.stringify(this.devices));
|
|
72601
|
+
});
|
|
72602
|
+
}
|
|
72603
|
+
/** Drop every registration; returns how many went. Registrations carry no
|
|
72604
|
+
* SSH key, so removing a phone cannot pick out its own: all go, and the
|
|
72605
|
+
* phones still paired register again the next time Phren renews (hourly, on open). */
|
|
72606
|
+
async forgetAll() {
|
|
72607
|
+
return this.change(async () => {
|
|
72608
|
+
const removed = this.devices.length;
|
|
72609
|
+
this.devices = [];
|
|
72610
|
+
await atomic(this.devicesFile, JSON.stringify(this.devices));
|
|
72611
|
+
return removed;
|
|
72612
|
+
});
|
|
72525
72613
|
}
|
|
72526
72614
|
/** One phone: the relay when it registered through one, otherwise direct. */
|
|
72527
72615
|
async send(device, payload, headers) {
|
|
72528
72616
|
if (device.relay) {
|
|
72529
72617
|
const result = await sendThroughRelay(device.relay, payload, headers);
|
|
72530
72618
|
if (result === "gone") {
|
|
72531
|
-
|
|
72532
|
-
|
|
72619
|
+
await this.change(async () => {
|
|
72620
|
+
this.devices = this.devices.filter((item) => item.deviceID !== device.deviceID);
|
|
72621
|
+
await atomic(this.devicesFile, JSON.stringify(this.devices));
|
|
72622
|
+
}).catch(() => {
|
|
72533
72623
|
});
|
|
72534
72624
|
}
|
|
72535
72625
|
return result === "sent";
|
|
@@ -90110,8 +90200,12 @@ function createRouteHandler(ctx) {
|
|
|
90110
90200
|
} else if (url2.pathname === "/v1/sets/link") {
|
|
90111
90201
|
result = await linkSetMember(data, request10);
|
|
90112
90202
|
} else if (url2.pathname === "/v1/push/register") {
|
|
90203
|
+
if (!ownerRequest(request10, data)) throw new BridgeError(403, "Only the owner's phone registers for notifications.");
|
|
90113
90204
|
await agentHooks.push.register(data);
|
|
90114
90205
|
result = { ok: true, configured: agentHooks.push.status.configured };
|
|
90206
|
+
} else if (url2.pathname === "/v1/push/forget") {
|
|
90207
|
+
if (!ownerRequest(request10, data)) throw new BridgeError(403, "Only the owner removes notification registrations.");
|
|
90208
|
+
result = { ok: true, removed: await agentHooks.push.forgetAll() };
|
|
90115
90209
|
} else if (url2.pathname === "/v1/sudo/answer") {
|
|
90116
90210
|
if (!ownerRequest(request10, data)) throw new BridgeError(403, "Only the owner answers a sudo request, from the phone.");
|
|
90117
90211
|
let parsed;
|
|
@@ -92864,7 +92958,7 @@ async function main() {
|
|
|
92864
92958
|
return askpass2(args[1]);
|
|
92865
92959
|
}
|
|
92866
92960
|
const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
|
|
92867
|
-
return runBridge2(args, "0.3.
|
|
92961
|
+
return runBridge2(args, "0.3.76");
|
|
92868
92962
|
}
|
|
92869
92963
|
main().then((code) => {
|
|
92870
92964
|
process.exitCode = code;
|
package/dist/cli-registry.js
CHANGED
|
@@ -145,6 +145,11 @@ export const REGISTRY = [
|
|
|
145
145
|
{ name: "ask", usage: 'phren browser ask "<reason>" [--browser <id>] [--timeout <s>]', summary: "Wait for owner help (900 s default); Ctrl-C cancels" },
|
|
146
146
|
],
|
|
147
147
|
run: async (args) => { const { runBrowser } = await import("./bridge/browser-env.js"); return runBrowser(args); } },
|
|
148
|
+
{
|
|
149
|
+
name: "unpair", topic: "setup", usage: "phren unpair [<number> | SHA256:<fingerprint> | --all | --notifications]",
|
|
150
|
+
summary: "List the phones paired with this computer, or remove one, end its open connections and stop its notifications",
|
|
151
|
+
run: async (args) => { const { runUnpair } = await import("./bridge/unpair.js"); return runUnpair(args); },
|
|
152
|
+
},
|
|
148
153
|
{
|
|
149
154
|
name: "pair", topic: "setup", usage: "phren pair [--minutes <1-30>] [--port <n>] [--no-install] | phren pair --scope gitboy-read|gitboy-write --key <public-key-file|->",
|
|
150
155
|
summary: "Connect your phone with a pairing QR code, or authorize a scoped key for gitboy (gitboy-read: project memory; gitboy-write: save findings)",
|
package/dist/modules/registry.js
CHANGED
|
@@ -69,7 +69,7 @@ export const BUILTIN_MODULES = [
|
|
|
69
69
|
tools: [],
|
|
70
70
|
cliCommands: [
|
|
71
71
|
"bridge", "bridge install", "bridge update", "bridge uninstall", "bridge rollback", "bridge status",
|
|
72
|
-
"browser", "bridge doctor", "bridge usage", "bridge usage-statusline", "bridge hook", "bridge serve", "bridge ssh", "pair",
|
|
72
|
+
"browser", "bridge doctor", "bridge usage", "bridge usage-statusline", "bridge hook", "bridge serve", "bridge ssh", "pair", "unpair",
|
|
73
73
|
"bridge fanouts archive", "bridge accounts", "bridge askpass", "canary", "computers", "computers mcp", "usage", "sudo",
|
|
74
74
|
],
|
|
75
75
|
agentHooks: [
|
|
@@ -90,7 +90,7 @@ export const BUILTIN_MODULES = [
|
|
|
90
90
|
"/v1/subagents", "/v1/subagents/transcript", "/v1/subagents/messages", "/v1/sessions/move", "/v1/sessions/moves", "/v1/sessions/move/computers", "/v1/sessions/move/availability", "/v1/sessions/move/intent", "/v1/sessions/move/launch", "/v1/dispatch/relocation", "/v1/dispatch/arrival",
|
|
91
91
|
]),
|
|
92
92
|
...routes("POST", [
|
|
93
|
-
"/v1/push/register", "/v1/push/answer", "/v1/push/target", "/v1/push/presence", "/v1/files", "/v1/files/delete", "/v1/projects/add", "/v1/simulators/action",
|
|
93
|
+
"/v1/push/register", "/v1/push/forget", "/v1/push/answer", "/v1/push/target", "/v1/push/presence", "/v1/files", "/v1/files/delete", "/v1/projects/add", "/v1/simulators/action",
|
|
94
94
|
"/v1/workspaces/launch", "/v1/workspaces/create", "/v1/workspaces/focus", "/v1/workspaces/rename",
|
|
95
95
|
"/v1/workspaces/close", "/v1/sessions/rename", "/v1/sessions/seen", "/v1/sessions/move", "/v1/accounts/claude/add", "/v1/accounts/claude/settings", "/v1/accounts/allowed-pools", "/v1/sessions/move/abort", "/v1/sessions/move/launch", "/v1/prompt", "/v1/prompt/status", "/v1/prompt/after-turn", "/v1/prompt/after-turn/list", "/v1/prompt/after-turn/edit", "/v1/prompt/after-turn/cancel", "/v1/prompt/queue", "/v1/model", "/v1/settings", "/v1/agents/permission-mode", "/v1/side-question/dismiss", "/v1/keys", "/v1/secret", "/v1/upload",
|
|
96
96
|
"/v1/approvals/answer", "/v1/questions/answer", "/v1/subagents/resume", "/v1/subagents/archive-finished", "/v1/canary",
|