@phren/cli 0.3.74 → 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.
@@ -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.devices = upsertPushDevice(this.devices, value);
238
- await atomic(this.devicesFile, JSON.stringify(this.devices));
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
- this.devices = this.devices.filter(item => item.deviceID !== device.deviceID);
246
- await atomic(this.devicesFile, JSON.stringify(this.devices)).catch(() => { });
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
+ }