@peer2peer/codex-bridge 0.0.0-stage → 0.1.0
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/LICENSE +201 -0
- package/README.md +214 -2
- package/dist/bridge.d.ts +380 -0
- package/dist/bridge.js +1116 -0
- package/dist/commands.d.ts +47 -0
- package/dist/commands.js +141 -0
- package/dist/confirm.d.ts +68 -0
- package/dist/confirm.js +248 -0
- package/dist/hook.d.ts +22 -0
- package/dist/hook.js +144 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +18 -0
- package/dist/install.d.ts +76 -0
- package/dist/install.js +264 -0
- package/dist/ipc.d.ts +69 -0
- package/dist/ipc.js +302 -0
- package/dist/knobs.d.ts +266 -0
- package/dist/knobs.js +1020 -0
- package/dist/lib.d.ts +374 -0
- package/dist/lib.js +987 -0
- package/dist/mcp.d.ts +66 -0
- package/dist/mcp.js +181 -0
- package/dist/p2p.d.ts +135 -0
- package/dist/p2p.js +121 -0
- package/dist/server.d.ts +41 -0
- package/dist/server.js +274 -0
- package/dist/tools.d.ts +7 -0
- package/dist/tools.js +207 -0
- package/dist/trusted.d.ts +46 -0
- package/dist/trusted.js +177 -0
- package/package.json +48 -4
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { Env } from "./server.js";
|
|
2
|
+
export declare class CodexCommandError extends Error {
|
|
3
|
+
readonly code: string;
|
|
4
|
+
constructor(code: string, message: string);
|
|
5
|
+
}
|
|
6
|
+
export type Output = {
|
|
7
|
+
json: unknown;
|
|
8
|
+
human: string;
|
|
9
|
+
};
|
|
10
|
+
/** Refuses a person-only command run from inside a Codex session's own tool call. */
|
|
11
|
+
export declare function requirePerson(env: Env, what: string): void;
|
|
12
|
+
export declare function installCommand(o: {
|
|
13
|
+
env: Env;
|
|
14
|
+
node?: string;
|
|
15
|
+
script: string;
|
|
16
|
+
codexHome?: string;
|
|
17
|
+
write?: boolean;
|
|
18
|
+
remove?: boolean;
|
|
19
|
+
now?: Date;
|
|
20
|
+
pinFile?: string;
|
|
21
|
+
}): Output;
|
|
22
|
+
export declare function sessionsCommand(o: {
|
|
23
|
+
env: Env;
|
|
24
|
+
}): Promise<Output>;
|
|
25
|
+
export declare function heldCommand(o: {
|
|
26
|
+
env: Env;
|
|
27
|
+
now?: number;
|
|
28
|
+
}): Promise<Output>;
|
|
29
|
+
export interface PersonIo {
|
|
30
|
+
/** Whether stdin and stdout are a real terminal. */
|
|
31
|
+
isTTY: boolean;
|
|
32
|
+
/** Asks the person one line (on the terminal). */
|
|
33
|
+
prompt?: (question: string) => Promise<string>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* `p2p codex release|decline <id>`: the person's own, in a real terminal.
|
|
37
|
+
* Each request first writes a nonce file into P2P_HOME/codex/confirm/,
|
|
38
|
+
* which the bridge accepts only while P2P_HOME is out of the session's
|
|
39
|
+
* sandbox; when its Codex window is a terminal, the bridge also prints a
|
|
40
|
+
* one-time code there that the person types back here.
|
|
41
|
+
*/
|
|
42
|
+
export declare function resolveCommand(o: {
|
|
43
|
+
env: Env;
|
|
44
|
+
id: string;
|
|
45
|
+
decline?: boolean;
|
|
46
|
+
io: PersonIo;
|
|
47
|
+
}): Promise<Output>;
|
package/dist/commands.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// The `p2p codex …` commands, as plain functions the `p2p` CLI wires up:
|
|
4
|
+
// install [--write] [--remove] print (or apply) the Codex config
|
|
5
|
+
// mcp the MCP server Codex starts
|
|
6
|
+
// hook <Event> a Codex hook
|
|
7
|
+
// sessions this machine's live Codex sessions
|
|
8
|
+
// held messages held for the person, with previews
|
|
9
|
+
// release <id> / decline <id> the person's Deliver / Decline
|
|
10
|
+
// `held`, `release`, `decline` and `install --write` are the person's own:
|
|
11
|
+
// run from inside a Codex tool call (CODEX_THREAD_ID is set there), they are
|
|
12
|
+
// refused. That is a backstop, like the PreToolUse guard, not a sandbox.
|
|
13
|
+
import { writeNonce } from "./confirm.js";
|
|
14
|
+
import { applyChanges, codexHomeOf, installEnv, planChanges, printedInstructions } from "./install.js";
|
|
15
|
+
import { ask, readEntries } from "./ipc.js";
|
|
16
|
+
import { inert } from "./lib.js";
|
|
17
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
18
|
+
import { bridgeHome, pinFile, tempRoots, unsafeLocation, userHome, writePin } from "./knobs.js";
|
|
19
|
+
export class CodexCommandError extends Error {
|
|
20
|
+
code;
|
|
21
|
+
constructor(code, message) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.code = code;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Refuses a person-only command run from inside a Codex session's own tool call. */
|
|
27
|
+
export function requirePerson(env, what) {
|
|
28
|
+
if (env.CODEX_THREAD_ID || env.CODEX_SESSION_ID) {
|
|
29
|
+
throw new CodexCommandError("refused", `${what} is for you to run in your own terminal, not from inside a Codex session (its tool calls set CODEX_THREAD_ID)`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function installCommand(o) {
|
|
33
|
+
const env = installEnv(o.env);
|
|
34
|
+
// Codex runs the server with its own PATH (and a project config can change it): the node binary by absolute path.
|
|
35
|
+
const node = o.node && isAbsolute(o.node) ? o.node : process.execPath;
|
|
36
|
+
const plan = { codexHome: o.codexHome ?? codexHomeOf(o.env), node, script: o.script, ...(Object.keys(env).length > 0 ? { env } : {}) };
|
|
37
|
+
if (!o.write) {
|
|
38
|
+
if (o.remove)
|
|
39
|
+
return { json: { written: false, remove: true, ...planChanges(plan, { remove: true }) }, human: "Run with --write to remove the peer2peer entries (each file is backed up first)." };
|
|
40
|
+
return { json: { written: false, plan, instructions: printedInstructions(plan) }, human: printedInstructions(plan) };
|
|
41
|
+
}
|
|
42
|
+
requirePerson(o.env, "`p2p codex install --write`");
|
|
43
|
+
const { changes, error } = planChanges(plan, { remove: o.remove === true });
|
|
44
|
+
if (error)
|
|
45
|
+
throw new CodexCommandError("conflict", error);
|
|
46
|
+
const stamp = (o.now ?? new Date()).toISOString().replace(/[:.]/g, "-");
|
|
47
|
+
const done = applyChanges(changes, stamp);
|
|
48
|
+
// A CODEX_HOME other than ~/.codex is pinned outside any project: where the bridge can't read Codex's
|
|
49
|
+
// own environment (Windows, a non-dumpable Codex), it trusts no other CODEX_HOME (knobs.ts).
|
|
50
|
+
const codexHome = resolve(plan.codexHome);
|
|
51
|
+
const isDefault = codexHome === join(userHome(), ".codex");
|
|
52
|
+
const pin = o.pinFile ?? pinFile();
|
|
53
|
+
const pinned = !isDefault || o.remove ? writePin(codexHome, { file: pin, remove: o.remove === true }) : false;
|
|
54
|
+
const temp = unsafeLocation(codexHome, { projectDirs: [], temp: tempRoots([o.env.TMPDIR]) });
|
|
55
|
+
const lines = done.length === 0
|
|
56
|
+
? [o.remove ? "Nothing to remove: no peer2peer entries found." : "Already installed: nothing changed."]
|
|
57
|
+
: done.map((c) => `${o.remove ? "Updated" : "Wrote"} ${c.path}${c.backup ? ` (backup: ${c.backup})` : ""}`);
|
|
58
|
+
if (pinned)
|
|
59
|
+
lines.push(`${o.remove ? "Unpinned" : "Pinned"} ${codexHome} in ${pin}`);
|
|
60
|
+
if (temp && !o.remove)
|
|
61
|
+
lines.push(`Warning: the bridge never uses a CODEX_HOME in a temp folder (${temp}); it will hold every message there. Use a folder of your own.`);
|
|
62
|
+
if (!o.remove && done.length > 0) {
|
|
63
|
+
lines.push("", "Next: restart Codex, then trust the new hooks once with /hooks.", "Your identity: run `p2p setup` (once per machine) and `p2p join <code>` with a code from a friend, in this terminal.");
|
|
64
|
+
}
|
|
65
|
+
return { json: { written: true, files: done.map((c) => ({ path: c.path, ...(c.backup ? { backup: c.backup } : {}) })) }, human: lines.join("\n") };
|
|
66
|
+
}
|
|
67
|
+
async function everySession(env) {
|
|
68
|
+
const home = bridgeHome(env);
|
|
69
|
+
const out = [];
|
|
70
|
+
for (const e of readEntries(home)) {
|
|
71
|
+
try {
|
|
72
|
+
out.push({ sock: e.sock, answer: await ask(e.sock, { op: "held" }, 3_000) });
|
|
73
|
+
}
|
|
74
|
+
catch { }
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
export async function sessionsCommand(o) {
|
|
79
|
+
const all = await everySession(o.env);
|
|
80
|
+
const sessions = all.map((s) => s.answer.session).filter(Boolean);
|
|
81
|
+
const human = sessions.length === 0
|
|
82
|
+
? "No live Codex sessions with Peer2Peer on this machine."
|
|
83
|
+
: sessions
|
|
84
|
+
.map((s) => `${inert(String(s.address))} sid ${inert(String(s.sid))} ${s.status}${s.online ? "" : " (offline)"} ${s.private ? "private" : `circle ${inert(String(s.circle ?? ""))}`} held ${s.held} ${s.holdsFromOthers ? "holds messages from others" : "delivers from friends"} (${inert(String(s.mode))})${s.hooks ? "" : " [no hooks seen]"}${s.problem ? `\n ! ${inert(String(s.problem))}` : ""}`)
|
|
85
|
+
.join("\n") + "\n\nShare a session with someone: p2p session roster <sid> --add <user>";
|
|
86
|
+
return { json: { sessions }, human };
|
|
87
|
+
}
|
|
88
|
+
export async function heldCommand(o) {
|
|
89
|
+
requirePerson(o.env, "`p2p codex held`");
|
|
90
|
+
const all = await everySession(o.env);
|
|
91
|
+
const rows = all.flatMap((s) => (s.answer.held ?? []).map((h) => ({ ...h, session: String(s.answer.session?.address ?? "") })));
|
|
92
|
+
const now = o.now ?? Date.now();
|
|
93
|
+
const human = rows.length === 0
|
|
94
|
+
? "Nothing is held for you in your Codex sessions."
|
|
95
|
+
: rows
|
|
96
|
+
.map((h) => `${inert(h.id)} from ${inert(h.from)} to ${inert(h.session)} (${Math.max(0, Math.round((now - h.at) / 60_000))} min ago)\n why: ${inert(h.why)}\n p2p codex release ${inert(h.id)} | p2p codex decline ${inert(h.id)}`)
|
|
97
|
+
.join("\n\n") + "\n\nThe text isn't shown here. `p2p codex release` shows it, with a confirmation code, in that session's Codex window.";
|
|
98
|
+
return { json: { held: rows }, human };
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* `p2p codex release|decline <id>`: the person's own, in a real terminal.
|
|
102
|
+
* Each request first writes a nonce file into P2P_HOME/codex/confirm/,
|
|
103
|
+
* which the bridge accepts only while P2P_HOME is out of the session's
|
|
104
|
+
* sandbox; when its Codex window is a terminal, the bridge also prints a
|
|
105
|
+
* one-time code there that the person types back here.
|
|
106
|
+
*/
|
|
107
|
+
export async function resolveCommand(o) {
|
|
108
|
+
const op = o.decline ? "decline" : "release";
|
|
109
|
+
requirePerson(o.env, `\`p2p codex ${op}\``);
|
|
110
|
+
if (!o.io.isTTY || !o.io.prompt)
|
|
111
|
+
throw new CodexCommandError("refused", `\`p2p codex ${op}\` needs a real terminal: run it yourself in your own terminal`);
|
|
112
|
+
const home = bridgeHome(o.env);
|
|
113
|
+
for (const e of readEntries(home)) {
|
|
114
|
+
let held;
|
|
115
|
+
try {
|
|
116
|
+
held = await ask(e.sock, { op: "held" }, 5_000);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (!held.held?.some((h) => h.id === o.id))
|
|
122
|
+
continue;
|
|
123
|
+
// Each request carries a fresh nonce file, which only something outside the sandbox can write.
|
|
124
|
+
let r = await ask(e.sock, { op, id: o.id, nonce: writeNonce(home, op, o.id) }, 15_000);
|
|
125
|
+
for (let tries = 0; !r.ok && r.needsCode && tries < 3; tries++) {
|
|
126
|
+
const code = (await o.io.prompt(`Type the code shown in that session's Codex window: `)).trim();
|
|
127
|
+
if (!code)
|
|
128
|
+
break;
|
|
129
|
+
r = await ask(e.sock, { op, id: o.id, code, nonce: writeNonce(home, op, o.id) }, 15_000);
|
|
130
|
+
if (!r.ok && !r.needsCode && r.reason === "wrong code")
|
|
131
|
+
r = { ok: false, needsCode: true, reason: r.reason };
|
|
132
|
+
}
|
|
133
|
+
if (!r.ok)
|
|
134
|
+
throw new CodexCommandError("refused", inert(r.reason ?? `not ${op}d`));
|
|
135
|
+
return {
|
|
136
|
+
json: { id: o.id, [o.decline ? "declined" : "released"]: true },
|
|
137
|
+
human: o.decline ? "Declined: the sender gets one delivery notice." : "Released: the session's model reads it at its next prompt, tool round or turn end.",
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
throw new CodexCommandError("not_found", `no live Codex session holds ${inert(o.id)} (it may have expired after 10 minutes)`);
|
|
141
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
export declare const NONCE_TTL_MS = 60000;
|
|
2
|
+
/** Requests (challenges and confirmations) allowed per minute, across all held items. */
|
|
3
|
+
export declare const RATE_PER_MINUTE = 5;
|
|
4
|
+
export type GateAnswer = {
|
|
5
|
+
ok: true;
|
|
6
|
+
} | {
|
|
7
|
+
ok: false;
|
|
8
|
+
needsCode?: true;
|
|
9
|
+
reason: string;
|
|
10
|
+
};
|
|
11
|
+
export type Nonce = {
|
|
12
|
+
secret: string;
|
|
13
|
+
};
|
|
14
|
+
export interface GateDeps {
|
|
15
|
+
/** A writer for this bridge's terminal, or null when it has none. */
|
|
16
|
+
tty: () => ((text: string) => void) | null;
|
|
17
|
+
/** Whether that pid descends from Codex (or this bridge). */
|
|
18
|
+
descends: (pid: number) => Promise<boolean>;
|
|
19
|
+
/** Whether releases over the socket can be trusted at all (P2P_HOME out of the sandbox's reach). */
|
|
20
|
+
reach: () => {
|
|
21
|
+
ok: true;
|
|
22
|
+
} | {
|
|
23
|
+
ok: false;
|
|
24
|
+
reason: string;
|
|
25
|
+
};
|
|
26
|
+
/** Checks and consumes the person's nonce file. */
|
|
27
|
+
nonce: (op: string, id: string, nonce: Nonce | undefined) => boolean;
|
|
28
|
+
now: () => number;
|
|
29
|
+
code?: () => string;
|
|
30
|
+
/** Requests a minute (default RATE_PER_MINUTE). */
|
|
31
|
+
ratePerMinute?: number;
|
|
32
|
+
}
|
|
33
|
+
/** A writer for `path` (default: the controlling terminal), or null when it can't be opened. */
|
|
34
|
+
export declare function ttyWriter(path: string | undefined): () => ((text: string) => void) | null;
|
|
35
|
+
export declare function newCode(): string;
|
|
36
|
+
export declare function confirmDir(home: string): string;
|
|
37
|
+
/** The nonce file's name, derived from the secret the CLI keeps: a folder listing (or the file) never reveals the secret. */
|
|
38
|
+
export declare function nonceFileName(secret: string): string;
|
|
39
|
+
/**
|
|
40
|
+
* `p2p codex release|decline`, before each request: a nonce file in
|
|
41
|
+
* P2P_HOME/codex/confirm/ (folder 0700, file 0600) naming the operation and
|
|
42
|
+
* the held id. Its name is a hash of a secret only this process keeps and
|
|
43
|
+
* sends over the socket, so a sandboxed process that can read the folder
|
|
44
|
+
* still can't present it (and so can't spend it). The bridge consumes it.
|
|
45
|
+
*/
|
|
46
|
+
export declare function writeNonce(home: string, op: string, id: string): Nonce;
|
|
47
|
+
/**
|
|
48
|
+
* The bridge's check: the file the secret names exists in a real (not
|
|
49
|
+
* symlinked) P2P_HOME/codex/confirm, is a regular file owned by this user,
|
|
50
|
+
* is fresh, and holds this operation and this id. It is deleted either way.
|
|
51
|
+
*/
|
|
52
|
+
export declare function consumeNonce(home: string, op: string, id: string, nonce: Nonce | undefined, now: number): boolean;
|
|
53
|
+
export declare class PersonGate {
|
|
54
|
+
private readonly deps;
|
|
55
|
+
private readonly challenges;
|
|
56
|
+
/** The person's requests (they came with a valid nonce): code failures back off here. */
|
|
57
|
+
private readonly person;
|
|
58
|
+
/** Everything else (no valid nonce, or a Codex descendant): counted apart, so it never delays the person. */
|
|
59
|
+
private readonly stranger;
|
|
60
|
+
constructor(deps: GateDeps);
|
|
61
|
+
/**
|
|
62
|
+
* Checks one release/decline request. `what` is how the terminal line
|
|
63
|
+
* names the message (the sender, and a one-line preview, which only the
|
|
64
|
+
* person's Codex window shows); `peer` finds the caller's pid where the OS
|
|
65
|
+
* says; `nonce` carries the secret naming the person's nonce file.
|
|
66
|
+
*/
|
|
67
|
+
check(op: "release" | "decline", id: string, code: string | undefined, what: string, peer: () => Promise<number | undefined>, nonce: Nonce | undefined): Promise<GateAnswer>;
|
|
68
|
+
}
|
package/dist/confirm.js
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// Who may release (or decline) a held message: the person, never the model.
|
|
4
|
+
// The local socket is reachable by anything running as the user, the
|
|
5
|
+
// model's own commands included (Codex's sandbox lets them open Unix
|
|
6
|
+
// sockets), and process ancestry proves nothing (setsid plus a double fork
|
|
7
|
+
// reparents a daemon to init). What a sandboxed command can't escape is the
|
|
8
|
+
// sandbox itself, so a release rests on it:
|
|
9
|
+
// 1. a nonce file: `p2p codex release` first writes a file into
|
|
10
|
+
// P2P_HOME/codex/confirm/ (0600) named by the hash of a secret it keeps,
|
|
11
|
+
// then sends the secret; the bridge accepts only a fresh (< 60 s),
|
|
12
|
+
// matching file, owned by this user, in real (not symlinked) folders,
|
|
13
|
+
// and deletes it. Reading the folder isn't enough to spend it;
|
|
14
|
+
// 2. P2P_HOME out of the sandbox's reach: the bridge checks P2P_HOME is
|
|
15
|
+
// outside every writable root of the session's trusted turn context
|
|
16
|
+
// (Bridge.releaseReach). Inside one, under danger-full-access, or with
|
|
17
|
+
// unknown roots, releases over the socket are refused outright;
|
|
18
|
+
// 3. a second factor when the bridge has a terminal (Codex's own window):
|
|
19
|
+
// a one-time code printed only there, typed back into the command.
|
|
20
|
+
// Plus rate limits with backoff, so nothing can spam banners or guess
|
|
21
|
+
// codes, kept apart: requests without a valid nonce (or from a Codex
|
|
22
|
+
// descendant) never push the person's own releases into backoff. And a
|
|
23
|
+
// refusal for callers the OS shows descend from Codex (cheap, never
|
|
24
|
+
// sufficient on its own).
|
|
25
|
+
import { createHash, randomBytes, randomInt } from "node:crypto";
|
|
26
|
+
import { chmodSync, closeSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync, writeSync } from "node:fs";
|
|
27
|
+
import { join } from "node:path";
|
|
28
|
+
const CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
|
|
29
|
+
const CODE_TTL_MS = 2 * 60_000;
|
|
30
|
+
const MAX_TRIES = 3;
|
|
31
|
+
export const NONCE_TTL_MS = 60_000;
|
|
32
|
+
/** Requests (challenges and confirmations) allowed per minute, across all held items. */
|
|
33
|
+
export const RATE_PER_MINUTE = 5;
|
|
34
|
+
const BACKOFF_BASE_MS = 2_000;
|
|
35
|
+
const BACKOFF_MAX_MS = 15 * 60_000;
|
|
36
|
+
/** Requests without a valid nonce (or from a Codex descendant) a minute: counted apart from the person's. */
|
|
37
|
+
const STRANGER_PER_MINUTE = 30;
|
|
38
|
+
/** A writer for `path` (default: the controlling terminal), or null when it can't be opened. */
|
|
39
|
+
export function ttyWriter(path) {
|
|
40
|
+
return () => {
|
|
41
|
+
const target = path?.trim() || (process.platform === "win32" ? "" : "/dev/tty");
|
|
42
|
+
if (!target)
|
|
43
|
+
return null;
|
|
44
|
+
let fd;
|
|
45
|
+
try {
|
|
46
|
+
fd = openSync(target, "a");
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
return (text) => {
|
|
52
|
+
try {
|
|
53
|
+
writeSync(fd, text);
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
closeSync(fd);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export function newCode() {
|
|
62
|
+
let out = "";
|
|
63
|
+
for (let i = 0; i < 6; i++)
|
|
64
|
+
out += CODE_ALPHABET[randomInt(CODE_ALPHABET.length)];
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
export function confirmDir(home) {
|
|
68
|
+
return join(home, "codex", "confirm");
|
|
69
|
+
}
|
|
70
|
+
const SECRET_RE = /^[0-9a-f]{64}$/;
|
|
71
|
+
/** The nonce file's name, derived from the secret the CLI keeps: a folder listing (or the file) never reveals the secret. */
|
|
72
|
+
export function nonceFileName(secret) {
|
|
73
|
+
return `${createHash("sha256").update(`p2p-codex-nonce:${secret}`).digest("hex")}.nonce`;
|
|
74
|
+
}
|
|
75
|
+
/** P2P_HOME/codex and its confirm/ folder are real folders, not symbolic links (which could lead the file anywhere). */
|
|
76
|
+
function confirmDirIsReal(home) {
|
|
77
|
+
for (const dir of [join(home, "codex"), confirmDir(home)]) {
|
|
78
|
+
try {
|
|
79
|
+
const st = lstatSync(dir);
|
|
80
|
+
if (st.isSymbolicLink() || !st.isDirectory())
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* `p2p codex release|decline`, before each request: a nonce file in
|
|
91
|
+
* P2P_HOME/codex/confirm/ (folder 0700, file 0600) naming the operation and
|
|
92
|
+
* the held id. Its name is a hash of a secret only this process keeps and
|
|
93
|
+
* sends over the socket, so a sandboxed process that can read the folder
|
|
94
|
+
* still can't present it (and so can't spend it). The bridge consumes it.
|
|
95
|
+
*/
|
|
96
|
+
export function writeNonce(home, op, id) {
|
|
97
|
+
const dir = confirmDir(home);
|
|
98
|
+
for (const d of [join(home, "codex"), dir]) {
|
|
99
|
+
try {
|
|
100
|
+
if (lstatSync(d).isSymbolicLink())
|
|
101
|
+
throw new Error(`${d} is a symbolic link: refusing to write a confirmation there`);
|
|
102
|
+
}
|
|
103
|
+
catch (e) {
|
|
104
|
+
if (e.code !== "ENOENT")
|
|
105
|
+
throw e;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
109
|
+
try {
|
|
110
|
+
chmodSync(dir, 0o700);
|
|
111
|
+
}
|
|
112
|
+
catch { }
|
|
113
|
+
const secret = randomBytes(32).toString("hex");
|
|
114
|
+
const name = nonceFileName(secret);
|
|
115
|
+
const tmp = join(dir, `.${name}.tmp`);
|
|
116
|
+
writeFileSync(tmp, JSON.stringify({ op, id }), { mode: 0o600 });
|
|
117
|
+
renameSync(tmp, join(dir, name));
|
|
118
|
+
return { secret };
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* The bridge's check: the file the secret names exists in a real (not
|
|
122
|
+
* symlinked) P2P_HOME/codex/confirm, is a regular file owned by this user,
|
|
123
|
+
* is fresh, and holds this operation and this id. It is deleted either way.
|
|
124
|
+
*/
|
|
125
|
+
export function consumeNonce(home, op, id, nonce, now) {
|
|
126
|
+
if (!nonce || typeof nonce.secret !== "string" || !SECRET_RE.test(nonce.secret))
|
|
127
|
+
return false;
|
|
128
|
+
if (!confirmDirIsReal(home))
|
|
129
|
+
return false;
|
|
130
|
+
const file = join(confirmDir(home), nonceFileName(nonce.secret));
|
|
131
|
+
try {
|
|
132
|
+
const st = lstatSync(file);
|
|
133
|
+
if (!st.isFile() || st.isSymbolicLink())
|
|
134
|
+
return false;
|
|
135
|
+
if (typeof process.getuid === "function" && st.uid !== process.getuid())
|
|
136
|
+
return false;
|
|
137
|
+
if (now - st.mtimeMs > NONCE_TTL_MS || st.mtimeMs - now > 5_000)
|
|
138
|
+
return false;
|
|
139
|
+
const v = JSON.parse(readFileSync(file, "utf8"));
|
|
140
|
+
return v.op === op && v.id === id;
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
rmSync(file, { force: true });
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/** A sliding-window rate limit with exponential backoff after failures. */
|
|
150
|
+
class Limiter {
|
|
151
|
+
perMinute;
|
|
152
|
+
now;
|
|
153
|
+
recent = [];
|
|
154
|
+
failures = 0;
|
|
155
|
+
blockedUntil = 0;
|
|
156
|
+
constructor(perMinute, now) {
|
|
157
|
+
this.perMinute = perMinute;
|
|
158
|
+
this.now = now;
|
|
159
|
+
}
|
|
160
|
+
/** Why a request must wait, or undefined (and the request is counted). */
|
|
161
|
+
take() {
|
|
162
|
+
const now = this.now();
|
|
163
|
+
if (now < this.blockedUntil)
|
|
164
|
+
return `too many failed attempts: wait ${Math.ceil((this.blockedUntil - now) / 1000)} s`;
|
|
165
|
+
this.recent = this.recent.filter((at) => now - at < 60_000);
|
|
166
|
+
if (this.recent.length >= this.perMinute)
|
|
167
|
+
return `at most ${this.perMinute} release or decline requests a minute: wait a moment`;
|
|
168
|
+
this.recent.push(now);
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
fail() {
|
|
172
|
+
this.failures += 1;
|
|
173
|
+
if (this.failures >= 2)
|
|
174
|
+
this.blockedUntil = this.now() + Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** (this.failures - 2));
|
|
175
|
+
}
|
|
176
|
+
succeed() {
|
|
177
|
+
this.failures = 0;
|
|
178
|
+
this.blockedUntil = 0;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
export class PersonGate {
|
|
182
|
+
deps;
|
|
183
|
+
challenges = new Map();
|
|
184
|
+
/** The person's requests (they came with a valid nonce): code failures back off here. */
|
|
185
|
+
person;
|
|
186
|
+
/** Everything else (no valid nonce, or a Codex descendant): counted apart, so it never delays the person. */
|
|
187
|
+
stranger;
|
|
188
|
+
constructor(deps) {
|
|
189
|
+
this.deps = deps;
|
|
190
|
+
this.person = new Limiter(deps.ratePerMinute ?? RATE_PER_MINUTE, deps.now);
|
|
191
|
+
this.stranger = new Limiter(STRANGER_PER_MINUTE, deps.now);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Checks one release/decline request. `what` is how the terminal line
|
|
195
|
+
* names the message (the sender, and a one-line preview, which only the
|
|
196
|
+
* person's Codex window shows); `peer` finds the caller's pid where the OS
|
|
197
|
+
* says; `nonce` carries the secret naming the person's nonce file.
|
|
198
|
+
*/
|
|
199
|
+
async check(op, id, code, what, peer, nonce) {
|
|
200
|
+
const reach = this.deps.reach();
|
|
201
|
+
if (!reach.ok)
|
|
202
|
+
return { ok: false, reason: reach.reason };
|
|
203
|
+
if (!this.deps.nonce(op, id, nonce)) {
|
|
204
|
+
const wait = this.stranger.take();
|
|
205
|
+
this.stranger.fail();
|
|
206
|
+
return { ok: false, reason: wait ?? `refused: no fresh confirmation file from \`p2p codex ${op}\` (it writes one in P2P_HOME/codex/confirm; run it yourself, with the same P2P_HOME as Codex)` };
|
|
207
|
+
}
|
|
208
|
+
const pid = await peer();
|
|
209
|
+
if (pid !== undefined && (await this.deps.descends(pid))) {
|
|
210
|
+
this.stranger.fail();
|
|
211
|
+
return { ok: false, reason: `refused: this ${op} came from a process Codex started (possibly the model's own command). Run \`p2p codex ${op}\` in a separate terminal, outside Codex.` };
|
|
212
|
+
}
|
|
213
|
+
const wait = this.person.take();
|
|
214
|
+
if (wait)
|
|
215
|
+
return { ok: false, reason: wait };
|
|
216
|
+
const write = this.deps.tty();
|
|
217
|
+
// No terminal: the nonce file, which only something outside the sandbox can write, is enough.
|
|
218
|
+
if (!write) {
|
|
219
|
+
this.person.succeed();
|
|
220
|
+
return { ok: true };
|
|
221
|
+
}
|
|
222
|
+
const now = this.deps.now();
|
|
223
|
+
const key = `${op}:${id}`;
|
|
224
|
+
const have = this.challenges.get(key);
|
|
225
|
+
if (code !== undefined && have) {
|
|
226
|
+
if (have.exp > now && have.code === code.trim().toUpperCase()) {
|
|
227
|
+
this.challenges.delete(key);
|
|
228
|
+
this.person.succeed();
|
|
229
|
+
return { ok: true };
|
|
230
|
+
}
|
|
231
|
+
have.tries += 1;
|
|
232
|
+
if (have.tries >= MAX_TRIES || have.exp <= now)
|
|
233
|
+
this.challenges.delete(key);
|
|
234
|
+
this.person.fail();
|
|
235
|
+
return { ok: false, reason: have.exp <= now ? "that code expired: run the command again for a new one" : "wrong code" };
|
|
236
|
+
}
|
|
237
|
+
const fresh = (this.deps.code ?? newCode)();
|
|
238
|
+
this.challenges.set(key, { code: fresh, exp: now + CODE_TTL_MS, tries: 0 });
|
|
239
|
+
try {
|
|
240
|
+
write(`\r\n[Peer2Peer] To ${op} ${what}: type ${fresh} into \`p2p codex ${op}\` in a separate terminal (valid 2 minutes). Never paste it into Codex.\r\n`);
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
this.challenges.delete(key);
|
|
244
|
+
return { ok: false, reason: "couldn't show a confirmation code in the Codex window" };
|
|
245
|
+
}
|
|
246
|
+
return { ok: false, needsCode: true, reason: "type the code shown in your Codex window" };
|
|
247
|
+
}
|
|
248
|
+
}
|
package/dist/hook.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** The shell command a PreToolUse payload carries, as one string. */
|
|
2
|
+
export declare function commandOf(input: unknown): string;
|
|
3
|
+
/** PreToolUse: the denial for a shell command the model may not run, or null. */
|
|
4
|
+
export declare function guard(toolName: string, input: unknown, binNames?: readonly string[], ownSid?: string): string | null;
|
|
5
|
+
/**
|
|
6
|
+
* The paths a tool call names outside its folder (a shell command's absolute, ~ and .. paths; the
|
|
7
|
+
* files an apply_patch or edit names), resolved: the bridge binds each one's project (projects.ts).
|
|
8
|
+
*/
|
|
9
|
+
export declare function touchedPaths(toolName: string, input: unknown, cwd: string | undefined, home: string | undefined): {
|
|
10
|
+
paths: string[];
|
|
11
|
+
over: boolean;
|
|
12
|
+
};
|
|
13
|
+
export interface HookDeps {
|
|
14
|
+
home: string;
|
|
15
|
+
/** P2P_BIN and the like, so the guard recognises the CLI under another name. */
|
|
16
|
+
binNames?: readonly string[];
|
|
17
|
+
ancestors?: () => Promise<number[]>;
|
|
18
|
+
/** The user's home folder, for `~` in shell paths. */
|
|
19
|
+
homeDir?: string;
|
|
20
|
+
}
|
|
21
|
+
/** Runs one hook: the JSON to print (empty for nothing). */
|
|
22
|
+
export declare function runHook(event: string, stdin: string, deps: HookDeps): Promise<string>;
|
package/dist/hook.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// `p2p codex hook <Event>`: a Codex hook. Codex runs it with the event's JSON
|
|
4
|
+
// on stdin and reads JSON from stdout. It:
|
|
5
|
+
// - PreToolUse: refuses shell commands that run mutating `p2p` verbs or
|
|
6
|
+
// read the backup phrase / key store (a backstop, like the Claude mod's
|
|
7
|
+
// guard: parsed conservatively, not a sandbox);
|
|
8
|
+
// - every other event: reports to its session's bridge over the local
|
|
9
|
+
// socket and prints what the bridge answers (context for the model, or a
|
|
10
|
+
// Stop continuation).
|
|
11
|
+
// What it reports: the session id, cwd, `permission_mode` and (PostToolUse)
|
|
12
|
+
// the files a tool changed. Never the prompt text: that stays in this
|
|
13
|
+
// process. The socket is reachable by anything running as the user (a
|
|
14
|
+
// sandboxed command too), so the bridge treats a report as untrusted: it
|
|
15
|
+
// can only make the mode stricter, it never binds the thread, and files
|
|
16
|
+
// must exist in the repo.
|
|
17
|
+
// Failing open is safe here (the hold rule lives in the bridge, and no
|
|
18
|
+
// bridge means no messages): any error prints nothing and exits 0.
|
|
19
|
+
import { isAbsolute } from "node:path";
|
|
20
|
+
import { boundaryRefusal, editedFiles, MAX_COMMAND_PATHS, mutatingP2PVerb, namesP2PCli, resolveLike, shellPaths, touchesSecrets } from "./lib.js";
|
|
21
|
+
import { ancestors, ask, findEntry, readEntries } from "./ipc.js";
|
|
22
|
+
const SHELL_TOOLS = /^(bash|shell|local_shell|exec_command|unified_exec|container\.exec|powershell|write_stdin)$/i;
|
|
23
|
+
/** The shell command a PreToolUse payload carries, as one string. */
|
|
24
|
+
export function commandOf(input) {
|
|
25
|
+
if (typeof input === "string")
|
|
26
|
+
return input;
|
|
27
|
+
if (typeof input !== "object" || input === null)
|
|
28
|
+
return "";
|
|
29
|
+
const o = input;
|
|
30
|
+
const c = o.command ?? o.cmd ?? o.chars;
|
|
31
|
+
if (Array.isArray(c))
|
|
32
|
+
return c.map(String).join(" ");
|
|
33
|
+
return typeof c === "string" ? c : "";
|
|
34
|
+
}
|
|
35
|
+
/** PreToolUse: the denial for a shell command the model may not run, or null. */
|
|
36
|
+
export function guard(toolName, input, binNames = [], ownSid) {
|
|
37
|
+
if (!SHELL_TOOLS.test(toolName))
|
|
38
|
+
return null;
|
|
39
|
+
const command = commandOf(input);
|
|
40
|
+
const verb = mutatingP2PVerb(command, binNames);
|
|
41
|
+
if (verb) {
|
|
42
|
+
return `Refused by Peer2Peer: \`p2p ${verb}\` changes who reaches your user (or touches their keys or held messages). Only your user runs it, in their own terminal. Tell them what you'd suggest instead.`;
|
|
43
|
+
}
|
|
44
|
+
if (touchesSecrets(command))
|
|
45
|
+
return "Refused by Peer2Peer: that command reaches the Peer2Peer backup phrase or key store, which never enters model context.";
|
|
46
|
+
const boundary = boundaryRefusal(command, ownSid);
|
|
47
|
+
if (boundary)
|
|
48
|
+
return `Refused by Peer2Peer: ${boundary}.`;
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The paths a tool call names outside its folder (a shell command's absolute, ~ and .. paths; the
|
|
53
|
+
* files an apply_patch or edit names), resolved: the bridge binds each one's project (projects.ts).
|
|
54
|
+
*/
|
|
55
|
+
export function touchedPaths(toolName, input, cwd, home) {
|
|
56
|
+
const out = [];
|
|
57
|
+
let over = false;
|
|
58
|
+
if (SHELL_TOOLS.test(toolName)) {
|
|
59
|
+
// No folder to resolve against: what it names can't be placed, so private.
|
|
60
|
+
if (!cwd)
|
|
61
|
+
over = true;
|
|
62
|
+
else {
|
|
63
|
+
const r = shellPaths(commandOf(input), cwd, home);
|
|
64
|
+
out.push(...r.paths);
|
|
65
|
+
over ||= r.over;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
for (const f of editedFiles(toolName, input)) {
|
|
69
|
+
if (cwd || isAbsolute(f))
|
|
70
|
+
out.push(resolveLike(cwd ?? "/", f));
|
|
71
|
+
else
|
|
72
|
+
over = true;
|
|
73
|
+
}
|
|
74
|
+
if (out.length > MAX_COMMAND_PATHS)
|
|
75
|
+
over = true;
|
|
76
|
+
return { paths: out.slice(0, MAX_COMMAND_PATHS), over };
|
|
77
|
+
}
|
|
78
|
+
/** Runs one hook: the JSON to print (empty for nothing). */
|
|
79
|
+
export async function runHook(event, stdin, deps) {
|
|
80
|
+
let payload;
|
|
81
|
+
try {
|
|
82
|
+
payload = JSON.parse(stdin || "{}");
|
|
83
|
+
if (typeof payload !== "object" || payload === null)
|
|
84
|
+
return "";
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return "";
|
|
88
|
+
}
|
|
89
|
+
const name = typeof payload.hook_event_name === "string" ? payload.hook_event_name : event;
|
|
90
|
+
const sessionId = typeof payload.session_id === "string" ? payload.session_id : undefined;
|
|
91
|
+
const cwd = typeof payload.cwd === "string" ? payload.cwd : undefined;
|
|
92
|
+
const entries = readEntries(deps.home);
|
|
93
|
+
// A bridge already bound to this thread needs no process-tree walk (hooks run on every tool call).
|
|
94
|
+
const bound = sessionId ? entries.find((e) => e.threadId === sessionId) : undefined;
|
|
95
|
+
const entry = bound ?? findEntry(entries, { ...(sessionId ? { sessionId } : {}), ancestors: await (deps.ancestors ?? ancestors)(), ...(cwd ? { cwd } : {}) });
|
|
96
|
+
if (name === "PreToolUse") {
|
|
97
|
+
// This bridge's own session is the only one the model's shell may name (none known: none at all).
|
|
98
|
+
// Fails closed: a guard that throws on a command naming p2p denies it.
|
|
99
|
+
let deny;
|
|
100
|
+
try {
|
|
101
|
+
deny = guard(String(payload.tool_name ?? ""), payload.tool_input, deps.binNames, entry?.sid);
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
deny = namesP2PCli(commandOf(payload.tool_input)) ? "Refused by Peer2Peer: this command couldn't be checked; ask your user to run it." : null;
|
|
105
|
+
}
|
|
106
|
+
if (deny)
|
|
107
|
+
return JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: deny } });
|
|
108
|
+
// Paths the call reaches bind their projects before it runs (any that can't be placed: private).
|
|
109
|
+
const t = entry ? touchedPaths(String(payload.tool_name ?? ""), payload.tool_input, cwd, deps.homeDir) : { paths: [], over: false };
|
|
110
|
+
if (entry && (t.paths.length > 0 || t.over)) {
|
|
111
|
+
// The bridge must hear it before the call runs: if it can't be told, the call doesn't run.
|
|
112
|
+
const told = await ask(entry.sock, { op: "hook", report: { event: "PreToolUse", ...(sessionId ? { sessionId } : {}), ...(cwd ? { cwd } : {}), mode: {}, dirs: t.paths, ...(t.over ? { over: true } : {}) } }, 8_000)
|
|
113
|
+
.then((r) => r?.ok === true)
|
|
114
|
+
.catch(() => false);
|
|
115
|
+
if (!told) {
|
|
116
|
+
return JSON.stringify({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: "Refused by Peer2Peer: this call reaches folders outside the session's, and the Peer2Peer bridge couldn't be told (its project boundary would be wrong). Try again; if it keeps failing, ask your user." } });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return "";
|
|
120
|
+
}
|
|
121
|
+
// Subagents' events belong to the parent's turn: only the main thread reports.
|
|
122
|
+
if (typeof payload.agent_id === "string" && payload.agent_id !== "")
|
|
123
|
+
return "";
|
|
124
|
+
if (!entry)
|
|
125
|
+
return "";
|
|
126
|
+
// Only what may make the bridge stricter: it reads the mode itself from
|
|
127
|
+
// this thread's rollout file, and ignores a report that would loosen it.
|
|
128
|
+
const mode = typeof payload.permission_mode === "string" ? { permissionMode: payload.permission_mode } : {};
|
|
129
|
+
const report = {
|
|
130
|
+
event: name,
|
|
131
|
+
...(sessionId ? { sessionId } : {}),
|
|
132
|
+
...(cwd ? { cwd } : {}),
|
|
133
|
+
mode,
|
|
134
|
+
...(name === "PostToolUse" ? { files: editedFiles(String(payload.tool_name ?? ""), payload.tool_input).slice(0, 50) } : {}),
|
|
135
|
+
...(name === "Stop" ? { stopHookActive: payload.stop_hook_active === true } : {}),
|
|
136
|
+
};
|
|
137
|
+
try {
|
|
138
|
+
const r = await ask(entry.sock, { op: "hook", report }, 8_000);
|
|
139
|
+
return r.ok && r.output && Object.keys(r.output).length > 0 ? JSON.stringify(r.output) : "";
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return "";
|
|
143
|
+
}
|
|
144
|
+
}
|