@phren/cli 0.3.77 → 0.3.79
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/agent-hooks.d.ts +3 -0
- package/dist/bridge/agent-hooks.js +20 -11
- package/dist/bridge/command.js +1 -1
- package/dist/bridge/files.d.ts +1 -1
- package/dist/bridge/hook-main.js +4 -0
- package/dist/bridge/owner-proof.d.ts +41 -0
- package/dist/bridge/owner-proof.js +118 -0
- package/dist/bridge/secret.d.ts +161 -0
- package/dist/bridge/secret.js +485 -0
- package/dist/bridge/server-overview.d.ts +9 -2
- package/dist/bridge/server-overview.js +10 -3
- package/dist/bridge/server-routes.d.ts +2 -0
- package/dist/bridge/server-routes.js +28 -2
- package/dist/bridge/server.js +2 -1
- package/dist/bridge/sudo.d.ts +21 -0
- package/dist/bridge/sudo.js +6 -6
- package/dist/bridge-hook.mjs +2766 -2128
- package/dist/cli-registry.js +5 -0
- package/dist/modules/registry.js +4 -4
- package/package.json +1 -1
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { EventEmitter } from "node:events";
|
|
4
|
+
import { readdir, readlink } from "node:fs/promises";
|
|
5
|
+
import { readlinkSync } from "node:fs";
|
|
6
|
+
import { request } from "node:http";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { promisify } from "node:util";
|
|
9
|
+
import { bridgeRoot, object } from "./protocol.js";
|
|
10
|
+
import { localSocket } from "./agent-hook-stores.js";
|
|
11
|
+
import { terminalPaneFromEnv } from "./terminal.js";
|
|
12
|
+
import { briefId } from "./launch-brief.js";
|
|
13
|
+
import { askpassInstalled, askpassPath, connectionHolders, deliverToListener, deliveryFrom, deliveryListener, listenerHolders, listeningInode, placeFrom, PRELOADS, processStart, readProcess, SUDO_HOLD_MS, userName, } from "./sudo.js";
|
|
14
|
+
/**
|
|
15
|
+
* A secret typed on the phone, handed to one command's stdin.
|
|
16
|
+
*
|
|
17
|
+
* `phren secret-exec [--prompt <text>] [--plist <key> [--field K=V]...] -- <command...>`
|
|
18
|
+
* starts the command with a fresh pipe on its stdin, then runs the Hook's
|
|
19
|
+
* askpass script (`<bridge>/askpass --secret-exec`) with its stdout on that
|
|
20
|
+
* same pipe and closes its own copy. The askpass helper asks the Hook over
|
|
21
|
+
* agent.sock, as `sudo -A`'s does, and writes what the phone sends (one line,
|
|
22
|
+
* or a plist with the secret under `<key>`) into the pipe. The agent that ran
|
|
23
|
+
* secret-exec never holds the pipe, so the secret reaches the command and
|
|
24
|
+
* nothing else: not the agent's stdout, stderr, logs or transcript.
|
|
25
|
+
*
|
|
26
|
+
* Before asking the phone the Hook checks the chain (`verifySecretAsker`): the
|
|
27
|
+
* helper is this Hook's node running its bundle as `askpass --secret-exec`
|
|
28
|
+
* with nothing that loads other code, its parent is the installed script,
|
|
29
|
+
* that script has exactly one sibling (the command), and the helper's stdout
|
|
30
|
+
* is a pipe that no process of the owner's reads except that command and its
|
|
31
|
+
* descendants. The connection is bound to the helper the same way sudo's is.
|
|
32
|
+
* The Hook reads the command line itself (never what the caller claims) and
|
|
33
|
+
* the phone shows it, the prompt, the stdin format and the session asking,
|
|
34
|
+
* and needs an approval per run. The secret is never logged, stored or kept
|
|
35
|
+
* past the write. Only phones that subscribe to `secrets` frames can answer
|
|
36
|
+
* (an older app never sees these requests); with none open the request is
|
|
37
|
+
* refused at once.
|
|
38
|
+
*/
|
|
39
|
+
export const SECRET_FLAG = "--secret-exec";
|
|
40
|
+
export const MAX_SECRET_PENDING = 4;
|
|
41
|
+
export const SECRET_SPEC_ENV = "PHREN_SECRET_SPEC";
|
|
42
|
+
const plistKey = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
43
|
+
const printable = (value, max) => typeof value === "string" && value.length >= 1 && value.length <= max && !/[\x00-\x1f\x7f]/.test(value);
|
|
44
|
+
/** A spec from the helper's request, or undefined when anything is off. */
|
|
45
|
+
export function secretSpec(value) {
|
|
46
|
+
const item = object(value);
|
|
47
|
+
if (item.prompt !== undefined && !printable(item.prompt, 200))
|
|
48
|
+
return undefined;
|
|
49
|
+
const prompt = item.prompt;
|
|
50
|
+
if (item.format === "line" && item.key === undefined && item.fields === undefined)
|
|
51
|
+
return { ...(prompt ? { prompt } : {}), format: "line" };
|
|
52
|
+
if (item.format !== "plist" || typeof item.key !== "string" || !plistKey.test(item.key))
|
|
53
|
+
return undefined;
|
|
54
|
+
const fields = {};
|
|
55
|
+
if (item.fields !== undefined) {
|
|
56
|
+
const raw = object(item.fields);
|
|
57
|
+
if (Array.isArray(item.fields) || Object.keys(raw).length > 16)
|
|
58
|
+
return undefined;
|
|
59
|
+
for (const [name, field] of Object.entries(raw)) {
|
|
60
|
+
if (!plistKey.test(name) || name === item.key || !printable(field, 256))
|
|
61
|
+
return undefined;
|
|
62
|
+
fields[name] = field;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return { ...(prompt ? { prompt } : {}), format: "plist", key: item.key, ...(Object.keys(fields).length ? { fields } : {}) };
|
|
66
|
+
}
|
|
67
|
+
const xml = (value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
68
|
+
/** What the command reads on stdin. */
|
|
69
|
+
export function secretPayload(spec, secret) {
|
|
70
|
+
if (spec.format === "line")
|
|
71
|
+
return `${secret}\n`;
|
|
72
|
+
const entries = [...Object.entries(spec.fields ?? {}), [spec.key, secret]]
|
|
73
|
+
.map(([name, value]) => `\t<key>${xml(name)}</key>\n\t<string>${xml(value)}</string>\n`).join("");
|
|
74
|
+
return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n<dict>\n${entries}</dict>\n</plist>\n`;
|
|
75
|
+
}
|
|
76
|
+
/** A secret as the phone may send it: one line, nothing a listener would cut. */
|
|
77
|
+
export const validSecret = (value) => typeof value === "string" && value.length >= 1 && value.length <= 1_024 && !/[\x00\n\r]/.test(value);
|
|
78
|
+
const exec = promisify(execFile);
|
|
79
|
+
/** Every process's parent, from `ps`. */
|
|
80
|
+
export async function processTable() {
|
|
81
|
+
const { stdout } = await exec("ps", ["-A", "-o", "pid=", "-o", "ppid="], { timeout: 5_000, maxBuffer: 16 * 1_048_576 });
|
|
82
|
+
const table = new Map();
|
|
83
|
+
for (const row of stdout.split("\n")) {
|
|
84
|
+
const match = /^\s*(\d+)\s+(\d+)\s*$/.exec(row);
|
|
85
|
+
if (match)
|
|
86
|
+
table.set(Number(match[1]), Number(match[2]));
|
|
87
|
+
}
|
|
88
|
+
return table;
|
|
89
|
+
}
|
|
90
|
+
export const childrenIn = (table, parent) => [...table].filter(([, ppid]) => ppid === parent).map(([pid]) => pid);
|
|
91
|
+
export function descendantsIn(table, root) {
|
|
92
|
+
const found = new Set([root]);
|
|
93
|
+
for (let grew = true; grew;) {
|
|
94
|
+
grew = false;
|
|
95
|
+
for (const [pid, ppid] of table)
|
|
96
|
+
if (!found.has(pid) && found.has(ppid)) {
|
|
97
|
+
found.add(pid);
|
|
98
|
+
grew = true;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return found;
|
|
102
|
+
}
|
|
103
|
+
/** The owner's processes, other than `exclude`, that hold the pipe on `pid`'s
|
|
104
|
+
* stdout (on macOS, its read end). Undefined when stdout is no pipe or the
|
|
105
|
+
* Hook cannot tell. Processes of other users (root) are never listed. */
|
|
106
|
+
export async function pipeHolders(pid, exclude) {
|
|
107
|
+
try {
|
|
108
|
+
if (process.platform === "linux") {
|
|
109
|
+
const target = await readlink(`/proc/${pid}/fd/1`);
|
|
110
|
+
if (!/^pipe:\[\d+\]$/.test(target))
|
|
111
|
+
return undefined;
|
|
112
|
+
const holders = [];
|
|
113
|
+
for (const holder of (await readdir("/proc")).map(Number)) {
|
|
114
|
+
if (!Number.isInteger(holder) || holder === pid || exclude.includes(holder))
|
|
115
|
+
continue;
|
|
116
|
+
const fds = await readdir(`/proc/${holder}/fd`).catch(() => []);
|
|
117
|
+
if (fds.some(fd => { try {
|
|
118
|
+
return readlinkSync(`/proc/${holder}/fd/${fd}`) === target;
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return false;
|
|
122
|
+
} }))
|
|
123
|
+
holders.push(holder);
|
|
124
|
+
}
|
|
125
|
+
return holders;
|
|
126
|
+
}
|
|
127
|
+
const own = await exec("lsof", ["-nP", "-a", "-p", String(pid), "-d", "1", "-F", "tdn"], { timeout: 5_000, maxBuffer: 65_536 });
|
|
128
|
+
const type = /^t(.+)$/m.exec(own.stdout)?.[1], peer = /^n->(0x[0-9a-f]+)$/m.exec(own.stdout)?.[1];
|
|
129
|
+
if (type !== "PIPE" || !peer)
|
|
130
|
+
return undefined;
|
|
131
|
+
const all = await exec("lsof", ["-nP", "-u", String(process.getuid?.() ?? ""), "-F", "pd"], { timeout: 10_000, maxBuffer: 64 * 1_048_576 }).catch(error => error);
|
|
132
|
+
if (!all.stdout)
|
|
133
|
+
return undefined;
|
|
134
|
+
const holders = new Set();
|
|
135
|
+
let holder = 0;
|
|
136
|
+
for (const row of String(all.stdout).split("\n")) {
|
|
137
|
+
if (row.startsWith("p"))
|
|
138
|
+
holder = Number(row.slice(1));
|
|
139
|
+
else if (row === `d${peer}` && holder !== pid && !exclude.includes(holder))
|
|
140
|
+
holders.add(holder);
|
|
141
|
+
}
|
|
142
|
+
return [...holders];
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const REFUSED = "phren askpass --secret-exec only answers phren secret-exec.";
|
|
149
|
+
/** The chain from the helper to the one command it feeds, or why it is refused. */
|
|
150
|
+
export async function verifySecretAsker(pid, check) {
|
|
151
|
+
const asker = await check.processes(pid);
|
|
152
|
+
const script = asker ? await check.processes(asker.ppid) : undefined;
|
|
153
|
+
if (!asker || !script)
|
|
154
|
+
return { refused: REFUSED };
|
|
155
|
+
// Exactly the helper: no prompt argument, no flags that could load other code.
|
|
156
|
+
if (!check.bundles.some(bundle => asker.line === `${check.node} ${bundle} askpass ${SECRET_FLAG}`) || script.line !== `/bin/sh ${check.script} ${SECRET_FLAG}`)
|
|
157
|
+
return { refused: REFUSED };
|
|
158
|
+
if (asker.env?.some(name => [...PRELOADS, "NODE_OPTIONS"].includes(name)) || script.env?.some(name => PRELOADS.includes(name))) {
|
|
159
|
+
return { refused: "askpass refused an environment that loads other code." };
|
|
160
|
+
}
|
|
161
|
+
const table = await check.table().catch(() => undefined);
|
|
162
|
+
if (!table)
|
|
163
|
+
return { refused: "Phren Hook could not read the process table." };
|
|
164
|
+
const siblings = childrenIn(table, script.ppid).filter(item => item !== asker.ppid);
|
|
165
|
+
if (siblings.length !== 1)
|
|
166
|
+
return { refused: "phren secret-exec must run exactly one command." };
|
|
167
|
+
const [commandPid] = siblings;
|
|
168
|
+
const command = await check.processes(commandPid);
|
|
169
|
+
if (!command)
|
|
170
|
+
return { refused: "The command that would read the secret has exited." };
|
|
171
|
+
const holders = await check.holders(pid, [asker.ppid]);
|
|
172
|
+
if (!holders)
|
|
173
|
+
return { refused: "Phren Hook could not check where the secret goes." };
|
|
174
|
+
const allowed = descendantsIn(table, commandPid);
|
|
175
|
+
if (holders.some(holder => !allowed.has(holder)))
|
|
176
|
+
return { refused: "The secret must go to the command alone." };
|
|
177
|
+
const connection = await check.connection(pid);
|
|
178
|
+
if (connection !== "asker")
|
|
179
|
+
return { refused: connection === "other" ? "Only askpass itself may ask for its secret." : "Phren Hook could not check who asked." };
|
|
180
|
+
return { command, commandPid };
|
|
181
|
+
}
|
|
182
|
+
async function defaultVerify(pid, hookFd, delivery) {
|
|
183
|
+
const linux = process.platform === "linux";
|
|
184
|
+
const running = process.argv[1] ? [path.resolve(process.argv[1])] : [];
|
|
185
|
+
const start = linux ? await processStart(pid) : undefined;
|
|
186
|
+
const inode = linux && delivery ? await listeningInode(delivery.socket) : undefined;
|
|
187
|
+
// Linux needs the helper's own listener: no fallback to writing its stdout.
|
|
188
|
+
if (linux && (!start || !delivery || !inode))
|
|
189
|
+
return { refused: "Phren Hook could not check who asked." };
|
|
190
|
+
const result = await verifySecretAsker(pid, { processes: readProcess, table: processTable, holders: pipeHolders, node: process.execPath, script: askpassPath(),
|
|
191
|
+
bundles: [...new Set([path.join(bridgeRoot(), "current/bridge-hook.mjs"), ...running])],
|
|
192
|
+
connection: linux ? asker => listenerHolders(asker, inode) : asker => connectionHolders(asker, hookFd) });
|
|
193
|
+
if ("refused" in result)
|
|
194
|
+
return result;
|
|
195
|
+
const send = linux ? (secret) => deliverToListener(pid, start, delivery, inode, secret) : async (secret) => ({ password: secret });
|
|
196
|
+
// The answer can come minutes after the check. On Linux any process of the
|
|
197
|
+
// owner's can open /proc/<helper>/fd/1 meanwhile and read the pipe, so who
|
|
198
|
+
// holds it is checked again right before the secret goes in.
|
|
199
|
+
return { command: result.command, deliver: async (secret) => {
|
|
200
|
+
const still = await stillOnlyTheCommand(pid, result.commandPid);
|
|
201
|
+
return still ? send(secret) : { status: 409, error: "Something else opened the command's input; the secret was not sent." };
|
|
202
|
+
} };
|
|
203
|
+
}
|
|
204
|
+
/** Whether, now, only the command and what it started hold the helper's stdout. */
|
|
205
|
+
export async function stillOnlyTheCommand(pid, commandPid, check = { processes: readProcess, table: processTable, holders: pipeHolders }) {
|
|
206
|
+
const asker = await check.processes(pid).catch(() => undefined);
|
|
207
|
+
const table = await check.table().catch(() => undefined);
|
|
208
|
+
if (!asker || !table)
|
|
209
|
+
return false;
|
|
210
|
+
const holders = await check.holders(pid, [asker.ppid]);
|
|
211
|
+
if (!holders)
|
|
212
|
+
return false;
|
|
213
|
+
const allowed = descendantsIn(table, commandPid);
|
|
214
|
+
return holders.every(holder => allowed.has(holder));
|
|
215
|
+
}
|
|
216
|
+
export class SecretBroker {
|
|
217
|
+
options;
|
|
218
|
+
pending = new Map();
|
|
219
|
+
events = new EventEmitter();
|
|
220
|
+
watchers = 0;
|
|
221
|
+
constructor(options) {
|
|
222
|
+
this.options = options;
|
|
223
|
+
this.events.setMaxListeners(64);
|
|
224
|
+
}
|
|
225
|
+
list() { return [...this.pending.values()].map(entry => entry.view); }
|
|
226
|
+
/** Overview sockets that asked for `secrets` frames; each is a phone that can answer. */
|
|
227
|
+
subscribe(listener) {
|
|
228
|
+
this.watchers++;
|
|
229
|
+
const handler = () => listener(this.list());
|
|
230
|
+
this.events.on("change", handler);
|
|
231
|
+
let open = true;
|
|
232
|
+
return () => { if (!open)
|
|
233
|
+
return; open = false; this.watchers--; this.events.off("change", handler); };
|
|
234
|
+
}
|
|
235
|
+
changed() { this.events.emit("change"); }
|
|
236
|
+
async ask(body, respond, hookFd) {
|
|
237
|
+
const none = { cancel: () => { } };
|
|
238
|
+
const spec = secretSpec(body.spec);
|
|
239
|
+
if (!spec) {
|
|
240
|
+
respond({ status: 400, error: "phren secret-exec sent an invalid request." });
|
|
241
|
+
return none;
|
|
242
|
+
}
|
|
243
|
+
// Push is not used: an app that predates secrets would show this as sudo.
|
|
244
|
+
if (this.watchers === 0) {
|
|
245
|
+
respond({ status: 503, error: "No phone can answer right now. Open Phren on your phone (an app that supports secret-exec)." });
|
|
246
|
+
return none;
|
|
247
|
+
}
|
|
248
|
+
if (this.pending.size >= MAX_SECRET_PENDING) {
|
|
249
|
+
respond({ status: 429, error: "Too many secret requests are waiting for the phone." });
|
|
250
|
+
return none;
|
|
251
|
+
}
|
|
252
|
+
const verified = await (this.options.verify ?? defaultVerify)(Number(body.pid), hookFd, deliveryFrom(body.delivery));
|
|
253
|
+
if ("refused" in verified) {
|
|
254
|
+
respond({ status: 400, error: verified.refused });
|
|
255
|
+
return none;
|
|
256
|
+
}
|
|
257
|
+
const place = placeFrom(body.place);
|
|
258
|
+
const dispatch = briefId.safeParse(body.dispatchId).success ? String(body.dispatchId) : undefined;
|
|
259
|
+
const described = place && this.options.describe ? await this.options.describe(place).catch(() => undefined) : undefined;
|
|
260
|
+
const dispatchLabel = dispatch && this.options.label ? await this.options.label(dispatch).catch(() => undefined) : undefined;
|
|
261
|
+
const label = dispatchLabel ?? described?.label;
|
|
262
|
+
const session = place || described || label
|
|
263
|
+
? { ...(described?.source ? { source: described.source } : {}), ...(label ? { label: label.slice(0, 120) } : {}), ...place } : undefined;
|
|
264
|
+
const cwd = typeof body.cwd === "string" && path.isAbsolute(body.cwd) && body.cwd.length <= 1_024 ? body.cwd : undefined;
|
|
265
|
+
const at = (this.options.now ?? Date.now)(), hold = this.options.holdMs ?? SUDO_HOLD_MS;
|
|
266
|
+
const account = this.options.account ?? userName();
|
|
267
|
+
const view = { id: randomUUID(), kind: "secret", computer: this.options.computer(), command: verified.command.line.slice(0, 2_000),
|
|
268
|
+
...(spec.prompt ? { prompt: spec.prompt } : {}),
|
|
269
|
+
stdin: spec.format === "line" ? { format: "line" } : { format: "plist", key: spec.key, ...(spec.fields ? { fields: spec.fields } : {}) },
|
|
270
|
+
...(account ? { account } : {}), ...(cwd ? { cwd } : {}), ...(session ? { session } : {}),
|
|
271
|
+
askedAt: new Date(at).toISOString(), expiresAt: new Date(at + hold).toISOString() };
|
|
272
|
+
const finish = (reply) => {
|
|
273
|
+
const entry = this.pending.get(view.id);
|
|
274
|
+
if (!entry)
|
|
275
|
+
return;
|
|
276
|
+
clearTimeout(entry.timer);
|
|
277
|
+
this.pending.delete(view.id);
|
|
278
|
+
this.changed();
|
|
279
|
+
void Promise.resolve(reply).catch(() => ({ status: 410, error: "askpass went away." })).then(respond);
|
|
280
|
+
};
|
|
281
|
+
const timer = setTimeout(() => finish({ status: 408, error: "No answer from the phone in time." }), hold);
|
|
282
|
+
this.pending.set(view.id, { view, respond: finish, deliver: verified.deliver, timer });
|
|
283
|
+
this.changed();
|
|
284
|
+
return { cancel: () => { const entry = this.pending.get(view.id); if (!entry)
|
|
285
|
+
return; clearTimeout(entry.timer); this.pending.delete(view.id); this.changed(); } };
|
|
286
|
+
}
|
|
287
|
+
/** The phone's answer, single use. */
|
|
288
|
+
answer(id, answer) {
|
|
289
|
+
const entry = this.pending.get(id);
|
|
290
|
+
if (!entry)
|
|
291
|
+
return false;
|
|
292
|
+
entry.respond("secret" in answer ? entry.deliver(answer.secret) : { status: 403, error: "Denied on the phone." });
|
|
293
|
+
return true;
|
|
294
|
+
}
|
|
295
|
+
close() { for (const entry of [...this.pending.values()])
|
|
296
|
+
entry.respond({ status: 503, error: "Phren Hook stopped." }); }
|
|
297
|
+
/** The agent.sock `/secret` route. */
|
|
298
|
+
async handle(req, res) {
|
|
299
|
+
let size = 0;
|
|
300
|
+
const chunks = [];
|
|
301
|
+
for await (const bytes of req) {
|
|
302
|
+
size += bytes.length;
|
|
303
|
+
if (size > 16_384)
|
|
304
|
+
throw new Error("Oversized secret request");
|
|
305
|
+
chunks.push(bytes);
|
|
306
|
+
}
|
|
307
|
+
const body = object(JSON.parse(Buffer.concat(chunks).toString()));
|
|
308
|
+
let done = false, gone = false, held;
|
|
309
|
+
res.on("close", () => { gone = true; if (!done) {
|
|
310
|
+
done = true;
|
|
311
|
+
held?.cancel();
|
|
312
|
+
} });
|
|
313
|
+
held = await this.ask(body, reply => {
|
|
314
|
+
if (done)
|
|
315
|
+
return;
|
|
316
|
+
done = true;
|
|
317
|
+
if ("status" in reply) {
|
|
318
|
+
res.statusCode = reply.status;
|
|
319
|
+
res.end(JSON.stringify({ error: reply.error }));
|
|
320
|
+
}
|
|
321
|
+
else {
|
|
322
|
+
res.statusCode = 200;
|
|
323
|
+
res.end(JSON.stringify(reply));
|
|
324
|
+
}
|
|
325
|
+
}, req.socket._handle?.fd);
|
|
326
|
+
if (gone)
|
|
327
|
+
held.cancel();
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
/** `POST /v1/secrets/answer`. Checked by hand: a schema error could echo the value it refused. */
|
|
331
|
+
export function secretAnswer(data) {
|
|
332
|
+
const id = typeof data.id === "string" && /^[0-9a-f-]{36}$/i.test(data.id) ? data.id : undefined;
|
|
333
|
+
if (!id)
|
|
334
|
+
throw new SecretAnswerError();
|
|
335
|
+
if (data.deny !== undefined) {
|
|
336
|
+
if (data.deny === true && data.secret === undefined)
|
|
337
|
+
return { id, answer: { deny: true } };
|
|
338
|
+
throw new SecretAnswerError();
|
|
339
|
+
}
|
|
340
|
+
if (!validSecret(data.secret))
|
|
341
|
+
throw new SecretAnswerError();
|
|
342
|
+
return { id, answer: { secret: data.secret } };
|
|
343
|
+
}
|
|
344
|
+
export class SecretAnswerError extends Error {
|
|
345
|
+
constructor() { super("Send an id and a secret, or deny."); }
|
|
346
|
+
}
|
|
347
|
+
/** The helper, `askpass --secret-exec`: asks the Hook, writes the payload to
|
|
348
|
+
* stdout (the command's stdin pipe), and wipes its copy. */
|
|
349
|
+
export async function secretAskpass(env = process.env) {
|
|
350
|
+
let spec;
|
|
351
|
+
try {
|
|
352
|
+
spec = secretSpec(JSON.parse(env[SECRET_SPEC_ENV] ?? ""));
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
spec = undefined;
|
|
356
|
+
}
|
|
357
|
+
if (!spec) {
|
|
358
|
+
process.stderr.write("phren secret-exec: invalid request.\n");
|
|
359
|
+
return 1;
|
|
360
|
+
}
|
|
361
|
+
const place = await terminalPaneFromEnv(env).catch(() => undefined);
|
|
362
|
+
const dispatchId = env.PHREN_DISPATCH_ID && briefId.safeParse(env.PHREN_DISPATCH_ID).success ? env.PHREN_DISPATCH_ID : undefined;
|
|
363
|
+
let received;
|
|
364
|
+
let listener;
|
|
365
|
+
if (process.platform === "linux") {
|
|
366
|
+
listener = await deliveryListener(secret => { received = secret; }).catch(() => undefined);
|
|
367
|
+
if (!listener) {
|
|
368
|
+
process.stderr.write("phren secret-exec: could not open its delivery socket.\n");
|
|
369
|
+
return 1;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
try {
|
|
373
|
+
const data = JSON.stringify({ pid: process.pid, cwd: process.cwd(), spec, ...(place ? { place } : {}), ...(dispatchId ? { dispatchId } : {}),
|
|
374
|
+
...(listener ? { delivery: listener.delivery } : {}) });
|
|
375
|
+
const reply = await new Promise(resolve => {
|
|
376
|
+
const req = request({ socketPath: localSocket(), path: "/secret", method: "POST", timeout: SUDO_HOLD_MS + 15_000,
|
|
377
|
+
headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
|
|
378
|
+
let text = "";
|
|
379
|
+
res.on("data", chunk => { text += chunk.toString(); if (text.length > 16_384)
|
|
380
|
+
req.destroy(); });
|
|
381
|
+
res.on("end", () => { try {
|
|
382
|
+
resolve({ status: res.statusCode ?? 0, body: object(JSON.parse(text)) });
|
|
383
|
+
}
|
|
384
|
+
catch {
|
|
385
|
+
resolve({ status: 0, body: {} });
|
|
386
|
+
} });
|
|
387
|
+
});
|
|
388
|
+
req.on("timeout", () => req.destroy());
|
|
389
|
+
req.on("error", () => resolve({ status: 0, body: { error: "Phren Hook is not running on this computer (phren bridge status)." } }));
|
|
390
|
+
req.end(data);
|
|
391
|
+
});
|
|
392
|
+
const secret = reply.status === 200 ? (typeof reply.body.password === "string" ? reply.body.password : reply.body.delivered === true ? received : undefined) : undefined;
|
|
393
|
+
reply.body.password = "";
|
|
394
|
+
received = undefined;
|
|
395
|
+
if (secret === undefined || !validSecret(secret)) {
|
|
396
|
+
process.stderr.write(`phren secret-exec: ${typeof reply.body.error === "string" ? reply.body.error : "not approved."}\n`);
|
|
397
|
+
return 1;
|
|
398
|
+
}
|
|
399
|
+
const payload = Buffer.from(secretPayload(spec, secret), "utf8");
|
|
400
|
+
try {
|
|
401
|
+
await new Promise((resolve, reject) => process.stdout.write(payload, error => error ? reject(error) : resolve()));
|
|
402
|
+
}
|
|
403
|
+
catch {
|
|
404
|
+
process.stderr.write("phren secret-exec: the command closed its input.\n");
|
|
405
|
+
return 1;
|
|
406
|
+
}
|
|
407
|
+
finally {
|
|
408
|
+
payload.fill(0);
|
|
409
|
+
}
|
|
410
|
+
return 0;
|
|
411
|
+
}
|
|
412
|
+
finally {
|
|
413
|
+
listener?.close();
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
export const SECRET_EXEC_USAGE = "Usage: phren secret-exec [--prompt <text>] [--plist <key> [--field <key>=<value>]...] -- <command...>\n"
|
|
417
|
+
+ "Runs <command> and writes a secret typed on your phone to its stdin (one line, or a plist with the secret under <key>).\n"
|
|
418
|
+
+ "Your phone shows the exact command, the prompt and the session, and asks you to approve each run. The secret never reaches this terminal.";
|
|
419
|
+
/** Parsed `phren secret-exec` arguments. */
|
|
420
|
+
export function secretExecArgs(args) {
|
|
421
|
+
const split = args.indexOf("--");
|
|
422
|
+
if (split < 0 || split === args.length - 1)
|
|
423
|
+
throw new Error(SECRET_EXEC_USAGE);
|
|
424
|
+
const options = args.slice(0, split), command = args.slice(split + 1);
|
|
425
|
+
let prompt, key;
|
|
426
|
+
const fields = {};
|
|
427
|
+
for (let index = 0; index < options.length; index++) {
|
|
428
|
+
const name = options[index], value = options[++index];
|
|
429
|
+
if (value === undefined)
|
|
430
|
+
throw new Error(SECRET_EXEC_USAGE);
|
|
431
|
+
if (name === "--prompt")
|
|
432
|
+
prompt = value;
|
|
433
|
+
else if (name === "--plist")
|
|
434
|
+
key = value;
|
|
435
|
+
else if (name === "--field") {
|
|
436
|
+
const at = value.indexOf("=");
|
|
437
|
+
if (at < 1)
|
|
438
|
+
throw new Error(`--field takes <key>=<value>, not "${value}".`);
|
|
439
|
+
fields[value.slice(0, at)] = value.slice(at + 1);
|
|
440
|
+
}
|
|
441
|
+
else
|
|
442
|
+
throw new Error(SECRET_EXEC_USAGE);
|
|
443
|
+
}
|
|
444
|
+
if (Object.keys(fields).length && !key)
|
|
445
|
+
throw new Error("--field needs --plist.");
|
|
446
|
+
const spec = secretSpec(key ? { prompt, format: "plist", key, ...(Object.keys(fields).length ? { fields } : {}) } : { prompt, format: "line" });
|
|
447
|
+
if (!spec)
|
|
448
|
+
throw new Error("Invalid --prompt, --plist or --field: printable text, keys of letters, digits, _ . - only, at most 16 fields.");
|
|
449
|
+
return { spec, command };
|
|
450
|
+
}
|
|
451
|
+
const signalCode = (code, signal) => code ?? (signal ? 128 + ({ SIGINT: 2, SIGTERM: 15, SIGKILL: 9, SIGHUP: 1 }[signal] ?? 1) : 1);
|
|
452
|
+
/** `phren secret-exec`. Exits with the command's status, or 1 when the
|
|
453
|
+
* secret was not given (the command is stopped then). */
|
|
454
|
+
export async function runSecretExec(args, options = {}) {
|
|
455
|
+
if (!args.length || args[0] === "--help" || args[0] === "-h") {
|
|
456
|
+
console.log(SECRET_EXEC_USAGE);
|
|
457
|
+
return args.length ? 0 : 1;
|
|
458
|
+
}
|
|
459
|
+
if (process.platform === "win32")
|
|
460
|
+
throw new Error("phren secret-exec runs where Phren Hook runs: macOS, Linux or WSL.");
|
|
461
|
+
const { spec, command } = secretExecArgs(args);
|
|
462
|
+
const script = options.script ?? askpassPath();
|
|
463
|
+
if (!options.script && !askpassInstalled())
|
|
464
|
+
throw new Error("Phren Hook's askpass helper is missing. Run phren bridge install.");
|
|
465
|
+
const child = spawn(command[0], command.slice(1), { stdio: ["pipe", "inherit", "inherit"] });
|
|
466
|
+
const exited = new Promise(resolve => {
|
|
467
|
+
child.on("error", error => { process.stderr.write(`phren secret-exec: ${error.message}\n`); resolve(127); });
|
|
468
|
+
child.on("exit", (code, signal) => resolve(signalCode(code, signal)));
|
|
469
|
+
});
|
|
470
|
+
child.stdin.on("error", () => { });
|
|
471
|
+
// The helper writes straight into the command's stdin; this process keeps no copy of that pipe.
|
|
472
|
+
const env = { ...process.env, [SECRET_SPEC_ENV]: JSON.stringify(spec) };
|
|
473
|
+
for (const name of ["NODE_OPTIONS", "NODE_PATH", "LD_PRELOAD", "LD_LIBRARY_PATH", "DYLD_INSERT_LIBRARIES", "DYLD_LIBRARY_PATH"])
|
|
474
|
+
delete env[name];
|
|
475
|
+
const helper = spawn("/bin/sh", [script, SECRET_FLAG], { stdio: ["ignore", child.stdin, "inherit"], env });
|
|
476
|
+
child.stdin.destroy();
|
|
477
|
+
const helped = await new Promise(resolve => {
|
|
478
|
+
helper.on("error", () => resolve(1));
|
|
479
|
+
helper.on("exit", (code, signal) => resolve(signalCode(code, signal)));
|
|
480
|
+
});
|
|
481
|
+
if (helped !== 0 && child.exitCode === null && child.signalCode === null)
|
|
482
|
+
child.kill("SIGTERM");
|
|
483
|
+
const code = await exited;
|
|
484
|
+
return helped !== 0 ? 1 : code;
|
|
485
|
+
}
|
|
@@ -18,7 +18,9 @@ import type { WorkspacesReader } from "./server-routes.js";
|
|
|
18
18
|
* gets `{ type: "resources", resources }` after the first overview, then at
|
|
19
19
|
* `OVERVIEW_RESOURCES_MS` intervals (an older phone never asks, so never meets it).
|
|
20
20
|
* One that asks with `sudo=1` gets `{ type: "sudo", requests }` after the first
|
|
21
|
-
* overview and whenever the pending sudo requests change
|
|
21
|
+
* overview and whenever the pending sudo requests change, and one that asks
|
|
22
|
+
* with `secrets=1` gets `{ type: "secrets", requests }` the same way for
|
|
23
|
+
* `phren secret-exec` (an older phone never asks, so never sees them).
|
|
22
24
|
*/
|
|
23
25
|
export declare const OVERVIEW_TICK_MS: number;
|
|
24
26
|
export declare const OVERVIEW_REFRESH_MS: number;
|
|
@@ -35,6 +37,11 @@ export interface OverviewStreamOptions {
|
|
|
35
37
|
list(): unknown[];
|
|
36
38
|
subscribe(listener: (requests: unknown[]) => void): () => void;
|
|
37
39
|
};
|
|
40
|
+
/** Pending secret-exec requests (`GET /v1/secrets`), for phones that ask with `secrets=1`. */
|
|
41
|
+
secrets?: {
|
|
42
|
+
list(): unknown[];
|
|
43
|
+
subscribe(listener: (requests: unknown[]) => void): () => void;
|
|
44
|
+
};
|
|
38
45
|
/** This computer's resources (`GET /v1/resources`), for phones that ask. */
|
|
39
46
|
resources?: () => Promise<unknown>;
|
|
40
47
|
snapshot?: (server: string, maxAgeMs: number) => Promise<Json>;
|
|
@@ -52,7 +59,7 @@ export interface OverviewClient {
|
|
|
52
59
|
close(code?: number, reason?: string): void;
|
|
53
60
|
once(event: "close" | "error", listener: () => void): unknown;
|
|
54
61
|
}
|
|
55
|
-
export declare function overviewStream(options: OverviewStreamOptions): (client: OverviewClient, server: string, watchApprovals: boolean, withResources?: boolean, typedMux?: boolean, withSudo?: boolean) => {
|
|
62
|
+
export declare function overviewStream(options: OverviewStreamOptions): (client: OverviewClient, server: string, watchApprovals: boolean, withResources?: boolean, typedMux?: boolean, withSudo?: boolean, withSecrets?: boolean) => {
|
|
56
63
|
tick: () => Promise<void>;
|
|
57
64
|
stop: () => void;
|
|
58
65
|
};
|
|
@@ -24,7 +24,9 @@ import { streamCloseReason } from "./server-stream.js";
|
|
|
24
24
|
* gets `{ type: "resources", resources }` after the first overview, then at
|
|
25
25
|
* `OVERVIEW_RESOURCES_MS` intervals (an older phone never asks, so never meets it).
|
|
26
26
|
* One that asks with `sudo=1` gets `{ type: "sudo", requests }` after the first
|
|
27
|
-
* overview and whenever the pending sudo requests change
|
|
27
|
+
* overview and whenever the pending sudo requests change, and one that asks
|
|
28
|
+
* with `secrets=1` gets `{ type: "secrets", requests }` the same way for
|
|
29
|
+
* `phren secret-exec` (an older phone never asks, so never sees them).
|
|
28
30
|
*/
|
|
29
31
|
export const OVERVIEW_TICK_MS = intervalFromEnv("PHREN_OVERVIEW_TICK_MS", 5_000, 250, 60_000);
|
|
30
32
|
export const OVERVIEW_REFRESH_MS = intervalFromEnv("PHREN_OVERVIEW_REFRESH_MS", 10_000, 1_000, 120_000);
|
|
@@ -50,12 +52,15 @@ export function overviewStream(options) {
|
|
|
50
52
|
}
|
|
51
53
|
/** Streams one server's overview until the client closes. Returns the
|
|
52
54
|
* tick function, for tests that drive time themselves. */
|
|
53
|
-
return function stream(client, server, watchApprovals, withResources = false, typedMux = false, withSudo = false) {
|
|
55
|
+
return function stream(client, server, watchApprovals, withResources = false, typedMux = false, withSudo = false, withSecrets = false) {
|
|
54
56
|
let closed = false, busy = false, resourcesPending = false, first = true, overviewSent = false;
|
|
55
57
|
// Subscribed at once, so the phone counts as able to answer while the first overview builds.
|
|
56
58
|
const unsubscribe = withSudo && options.sudo
|
|
57
59
|
? options.sudo.subscribe(requests => { if (!closed && overviewSent)
|
|
58
60
|
send(client, { type: "sudo", requests }); }) : undefined;
|
|
61
|
+
const unsubscribeSecrets = withSecrets && options.secrets
|
|
62
|
+
? options.secrets.subscribe(requests => { if (!closed && overviewSent)
|
|
63
|
+
send(client, { type: "secrets", requests }); }) : undefined;
|
|
59
64
|
let snapshotKey = "", builtAt = 0, sentKey = "", sentAt = 0, resourcesAt = -Infinity;
|
|
60
65
|
const collectResources = () => {
|
|
61
66
|
const at = now();
|
|
@@ -96,6 +101,8 @@ export function overviewStream(options) {
|
|
|
96
101
|
sentAt = at;
|
|
97
102
|
if (!overviewSent && unsubscribe)
|
|
98
103
|
send(client, { type: "sudo", requests: options.sudo.list() });
|
|
104
|
+
if (!overviewSent && unsubscribeSecrets)
|
|
105
|
+
send(client, { type: "secrets", requests: options.secrets.list() });
|
|
99
106
|
overviewSent = true;
|
|
100
107
|
}
|
|
101
108
|
first = false;
|
|
@@ -123,7 +130,7 @@ export function overviewStream(options) {
|
|
|
123
130
|
}
|
|
124
131
|
};
|
|
125
132
|
const timer = setInterval(() => { void tick(); }, tickMs);
|
|
126
|
-
const stop = () => { closed = true; clearInterval(timer); unsubscribe?.(); };
|
|
133
|
+
const stop = () => { closed = true; clearInterval(timer); unsubscribe?.(); unsubscribeSecrets?.(); };
|
|
127
134
|
client.once("close", stop);
|
|
128
135
|
client.once("error", stop);
|
|
129
136
|
void tick();
|