@phren/cli 0.3.34 → 0.3.36
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 +11 -1
- package/dist/bridge/agent-hooks.js +56 -19
- package/dist/bridge/changes.js +30 -13
- package/dist/bridge/dispatch-command.js +3 -1
- package/dist/bridge/health.js +3 -1
- package/dist/bridge/host-key.d.ts +16 -0
- package/dist/bridge/host-key.js +35 -0
- package/dist/bridge/launch-brief.d.ts +2 -0
- package/dist/bridge/launch-brief.js +5 -0
- package/dist/bridge/link.js +11 -4
- package/dist/bridge/owner-inbox-sources.d.ts +5 -0
- package/dist/bridge/owner-inbox-sources.js +94 -0
- package/dist/bridge/owner-inbox-view.js +20 -1
- package/dist/bridge/owner-inbox.d.ts +7 -3
- package/dist/bridge/owner-inbox.js +113 -69
- package/dist/bridge/pair.js +3 -2
- package/dist/bridge/server.js +3 -23
- package/dist/bridge/sudo.d.ts +36 -6
- package/dist/bridge/sudo.js +180 -37
- package/dist/bridge/worker-reports.d.ts +8 -1
- package/dist/bridge/worker-reports.js +28 -7
- package/dist/bridge-hook.mjs +817 -473
- package/dist/clanker.d.ts +54 -0
- package/dist/clanker.js +188 -0
- package/dist/cli/config.js +30 -0
- package/dist/cli/hooks-output.d.ts +1 -1
- package/dist/cli/hooks-output.js +28 -21
- package/dist/cli/hooks.js +1 -1
- package/dist/cli/namespaces-skills.js +2 -2
- package/dist/cli/namespaces-tasks.js +46 -7
- package/dist/cli/session-start.js +12 -3
- package/dist/cli/session-stop.js +9 -0
- package/dist/cli/team.js +3 -0
- package/dist/cli-handlers.js +7 -0
- package/dist/cli-registry.js +1 -0
- package/dist/data/task-format.d.ts +5 -1
- package/dist/data/task-format.js +13 -5
- package/dist/index.js +82 -50
- package/dist/init/init-configure.d.ts +2 -0
- package/dist/init/init-configure.js +12 -0
- package/dist/init/init-uninstall.js +21 -2
- package/dist/init/init.d.ts +2 -0
- package/dist/init/init.js +11 -3
- package/dist/init/preferences.d.ts +6 -0
- package/dist/init/teardown.js +18 -4
- package/dist/link/doctor.js +2 -2
- package/dist/link/link.js +9 -0
- package/dist/link/refresh.d.ts +10 -0
- package/dist/link/refresh.js +34 -0
- package/dist/mcp/local-index.d.ts +20 -0
- package/dist/mcp/local-index.js +39 -1
- package/dist/shared/index.d.ts +14 -0
- package/dist/shared/index.js +88 -74
- package/dist/shared/retrieval.js +1 -1
- package/dist/skill/files.js +40 -11
- package/dist/skill/registry.d.ts +6 -0
- package/dist/skill/registry.js +21 -5
- package/dist/task/lifecycle.js +3 -1
- package/dist/tools/dispatch.js +5 -2
- package/dist/tools/finding.js +20 -11
- package/dist/tools/graph.d.ts +2 -0
- package/dist/tools/graph.js +2 -0
- package/dist/tools/search.d.ts +2 -0
- package/dist/tools/search.js +88 -6
- package/dist/tools/tasks.js +45 -0
- package/dist/tools/types.d.ts +3 -1
- package/dist/tools/types.js +3 -2
- package/package.json +1 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { lstat, readFile } from "node:fs/promises";
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { lstat, mkdir, readFile } from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
import { atomicInPrivateDir, BridgeError, bridgeRoot, targetSchema, startingTargetSchema, computerName } from "./protocol.js";
|
|
6
|
-
import {
|
|
6
|
+
import { tryFileLock } from "../governance/locks.js";
|
|
7
7
|
const title = z.string().trim().min(1).max(500).refine(s => !/[\x00-\x1f\x7f]/.test(s));
|
|
8
8
|
export const inboxTargetSchema = z.union([targetSchema, startingTargetSchema]);
|
|
9
9
|
const itemSchema = z.object({
|
|
@@ -20,9 +20,15 @@ export const ownerInboxSchema = z.object({
|
|
|
20
20
|
id: z.string().uuid().optional(), resolution: z.string().max(2000).optional(),
|
|
21
21
|
includeResolved: z.boolean().optional(), computer: computerName.optional(),
|
|
22
22
|
}).strict();
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
// Prompt prose, counters and timestamps are observations, not identities.
|
|
24
|
+
function sourceKey(row) {
|
|
25
|
+
const t = row.target;
|
|
26
|
+
return t ? JSON.stringify([row.computer ?? "local", t.server, t.workspace, t.tab, t.pane, t.source,
|
|
27
|
+
"session" in t ? t.session : t.startingToken, row.actionId ?? "waiting"])
|
|
28
|
+
: row.dispatch ? `dispatch:${row.dispatch}:${row.actionId ?? "waiting"}` : row.source;
|
|
29
|
+
}
|
|
30
|
+
/** Reconcile automatic work against current sources; manual work is owner-owned.
|
|
31
|
+
* The first reconciliation also migrates old stale/duplicate automatic rows. */
|
|
26
32
|
export class OwnerInbox {
|
|
27
33
|
sources;
|
|
28
34
|
file;
|
|
@@ -42,76 +48,114 @@ export class OwnerInbox {
|
|
|
42
48
|
}
|
|
43
49
|
run(input) {
|
|
44
50
|
const run = this.pending.then(async () => {
|
|
45
|
-
const data = ownerInboxSchema.parse(input)
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
project: receipt.project, computer: receipt.computer, ...("session" in (receipt.target ?? {}) ? { target: receipt.target } : {}), dispatch: receipt.id, ...(actionId ? { actionId } : {}) });
|
|
57
|
-
}
|
|
58
|
-
for (const source of await this.sources()) {
|
|
59
|
-
if (source.actionId && sources.some(other => other.actionId === source.actionId && JSON.stringify(other.target) === JSON.stringify(source.target)))
|
|
60
|
-
continue;
|
|
61
|
-
sources.push(source);
|
|
51
|
+
const data = ownerInboxSchema.parse(input);
|
|
52
|
+
// Wait asynchronously: another instance in this process must be able to
|
|
53
|
+
// finish its write while we contend, just like another CLI process.
|
|
54
|
+
await mkdir(path.dirname(this.file), { recursive: true, mode: 0o700 });
|
|
55
|
+
const deadline = Date.now() + 30_000;
|
|
56
|
+
let release = tryFileLock(this.file);
|
|
57
|
+
while (!release) {
|
|
58
|
+
if (Date.now() >= deadline)
|
|
59
|
+
throw new BridgeError(503, "The owner inbox is busy; retry the operation.");
|
|
60
|
+
await new Promise(resolve => setTimeout(resolve, 20));
|
|
61
|
+
release = tryFileLock(this.file);
|
|
62
62
|
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
63
|
+
try {
|
|
64
|
+
const rows = await this.read(), at = new Date().toISOString();
|
|
65
|
+
let changed = false;
|
|
66
|
+
// Manual adds/resolves must work even when source discovery is offline.
|
|
67
|
+
if (data.action === "list") {
|
|
68
|
+
const observed = await this.sources();
|
|
69
|
+
const { sources, unavailableDispatches = [] } = Array.isArray(observed) ? { sources: observed } : observed;
|
|
70
|
+
const active = new Map(sources.map(source => [sourceKey(source), source]));
|
|
71
|
+
const retained = new Set();
|
|
72
|
+
const resolve = (row, reason) => {
|
|
73
|
+
row.state = "resolved";
|
|
74
|
+
row.live = false;
|
|
75
|
+
row.resolvedAt = at;
|
|
76
|
+
row.updatedAt = at;
|
|
77
|
+
row.resolution = reason;
|
|
78
|
+
changed = true;
|
|
79
|
+
};
|
|
80
|
+
for (const row of rows) {
|
|
81
|
+
if (row.kind === "manual")
|
|
82
|
+
continue;
|
|
83
|
+
// Retired history cannot suppress a later wait on the same pane.
|
|
84
|
+
// An owner dismissal remains live until its current wait ends.
|
|
85
|
+
if (row.state === "resolved" && !row.live)
|
|
86
|
+
continue;
|
|
87
|
+
const key = sourceKey(row), source = key ? active.get(key) : undefined;
|
|
88
|
+
const unavailable = !!row.dispatch && unavailableDispatches.includes(row.dispatch);
|
|
89
|
+
const live = !!source && !retained.has(key);
|
|
90
|
+
if (row.live !== live) {
|
|
91
|
+
row.live = live;
|
|
92
|
+
row.updatedAt = at;
|
|
93
|
+
changed = true;
|
|
94
|
+
}
|
|
95
|
+
if (!source) {
|
|
96
|
+
if (row.state === "open" && !unavailable)
|
|
97
|
+
resolve(row, "stale: source gone");
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (retained.has(key)) {
|
|
101
|
+
if (row.state === "open")
|
|
102
|
+
resolve(row, "duplicate: source");
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
retained.add(key);
|
|
106
|
+
if (row.state === "open" && JSON.stringify({ ...row, ...source }) !== JSON.stringify(row)) {
|
|
107
|
+
Object.assign(row, source, { updatedAt: at });
|
|
108
|
+
changed = true;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
for (const [key, source] of active) {
|
|
112
|
+
if (retained.has(key))
|
|
113
|
+
continue;
|
|
114
|
+
if (rows.length >= 10000)
|
|
115
|
+
throw new BridgeError(409, "The owner inbox is full.");
|
|
116
|
+
rows.push(itemSchema.parse({ ...source, id: randomUUID(), state: "open", live: true, createdAt: at, updatedAt: at }));
|
|
117
|
+
changed = true;
|
|
118
|
+
}
|
|
70
119
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
if (!prior) {
|
|
88
|
-
if (rows.length >= 10000)
|
|
89
|
-
throw new BridgeError(409, "The owner inbox is full.");
|
|
90
|
-
rows.push(item);
|
|
91
|
-
changed = true;
|
|
120
|
+
if (data.action === "add") {
|
|
121
|
+
if (!data.title)
|
|
122
|
+
throw new BridgeError(400, "Name the owner inbox item.");
|
|
123
|
+
const item = itemSchema.parse({ id: data.id ?? randomUUID(), kind: "manual", title: data.title, state: "open", createdAt: at, updatedAt: at, ...(data.project ? { project: data.project } : {}) });
|
|
124
|
+
const prior = rows.find(row => row.id === item.id);
|
|
125
|
+
if (prior && (prior.title !== item.title || prior.project !== item.project || prior.kind !== "manual"))
|
|
126
|
+
throw new BridgeError(409, "This inbox id names another item.");
|
|
127
|
+
if (!prior) {
|
|
128
|
+
if (rows.length >= 10000)
|
|
129
|
+
throw new BridgeError(409, "The owner inbox is full.");
|
|
130
|
+
rows.push(item);
|
|
131
|
+
changed = true;
|
|
132
|
+
}
|
|
133
|
+
if (changed)
|
|
134
|
+
await atomicInPrivateDir(this.file, rows);
|
|
135
|
+
return { ok: true, item: prior ?? item };
|
|
92
136
|
}
|
|
93
|
-
if (
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
137
|
+
if (data.action === "resolve") {
|
|
138
|
+
const item = rows.find(row => row.id === data.id);
|
|
139
|
+
if (!item)
|
|
140
|
+
throw new BridgeError(404, "No owner inbox item with that id.");
|
|
141
|
+
if (item.state !== "resolved") {
|
|
142
|
+
item.state = "resolved";
|
|
143
|
+
item.resolvedAt = at;
|
|
144
|
+
item.updatedAt = at;
|
|
145
|
+
item.resolution = data.resolution;
|
|
146
|
+
changed = true;
|
|
147
|
+
}
|
|
148
|
+
if (changed)
|
|
149
|
+
await atomicInPrivateDir(this.file, rows);
|
|
150
|
+
return { ok: true, item };
|
|
107
151
|
}
|
|
108
152
|
if (changed)
|
|
109
153
|
await atomicInPrivateDir(this.file, rows);
|
|
110
|
-
return { ok: true,
|
|
154
|
+
return { ok: true, items: rows.filter(row => data.includeResolved || (row.state === "open" && (row.kind === "manual" || row.live === true))).sort((a, b) => a.createdAt.localeCompare(b.createdAt)) };
|
|
155
|
+
}
|
|
156
|
+
finally {
|
|
157
|
+
release();
|
|
111
158
|
}
|
|
112
|
-
if (changed)
|
|
113
|
-
await atomicInPrivateDir(this.file, rows);
|
|
114
|
-
return { ok: true, items: rows.filter(row => data.includeResolved || row.state === "open").sort((a, b) => a.createdAt.localeCompare(b.createdAt)) };
|
|
115
159
|
});
|
|
116
160
|
this.pending = run.catch(() => { });
|
|
117
161
|
return run;
|
package/dist/bridge/pair.js
CHANGED
|
@@ -8,6 +8,7 @@ import path from "node:path";
|
|
|
8
8
|
import { promisify } from "node:util";
|
|
9
9
|
import { z } from "zod";
|
|
10
10
|
import { appendAuthorizedKey, publicComputerKey } from "./computers.js";
|
|
11
|
+
import { localHostKeyLine } from "./host-key.js";
|
|
11
12
|
import { forcedCommand, install } from "./install.js";
|
|
12
13
|
import { BridgeError, bridgeRoot } from "./protocol.js";
|
|
13
14
|
// `phren pair` connects a phone in one scan. The QR code carries where to
|
|
@@ -42,8 +43,8 @@ export function keyFingerprint(publicKeyLine) {
|
|
|
42
43
|
return undefined;
|
|
43
44
|
return "SHA256:" + createHash("sha256").update(Buffer.from(blob, "base64")).digest("base64").replace(/=+$/, "");
|
|
44
45
|
}
|
|
45
|
-
export async function hostFingerprint(file
|
|
46
|
-
return keyFingerprint(await readFile(file, "utf8").catch(() => ""));
|
|
46
|
+
export async function hostFingerprint(file) {
|
|
47
|
+
return keyFingerprint((file ? await readFile(file, "utf8").catch(() => "") : await localHostKeyLine()) ?? "");
|
|
47
48
|
}
|
|
48
49
|
/** Addresses the phone can try, best first: Tailscale name and address, then LAN IPv4. */
|
|
49
50
|
export async function pairingHosts() {
|
package/dist/bridge/server.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ownerInboxSources } from "./owner-inbox-sources.js";
|
|
2
|
+
import { OwnerInbox } from "./owner-inbox.js";
|
|
2
3
|
import { closeFinishedWorker } from "./worker-close.js";
|
|
3
4
|
import { isLocalComputer } from "./dispatch-hosts.js";
|
|
4
5
|
import { hookPeers, peerRequest } from "./peers.js";
|
|
@@ -111,28 +112,7 @@ export async function serve(version, options = {}) {
|
|
|
111
112
|
if ("approvalPush" in activeCapabilities) {
|
|
112
113
|
Object.defineProperty(activeCapabilities, "approvalPush", { enumerable: true, get: () => approvalPushCapability(agentHooks.push.status) });
|
|
113
114
|
}
|
|
114
|
-
const inbox = dispatches ? new OwnerInbox(
|
|
115
|
-
const items = [];
|
|
116
|
-
for (const server of await recentServers()) {
|
|
117
|
-
const name = String(server.session), state = await sharedSnapshot(name, 4000);
|
|
118
|
-
for (const pane of objects(state.panes)) {
|
|
119
|
-
const chat = await paneChatState(name, pane, { tokenWhenIdentified: false }).catch(() => ({}));
|
|
120
|
-
const parsed = inboxTargetSchema.safeParse({ server: name, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id, source: pane.agent,
|
|
121
|
-
...(chat.sessionId ? { session: chat.sessionId } : { starting: true, startingToken: chat.startingToken }) });
|
|
122
|
-
if (!parsed.success)
|
|
123
|
-
continue;
|
|
124
|
-
const target = parsed.data, approval = "session" in target ? agentHooks.workerApproval(target) : undefined, question = "session" in target ? agentHooks.servedQuestion(target) : undefined, terminal = "session" in target ? agentHooks.terminalPrompt(target) : undefined;
|
|
125
|
-
const request = approval?.request ?? (question ? "The worker has a question for the owner." : undefined) ?? terminal?.message
|
|
126
|
-
?? (["blocked", "waiting"].includes(String(pane.agent_status)) ? `${pane.agent} needs terminal input.` : undefined);
|
|
127
|
-
if (!request)
|
|
128
|
-
continue;
|
|
129
|
-
const source = `prompt:${JSON.stringify(target)}:${approval?.actionId ?? JSON.stringify(question ?? terminal)}`;
|
|
130
|
-
items.push({ source, kind: "blocked", title: String(request).replace(/[\x00-\x1f\x7f]+/g, " ").slice(0, 500), target,
|
|
131
|
-
...(approval?.actionId ? { actionId: approval.actionId } : {}) });
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
return items;
|
|
135
|
-
}) : undefined;
|
|
115
|
+
const inbox = dispatches ? new OwnerInbox(() => ownerInboxSources(agentHooks)) : undefined;
|
|
136
116
|
const modelCatalog = options.modelCatalog ?? new ModelCatalog();
|
|
137
117
|
const modelSwitcher = new ModelSwitcher(agentHooks, modelCatalog);
|
|
138
118
|
const settingsSwitcher = new SettingsSwitcher(agentHooks);
|
package/dist/bridge/sudo.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type IncomingMessage, type ServerResponse } from "node:http";
|
|
2
|
+
import { type Socket } from "node:net";
|
|
2
3
|
import { type Json } from "./protocol.js";
|
|
3
4
|
/**
|
|
4
5
|
* sudo with no terminal, answered from the phone.
|
|
@@ -13,9 +14,13 @@ import { type Json } from "./protocol.js";
|
|
|
13
14
|
* running as root (euid 0, which no process of the owner's can fake), and the
|
|
14
15
|
* asker's stdout is a pipe no other process of the owner's reads. The
|
|
15
16
|
* connection is bound to that process too: on macOS its other end must be
|
|
16
|
-
* held by the asker alone
|
|
17
|
-
*
|
|
18
|
-
*
|
|
17
|
+
* held by the asker alone. On Linux, where no unprivileged process can see a
|
|
18
|
+
* socket's peer, askpass listens on a fresh abstract socket and names it in
|
|
19
|
+
* its request; the listener must be held by the asker alone, and the Hook
|
|
20
|
+
* hands the password to that listener (with a one-time nonce askpass chose),
|
|
21
|
+
* which prints it to its own stdout. So a connection that names another
|
|
22
|
+
* process's pid gets nothing. (sudo creates askpass's stdout pipe as root,
|
|
23
|
+
* 0600, so the Hook cannot open `/proc/<pid>/fd/1` there.) It reads
|
|
19
24
|
* that sudo's command line itself and pushes the request to the phone; `GET /v1/sudo` and the overview socket's `sudo` frame
|
|
20
25
|
* list it. `POST /v1/sudo/answer` writes the password into the held
|
|
21
26
|
* connection and forgets the request: the password is never logged, stored,
|
|
@@ -62,8 +67,8 @@ export interface SudoRequestView {
|
|
|
62
67
|
askedAt: string;
|
|
63
68
|
expiresAt: string;
|
|
64
69
|
}
|
|
65
|
-
/** What askpass gets: the password to print, word that the Hook
|
|
66
|
-
* askpass's stdout
|
|
70
|
+
/** What askpass gets: the password to print, word that the Hook handed it to
|
|
71
|
+
* askpass's delivery socket or wrote it into askpass's stdout (Linux), or why not. */
|
|
67
72
|
export type SudoReply = {
|
|
68
73
|
password: string;
|
|
69
74
|
} | {
|
|
@@ -104,6 +109,31 @@ export declare function stdoutReaders(pid: number, allowed: number[]): Promise<"
|
|
|
104
109
|
export declare function connectionHolders(pid: number, hookFd: number | undefined): Promise<"asker" | "other" | "unknown">;
|
|
105
110
|
/** Linux: a process's start time, to tell it from a later one with its pid. */
|
|
106
111
|
export declare function processStart(pid: number): Promise<string | undefined>;
|
|
112
|
+
/** Linux: the abstract socket askpass listens on for its password, and the
|
|
113
|
+
* nonce the Hook must send first. Both are random and chosen by askpass. */
|
|
114
|
+
export interface AskpassDelivery {
|
|
115
|
+
socket: string;
|
|
116
|
+
nonce: string;
|
|
117
|
+
}
|
|
118
|
+
export declare function deliveryFrom(value: unknown): AskpassDelivery | undefined;
|
|
119
|
+
export declare function newDelivery(): AskpassDelivery;
|
|
120
|
+
/** Linux: the inode of the listening abstract socket `name`, from
|
|
121
|
+
* `/proc/net/unix` (`Num RefCount Protocol Flags Type St Inode Path`; a
|
|
122
|
+
* listener has `__SO_ACCEPTCON`, 0x10000, in Flags). */
|
|
123
|
+
export declare function listeningInode(name: string, table?: () => Promise<string>): Promise<string | undefined>;
|
|
124
|
+
/** Linux: whether the listening socket `inode` is held by `pid` and no other
|
|
125
|
+
* process of the owner's. */
|
|
126
|
+
export declare function listenerHolders(pid: number, inode: string): Promise<"asker" | "other" | "unknown">;
|
|
127
|
+
/** Linux: the password handed to askpass's own listener, if askpass is still
|
|
128
|
+
* the process that was verified and its listener is still the one checked.
|
|
129
|
+
* The check runs after connecting: a name is bound to one listener at a time,
|
|
130
|
+
* so while the asker still holds that listener, this connection reached it. */
|
|
131
|
+
export declare function deliverToListener(pid: number, start: string, delivery: AskpassDelivery, inode: string, password: string, checks?: {
|
|
132
|
+
start?: typeof processStart;
|
|
133
|
+
inode?: typeof listeningInode;
|
|
134
|
+
holders?: typeof listenerHolders;
|
|
135
|
+
connect?: (path: string) => Socket;
|
|
136
|
+
}): Promise<SudoReply>;
|
|
107
137
|
export interface AskerCheck {
|
|
108
138
|
processes: (pid: number) => Promise<ProcessRecord | undefined>;
|
|
109
139
|
stdout: (pid: number, allowed: number[]) => Promise<"sudo" | "other" | "unknown">;
|
|
@@ -139,7 +169,7 @@ export interface SudoBrokerOptions {
|
|
|
139
169
|
/** Reads a process, to see whether sudo is still running; tests replace it. */
|
|
140
170
|
processes?: (pid: number) => Promise<ProcessRecord | undefined>;
|
|
141
171
|
/** The askpass chain check and how the password then reaches it; tests replace it. */
|
|
142
|
-
verify?: (pid: number, hookFd: number | undefined) => Promise<Verified | {
|
|
172
|
+
verify?: (pid: number, hookFd: number | undefined, delivery?: AskpassDelivery) => Promise<Verified | {
|
|
143
173
|
refused: string;
|
|
144
174
|
}>;
|
|
145
175
|
holdMs?: number;
|
package/dist/bridge/sudo.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
3
3
|
import { EventEmitter } from "node:events";
|
|
4
4
|
import { existsSync, readlinkSync } from "node:fs";
|
|
5
5
|
import { open, readdir, readFile, readlink, unlink } from "node:fs/promises";
|
|
6
6
|
import { request } from "node:http";
|
|
7
|
+
import { createConnection, createServer } from "node:net";
|
|
7
8
|
import path from "node:path";
|
|
8
9
|
import { promisify } from "node:util";
|
|
9
10
|
import { userInfo } from "node:os";
|
|
@@ -25,9 +26,13 @@ import { briefId } from "./launch-brief.js";
|
|
|
25
26
|
* running as root (euid 0, which no process of the owner's can fake), and the
|
|
26
27
|
* asker's stdout is a pipe no other process of the owner's reads. The
|
|
27
28
|
* connection is bound to that process too: on macOS its other end must be
|
|
28
|
-
* held by the asker alone
|
|
29
|
-
*
|
|
30
|
-
*
|
|
29
|
+
* held by the asker alone. On Linux, where no unprivileged process can see a
|
|
30
|
+
* socket's peer, askpass listens on a fresh abstract socket and names it in
|
|
31
|
+
* its request; the listener must be held by the asker alone, and the Hook
|
|
32
|
+
* hands the password to that listener (with a one-time nonce askpass chose),
|
|
33
|
+
* which prints it to its own stdout. So a connection that names another
|
|
34
|
+
* process's pid gets nothing. (sudo creates askpass's stdout pipe as root,
|
|
35
|
+
* 0600, so the Hook cannot open `/proc/<pid>/fd/1` there.) It reads
|
|
31
36
|
* that sudo's command line itself and pushes the request to the phone; `GET /v1/sudo` and the overview socket's `sudo` frame
|
|
32
37
|
* list it. `POST /v1/sudo/answer` writes the password into the held
|
|
33
38
|
* connection and forgets the request: the password is never logged, stored,
|
|
@@ -145,6 +150,33 @@ export async function readProcess(pid) {
|
|
|
145
150
|
return undefined;
|
|
146
151
|
}
|
|
147
152
|
}
|
|
153
|
+
/** Linux: whether any process of the owner's other than `exclude` holds a
|
|
154
|
+
* descriptor that links to `target` (`pipe:[n]`, `socket:[n]`). */
|
|
155
|
+
async function heldElsewhere(target, exclude) {
|
|
156
|
+
const holders = (await readdir("/proc")).map(Number).filter(holder => Number.isInteger(holder) && !exclude.includes(holder));
|
|
157
|
+
let next = 0, other = false;
|
|
158
|
+
// Busy machines can have thousands of descriptors. Bound the process
|
|
159
|
+
// concurrency while checking every visible descriptor of each holder.
|
|
160
|
+
await Promise.all(Array.from({ length: Math.min(16, holders.length) }, async () => {
|
|
161
|
+
while (!other && next < holders.length) {
|
|
162
|
+
const holder = holders[next++];
|
|
163
|
+
const fds = await readdir(`/proc/${holder}/fd`).catch(() => []);
|
|
164
|
+
// procfs links are kernel metadata, without disk I/O. Reading a
|
|
165
|
+
// holder's links directly avoids thousands of thread-pool jobs;
|
|
166
|
+
// the directory awaits above still yield between holders.
|
|
167
|
+
for (const fd of fds) {
|
|
168
|
+
try {
|
|
169
|
+
if (readlinkSync(`/proc/${holder}/fd/${fd}`) === target) {
|
|
170
|
+
other = true;
|
|
171
|
+
break;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
catch { /* The descriptor closed or its process exited. */ }
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}));
|
|
178
|
+
return other;
|
|
179
|
+
}
|
|
148
180
|
/** Whether `pid`'s stdout is a pipe that no process of the owner's other than
|
|
149
181
|
* `allowed` holds. sudo, running as root, is never visible here. */
|
|
150
182
|
export async function stdoutReaders(pid, allowed) {
|
|
@@ -153,30 +185,7 @@ export async function stdoutReaders(pid, allowed) {
|
|
|
153
185
|
const target = await readlink(`/proc/${pid}/fd/1`);
|
|
154
186
|
if (!/^pipe:\[\d+\]$/.test(target))
|
|
155
187
|
return "other";
|
|
156
|
-
|
|
157
|
-
.filter(holder => Number.isInteger(holder) && holder !== pid && !allowed.includes(holder));
|
|
158
|
-
let next = 0, other = false;
|
|
159
|
-
// Busy machines can have thousands of descriptors. Bound the process
|
|
160
|
-
// concurrency while checking every visible descriptor of each holder.
|
|
161
|
-
await Promise.all(Array.from({ length: Math.min(16, holders.length) }, async () => {
|
|
162
|
-
while (!other && next < holders.length) {
|
|
163
|
-
const holder = holders[next++];
|
|
164
|
-
const fds = await readdir(`/proc/${holder}/fd`).catch(() => []);
|
|
165
|
-
// procfs links are kernel metadata, without disk I/O. Reading a
|
|
166
|
-
// holder's links directly avoids thousands of thread-pool jobs;
|
|
167
|
-
// the directory awaits above still yield between holders.
|
|
168
|
-
for (const fd of fds) {
|
|
169
|
-
try {
|
|
170
|
-
if (readlinkSync(`/proc/${holder}/fd/${fd}`) === target) {
|
|
171
|
-
other = true;
|
|
172
|
-
break;
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
catch { /* The descriptor closed or its process exited. */ }
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
}));
|
|
179
|
-
return other ? "other" : "sudo";
|
|
188
|
+
return await heldElsewhere(target, [pid, ...allowed]) ? "other" : "sudo";
|
|
180
189
|
}
|
|
181
190
|
// macOS: each pipe end has its own address, and `n->` names the other end.
|
|
182
191
|
const own = await exec("lsof", ["-nP", "-a", "-p", String(pid), "-d", "1", "-F", "tdn"], { timeout: 5_000, maxBuffer: 65_536 });
|
|
@@ -227,8 +236,81 @@ export async function processStart(pid) {
|
|
|
227
236
|
const stat = await readFile(`/proc/${pid}/stat`, "utf8").catch(() => undefined);
|
|
228
237
|
return stat?.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
|
|
229
238
|
}
|
|
230
|
-
|
|
231
|
-
|
|
239
|
+
const DELIVERY_SOCKET = /^phren-askpass-[0-9a-f]{32}$/, DELIVERY_NONCE = /^[0-9a-f]{64}$/;
|
|
240
|
+
export function deliveryFrom(value) {
|
|
241
|
+
const item = object(value);
|
|
242
|
+
return typeof item.socket === "string" && DELIVERY_SOCKET.test(item.socket) && typeof item.nonce === "string" && DELIVERY_NONCE.test(item.nonce)
|
|
243
|
+
? { socket: item.socket, nonce: item.nonce } : undefined;
|
|
244
|
+
}
|
|
245
|
+
export function newDelivery() {
|
|
246
|
+
return { socket: `phren-askpass-${randomBytes(16).toString("hex")}`, nonce: randomBytes(32).toString("hex") };
|
|
247
|
+
}
|
|
248
|
+
/** Linux: the inode of the listening abstract socket `name`, from
|
|
249
|
+
* `/proc/net/unix` (`Num RefCount Protocol Flags Type St Inode Path`; a
|
|
250
|
+
* listener has `__SO_ACCEPTCON`, 0x10000, in Flags). */
|
|
251
|
+
export async function listeningInode(name, table = () => readFile("/proc/net/unix", "utf8")) {
|
|
252
|
+
const text = await table().catch(() => "");
|
|
253
|
+
const found = text.split("\n").slice(1).map(row => row.trim().split(/\s+/))
|
|
254
|
+
.filter(cols => cols.length >= 8 && cols[7] === `@${name}` && (Number.parseInt(cols[3], 16) & 0x10000) !== 0 && /^\d+$/.test(cols[6]));
|
|
255
|
+
return found.length === 1 ? found[0][6] : undefined;
|
|
256
|
+
}
|
|
257
|
+
/** Linux: whether the listening socket `inode` is held by `pid` and no other
|
|
258
|
+
* process of the owner's. */
|
|
259
|
+
export async function listenerHolders(pid, inode) {
|
|
260
|
+
try {
|
|
261
|
+
const target = `socket:[${inode}]`;
|
|
262
|
+
const own = await readdir(`/proc/${pid}/fd`);
|
|
263
|
+
if (!own.some(fd => { try {
|
|
264
|
+
return readlinkSync(`/proc/${pid}/fd/${fd}`) === target;
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
return false;
|
|
268
|
+
} }))
|
|
269
|
+
return "other";
|
|
270
|
+
return await heldElsewhere(target, [pid]) ? "other" : "asker";
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
return "unknown";
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
/** Linux: the password handed to askpass's own listener, if askpass is still
|
|
277
|
+
* the process that was verified and its listener is still the one checked.
|
|
278
|
+
* The check runs after connecting: a name is bound to one listener at a time,
|
|
279
|
+
* so while the asker still holds that listener, this connection reached it. */
|
|
280
|
+
export async function deliverToListener(pid, start, delivery, inode, password, checks = {}) {
|
|
281
|
+
const gone = { status: 410, error: "askpass went away." };
|
|
282
|
+
const socket = (checks.connect ?? (target => createConnection({ path: target })))(`\0${delivery.socket}`);
|
|
283
|
+
try {
|
|
284
|
+
await new Promise((resolve, reject) => { socket.once("connect", resolve); socket.once("error", reject); setTimeout(() => reject(new Error("connect timeout")), 3_000).unref(); });
|
|
285
|
+
if (await (checks.start ?? processStart)(pid) !== start)
|
|
286
|
+
return gone;
|
|
287
|
+
if (await (checks.inode ?? listeningInode)(delivery.socket) !== inode)
|
|
288
|
+
return gone;
|
|
289
|
+
if (await (checks.holders ?? listenerHolders)(pid, inode) !== "asker")
|
|
290
|
+
return gone;
|
|
291
|
+
const ack = new Promise(resolve => {
|
|
292
|
+
let text = "";
|
|
293
|
+
socket.on("data", chunk => { text += chunk.toString(); if (text.includes("\n"))
|
|
294
|
+
resolve(text.startsWith("ok\n")); if (text.length > 64)
|
|
295
|
+
resolve(false); });
|
|
296
|
+
socket.once("close", () => resolve(false));
|
|
297
|
+
socket.once("error", () => resolve(false));
|
|
298
|
+
setTimeout(() => resolve(false), 5_000).unref();
|
|
299
|
+
});
|
|
300
|
+
socket.write(`${delivery.nonce}\n${password}\n`);
|
|
301
|
+
return await ack ? { delivered: true } : gone;
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
return gone;
|
|
305
|
+
}
|
|
306
|
+
finally {
|
|
307
|
+
socket.destroy();
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
/** Linux, an askpass that names no delivery socket (one from before it did):
|
|
311
|
+
* the password written into the asker's stdout, the pipe verified to reach
|
|
312
|
+
* sudo alone. Works only where that pipe is the owner's, not sudo's root-owned
|
|
313
|
+
* one. */
|
|
232
314
|
async function writeToAsker(pid, start, password) {
|
|
233
315
|
if (await processStart(pid) !== start)
|
|
234
316
|
return { status: 410, error: "askpass went away." };
|
|
@@ -282,19 +364,24 @@ function placeFrom(value) {
|
|
|
282
364
|
return Object.fromEntries(fields.map(key => [key, item[key]]));
|
|
283
365
|
}
|
|
284
366
|
/** The chain check against this Hook's own node, bundle and script. */
|
|
285
|
-
async function defaultVerify(pid, hookFd) {
|
|
367
|
+
async function defaultVerify(pid, hookFd, delivery) {
|
|
286
368
|
const linux = process.platform === "linux";
|
|
287
369
|
const running = process.argv[1] ? [path.resolve(process.argv[1])] : [];
|
|
288
370
|
const start = linux ? await processStart(pid) : undefined;
|
|
371
|
+
const inode = linux && delivery ? await listeningInode(delivery.socket) : undefined;
|
|
289
372
|
const result = await verifyAsker(pid, { processes: readProcess, stdout: stdoutReaders, node: process.execPath, script: askpassPath(),
|
|
290
373
|
bundles: [...new Set([path.join(bridgeRoot(), "current/bridge-hook.mjs"), ...running])],
|
|
291
|
-
// On Linux the password goes to the asker's
|
|
292
|
-
|
|
374
|
+
// On Linux the password goes to the asker's own listener (or, for an
|
|
375
|
+
// askpass that names none, its stdout), not this connection.
|
|
376
|
+
connection: linux
|
|
377
|
+
? async (asker) => !start ? "unknown" : !delivery ? "asker" : !inode ? "other" : listenerHolders(asker, inode)
|
|
378
|
+
: asker => connectionHolders(asker, hookFd),
|
|
293
379
|
// The real-Hook tests stand a copy of bash named sudo in for sudo, which cannot run as root.
|
|
294
380
|
unprivilegedSudo: process.env.NODE_ENV === "test" && process.env.PHREN_SUDO_TEST_PARENT === "1" });
|
|
295
381
|
if ("refused" in result)
|
|
296
382
|
return result;
|
|
297
|
-
return { sudo: result.sudo, sudoPid: result.sudoPid, deliver: linux ?
|
|
383
|
+
return { sudo: result.sudo, sudoPid: result.sudoPid, deliver: !linux ? async (password) => ({ password })
|
|
384
|
+
: delivery && inode ? password => deliverToListener(pid, start, delivery, inode, password) : password => writeToAsker(pid, start, password) };
|
|
298
385
|
}
|
|
299
386
|
export class SudoBroker {
|
|
300
387
|
options;
|
|
@@ -323,7 +410,7 @@ export class SudoBroker {
|
|
|
323
410
|
* an answer, a timeout, or `cancel` (the caller went away). */
|
|
324
411
|
async ask(body, respond, hookFd) {
|
|
325
412
|
const none = { cancel: () => { } };
|
|
326
|
-
const verified = await (this.options.verify ?? defaultVerify)(Number(body.pid), hookFd);
|
|
413
|
+
const verified = await (this.options.verify ?? defaultVerify)(Number(body.pid), hookFd, deliveryFrom(body.delivery));
|
|
327
414
|
if ("refused" in verified) {
|
|
328
415
|
respond({ status: 400, error: verified.refused });
|
|
329
416
|
return none;
|
|
@@ -487,8 +574,63 @@ export class SudoAnswerError extends Error {
|
|
|
487
574
|
export async function askpass(prompt, env = process.env) {
|
|
488
575
|
const place = await terminalPaneFromEnv(env).catch(() => undefined);
|
|
489
576
|
const dispatchId = env.PHREN_DISPATCH_ID && briefId.safeParse(env.PHREN_DISPATCH_ID).success ? env.PHREN_DISPATCH_ID : undefined;
|
|
577
|
+
// Linux: listen for the password before asking, so the Hook can check
|
|
578
|
+
// that this process alone holds the listener.
|
|
579
|
+
const listener = process.platform === "linux" ? await deliveryListener().catch(() => undefined) : undefined;
|
|
580
|
+
if (process.platform === "linux" && !listener) {
|
|
581
|
+
process.stderr.write("phren askpass: could not open its delivery socket.\n");
|
|
582
|
+
return 1;
|
|
583
|
+
}
|
|
584
|
+
try {
|
|
585
|
+
return await ask(prompt, place, dispatchId, listener);
|
|
586
|
+
}
|
|
587
|
+
finally {
|
|
588
|
+
listener?.close();
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
/** An abstract socket that takes one password from a connection that sends
|
|
592
|
+
* the nonce first, prints it to stdout, and acknowledges. Any other
|
|
593
|
+
* connection is dropped without an answer. */
|
|
594
|
+
function deliveryListener() {
|
|
595
|
+
const delivery = newDelivery(), expected = Buffer.from(delivery.nonce);
|
|
596
|
+
let printed = false;
|
|
597
|
+
const server = createServer(socket => {
|
|
598
|
+
let text = "";
|
|
599
|
+
socket.setTimeout(10_000, () => socket.destroy());
|
|
600
|
+
socket.on("error", () => { });
|
|
601
|
+
socket.on("data", chunk => {
|
|
602
|
+
if (printed) {
|
|
603
|
+
socket.destroy();
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
text += chunk.toString();
|
|
607
|
+
if (text.length > 2_200) {
|
|
608
|
+
socket.destroy();
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
const lines = text.split("\n");
|
|
612
|
+
if (lines.length < 3)
|
|
613
|
+
return;
|
|
614
|
+
const nonce = Buffer.from(lines[0]);
|
|
615
|
+
if (nonce.length !== expected.length || !timingSafeEqual(nonce, expected) || !lines[1]) {
|
|
616
|
+
socket.destroy();
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
printed = true;
|
|
620
|
+
process.stdout.write(`${lines[1]}\n`);
|
|
621
|
+
text = "";
|
|
622
|
+
socket.end("ok\n");
|
|
623
|
+
server.close();
|
|
624
|
+
});
|
|
625
|
+
});
|
|
626
|
+
return new Promise((resolve, reject) => {
|
|
627
|
+
server.once("error", reject);
|
|
628
|
+
server.listen({ path: `\0${delivery.socket}` }, () => resolve({ delivery, printed: () => printed, close: () => server.close() }));
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
async function ask(prompt, place, dispatchId, listener) {
|
|
490
632
|
const data = JSON.stringify({ pid: process.pid, cwd: process.cwd(), ...(prompt ? { prompt: prompt.slice(0, 200) } : {}),
|
|
491
|
-
...(place ? { place } : {}), ...(dispatchId ? { dispatchId } : {}) });
|
|
633
|
+
...(place ? { place } : {}), ...(dispatchId ? { dispatchId } : {}), ...(listener ? { delivery: listener.delivery } : {}) });
|
|
492
634
|
const reply = await new Promise(resolve => {
|
|
493
635
|
const req = request({ socketPath: localSocket(), path: "/sudo", method: "POST", timeout: SUDO_HOLD_MS + 15_000,
|
|
494
636
|
headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
|
|
@@ -510,7 +652,8 @@ export async function askpass(prompt, env = process.env) {
|
|
|
510
652
|
process.stdout.write(`${reply.body.password}\n`);
|
|
511
653
|
return 0;
|
|
512
654
|
}
|
|
513
|
-
// Linux: the Hook
|
|
655
|
+
// Linux: the Hook handed it to the listener, which printed it (or, an
|
|
656
|
+
// older Hook, wrote it into this process's stdout itself).
|
|
514
657
|
if (reply.status === 200 && reply.body.delivered === true)
|
|
515
658
|
return 0;
|
|
516
659
|
process.stderr.write(`phren askpass: ${typeof reply.body.error === "string" ? reply.body.error : "sudo was not approved."}\n`);
|