@phren/cli 0.3.77 → 0.3.78

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.
@@ -10,6 +10,7 @@ import { ApprovalWatchLeases } from "./agent-hook-stores.js";
10
10
  import { PromptDeliveries } from "./prompt-deliveries.js";
11
11
  import { type ConductorCall } from "./agent-hook-asks.js";
12
12
  import { SudoBroker } from "./sudo.js";
13
+ import { SecretBroker } from "./secret.js";
13
14
  import type { AppServerRequestId, PendingServerRequest } from "./codex-app-server.js";
14
15
  import { PaneServerWatcher, type PaneAsks } from "./opencode-panes.js";
15
16
  import type { PaneClient, PaneServerEntry } from "./opencode-pane-server.js";
@@ -125,6 +126,8 @@ export declare class AgentHooks {
125
126
  private computerName;
126
127
  /** sudo -A requests from askpass, answered from the phone (sudo.ts). */
127
128
  readonly sudo: SudoBroker;
129
+ /** phren secret-exec requests, answered from the phone (secret.ts). */
130
+ readonly secrets: SecretBroker;
128
131
  constructor(push?: ApprovalPushService, modules?: ModuleSnapshot | undefined, deliveriesFile?: string);
129
132
  private approvalsDirectory;
130
133
  private scheduleOpencodeSweep;
@@ -40,6 +40,7 @@ import { recordClaudeStatusLine } from "./usage.js";
40
40
  import { briefId, briefIdInPrompt, briefLabel, recordBriefArrival } from "./launch-brief.js";
41
41
  import { appServerApproval, appServerDecision, conductorCall, OPENCODE_APPROVAL_OPTIONS, opencodePermissionReply } from "./agent-hook-asks.js";
42
42
  import { SudoBroker } from "./sudo.js";
43
+ import { SecretBroker } from "./secret.js";
43
44
  import { codexServers } from "./codex-servers.js";
44
45
  import { paneClient, paneKey, PaneServerWatcher, rootSession, servedPane } from "./opencode-panes.js";
45
46
  export { permissionPrompt, terminalChoice, visibleTerminalChoice } from "./terminal-choice.js";
@@ -268,6 +269,8 @@ export class AgentHooks {
268
269
  computerName = hostname().replace(/\.local$/i, "").split(".")[0] || "Computer";
269
270
  /** sudo -A requests from askpass, answered from the phone (sudo.ts). */
270
271
  sudo;
272
+ /** phren secret-exec requests, answered from the phone (secret.ts). */
273
+ secrets;
271
274
  constructor(push = new ApprovalPushService(), modules, deliveriesFile) {
272
275
  this.push = push;
273
276
  this.modules = modules;
@@ -275,17 +278,18 @@ export class AgentHooks {
275
278
  // A push held while the owner was at the desktop is sent only if still unanswered.
276
279
  push.stillPending = binding => this.pushTarget(binding) !== undefined;
277
280
  void computerDisplayName().then(name => { this.computerName = name; }, () => { });
278
- this.sudo = new SudoBroker({ computer: () => this.computerName, push, label: briefLabel,
279
- describe: async (place) => {
280
- const s = await snapshot(place.server);
281
- const pane = findPane(s, place);
282
- if (!pane)
283
- return undefined;
284
- const tab = objects(s.tabs).find(item => item.tab_id === place.tab && item.workspace_id === place.workspace);
285
- const workspace = objects(s.workspaces).find(item => item.workspace_id === place.workspace);
286
- const label = [tab?.label, workspace?.label].find(value => typeof value === "string" && value.trim());
287
- return { ...(typeof pane.agent === "string" ? { source: pane.agent } : {}), ...(label ? { label } : {}) };
288
- } });
281
+ const describe = async (place) => {
282
+ const s = await snapshot(place.server);
283
+ const pane = findPane(s, place);
284
+ if (!pane)
285
+ return undefined;
286
+ const tab = objects(s.tabs).find(item => item.tab_id === place.tab && item.workspace_id === place.workspace);
287
+ const workspace = objects(s.workspaces).find(item => item.workspace_id === place.workspace);
288
+ const label = [tab?.label, workspace?.label].find(value => typeof value === "string" && value.trim());
289
+ return { ...(typeof pane.agent === "string" ? { source: pane.agent } : {}), ...(label ? { label } : {}) };
290
+ };
291
+ this.sudo = new SudoBroker({ computer: () => this.computerName, push, label: briefLabel, describe });
292
+ this.secrets = new SecretBroker({ computer: () => this.computerName, label: briefLabel, describe });
289
293
  }
290
294
  approvalsDirectory() { return path.join(phrenStoreRoot(), ".runtime", "approvals"); }
291
295
  scheduleOpencodeSweep() {
@@ -1777,6 +1781,10 @@ export class AgentHooks {
1777
1781
  await this.sudo.handle(req, res);
1778
1782
  return;
1779
1783
  }
1784
+ if (req.method === "POST" && req.url === "/secret") {
1785
+ await this.secrets.handle(req, res);
1786
+ return;
1787
+ }
1780
1788
  if (req.method !== "POST" || !["/hook", "/conductor-context", "/usage-statusline"].includes(req.url ?? ""))
1781
1789
  throw new Error("Invalid callback");
1782
1790
  let size = 0;
@@ -2131,6 +2139,7 @@ export class AgentHooks {
2131
2139
  this.deferredSubmissions.clear();
2132
2140
  this.closed = true;
2133
2141
  this.sudo.close();
2142
+ this.secrets.close();
2134
2143
  void this.changes.close().catch(() => { });
2135
2144
  for (const pending of this.pending.values()) {
2136
2145
  clearTimeout(pending.timer);
@@ -267,7 +267,7 @@ export async function runBridge(args, version) {
267
267
  process.exit(0);
268
268
  break;
269
269
  // sudo -A runs <bridge>/askpass, which runs this: the password on stdout, or exit 1.
270
- case "askpass": return askpass(args[1]);
270
+ case "askpass": return args[1] === "--secret-exec" && args.length === 2 ? (await import("./secret.js")).secretAskpass() : askpass(args[1]);
271
271
  case "serve": {
272
272
  // The subprocess bridge suite supplies this fixture; no agent binaries or
273
273
  // machine-specific catalogue caches should affect its HTTP assertions.
@@ -4,6 +4,10 @@ async function main() {
4
4
  const args = process.argv.slice(2);
5
5
  // sudo starts a fresh process for every password attempt. It needs only
6
6
  // the askpass client, rather than initializing the Hook server and tools.
7
+ if (args[0] === "askpass" && args[1] === "--secret-exec" && args.length === 2) {
8
+ const { secretAskpass } = await import("./secret.js");
9
+ return secretAskpass();
10
+ }
7
11
  if (args[0] === "askpass") {
8
12
  const { askpass } = await import("./sudo.js");
9
13
  return askpass(args[1]);
@@ -0,0 +1,161 @@
1
+ import { type IncomingMessage, type ServerResponse } from "node:http";
2
+ import { type Json } from "./protocol.js";
3
+ import { type AskpassDelivery, type ProcessRecord, type SudoReply, type SudoSession } from "./sudo.js";
4
+ /**
5
+ * A secret typed on the phone, handed to one command's stdin.
6
+ *
7
+ * `phren secret-exec [--prompt <text>] [--plist <key> [--field K=V]...] -- <command...>`
8
+ * starts the command with a fresh pipe on its stdin, then runs the Hook's
9
+ * askpass script (`<bridge>/askpass --secret-exec`) with its stdout on that
10
+ * same pipe and closes its own copy. The askpass helper asks the Hook over
11
+ * agent.sock, as `sudo -A`'s does, and writes what the phone sends (one line,
12
+ * or a plist with the secret under `<key>`) into the pipe. The agent that ran
13
+ * secret-exec never holds the pipe, so the secret reaches the command and
14
+ * nothing else: not the agent's stdout, stderr, logs or transcript.
15
+ *
16
+ * Before asking the phone the Hook checks the chain (`verifySecretAsker`): the
17
+ * helper is this Hook's node running its bundle as `askpass --secret-exec`
18
+ * with nothing that loads other code, its parent is the installed script,
19
+ * that script has exactly one sibling (the command), and the helper's stdout
20
+ * is a pipe that no process of the owner's reads except that command and its
21
+ * descendants. The connection is bound to the helper the same way sudo's is.
22
+ * The Hook reads the command line itself (never what the caller claims) and
23
+ * the phone shows it, the prompt, the stdin format and the session asking,
24
+ * and needs an approval per run. The secret is never logged, stored or kept
25
+ * past the write. Only phones that subscribe to `secrets` frames can answer
26
+ * (an older app never sees these requests); with none open the request is
27
+ * refused at once.
28
+ */
29
+ export declare const SECRET_FLAG = "--secret-exec";
30
+ export declare const MAX_SECRET_PENDING = 4;
31
+ export declare const SECRET_SPEC_ENV = "PHREN_SECRET_SPEC";
32
+ /** How the secret is written to the command's stdin. */
33
+ export interface SecretSpec {
34
+ prompt?: string;
35
+ format: "line" | "plist";
36
+ key?: string;
37
+ fields?: Record<string, string>;
38
+ }
39
+ /** A spec from the helper's request, or undefined when anything is off. */
40
+ export declare function secretSpec(value: unknown): SecretSpec | undefined;
41
+ /** What the command reads on stdin. */
42
+ export declare function secretPayload(spec: SecretSpec, secret: string): string;
43
+ /** A secret as the phone may send it: one line, nothing a listener would cut. */
44
+ export declare const validSecret: (value: unknown) => value is string;
45
+ /** What the phone sees. Never carries the secret. */
46
+ export interface SecretRequestView {
47
+ id: string;
48
+ kind: "secret";
49
+ computer: string;
50
+ /** The command that will read the secret, as the Hook read it from the process table. */
51
+ command: string;
52
+ /** The text the agent gave, shown as the agent's words, not the system's. */
53
+ prompt?: string;
54
+ stdin: {
55
+ format: "line";
56
+ } | {
57
+ format: "plist";
58
+ key: string;
59
+ fields?: Record<string, string>;
60
+ };
61
+ account?: string;
62
+ cwd?: string;
63
+ session?: SudoSession;
64
+ askedAt: string;
65
+ expiresAt: string;
66
+ }
67
+ /** Every process's parent, from `ps`. */
68
+ export declare function processTable(): Promise<Map<number, number>>;
69
+ export declare const childrenIn: (table: Map<number, number>, parent: number) => number[];
70
+ export declare function descendantsIn(table: Map<number, number>, root: number): Set<number>;
71
+ /** The owner's processes, other than `exclude`, that hold the pipe on `pid`'s
72
+ * stdout (on macOS, its read end). Undefined when stdout is no pipe or the
73
+ * Hook cannot tell. Processes of other users (root) are never listed. */
74
+ export declare function pipeHolders(pid: number, exclude: number[]): Promise<number[] | undefined>;
75
+ export interface SecretCheck {
76
+ processes: (pid: number) => Promise<ProcessRecord | undefined>;
77
+ table: () => Promise<Map<number, number>>;
78
+ holders: (pid: number, exclude: number[]) => Promise<number[] | undefined>;
79
+ connection: (pid: number) => Promise<"asker" | "other" | "unknown">;
80
+ node: string;
81
+ bundles: string[];
82
+ script: string;
83
+ }
84
+ /** The chain from the helper to the one command it feeds, or why it is refused. */
85
+ export declare function verifySecretAsker(pid: number, check: SecretCheck): Promise<{
86
+ command: ProcessRecord;
87
+ commandPid: number;
88
+ } | {
89
+ refused: string;
90
+ }>;
91
+ export interface SecretVerified {
92
+ command: ProcessRecord;
93
+ deliver: (secret: string) => Promise<SudoReply>;
94
+ }
95
+ /** Whether, now, only the command and what it started hold the helper's stdout. */
96
+ export declare function stillOnlyTheCommand(pid: number, commandPid: number, check?: Pick<SecretCheck, "processes" | "table" | "holders">): Promise<boolean>;
97
+ export interface SecretBrokerOptions {
98
+ computer: () => string;
99
+ describe?: (place: {
100
+ server: string;
101
+ workspace: string;
102
+ tab: string;
103
+ pane: string;
104
+ }) => Promise<Pick<SudoSession, "source" | "label"> | undefined>;
105
+ label?: (dispatchId: string) => Promise<string | undefined>;
106
+ verify?: (pid: number, hookFd: number | undefined, delivery?: AskpassDelivery) => Promise<SecretVerified | {
107
+ refused: string;
108
+ }>;
109
+ holdMs?: number;
110
+ account?: string;
111
+ now?: () => number;
112
+ }
113
+ export declare class SecretBroker {
114
+ private options;
115
+ private pending;
116
+ private events;
117
+ private watchers;
118
+ constructor(options: SecretBrokerOptions);
119
+ list(): SecretRequestView[];
120
+ /** Overview sockets that asked for `secrets` frames; each is a phone that can answer. */
121
+ subscribe(listener: (requests: SecretRequestView[]) => void): () => void;
122
+ private changed;
123
+ ask(body: Json, respond: (reply: SudoReply) => void, hookFd?: number): Promise<{
124
+ cancel: () => void;
125
+ }>;
126
+ /** The phone's answer, single use. */
127
+ answer(id: string, answer: {
128
+ secret: string;
129
+ } | {
130
+ deny: true;
131
+ }): boolean;
132
+ close(): void;
133
+ /** The agent.sock `/secret` route. */
134
+ handle(req: IncomingMessage, res: ServerResponse): Promise<void>;
135
+ }
136
+ /** `POST /v1/secrets/answer`. Checked by hand: a schema error could echo the value it refused. */
137
+ export declare function secretAnswer(data: Json): {
138
+ id: string;
139
+ answer: {
140
+ secret: string;
141
+ } | {
142
+ deny: true;
143
+ };
144
+ };
145
+ export declare class SecretAnswerError extends Error {
146
+ constructor();
147
+ }
148
+ /** The helper, `askpass --secret-exec`: asks the Hook, writes the payload to
149
+ * stdout (the command's stdin pipe), and wipes its copy. */
150
+ export declare function secretAskpass(env?: NodeJS.ProcessEnv): Promise<number>;
151
+ export declare const SECRET_EXEC_USAGE: string;
152
+ /** Parsed `phren secret-exec` arguments. */
153
+ export declare function secretExecArgs(args: string[]): {
154
+ spec: SecretSpec;
155
+ command: string[];
156
+ };
157
+ /** `phren secret-exec`. Exits with the command's status, or 1 when the
158
+ * secret was not given (the command is stopped then). */
159
+ export declare function runSecretExec(args: string[], options?: {
160
+ script?: string;
161
+ }): Promise<number>;