@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.
@@ -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.
@@ -1,6 +1,5 @@
1
1
  /** Read-only browsing beneath a root selected and verified by the server. */
2
2
  export declare function browseFiles(root: string, relative: string): Promise<{
3
- size?: undefined;
4
3
  path: string;
5
4
  kind: string;
6
5
  truncated: boolean;
@@ -9,6 +8,7 @@ export declare function browseFiles(root: string, relative: string): Promise<{
9
8
  path: string;
10
9
  kind: string;
11
10
  }[];
11
+ size?: undefined;
12
12
  data?: undefined;
13
13
  } | {
14
14
  truncated?: undefined;
@@ -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,41 @@
1
+ import type { IncomingMessage } from "node:http";
2
+ import { type Json } from "./protocol.js";
3
+ /**
4
+ * Owner proof for the actions an agent must not take for itself: release
5
+ * authority, raising a pane's permission mode, making or stopping the
6
+ * conductor, registering for this computer's alerts and linking computers.
7
+ *
8
+ * Agents run as the same Unix user as the Hook, so no header or local file can
9
+ * tell the owner's phone from an agent's `nc -U hook.sock`. The phone holds its
10
+ * paired SSH key's private half, so it signs these requests with it (the same
11
+ * key that already signs approval rules). Once the Hook has seen one valid
12
+ * signature, unsigned requests to these routes are refused: older apps keep
13
+ * working until the phone starts signing, and after that an agent cannot.
14
+ */
15
+ export declare const OWNER_PROOF_HEADER = "x-phren-owner-proof";
16
+ export declare const ownerProofRoute: (method: string | undefined, pathname: string) => boolean;
17
+ export declare const bodyDigest: (raw: Buffer) => string;
18
+ /** Paired phone keys (iPhone and Android) on the restricted dispatch command. Scoped, computer and plain keys cannot sign. */
19
+ export declare function deviceKeys(authorizedKeys: string): Set<string>;
20
+ export interface OwnerProofOptions {
21
+ root?: string;
22
+ keys?: () => Promise<Set<string>>;
23
+ now?: () => number;
24
+ }
25
+ export declare class OwnerProof {
26
+ private options;
27
+ private seen;
28
+ private required?;
29
+ constructor(options?: OwnerProofOptions);
30
+ private get root();
31
+ private get file();
32
+ private now;
33
+ private keys;
34
+ /** Whether a phone has signed before, so unsigned owner actions are refused. */
35
+ isRequired(): Promise<boolean>;
36
+ /**
37
+ * Throws 403 unless an owner-only request may go ahead. Requests that carry
38
+ * an agent or peer origin are left to the route, which refuses them anyway.
39
+ */
40
+ check(request: Pick<IncomingMessage, "headers" | "method">, pathname: string, data: Json, digest: string | undefined): Promise<void>;
41
+ }
@@ -0,0 +1,118 @@
1
+ import { createHash, createPublicKey, verify } from "node:crypto";
2
+ import { lstat, readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ import { homeDir } from "../home-paths.js";
6
+ import { atomic, BridgeError, bridgeRoot } from "./protocol.js";
7
+ import { ownerRequest } from "./request-origin.js";
8
+ /**
9
+ * Owner proof for the actions an agent must not take for itself: release
10
+ * authority, raising a pane's permission mode, making or stopping the
11
+ * conductor, registering for this computer's alerts and linking computers.
12
+ *
13
+ * Agents run as the same Unix user as the Hook, so no header or local file can
14
+ * tell the owner's phone from an agent's `nc -U hook.sock`. The phone holds its
15
+ * paired SSH key's private half, so it signs these requests with it (the same
16
+ * key that already signs approval rules). Once the Hook has seen one valid
17
+ * signature, unsigned requests to these routes are refused: older apps keep
18
+ * working until the phone starts signing, and after that an agent cannot.
19
+ */
20
+ export const OWNER_PROOF_HEADER = "x-phren-owner-proof";
21
+ const DOMAIN = "phren-owner-request-v1";
22
+ const WINDOW_MS = 300_000;
23
+ const ROUTES = new Set([
24
+ "POST /v1/authority", "POST /v1/authority/confirm", "DELETE /v1/authority",
25
+ "POST /v1/agents/permission-mode",
26
+ "POST /v1/conductor/make", "POST /v1/conductor/stop",
27
+ "POST /v1/push/register",
28
+ "POST /v1/sets/link",
29
+ ]);
30
+ const payloadSchema = z.object({
31
+ domain: z.literal(DOMAIN), nonce: z.string().uuid(), at: z.string().datetime({ offset: true }),
32
+ method: z.enum(["POST", "DELETE"]), path: z.string().min(1).max(4096), body: z.string().regex(/^[a-f0-9]{64}$/),
33
+ }).strict();
34
+ const envelopeSchema = z.object({ payload: z.string().min(1).max(8192), signature: z.string().min(1).max(128), publicKey: z.string().min(1).max(64) }).strict();
35
+ export const ownerProofRoute = (method, pathname) => ROUTES.has(`${method} ${pathname}`);
36
+ export const bodyDigest = (raw) => createHash("sha256").update(raw).digest("hex");
37
+ /** Paired phone keys (iPhone and Android) on the restricted dispatch command. Scoped, computer and plain keys cannot sign. */
38
+ export function deviceKeys(authorizedKeys) {
39
+ const result = new Set();
40
+ for (const line of authorizedKeys.split("\n")) {
41
+ const match = /^restrict,pty,command="sh ~\/\.local\/share\/phren\/bridge\/dispatch" ssh-ed25519 ([A-Za-z0-9+/]+={0,2}) phren-(?:iphone|android)\s*$/.exec(line);
42
+ if (!match)
43
+ continue;
44
+ const wire = Buffer.from(match[1], "base64");
45
+ // SSH string("ssh-ed25519"), string(32-byte key).
46
+ if (wire.length === 51 && wire.readUInt32BE(0) === 11 && wire.subarray(4, 15).toString() === "ssh-ed25519" && wire.readUInt32BE(15) === 32)
47
+ result.add(wire.subarray(19).toString("base64"));
48
+ }
49
+ return result;
50
+ }
51
+ export class OwnerProof {
52
+ options;
53
+ seen = new Map();
54
+ required;
55
+ constructor(options = {}) {
56
+ this.options = options;
57
+ }
58
+ get root() { return this.options.root ?? bridgeRoot(); }
59
+ get file() { return path.join(this.root, "owner-proof.json"); }
60
+ now() { return (this.options.now ?? Date.now)(); }
61
+ async keys() {
62
+ if (this.options.keys)
63
+ return this.options.keys();
64
+ return deviceKeys(await readFile(path.join(homeDir(), ".ssh", "authorized_keys"), "utf8").catch(() => ""));
65
+ }
66
+ /** Whether a phone has signed before, so unsigned owner actions are refused. */
67
+ async isRequired() {
68
+ if (this.required)
69
+ return true;
70
+ const info = await lstat(this.file).catch(() => undefined);
71
+ this.required = !!info?.isFile();
72
+ return this.required;
73
+ }
74
+ /**
75
+ * Throws 403 unless an owner-only request may go ahead. Requests that carry
76
+ * an agent or peer origin are left to the route, which refuses them anyway.
77
+ */
78
+ async check(request, pathname, data, digest) {
79
+ if (!ownerProofRoute(request.method, pathname) || !ownerRequest(request, data))
80
+ return;
81
+ const header = request.headers?.[OWNER_PROOF_HEADER];
82
+ if (typeof header !== "string") {
83
+ if (await this.isRequired())
84
+ throw new BridgeError(403, "Confirm this on your paired phone: this action needs its signature.", { code: "owner-proof-required" });
85
+ return;
86
+ }
87
+ const refused = () => new BridgeError(403, "The phone's signature for this action did not verify.", { code: "owner-proof-invalid" });
88
+ let envelope, payload;
89
+ try {
90
+ envelope = envelopeSchema.parse(JSON.parse(Buffer.from(header, "base64url").toString("utf8")));
91
+ payload = payloadSchema.parse(JSON.parse(Buffer.from(envelope.payload, "base64").toString("utf8")));
92
+ }
93
+ catch {
94
+ throw refused();
95
+ }
96
+ const raw = Buffer.from(envelope.publicKey, "base64"), signature = Buffer.from(envelope.signature, "base64");
97
+ if (raw.length !== 32 || signature.length !== 64 || !(await this.keys()).has(raw.toString("base64")))
98
+ throw refused();
99
+ const key = createPublicKey({ key: Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), raw]), format: "der", type: "spki" });
100
+ if (!verify(null, Buffer.from(envelope.payload, "base64"), key, signature))
101
+ throw refused();
102
+ const at = Date.parse(payload.at), now = this.now();
103
+ if (payload.method !== request.method || payload.path !== pathname || payload.body !== digest || !(Math.abs(now - at) <= WINDOW_MS))
104
+ throw refused();
105
+ for (const [nonce, until] of this.seen)
106
+ if (until < now)
107
+ this.seen.delete(nonce);
108
+ if (this.seen.has(payload.nonce))
109
+ throw refused();
110
+ if (this.seen.size >= 4096)
111
+ throw new BridgeError(429, "Too many signed owner actions. Try again in a few minutes.");
112
+ this.seen.set(payload.nonce, now + 2 * WINDOW_MS);
113
+ if (!(await this.isRequired())) {
114
+ await atomic(this.file, JSON.stringify({ since: new Date(now).toISOString(), key: createHash("sha256").update(raw).digest("hex") }));
115
+ this.required = true;
116
+ }
117
+ }
118
+ }
@@ -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>;