@priors/mcp 0.7.2 → 0.8.1

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.
@@ -0,0 +1,186 @@
1
+ // The agent wallet's key, from PRIORS_KEY (0.7.x and earlier) or from a file named by PRIORS_KEY_FILE (0.8.0).
2
+ //
3
+ // A key file keeps the key out of an MCP client's or an agent runtime's config: ElizaOS stores a character's settings
4
+ // in its database in plain text and returns them from its agents API, `claude mcp add -e` puts the value in `ps` and in
5
+ // Claude Code's config, and an OpenClaw or Hermes config file is often shared or committed. The file is read only when
6
+ // it is the user's own and nobody else can read it, the way ssh treats a private key: on Linux and macOS a regular
7
+ // file owned by the user running the server with no group or other permission bits (chmod 600 or 400); root may also
8
+ // read one another user owns (a key mounted owner-only into a container), but only when every directory above it, on
9
+ // the path as given and on the path it resolves to, belongs to root or to the file's owner and nobody else can write
10
+ // it: OpenSSH's secure_path rule (in /tmp, or under a directory another user owns, anyone could have put their own key
11
+ // at that path). On Windows, a file whose ACL lets nobody read it but the user, SYSTEM and the Administrators group
12
+ // (the rule OpenSSH for Windows applies), read with PowerShell's Get-Acl by SID so the answer does not depend on the
13
+ // system's language; PowerShell is run from System32 by its full path, never looked up by name (Windows searches the
14
+ // working directory, which the MCP client chooses, before PATH). Anything else is refused, and the key is not read at
15
+ // all: the server then starts with its read-only tools, and every tool that moves money says what to fix.
16
+ //
17
+ // The file holds the key alone (64 hex characters, with or without 0x), with an optional trailing newline (LF or
18
+ // CRLF) and an optional UTF-8 byte order mark (Notepad's). Its content is never echoed, whatever is wrong with it.
19
+ // The path may start with ~/ (or ~\ on Windows), the user's home directory; otherwise it must be absolute, since an
20
+ // MCP client starts the server in a directory of its own choosing. Setting both PRIORS_KEY and PRIORS_KEY_FILE is
21
+ // refused: the server never guesses which key signs.
22
+ import { closeSync, constants, fstatSync, openSync, readSync, realpathSync, statSync } from "node:fs";
23
+ import { homedir as osHomedir } from "node:os";
24
+ import path from "node:path";
25
+ import { spawnSync } from "node:child_process";
26
+
27
+ /** A private key: 64 hex characters, optional 0x. */
28
+ export const KEY_RE = /^(0x)?[0-9a-fA-F]{64}$/;
29
+ /** The most a key file may hold: a key with a BOM, 0x and CRLF is 71 bytes; anything far bigger is not a key file. */
30
+ const MAX_BYTES = 4096;
31
+ /** Windows SIDs that may hold read access besides the user: LocalSystem and BUILTIN\Administrators (OpenSSH's rule). */
32
+ const WIN_TRUSTED = new Set(["S-1-5-18", "S-1-5-32-544"]);
33
+ /** FileSystemRights bits that let a holder read the content: ReadData, GENERIC_ALL, GENERIC_READ (FullControl, Modify,
34
+ * Read and ReadAndExecute all include ReadData). */
35
+ const WIN_READ_BITS = [0x1, 0x10000000, 0x80000000];
36
+
37
+ /**
38
+ * The Get-Acl report for `p`, as lines: "ME <sid>", "OWNER <sid>", then "ACE <sid> <Allow|Deny> <rights>" per rule,
39
+ * explicit and inherited, with SIDs (not account names, which are translated). The path reaches PowerShell through
40
+ * the environment, never through the command text, so no character in it can change the command.
41
+ */
42
+ const ACL_SCRIPT = [
43
+ "$ErrorActionPreference = 'Stop'",
44
+ "$sid = [System.Security.Principal.SecurityIdentifier]",
45
+ "$acl = Get-Acl -LiteralPath $env:PRIORS_ACL_PATH",
46
+ "'ME ' + [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value",
47
+ "'OWNER ' + $acl.GetOwner($sid).Value",
48
+ "foreach ($r in $acl.GetAccessRules($true, $true, $sid)) { 'ACE ' + $r.IdentityReference.Value + ' ' + $r.AccessControlType + ' ' + [int64]$r.FileSystemRights }",
49
+ ].join("; ");
50
+
51
+ /** Who may read a Windows file, from Get-Acl's report (aclReport): null when only the user, SYSTEM and Administrators
52
+ * can, else a sentence naming the first other SID (and what to run). Pure, for tests. */
53
+ export function aclVerdict(report, file) {
54
+ const lines = String(report ?? "").split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
55
+ const me = lines.find((l) => l.startsWith("ME "))?.slice(3).trim();
56
+ const owner = lines.find((l) => l.startsWith("OWNER "))?.slice(6).trim();
57
+ const fix = `icacls "${file}" /inheritance:r /grant:r "%USERNAME%:R"`;
58
+ if (!me || !/^S-1-[0-9-]+$/.test(me)) return `could not tell who can read it (no answer from Get-Acl). Fix its access with: ${fix}`;
59
+ if (!owner || (owner !== me && !WIN_TRUSTED.has(owner))) return `it is owned by ${owner || "an unknown account"}, not by the user running the server. Fix it with: ${fix}`;
60
+ for (const l of lines.filter((x) => x.startsWith("ACE "))) {
61
+ const [, who, type, rights] = l.split(/\s+/);
62
+ if (type !== "Allow") continue; // a Deny rule only takes access away
63
+ const mask = Number(rights) >>> 0; // GENERIC_READ comes back negative as a 32-bit enum
64
+ if (!WIN_READ_BITS.some((b) => (mask & b) !== 0)) continue;
65
+ if (who === me || WIN_TRUSTED.has(who)) continue;
66
+ return `${who === "S-1-1-0" ? "Everyone" : who === "S-1-5-32-545" ? "the Users group" : who === "S-1-5-11" ? "Authenticated Users" : `another account (${who})`} can read it. Let only your own user read it: ${fix}`;
67
+ }
68
+ return null;
69
+ }
70
+
71
+ /** Windows PowerShell 5.1 by its full path (it ships in System32 with every supported Windows), and the directory it
72
+ * runs in. Never "powershell.exe" alone: Windows looks a bare name up in the working directory before PATH, and the
73
+ * MCP client picks that directory (Claude Code starts the server in the project, which can be a cloned repo holding
74
+ * a powershell.exe of its own that would then run as the user and answer the ACL check). SystemRoot is set by Windows
75
+ * for every process; a value that is not an absolute drive path falls back to C:\Windows. Pure, for tests. */
76
+ export function powershellCommand(env = process.env) {
77
+ const root = /^[A-Za-z]:\\/.test(String(env.SystemRoot ?? "")) ? path.win32.normalize(env.SystemRoot) : "C:\\Windows";
78
+ return { exe: path.win32.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), cwd: path.win32.join(root, "System32") };
79
+ }
80
+
81
+ /** Get-Acl's report for a Windows file (PowerShell 5.1 ships with every supported Windows). Throws when it cannot run.
82
+ * `spawn` is replaceable for tests. */
83
+ export function windowsAclReport(file, { spawn = spawnSync, env = process.env } = {}) {
84
+ const ps = powershellCommand(env);
85
+ const r = spawn(ps.exe, ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", ACL_SCRIPT], {
86
+ cwd: ps.cwd, env: { ...env, PRIORS_ACL_PATH: file }, encoding: "utf8", timeout: 15_000, windowsHide: true,
87
+ });
88
+ if (r.error || r.status !== 0) throw new Error(r.error?.code === "ENOENT" ? "PowerShell was not found" : `Get-Acl failed${r.stderr ? `: ${String(r.stderr).split(/\r?\n/)[0].slice(0, 200)}` : ""}`);
89
+ return r.stdout;
90
+ }
91
+
92
+ /**
93
+ * For root reading a POSIX file another user owns: null when nobody but root and the file's owner could have put it at
94
+ * `file`, else what is wrong (in words, never the content). OpenSSH's secure_path rule: every directory above the file
95
+ * belongs to root or to the file's owner and has no group or other write bit (a root-owned sticky /tmp fails too). It
96
+ * is checked on the path as given (whoever can write one of its directories could have put a symlink there) and on
97
+ * the path that resolves to (realpath), up to /, and the resolved file must be the one that was opened (`st`, its
98
+ * fstat: same device and inode), so nothing was swapped in between. `fs` needs realpathSync and statSync.
99
+ */
100
+ export function securePathProblem(file, st, fs) {
101
+ let real, rs;
102
+ try { real = fs.realpathSync(file); rs = fs.statSync(real); } catch (e) { return `its path could not be resolved (${e?.code || "error"})`; }
103
+ if (rs.dev !== st.dev || rs.ino !== st.ino) return "it changed while it was being checked";
104
+ const dirs = [];
105
+ for (const p of [file, real]) {
106
+ for (let d = path.posix.dirname(p); ; d = path.posix.dirname(d)) {
107
+ if (!dirs.includes(d)) dirs.push(d);
108
+ if (d === path.posix.dirname(d)) break;
109
+ }
110
+ }
111
+ for (const d of dirs) {
112
+ let ds;
113
+ try { ds = fs.statSync(d); } catch (e) { return `the directory ${d} could not be checked (${e?.code || "error"})`; }
114
+ if (ds.uid !== 0 && ds.uid !== st.uid) return `the directory ${d} belongs to yet another user (uid ${ds.uid})`;
115
+ if ((ds.mode & 0o022) !== 0) return `the directory ${d} can be written by other users (mode ${(ds.mode & 0o7777).toString(8).padStart(4, "0")})`;
116
+ }
117
+ return null;
118
+ }
119
+
120
+ /** The absolute path PRIORS_KEY_FILE names on `platform` (~ expanded), or a problem. */
121
+ export function keyFilePath(raw, { platform = process.platform, homedir = osHomedir } = {}) {
122
+ const p = platform === "win32" ? path.win32 : path.posix;
123
+ const s = String(raw ?? "").trim().replace(/^"(.*)"$/, "$1"); // a path pasted with its quotes, as Explorer's "Copy as path" gives it
124
+ if (!s) return { problem: "PRIORS_KEY_FILE is empty" };
125
+ if (/[\0\r\n]/.test(s)) return { problem: "PRIORS_KEY_FILE is not a file path" };
126
+ let full = s;
127
+ if (s === "~" || s.startsWith("~/") || (platform === "win32" && s.startsWith("~\\"))) full = p.join(homedir(), s.slice(1));
128
+ if (!p.isAbsolute(full)) return { problem: `PRIORS_KEY_FILE must be an absolute path (or start with ~/), not a relative one: an MCP client starts the server in a directory of its own choosing` };
129
+ return { file: p.normalize(full) };
130
+ }
131
+
132
+ /**
133
+ * The key the server signs with, from the environment: { key, source, problem }. `key` is the trimmed key text ("" when
134
+ * none), `source` names where it came from, `problem` (when set) says why a key that was configured is not used. The
135
+ * key file's content never appears in `problem`. `deps` replaces the platform, the file system, the home directory,
136
+ * the user id and the Windows ACL report for tests.
137
+ */
138
+ export function keyFromEnv(env = process.env, deps = {}) {
139
+ const platform = deps.platform ?? process.platform;
140
+ const fs = deps.fs ?? { openSync, fstatSync, readSync, closeSync, statSync, realpathSync };
141
+ const inline = typeof env.PRIORS_KEY === "string" ? env.PRIORS_KEY.trim() : "";
142
+ const fileRaw = typeof env.PRIORS_KEY_FILE === "string" ? env.PRIORS_KEY_FILE.trim() : "";
143
+ if (!fileRaw) return { key: inline, source: inline ? "PRIORS_KEY" : null, problem: null };
144
+ if (inline) return { key: "", source: null, problem: "PRIORS_KEY and PRIORS_KEY_FILE are both set: keep one (PRIORS_KEY_FILE, so the key stays out of the client's config)" };
145
+ const at = keyFilePath(fileRaw, { platform, homedir: deps.homedir ?? osHomedir });
146
+ if (at.problem) return { key: "", source: null, problem: at.problem };
147
+ const file = at.file;
148
+ let fd;
149
+ // non-blocking: a FIFO named as the key file would otherwise hold the start until something writes to it (it is then
150
+ // refused below, as anything but a regular file is)
151
+ try { fd = fs.openSync(file, constants.O_RDONLY | (platform === "win32" ? 0 : constants.O_NONBLOCK ?? 0)); } catch (e) {
152
+ return { key: "", source: null, problem: `PRIORS_KEY_FILE ${file} could not be opened (${e?.code === "ENOENT" ? "no such file" : e?.code === "EACCES" || e?.code === "EPERM" ? "permission denied" : e?.code || "error"})` };
153
+ }
154
+ try {
155
+ // The checks read the opened file itself (fstat), so the file cannot be swapped between the check and the read.
156
+ const st = fs.fstatSync(fd);
157
+ if (!st.isFile()) return { key: "", source: null, problem: `PRIORS_KEY_FILE ${file} is not a regular file` };
158
+ if (st.size > MAX_BYTES) return { key: "", source: null, problem: `PRIORS_KEY_FILE ${file} is too large to be a key file` };
159
+ if (platform === "win32") {
160
+ let report;
161
+ try { report = (deps.aclReport ?? windowsAclReport)(file); } catch (e) {
162
+ return { key: "", source: null, problem: `PRIORS_KEY_FILE ${file}: could not check who can read it (${String(e?.message || e).slice(0, 200)}), so it was not read` };
163
+ }
164
+ const why = aclVerdict(report, file);
165
+ if (why) return { key: "", source: null, problem: `PRIORS_KEY_FILE ${file} was not read: ${why}` };
166
+ } else {
167
+ const uid = deps.uid ?? (typeof process.getuid === "function" ? process.getuid() : -1);
168
+ if ((st.mode & 0o077) !== 0) return { key: "", source: null, problem: `PRIORS_KEY_FILE ${file} was not read: other users can access it (mode ${(st.mode & 0o777).toString(8).padStart(3, "0")}). Let only your own user read it: chmod 600 ${file}` };
169
+ if (uid !== 0 && st.uid !== uid) return { key: "", source: null, problem: `PRIORS_KEY_FILE ${file} was not read: it belongs to another user (uid ${st.uid}), not to the user running the server (uid ${uid})` };
170
+ // root reads a file another user owns (a key mounted owner-only into a container) only where nobody but root and
171
+ // that owner could have put it: in /tmp, or anywhere below a directory someone else owns or can write, anyone could
172
+ // have put their own file (their key) at that path
173
+ if (uid === 0 && st.uid !== 0) {
174
+ const why = securePathProblem(file, st, fs);
175
+ if (why) return { key: "", source: null, problem: `PRIORS_KEY_FILE ${file} was not read: it belongs to another user (uid ${st.uid}), and ${why}, so anyone could have put their own key at that path. Keep it where every directory above it belongs to root or to its owner and nobody else can write it (as ssh requires), or chown it to root` };
176
+ }
177
+ }
178
+ const buf = Buffer.alloc(MAX_BYTES + 1);
179
+ let n = 0;
180
+ for (;;) { const got = fs.readSync(fd, buf, n, buf.length - n, null); if (got <= 0) break; n += got; if (n >= buf.length) break; }
181
+ const text = buf.subarray(0, n).toString("utf8").replace(/^\ufeff/, "").trim();
182
+ buf.fill(0);
183
+ if (!KEY_RE.test(text)) return { key: "", source: null, problem: `PRIORS_KEY_FILE ${file} does not hold a private key (64 hex characters, with or without 0x, alone in the file)` };
184
+ return { key: text, source: "PRIORS_KEY_FILE", problem: null };
185
+ } finally { try { fs.closeSync(fd); } catch (_) { /* closed */ } }
186
+ }
@@ -0,0 +1,137 @@
1
+ // `priors-mcp link-wallet` (0.8.0): the agent's own key signs the ERC-8004 registry's AgentWalletSet message, so
2
+ // the agent's owner can declare that key the agent's wallet (`setAgentWallet`) and so prove, before any money moves,
3
+ // that the runtime really holds the key. A pasted address proves nothing: a typo, or someone else's address, would
4
+ // receive the USDG Go mode borrows for the agent. Declared, the wallet's x402 income also counts as the agent's.
5
+ //
6
+ // What is signed is exactly what the live registry checks (IdentityRegistryUpgradeable 2.0.0 on Robinhood Chain, read
7
+ // on 2026-10-09: eip712Domain() answers "ERC8004IdentityRegistry", version "1", chain 4663, the registry itself, no salt;
8
+ // the type hash below is in its code):
9
+ // AgentWalletSet(uint256 agentId,address newWallet,address owner,uint256 deadline)
10
+ // with `owner` the agent's owner (ownerOf) when the owner sends the call, and `deadline` at most 5 minutes after the
11
+ // block that includes it (MAX_DEADLINE_DELAY). So the signature is good for a few minutes only: this command signs
12
+ // for 4 minutes past the chain's latest block by default (--valid, 30 to 290 seconds), and is run again for a fresh one.
13
+ //
14
+ // Before signing it reads the registry's eip712Domain() and refuses if any field differs from the one above (another
15
+ // contract, another chain, an upgrade that changed the domain): it never signs for a domain it does not know. It reads
16
+ // the owner from the chain (--owner, when given, must match it), never from the agent's text. It is a command the
17
+ // operator runs, never an MCP tool: a model reading untrusted text must not be able to sign a wallet over to an agent
18
+ // someone else names. The key comes from PRIORS_KEY_FILE or PRIORS_KEY, as for the server, and is never printed.
19
+ import { ethers } from "ethers";
20
+ import { readFileSync } from "node:fs";
21
+ import { keyFromEnv } from "./key-file.mjs";
22
+
23
+ export const REGISTRY_EIP712 = Object.freeze({ name: "ERC8004IdentityRegistry", version: "1" });
24
+ export const AGENT_WALLET_TYPES = Object.freeze({ AgentWalletSet: [
25
+ { name: "agentId", type: "uint256" }, { name: "newWallet", type: "address" }, { name: "owner", type: "address" }, { name: "deadline", type: "uint256" },
26
+ ] });
27
+ /** The registry's MAX_DEADLINE_DELAY: a deadline later than this past the including block is refused ("deadline too far"). */
28
+ export const MAX_DEADLINE_DELAY_S = 300;
29
+ export const DEFAULT_VALID_S = 240;
30
+ export const REGISTRY_ABI = [
31
+ "function eip712Domain() view returns (bytes1 fields, string name, string version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] extensions)",
32
+ "function ownerOf(uint256 agentId) view returns (address)",
33
+ "function getAgentWallet(uint256 agentId) view returns (address)",
34
+ "function setAgentWallet(uint256 agentId, address newWallet, uint256 deadline, bytes signature)",
35
+ ];
36
+
37
+ export class LinkError extends Error {}
38
+
39
+ /**
40
+ * Sign AgentWalletSet for `agentId` with `signer` (an ethers Wallet, the agent's key) against `registry` on chain
41
+ * `chainId`, reading the domain, the owner, the declared wallet and the latest block through `provider`. Returns what
42
+ * the owner needs to send `setAgentWallet`, or { alreadyLinked: true } when the key is already the agent's wallet.
43
+ */
44
+ export async function signAgentWallet({ signer, provider, registry, chainId = 4663, agentId, validSeconds = DEFAULT_VALID_S, expectOwner = null }) {
45
+ if (!Number.isInteger(validSeconds) || validSeconds < 30 || validSeconds > MAX_DEADLINE_DELAY_S - 10) throw new LinkError(`--valid must be a whole number of seconds from 30 to ${MAX_DEADLINE_DELAY_S - 10} (the registry takes a deadline at most ${MAX_DEADLINE_DELAY_S / 60} minutes ahead)`);
46
+ const id = BigInt(agentId);
47
+ const reg = new ethers.Contract(registry, REGISTRY_ABI, provider);
48
+ let d;
49
+ try { d = await reg.eip712Domain(); } catch (e) { throw new LinkError(`the registry at ${registry} did not answer eip712Domain() (${e?.shortMessage || e?.message || e}); nothing was signed`); }
50
+ const same = d.name === REGISTRY_EIP712.name && d.version === REGISTRY_EIP712.version && BigInt(d.chainId) === BigInt(chainId)
51
+ && ethers.getAddress(d.verifyingContract) === ethers.getAddress(registry) && d.fields === "0x0f" && /^0x0{64}$/.test(d.salt) && d.extensions.length === 0;
52
+ if (!same) throw new LinkError(`the registry's EIP-712 domain is not the one this version signs for (it answered "${String(d.name).slice(0, 60)}" version "${String(d.version).slice(0, 20)}" on chain ${d.chainId} for ${d.verifyingContract}); nothing was signed. Update @priors/mcp.`);
53
+ let owner;
54
+ try { owner = ethers.getAddress(await reg.ownerOf(id)); } catch (_) { throw new LinkError(`agent #${id} does not exist on the registry (ownerOf failed); nothing was signed`); }
55
+ if (expectOwner && ethers.getAddress(expectOwner) !== owner) throw new LinkError(`agent #${id} is owned by ${owner}, not by ${ethers.getAddress(expectOwner)}; nothing was signed`);
56
+ const newWallet = ethers.getAddress(await signer.getAddress());
57
+ let current = null;
58
+ try { current = ethers.getAddress(await reg.getAgentWallet(id)); } catch (_) { /* unknown: sign anyway */ }
59
+ const base = { registry: ethers.getAddress(registry), chainId: Number(chainId), agentId: String(id), newWallet, owner };
60
+ if (current === newWallet) return { ...base, alreadyLinked: true };
61
+ const block = await provider.getBlock("latest");
62
+ if (!block || !Number.isSafeInteger(Number(block.timestamp))) throw new LinkError("could not read the chain's latest block; nothing was signed");
63
+ const deadline = BigInt(block.timestamp) + BigInt(validSeconds);
64
+ const domain = { ...REGISTRY_EIP712, chainId: Number(chainId), verifyingContract: base.registry };
65
+ const message = { agentId: id, newWallet, owner, deadline };
66
+ const signature = await signer.signTypedData(domain, AGENT_WALLET_TYPES, message);
67
+ if (ethers.verifyTypedData(domain, AGENT_WALLET_TYPES, message, signature) !== newWallet) throw new LinkError("the signature did not verify; nothing to send");
68
+ const calldata = new ethers.Interface(REGISTRY_ABI).encodeFunctionData("setAgentWallet", [id, newWallet, deadline, signature]);
69
+ return { ...base, alreadyLinked: false, deadline: String(deadline), expiresAt: new Date(Number(deadline) * 1000).toISOString().replace(".000Z", "Z"), signature, digest: ethers.TypedDataEncoder.hash(domain, AGENT_WALLET_TYPES, message), calldata };
70
+ }
71
+
72
+ const HELP = `priors-mcp link-wallet: sign the ERC-8004 AgentWalletSet message with the agent's key, so its owner can declare
73
+ this key the agent's wallet (setAgentWallet on the identity registry).
74
+
75
+ priors-mcp link-wallet --agent <id> [--owner <0x address>] [--valid <seconds>] [--json]
76
+
77
+ The key comes from PRIORS_KEY_FILE (a file only you can read) or PRIORS_KEY, never from the command line; PRIORS_RPC
78
+ picks the endpoint. The owner must send the call within --valid seconds (default ${DEFAULT_VALID_S}, at most ${MAX_DEADLINE_DELAY_S - 10}): the
79
+ registry takes a signature at most 5 minutes ahead. Run it again for a fresh one.
80
+ `;
81
+
82
+ /** The command: parses `argv` (after "link-wallet"), prints to `out`/`err`, returns the exit code. */
83
+ export async function runLinkWallet(argv, { env = process.env, out = (s) => process.stdout.write(s), err = (s) => process.stderr.write(s), deps = {} } = {}) {
84
+ const o = { json: false };
85
+ for (let i = 0; i < argv.length; i++) {
86
+ const a = argv[i];
87
+ const [flag, inline] = a.startsWith("--") && a.includes("=") ? [a.slice(0, a.indexOf("=")), a.slice(a.indexOf("=") + 1)] : [a, undefined];
88
+ const val = () => { if (inline !== undefined) return inline; i++; if (i >= argv.length) throw new LinkError(`${flag} needs a value`); return argv[i]; };
89
+ try {
90
+ if (flag === "--help" || flag === "-h") { err(HELP); return 0; }
91
+ else if (flag === "--json") o.json = true;
92
+ else if (flag === "--agent") o.agent = val();
93
+ else if (flag === "--owner") o.owner = val();
94
+ else if (flag === "--valid") o.valid = val();
95
+ else throw new LinkError(`unknown argument ${JSON.stringify(a.slice(0, 40))} (see --help)`);
96
+ } catch (e) { err(`priors-mcp link-wallet: ${e.message}\n`); return 2; }
97
+ }
98
+ const fail = (m, code = 1) => { err(`priors-mcp link-wallet: ${m}\n`); return code; };
99
+ const agentRaw = String(o.agent ?? env.PRIORS_AGENT_ID ?? "").trim();
100
+ if (!/^\d{1,78}$/.test(agentRaw)) return fail(agentRaw ? "--agent must be a decimal agent id" : "name the agent: --agent <id> (or set PRIORS_AGENT_ID)", 2);
101
+ if (o.owner !== undefined && !/^0x[0-9a-fA-F]{40}$/.test(o.owner)) return fail("--owner must be a 0x address", 2);
102
+ if (o.valid !== undefined && !/^\d{1,4}$/.test(o.valid)) return fail(`--valid must be a whole number of seconds from 30 to ${MAX_DEADLINE_DELAY_S - 10}`, 2);
103
+ const keyed = deps.key ?? keyFromEnv(env, deps.keyFile);
104
+ if (keyed.problem) return fail(`${keyed.problem}. Nothing was signed.`);
105
+ if (!keyed.key) return fail("no key: set PRIORS_KEY_FILE to a file holding the agent's key (only you may read it), or PRIORS_KEY. Never pass a key on the command line.");
106
+ if (!/^(0x)?[0-9a-fA-F]{64}$/.test(keyed.key)) return fail("PRIORS_KEY is not a 32-byte hex private key. Nothing was signed.");
107
+ const dep = deps.deployments ?? JSON.parse(readFileSync(new URL("../deployments/4663.v2.json", import.meta.url), "utf8"));
108
+ const provider = deps.provider ?? new ethers.JsonRpcProvider(env.PRIORS_RPC || "https://rpc.mainnet.chain.robinhood.com", ethers.Network.from(4663), { staticNetwork: true, cacheTimeout: -1, batchMaxCount: 1 });
109
+ const signer = new ethers.Wallet(keyed.key);
110
+ const secret = keyed.key.replace(/^0x/i, "").toLowerCase();
111
+ const clean = (s) => String(s).split(secret).join("<redacted>").split(secret.toUpperCase()).join("<redacted>");
112
+ let r;
113
+ try {
114
+ r = await signAgentWallet({ signer, provider, registry: dep.registry, chainId: dep.chainId ?? 4663, agentId: agentRaw, validSeconds: o.valid === undefined ? DEFAULT_VALID_S : Number(o.valid), expectOwner: o.owner ?? null });
115
+ } catch (e) {
116
+ const m = e instanceof LinkError ? e.message : `could not reach the chain (${e?.shortMessage || e?.message || e}); nothing was signed`;
117
+ // a private RPC URL (it can carry a token) is cut whole and by its host, as the server cuts it from answers
118
+ let t = clean(m);
119
+ if (env.PRIORS_RPC) { const parts = [env.PRIORS_RPC]; try { const u = new URL(env.PRIORS_RPC); parts.push(u.href, u.host, u.hostname); } catch (_) { /* the literal */ } for (const p of parts.filter((x) => x && x.length >= 6).sort((a, b) => b.length - a.length)) t = t.split(p).join("<rpc>"); }
120
+ return fail(t);
121
+ } finally { if (!deps.provider) provider.destroy?.(); }
122
+ if (o.json) { out(`${JSON.stringify(r)}\n`); return 0; }
123
+ if (r.alreadyLinked) { out(`${r.newWallet} is already agent #${r.agentId}'s ERC-8004 wallet (owner ${r.owner}): nothing to sign.\n`); return 0; }
124
+ const paste = JSON.stringify({ agentId: r.agentId, newWallet: r.newWallet, owner: r.owner, deadline: r.deadline, signature: r.signature });
125
+ out([
126
+ `Signed: ${r.newWallet} (this key) as agent #${r.agentId}'s ERC-8004 wallet, for its owner ${r.owner}.`,
127
+ `The owner sends it before ${r.expiresAt} (the registry takes a signature for at most 5 minutes; run this again for a fresh one):`,
128
+ ` to ${r.registry} (the ERC-8004 identity registry, Robinhood Chain ${r.chainId})`,
129
+ ` call setAgentWallet(${r.agentId}, ${r.newWallet}, ${r.deadline}, signature)`,
130
+ ` data ${r.calldata}`,
131
+ `signature ${r.signature}`,
132
+ `For Priors: ${paste}`,
133
+ "To let this key also borrow on the agent's line, the owner names it the agent's delegate on the pool (setDelegate) in the same step.",
134
+ "",
135
+ ].join("\n"));
136
+ return 0;
137
+ }
@@ -0,0 +1,65 @@
1
+ // PRIORS_PAY_HOSTS (0.8.0): the hosts pay_url may pay, for an agent that reads untrusted text all day (posts on X, mail,
2
+ // web pages) and could be talked into paying a URL someone planted there. Unset, pay_url pays any public https host,
3
+ // as before.
4
+ //
5
+ // Each entry is a host name (or an IP literal), with an optional port, separated by commas or spaces:
6
+ // `api.example.com, data.example.org:8443`. A match is exact: no wildcard, no parent domain covering its subdomains, and
7
+ // a port only when the entry names it (a bare name is the https default, 443). Both sides go through the WHATWG URL
8
+ // parser, the one fetch uses, so what is compared is what would be connected to: lowercase, an internationalised name
9
+ // in its punycode (xn--) form, full-width dots and percent-escapes in the name decoded, an IPv4 address in its dotted
10
+ // form whatever way it was written, and one trailing dot dropped (a fully qualified name is the same host). An entry
11
+ // that is not a plain host (a URL with a path, a wildcard, user info, spaces inside) stops the server at start, so a
12
+ // typo never widens the list.
13
+ //
14
+ // pay_url never follows a redirect (the payer sends every request with redirect: "manual" and hands a 3xx back as the
15
+ // answer, its Location fenced as merchant text); on top of that the allowlist is checked twice: on the URL before
16
+ // anything is fetched (so a refused host sees no request at all), and on every request the payer sends (guardFetch),
17
+ // so no code path can carry a payment header to a host off the list.
18
+
19
+ /** The comparable form of a host ("name" or "name:port"), as fetch would connect to it; throws on anything else. */
20
+ export function normalHost(entry) {
21
+ const s = String(entry ?? "").trim();
22
+ if (!s || /[\s/\\?#@*]/.test(s) || s.includes("://")) throw new Error(`"${s.slice(0, 80)}" is not a host name`);
23
+ let u;
24
+ try { u = new URL(`https://${s}/`); } catch (_) { throw new Error(`"${s.slice(0, 80)}" is not a host name`); }
25
+ if (u.username || u.password || u.pathname !== "/" || u.search || u.hash || !u.hostname) throw new Error(`"${s.slice(0, 80)}" is not a host name`);
26
+ return hostKey(u);
27
+ }
28
+
29
+ /** The comparable host of a parsed URL: hostname without one trailing dot, plus the port when it is not the default. */
30
+ export function hostKey(u) {
31
+ const name = u.hostname.toLowerCase().replace(/\.$/, "");
32
+ return u.port ? `${name}:${u.port}` : name;
33
+ }
34
+
35
+ /** PRIORS_PAY_HOSTS → a frozen Set of comparable hosts, or null when unset (every host, as in 0.7.x). Throws on a bad entry. */
36
+ export function parsePayHosts(raw) {
37
+ const s = String(raw ?? "").trim();
38
+ if (s === "") return null;
39
+ const out = new Set();
40
+ for (const part of s.split(/[\s,]+/).filter(Boolean)) {
41
+ try { out.add(normalHost(part)); } catch (e) { throw new Error(`PRIORS_PAY_HOSTS: ${e.message}; list exact host names, comma-separated (like api.example.com, data.example.org:8443)`); }
42
+ }
43
+ if (out.size === 0) throw new Error("PRIORS_PAY_HOSTS is set but names no host");
44
+ return Object.freeze(out);
45
+ }
46
+
47
+ /** Whether `url` (a string or URL) is on the list; null (no list) allows every URL. */
48
+ export function hostAllowed(hosts, url) {
49
+ if (!hosts) return true;
50
+ let u;
51
+ try { u = url instanceof URL ? url : new URL(String(url)); } catch (_) { return false; }
52
+ // the default port of the URL's own scheme is already dropped by the parser; an http URL (only with
53
+ // PRIORS_ALLOW_LOCAL) on port 80 compares as the bare name, like an https one on 443
54
+ return hosts.has(hostKey(u));
55
+ }
56
+
57
+ /** fetch that refuses any request to a host off the list, before it is sent, and never follows a redirect. */
58
+ export function guardFetch(fetchImpl, hosts) {
59
+ if (!hosts) return fetchImpl;
60
+ return async (input, init) => {
61
+ const r = input instanceof Request ? input : new Request(input, init);
62
+ if (!hostAllowed(hosts, r.url)) throw Object.assign(new Error(`refused: ${new URL(r.url).host} is not in PRIORS_PAY_HOSTS`), { code: "HOST_NOT_ALLOWED" });
63
+ return fetchImpl(r.redirect === "manual" ? r : new Request(r, { redirect: "manual" }));
64
+ };
65
+ }