@phren/cli 0.3.78 → 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/files.d.ts +1 -1
- package/dist/bridge/owner-proof.d.ts +41 -0
- package/dist/bridge/owner-proof.js +118 -0
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +10 -2
- package/dist/bridge-hook.mjs +373 -253
- package/dist/modules/registry.js +1 -1
- package/package.json +1 -1
package/dist/bridge/files.d.ts
CHANGED
|
@@ -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;
|
|
@@ -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
|
+
}
|
|
@@ -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";
|
|
@@ -118,7 +119,7 @@ export async function effectiveStatusRows(server, s, budgetMs = STATUS_ENRICH_BU
|
|
|
118
119
|
export const capabilities = { browsers: true, turnCheckpoints: true, transcript: true, progress: true, images: true, prompt: true, stop: true,
|
|
119
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,
|
|
120
121
|
approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
|
|
121
|
-
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, 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 };
|
|
122
123
|
export function capabilitiesForModules(snapshot) {
|
|
123
124
|
const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
|
|
124
125
|
const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
|
|
@@ -155,6 +156,9 @@ async function codePackageStatus(store, enabled) {
|
|
|
155
156
|
const from = loadedFrom();
|
|
156
157
|
return code && from ? { loadedFrom: from } : { missing: true };
|
|
157
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();
|
|
158
162
|
async function body(request, cap = 11_500_000) {
|
|
159
163
|
let size = 0;
|
|
160
164
|
const chunks = [];
|
|
@@ -164,7 +168,9 @@ async function body(request, cap = 11_500_000) {
|
|
|
164
168
|
throw new BridgeError(413, "Request is too large.");
|
|
165
169
|
chunks.push(chunk);
|
|
166
170
|
}
|
|
167
|
-
|
|
171
|
+
const raw = Buffer.concat(chunks);
|
|
172
|
+
bodyDigests.set(request, bodyDigest(raw));
|
|
173
|
+
return object(JSON.parse(raw.toString() || "{}"));
|
|
168
174
|
}
|
|
169
175
|
export function selectedServer(url) {
|
|
170
176
|
const mux = url.searchParams.get("mux");
|
|
@@ -995,6 +1001,7 @@ export function createRouteHandler(ctx) {
|
|
|
995
1001
|
}
|
|
996
1002
|
else if (request.method === "POST") {
|
|
997
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));
|
|
998
1005
|
if (url.pathname.startsWith("/v1/conductor/move/"))
|
|
999
1006
|
await ctx.succession.authorize(z.string().uuid().parse(data.id), requestPeer(request), url.pathname.endsWith("/prepare") ? z.string().uuid().parse(data.originId) : undefined);
|
|
1000
1007
|
const executeConductor = async (action, payload, origin, remote = false) => {
|
|
@@ -1441,6 +1448,7 @@ export function createRouteHandler(ctx) {
|
|
|
1441
1448
|
if (url.pathname !== "/v1/conductor/grants" && url.pathname !== "/v1/authority" && url.pathname !== "/v1/approval-rules")
|
|
1442
1449
|
throw new BridgeError(404, "Unknown Phren Hook route.");
|
|
1443
1450
|
const data = await body(request);
|
|
1451
|
+
await ownerProof.check(request, url.pathname, data, bodyDigests.get(request));
|
|
1444
1452
|
if (url.pathname === "/v1/conductor/grants" && request.headers?.["x-phren-origin"] === "peer")
|
|
1445
1453
|
throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
|
|
1446
1454
|
if (url.pathname === "/v1/approval-rules") {
|