presign-guard-wallet 0.20.0 → 0.20.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.
- package/README.md +1 -1
- package/ac2.d.ts +2 -0
- package/ac2.js +96 -53
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -185,7 +185,7 @@ Only the chat you name (or the `allowedUserIds` you list) can answer; anyone els
|
|
|
185
185
|
});
|
|
186
186
|
```
|
|
187
187
|
|
|
188
|
-
What you sign is a text that starts with `fizzl-approval-v1` and names the agent, the amount, the network, the recipient, the URL, presign-guard's verdict, an id and an expiry time. It is never a transaction (Algorand signs transactions over `TX` + the transaction), so a signed approval can't be used as a payment. A decline, no answer in time, or a signature from another key counts as Deny. Without `owner`, the account the AC2 service is paired with is used, fixed at the first request. If the AC2 service isn't running or
|
|
188
|
+
What you sign is a text that starts with `fizzl-approval-v1` and names the agent, the amount, the network, the recipient, the URL, presign-guard's verdict, an id and an expiry time. It is never a transaction (Algorand signs transactions over `TX` + the transaction), so a signed approval can't be used as a payment. A decline, no answer in time, or a signature from another key counts as Deny. Without `owner`, the account the AC2 service is paired with is used, fixed at the first request. Each request first registers with the AC2 service as an agent: after a restart or a dropped link the service only waits for your wallet again once an agent is there, and the request then waits up to a minute (`connectTimeoutMs`) for your wallet to come back, so keep AC2 Wallet open. If the AC2 service isn't running or your wallet doesn't come back, the wallet stops (`limit_unavailable`) rather than signing. The agent still signs and pays with its own key, on any network; only the approval comes from your wallet. This module talks to the AC2 service over its local socket (`~/.ac2/ac2d.sock`, or `AC2_DAEMON_SOCKET`) and adds no packages.
|
|
189
189
|
|
|
190
190
|
`verifyApproval(owner, payload, signature)` checks a stored approval again later.
|
|
191
191
|
|
package/ac2.d.ts
CHANGED
|
@@ -7,6 +7,8 @@ export interface Ac2ApproverOptions {
|
|
|
7
7
|
socket?: string;
|
|
8
8
|
/** How long the agent waits for your approval. Default 10 minutes; no answer counts as Deny. */
|
|
9
9
|
timeoutMs?: number;
|
|
10
|
+
/** How long to wait for your wallet to (re)connect to the AC2 service before asking. Default 1 minute. */
|
|
11
|
+
connectTimeoutMs?: number;
|
|
10
12
|
/** Name of the agent in the request. Default "Your agent". */
|
|
11
13
|
label?: string;
|
|
12
14
|
}
|
package/ac2.js
CHANGED
|
@@ -14,12 +14,15 @@
|
|
|
14
14
|
// transactions over "TX" + the transaction, so a signed approval can't be used as a payment.
|
|
15
15
|
//
|
|
16
16
|
// Needs the AC2 service (ac2-cli) running on this machine and paired with your wallet (`ac2 pair`). This module
|
|
17
|
-
// talks to it over its local socket (~/.ac2/ac2d.sock, or AC2_DAEMON_SOCKET) and needs no extra packages.
|
|
18
|
-
//
|
|
17
|
+
// talks to it over its local socket (~/.ac2/ac2d.sock, or AC2_DAEMON_SOCKET) and needs no extra packages. Each
|
|
18
|
+
// request registers as an agent first (agent.hello): after a restart or a dropped link the service only waits
|
|
19
|
+
// for the wallet again once an agent is there, and then this module waits (default 1 minute) for the wallet to
|
|
20
|
+
// come back, so keep AC2 Wallet open. If the service isn't running or the wallet doesn't come back, the wallet
|
|
21
|
+
// stops (limit_unavailable) rather than signing.
|
|
19
22
|
|
|
20
23
|
import { connect as netConnect } from "node:net";
|
|
21
24
|
import { createHash, createPublicKey, randomBytes, verify } from "node:crypto";
|
|
22
|
-
import { homedir } from "node:os";
|
|
25
|
+
import { homedir, hostname } from "node:os";
|
|
23
26
|
import { join } from "node:path";
|
|
24
27
|
|
|
25
28
|
const PREFIX = "fizzl-approval-v1";
|
|
@@ -66,16 +69,20 @@ export function verifyApproval(owner, payload, signature) {
|
|
|
66
69
|
}
|
|
67
70
|
}
|
|
68
71
|
|
|
69
|
-
//
|
|
70
|
-
|
|
71
|
-
|
|
72
|
+
// A connection to the AC2 service: newline-delimited JSON requests, answered by id on the same connection.
|
|
73
|
+
// Kept open for one approval, so the agent stays registered while it waits for the wallet.
|
|
74
|
+
function openSession(path, connect) {
|
|
75
|
+
return new Promise((resolveOpen, rejectOpen) => {
|
|
72
76
|
const sock = connect(path);
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
const
|
|
77
|
+
const pending = new Map();
|
|
78
|
+
let buf = "", seq = 0, open = false;
|
|
79
|
+
const failAll = (err) => { for (const p of pending.values()) { clearTimeout(p.timer); p.reject(err); } pending.clear(); };
|
|
76
80
|
sock.setEncoding("utf8");
|
|
77
|
-
sock.on("error", (err) =>
|
|
78
|
-
|
|
81
|
+
sock.on("error", (err) => {
|
|
82
|
+
const e = Object.assign(new Error(`can't reach the AC2 service at ${path} (${err.code ?? err.message}): start it (\`ac2 service start\`) and pair your wallet with \`ac2 pair\``), { code: "unreachable" });
|
|
83
|
+
if (!open) rejectOpen(e); else failAll(e);
|
|
84
|
+
});
|
|
85
|
+
sock.on("close", () => failAll(Object.assign(new Error("the AC2 service closed the connection"), { code: "unreachable" })));
|
|
79
86
|
sock.on("data", (chunk) => {
|
|
80
87
|
buf += chunk;
|
|
81
88
|
for (let nl = buf.indexOf("\n"); nl >= 0; nl = buf.indexOf("\n")) {
|
|
@@ -83,11 +90,26 @@ function controlRequest(path, method, params, { timeoutMs, connect }) {
|
|
|
83
90
|
buf = buf.slice(nl + 1);
|
|
84
91
|
let frame;
|
|
85
92
|
try { frame = JSON.parse(line); } catch { continue; }
|
|
86
|
-
|
|
87
|
-
if (
|
|
88
|
-
|
|
93
|
+
const p = frame.id !== undefined && pending.get(frame.id);
|
|
94
|
+
if (!p) continue; // events
|
|
95
|
+
pending.delete(frame.id);
|
|
96
|
+
clearTimeout(p.timer);
|
|
97
|
+
if (frame.error) p.reject(Object.assign(new Error(`AC2 service: ${frame.error.message ?? frame.error.code}`), { code: frame.error.code }));
|
|
98
|
+
else p.resolve(frame.result);
|
|
89
99
|
}
|
|
90
100
|
});
|
|
101
|
+
sock.on("connect", () => {
|
|
102
|
+
open = true;
|
|
103
|
+
resolveOpen({
|
|
104
|
+
request: (method, params, timeoutMs = 10_000) => new Promise((resolve, reject) => {
|
|
105
|
+
const id = ++seq;
|
|
106
|
+
const timer = setTimeout(() => { pending.delete(id); reject(Object.assign(new Error(`the AC2 service did not answer ${method} in time`), { code: "timeout" })); }, timeoutMs);
|
|
107
|
+
pending.set(id, { resolve, reject, timer });
|
|
108
|
+
sock.write(`${JSON.stringify({ id, method, params })}\n`);
|
|
109
|
+
}),
|
|
110
|
+
close: () => sock.destroy(),
|
|
111
|
+
});
|
|
112
|
+
});
|
|
91
113
|
});
|
|
92
114
|
}
|
|
93
115
|
|
|
@@ -113,54 +135,75 @@ export function approvalText(info, { label, id, expiresAt }) {
|
|
|
113
135
|
* @param {string} [o.owner] your Algorand address; only its signature approves. Default: the wallet the AC2 service is paired with, fixed at the first request.
|
|
114
136
|
* @param {string} [o.socket] the AC2 service's socket (default ~/.ac2/ac2d.sock or AC2_DAEMON_SOCKET)
|
|
115
137
|
* @param {number} [o.timeoutMs] how long the agent waits for you (default 10 minutes); no answer = deny
|
|
138
|
+
* @param {number} [o.connectTimeoutMs] how long to wait for the wallet to (re)connect to the service (default 1 minute)
|
|
116
139
|
* @param {string} [o.label] name of the agent in the request (default "Your agent")
|
|
117
140
|
*/
|
|
118
|
-
export function ac2Approver({ owner, socket = defaultSocketPath(), timeoutMs = 600_000, label = "Your agent", connect = netConnect, now = () => Date.now() } = {}) {
|
|
141
|
+
export function ac2Approver({ owner, socket = defaultSocketPath(), timeoutMs = 600_000, connectTimeoutMs = 60_000, label = "Your agent", connect = netConnect, now = () => Date.now(), pollMs = 1000 } = {}) {
|
|
119
142
|
if (owner !== undefined && !algorandPublicKey(owner)) throw new TypeError("owner must be an Algorand address (58 characters, with a valid checksum)");
|
|
120
143
|
if (!(timeoutMs > 0)) throw new TypeError("timeoutMs must be a positive number of milliseconds");
|
|
121
144
|
let pinned = owner ?? null;
|
|
122
|
-
const ask = (method, params, ms = 10_000) => controlRequest(socket, method, params, { timeoutMs: ms, connect });
|
|
123
145
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
const status = await ask("daemon.status", {});
|
|
127
|
-
const address = status?.connection?.walletAddress;
|
|
128
|
-
if (status?.connection?.state !== "connected" || !algorandPublicKey(address)) throw Object.assign(new Error("no wallet is paired with the AC2 service: run `ac2 pair` and scan the code with your wallet"), { code: "not_connected" });
|
|
129
|
-
pinned = address;
|
|
130
|
-
}
|
|
131
|
-
const id = randomBytes(8).toString("hex");
|
|
132
|
-
const expiresAt = now() + timeoutMs;
|
|
133
|
-
const text = approvalText(info, { label, id, expiresAt });
|
|
134
|
-
const where = info.purchase?.url ? (() => { try { return ` for ${new URL(info.purchase.url).host}`; } catch { return ""; } })() : "";
|
|
135
|
-
let result;
|
|
146
|
+
// Register as an agent (the service then waits for the wallet if it wasn't), and wait until the wallet is there.
|
|
147
|
+
async function walletReady(session) {
|
|
136
148
|
try {
|
|
137
|
-
|
|
138
|
-
type: "ac2/SigningRequest",
|
|
139
|
-
body: {
|
|
140
|
-
description: `${label}: over your limit${where}. ${info.summary ?? ""}`.slice(0, 300),
|
|
141
|
-
encoding: "base64",
|
|
142
|
-
payload: Buffer.from(text).toString("base64"),
|
|
143
|
-
schema: SCHEMA,
|
|
144
|
-
display_hint: "text",
|
|
145
|
-
sig_hint: "raw-ed25519",
|
|
146
|
-
key_type: "account",
|
|
147
|
-
},
|
|
148
|
-
responseTypes: ["ac2/SigningResponse", "ac2/SigningRejected"],
|
|
149
|
-
expires_in_seconds: Math.ceil(timeoutMs / 1000),
|
|
150
|
-
timeoutMs,
|
|
151
|
-
}, timeoutMs + 15_000);
|
|
149
|
+
await session.request("agent.hello", { agent: `presign-guard-wallet-${process.pid}`, host: hostname() });
|
|
152
150
|
} catch (err) {
|
|
153
|
-
if (err.code
|
|
154
|
-
|
|
151
|
+
if (err.code !== "agent_taken") throw err; // another request of this process holds the name: it is registered
|
|
152
|
+
}
|
|
153
|
+
const until = now() + connectTimeoutMs;
|
|
154
|
+
for (;;) {
|
|
155
|
+
const status = await session.request("daemon.status", {});
|
|
156
|
+
const c = status?.connection ?? {};
|
|
157
|
+
if (c.state === "connected" && !c.locked) return c;
|
|
158
|
+
if (now() >= until) throw Object.assign(new Error(`your wallet is not connected to the AC2 service (${c.state ?? "no connection"}${c.locked ? ", locked" : ""}): open AC2 Wallet on your phone, or pair it with \`ac2 pair\``), { code: "not_connected" });
|
|
159
|
+
await new Promise((ok) => setTimeout(ok, pollMs));
|
|
155
160
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
return async function onOverLimit(info) {
|
|
164
|
+
const session = await openSession(socket, connect);
|
|
165
|
+
try {
|
|
166
|
+
const connection = await walletReady(session);
|
|
167
|
+
if (!pinned) {
|
|
168
|
+
if (!algorandPublicKey(connection.walletAddress)) throw Object.assign(new Error("the AC2 service doesn't report your wallet's Algorand address: set owner to your address"), { code: "not_connected" });
|
|
169
|
+
pinned = connection.walletAddress;
|
|
170
|
+
}
|
|
171
|
+
const id = randomBytes(8).toString("hex");
|
|
172
|
+
const expiresAt = now() + timeoutMs;
|
|
173
|
+
const text = approvalText(info, { label, id, expiresAt });
|
|
174
|
+
const where = info.purchase?.url ? (() => { try { return ` for ${new URL(info.purchase.url).host}`; } catch { return ""; } })() : "";
|
|
175
|
+
let result;
|
|
176
|
+
try {
|
|
177
|
+
result = await session.request("agent.request", {
|
|
178
|
+
type: "ac2/SigningRequest",
|
|
179
|
+
body: {
|
|
180
|
+
description: `${label}: over your limit${where}. ${info.summary ?? ""}`.slice(0, 300),
|
|
181
|
+
encoding: "base64",
|
|
182
|
+
payload: Buffer.from(text).toString("base64"),
|
|
183
|
+
schema: SCHEMA,
|
|
184
|
+
display_hint: "text",
|
|
185
|
+
sig_hint: "raw-ed25519",
|
|
186
|
+
key_type: "account",
|
|
187
|
+
},
|
|
188
|
+
responseTypes: ["ac2/SigningResponse", "ac2/SigningRejected"],
|
|
189
|
+
expires_in_seconds: Math.ceil(timeoutMs / 1000),
|
|
190
|
+
timeoutMs,
|
|
191
|
+
}, timeoutMs + Math.min(15_000, timeoutMs)); // a little longer than the service waits, so it answers first
|
|
192
|
+
} catch (err) {
|
|
193
|
+
if (err.code === "timeout" || /timed? ?out/i.test(err.message)) return false; // no answer in time
|
|
194
|
+
throw err;
|
|
195
|
+
}
|
|
196
|
+
if (result?.status === "unavailable") throw Object.assign(new Error(`the AC2 service can't ask your wallet (${result.reason})`), { code: result.reason });
|
|
197
|
+
const msg = result?.message;
|
|
198
|
+
if (result?.status !== "response" || msg?.type !== "ac2/SigningResponse") return false; // declined
|
|
199
|
+
if (now() > expiresAt) return false;
|
|
200
|
+
if (!verifyApproval(pinned, text, msg.body?.signature)) {
|
|
201
|
+
console.warn("[presign-guard-wallet] AC2 approval refused: the signature is not from the owner's account");
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
return { approved: true, proof: { via: "ac2", owner: pinned, id, payload: text, signature: msg.body.signature, signedAt: new Date(now()).toISOString() } };
|
|
205
|
+
} finally {
|
|
206
|
+
session.close();
|
|
163
207
|
}
|
|
164
|
-
return { approved: true, proof: { via: "ac2", owner: pinned, id, payload: text, signature: msg.body.signature, signedAt: new Date(now()).toISOString() } };
|
|
165
208
|
};
|
|
166
209
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "presign-guard-wallet",
|
|
3
|
-
"version": "0.20.
|
|
3
|
+
"version": "0.20.1",
|
|
4
4
|
"description": "A wallet for AI agents (viem on EVM chains, Solana and Algorand) that asks presign-guard ($0.01 over x402) before every transaction, contract write and signature, refuses to sign red, and keeps to per-token spending limits, with approval from your phone over the limit (Telegram, or signed in your own wallet over AC2).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|