@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.
@@ -9,6 +9,7 @@ import { ACCOUNT_ROLES, isAccountRole, setAccountSettings, setComputerAllowedPoo
9
9
  import { claudeHome } from "./claude-accounts.js";
10
10
  import { localMoveAvailability, moveComputers } from "./move-computers.js";
11
11
  import { ownerRequest, requestPeer } from "./request-origin.js";
12
+ import { bodyDigest, OwnerProof } from "./owner-proof.js";
12
13
  import { listMoves, moveSessionFields, readMove } from "./session-move.js";
13
14
  import { getTaskRoute, getTaskDirectoryRoute, updateTaskRoute, createTaskRoute, saveTaskRoute, launchTaskRoute } from "./task-routes.js";
14
15
  import { ownerInboxView } from "./owner-inbox-view.js";
@@ -20,6 +21,7 @@ import path from "node:path";
20
21
  import { stat } from "node:fs/promises";
21
22
  import { z } from "zod";
22
23
  import { sudoAnswer } from "./sudo.js";
24
+ import { secretAnswer } from "./secret.js";
23
25
  import { saveCodeNote } from "./code-note.js";
24
26
  import { handOff } from "./hand-off.js";
25
27
  import { BUILTIN_MODULES, disabledHint } from "../modules/registry.js";
@@ -117,7 +119,7 @@ export async function effectiveStatusRows(server, s, budgetMs = STATUS_ENRICH_BU
117
119
  export const capabilities = { browsers: true, turnCheckpoints: true, transcript: true, progress: true, images: true, prompt: true, stop: true,
118
120
  terminal: "ssh-pty", shell: "ssh-pty", paneTerminal: "ssh-pty", paneLayout: true, deskPresence: true, herdr: true, sessionRename: true, sessionSeen: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
119
121
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
120
- files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", simulatorStream: process.platform === "darwin", simulatorDevices: process.platform === "darwin", simulatorDrag: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, afterTurnQueue: true, queuedMessageActions: ["claude"], deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, moveSummaryByTarget: true, moveConversationCopy: true, claudeAccountAdd: true, accountPools: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true, gitRemoteIdentity: true, gitWatch: true, worktreeRemove: true, terminalResolve: true, conversationSearch: true };
122
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, setLink: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", simulatorStream: process.platform === "darwin", simulatorDevices: process.platform === "darwin", simulatorDrag: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, afterTurnQueue: true, queuedMessageActions: ["claude"], deliveryFrames: true, paneDeliveries: true, resources: true, sudo: true, sudoOutcome: true, secretExec: true, ownerProof: 1, previewDeltas: true, quickChat: true, agentFolder: true, launchPermissionMode: true, sessionMove: true, moveNewChat: true, moveConductor: true, moveToComputer: true, moveConductorToComputer: true, moveResume: true, moveSummaryByTarget: true, moveConversationCopy: true, claudeAccountAdd: true, accountPools: true, workerRelocation: 1, projectMemory: true, fileWrite: true, fileSearch: true, gitReview: true, memoryStoreBatch: true, gitHosts: true, projectHostToken: true, gitRemoteIdentity: true, gitWatch: true, worktreeRemove: true, terminalResolve: true, conversationSearch: true };
121
123
  export function capabilitiesForModules(snapshot) {
122
124
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
123
125
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -154,6 +156,9 @@ async function codePackageStatus(store, enabled) {
154
156
  const from = loadedFrom();
155
157
  return code && from ? { loadedFrom: from } : { missing: true };
156
158
  }
159
+ /** Owner-only actions need the paired phone's signature once it has signed one (owner-proof.ts). */
160
+ const ownerProof = new OwnerProof();
161
+ const bodyDigests = new WeakMap();
157
162
  async function body(request, cap = 11_500_000) {
158
163
  let size = 0;
159
164
  const chunks = [];
@@ -163,7 +168,9 @@ async function body(request, cap = 11_500_000) {
163
168
  throw new BridgeError(413, "Request is too large.");
164
169
  chunks.push(chunk);
165
170
  }
166
- return object(JSON.parse(Buffer.concat(chunks).toString() || "{}"));
171
+ const raw = Buffer.concat(chunks);
172
+ bodyDigests.set(request, bodyDigest(raw));
173
+ return object(JSON.parse(raw.toString() || "{}"));
167
174
  }
168
175
  export function selectedServer(url) {
169
176
  const mux = url.searchParams.get("mux");
@@ -830,6 +837,9 @@ export function createRouteHandler(ctx) {
830
837
  case "/v1/sudo":
831
838
  result = { requests: agentHooks.sudo.list() };
832
839
  break;
840
+ case "/v1/secrets":
841
+ result = { requests: agentHooks.secrets.list() };
842
+ break;
833
843
  case "/v1/projects/locate": {
834
844
  const candidates = await locateProject(String(url.searchParams.get("project") ?? ""), await journal.recent());
835
845
  for (const candidate of candidates) {
@@ -991,6 +1001,7 @@ export function createRouteHandler(ctx) {
991
1001
  }
992
1002
  else if (request.method === "POST") {
993
1003
  const data = await body(request, url.pathname === "/v1/schedules/events" ? SCHEDULE_EVENT_BODY_CAP : undefined);
1004
+ await ownerProof.check(request, url.pathname, data, bodyDigests.get(request));
994
1005
  if (url.pathname.startsWith("/v1/conductor/move/"))
995
1006
  await ctx.succession.authorize(z.string().uuid().parse(data.id), requestPeer(request), url.pathname.endsWith("/prepare") ? z.string().uuid().parse(data.originId) : undefined);
996
1007
  const executeConductor = async (action, payload, origin, remote = false) => {
@@ -1351,6 +1362,20 @@ export function createRouteHandler(ctx) {
1351
1362
  const outcome = parsed.outcome ? await answered.outcome : undefined;
1352
1363
  result = { ok: true, ...(outcome ? { outcome } : {}) };
1353
1364
  }
1365
+ else if (url.pathname === "/v1/secrets/answer") {
1366
+ if (data && typeof data === "object" && "origin" in data)
1367
+ throw new BridgeError(403, "Only the owner answers a secret request, from the phone.");
1368
+ let parsed;
1369
+ try {
1370
+ parsed = secretAnswer(data);
1371
+ }
1372
+ catch {
1373
+ throw new BridgeError(400, "Send an id and a secret, or deny.");
1374
+ }
1375
+ if (!agentHooks.secrets.answer(parsed.id, parsed.answer))
1376
+ throw new BridgeError(404, "This secret request is no longer pending.");
1377
+ result = { ok: true };
1378
+ }
1354
1379
  else if (url.pathname === "/v1/push/answer") {
1355
1380
  await agentHooks.answerPush(z.string().uuid().parse(data.binding), data.decision);
1356
1381
  result = { ok: true };
@@ -1423,6 +1448,7 @@ export function createRouteHandler(ctx) {
1423
1448
  if (url.pathname !== "/v1/conductor/grants" && url.pathname !== "/v1/authority" && url.pathname !== "/v1/approval-rules")
1424
1449
  throw new BridgeError(404, "Unknown Phren Hook route.");
1425
1450
  const data = await body(request);
1451
+ await ownerProof.check(request, url.pathname, data, bodyDigests.get(request));
1426
1452
  if (url.pathname === "/v1/conductor/grants" && request.headers?.["x-phren-origin"] === "peer")
1427
1453
  throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
1428
1454
  if (url.pathname === "/v1/approval-rules") {
@@ -299,6 +299,7 @@ export async function serve(version, options = {}) {
299
299
  renew: server => agentHooks.overview.renew(server),
300
300
  resources: () => resources.read(),
301
301
  sudo: agentHooks.sudo,
302
+ secrets: agentHooks.secrets,
302
303
  });
303
304
  const gitWatch = new GitWatch();
304
305
  // 256 KiB: gitboy's /memory/files asks about up to 500 paths in one query string.
@@ -331,7 +332,7 @@ export async function serve(version, options = {}) {
331
332
  ws.clients.delete(oldest);
332
333
  }
333
334
  if (overviewServer !== undefined) {
334
- overview(client, overviewServer, url.searchParams.get("watchApprovals") === "1", url.searchParams.get("resources") === "1", typedMuxRequest(url), url.searchParams.get("sudo") === "1");
335
+ overview(client, overviewServer, url.searchParams.get("watchApprovals") === "1", url.searchParams.get("resources") === "1", typedMuxRequest(url), url.searchParams.get("sudo") === "1", url.searchParams.get("secrets") === "1");
335
336
  return;
336
337
  }
337
338
  if (url.pathname === "/v1/git/watch") {
@@ -101,6 +101,9 @@ export interface ProcessRecord {
101
101
  }
102
102
  /** One process's parent, effective uid, name and arguments. */
103
103
  export declare function readProcess(pid: number): Promise<ProcessRecord | undefined>;
104
+ /** Linux: whether any process of the owner's other than `exclude` holds a
105
+ * descriptor that links to `target` (`pipe:[n]`, `socket:[n]`). */
106
+ export declare function heldElsewhere(target: string, exclude: number[]): Promise<boolean>;
104
107
  /** Whether `pid`'s stdout is a pipe that no process of the owner's other than
105
108
  * `allowed` holds. sudo, running as root, is never visible here. */
106
109
  export declare function stdoutReaders(pid: number, allowed: number[]): Promise<"sudo" | "other" | "unknown">;
@@ -145,6 +148,8 @@ export interface AskerCheck {
145
148
  script: string;
146
149
  unprivilegedSudo?: boolean;
147
150
  }
151
+ /** What would run other code in the shell script (which drops the rest) or in node. */
152
+ export declare const PRELOADS: string[], NODE_LOADERS: string[];
148
153
  /** The chain from askpass up to sudo, or why it is refused. */
149
154
  export declare function verifyAsker(pid: number, check: AskerCheck): Promise<{
150
155
  sudo: ProcessRecord;
@@ -178,6 +183,12 @@ export interface SudoBrokerOptions {
178
183
  account?: string;
179
184
  now?: () => number;
180
185
  }
186
+ export declare function placeFrom(value: unknown): {
187
+ server: string;
188
+ workspace: string;
189
+ tab: string;
190
+ pane: string;
191
+ } | undefined;
181
192
  export interface Verified {
182
193
  sudo: ProcessRecord;
183
194
  sudoPid: number;
@@ -217,6 +228,7 @@ export declare class SudoBroker {
217
228
  /** The agent.sock `/sudo` route. */
218
229
  handle(req: IncomingMessage, res: ServerResponse): Promise<void>;
219
230
  }
231
+ export declare function userName(): string | undefined;
220
232
  /** A password as sudo reads it from askpass: one line, nothing it would cut. */
221
233
  export declare function sudoAnswer(data: Json): {
222
234
  id: string;
@@ -233,6 +245,15 @@ export declare class SudoAnswerError extends Error {
233
245
  /** The bundle's `askpass` command, run by sudo through `<bridge>/askpass`.
234
246
  * Prints the password and exits 0, or explains on stderr and exits 1. */
235
247
  export declare function askpass(prompt: string | undefined, env?: NodeJS.ProcessEnv): Promise<number>;
248
+ export interface DeliveryListener {
249
+ delivery: AskpassDelivery;
250
+ printed: () => boolean;
251
+ close: () => void;
252
+ }
253
+ /** An abstract socket that takes one password from a connection that sends
254
+ * the nonce first, prints it to stdout, and acknowledges. Any other
255
+ * connection is dropped without an answer. */
256
+ export declare function deliveryListener(take?: (secret: string) => void): Promise<DeliveryListener>;
236
257
  /** `phren sudo <command...>`: `sudo -A` with this Hook's askpass, so the
237
258
  * password comes from the phone even with no terminal (a `!` command, an
238
259
  * agent's shell). Exits with sudo's status. */
@@ -152,7 +152,7 @@ export async function readProcess(pid) {
152
152
  }
153
153
  /** Linux: whether any process of the owner's other than `exclude` holds a
154
154
  * descriptor that links to `target` (`pipe:[n]`, `socket:[n]`). */
155
- async function heldElsewhere(target, exclude) {
155
+ export async function heldElsewhere(target, exclude) {
156
156
  const holders = (await readdir("/proc")).map(Number).filter(holder => Number.isInteger(holder) && !exclude.includes(holder));
157
157
  let next = 0, other = false;
158
158
  // Busy machines can have thousands of descriptors. Bound the process
@@ -329,7 +329,7 @@ async function writeToAsker(pid, start, password) {
329
329
  }
330
330
  }
331
331
  /** What would run other code in the shell script (which drops the rest) or in node. */
332
- const PRELOADS = ["LD_PRELOAD", "DYLD_INSERT_LIBRARIES"], NODE_LOADERS = [...PRELOADS, "NODE_OPTIONS"];
332
+ export const PRELOADS = ["LD_PRELOAD", "DYLD_INSERT_LIBRARIES"], NODE_LOADERS = [...PRELOADS, "NODE_OPTIONS"];
333
333
  /** The chain from askpass up to sudo, or why it is refused. */
334
334
  export async function verifyAsker(pid, check) {
335
335
  const asker = await check.processes(pid);
@@ -356,7 +356,7 @@ export async function verifyAsker(pid, check) {
356
356
  return { sudo, sudoPid: script.ppid };
357
357
  }
358
358
  const placeName = /^[A-Za-z0-9_.:%@-]{1,128}$/;
359
- function placeFrom(value) {
359
+ export function placeFrom(value) {
360
360
  const item = object(value);
361
361
  const fields = ["server", "workspace", "tab", "pane"];
362
362
  if (!fields.every(key => typeof item[key] === "string" && placeName.test(item[key])))
@@ -542,7 +542,7 @@ export class SudoBroker {
542
542
  held.cancel();
543
543
  }
544
544
  }
545
- function userName() { try {
545
+ export function userName() { try {
546
546
  return userInfo().username || undefined;
547
547
  }
548
548
  catch {
@@ -591,7 +591,7 @@ export async function askpass(prompt, env = process.env) {
591
591
  /** An abstract socket that takes one password from a connection that sends
592
592
  * the nonce first, prints it to stdout, and acknowledges. Any other
593
593
  * connection is dropped without an answer. */
594
- function deliveryListener() {
594
+ export function deliveryListener(take = secret => { process.stdout.write(`${secret}\n`); }) {
595
595
  const delivery = newDelivery(), expected = Buffer.from(delivery.nonce);
596
596
  let printed = false;
597
597
  const server = createServer(socket => {
@@ -617,7 +617,7 @@ function deliveryListener() {
617
617
  return;
618
618
  }
619
619
  printed = true;
620
- process.stdout.write(`${lines[1]}\n`);
620
+ take(lines[1]);
621
621
  text = "";
622
622
  socket.end("ok\n");
623
623
  server.close();