@phren/cli 0.3.75 → 0.3.77
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/approval-summary.js +12 -1
- 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/changes.d.ts +7 -0
- package/dist/bridge/changes.js +15 -3
- 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 +190 -90
- package/dist/cli-registry.js +5 -0
- package/dist/modules/registry.js +2 -2
- package/package.json +1 -1
|
@@ -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
|
+
}
|