presign-guard-wallet 0.19.0 → 0.20.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/README.md +26 -1
- package/ac2.d.ts +40 -0
- package/ac2.js +166 -0
- package/index.d.ts +4 -2
- package/index.js +2 -2
- package/limits.js +7 -4
- package/package.json +10 -2
package/README.md
CHANGED
|
@@ -70,7 +70,7 @@ try {
|
|
|
70
70
|
| `signers` | presign-guard's published signer | Accepted signer addresses |
|
|
71
71
|
| `authority` | the Fizzl payout wallet | Wallet whose certificates also make a signer trusted (key rotation); `null` accepts only `signers` |
|
|
72
72
|
| `limits` | | Spending limits per token, see [Spending limits](#spending-limits) |
|
|
73
|
-
| `onOverLimit` | | `async (info) => boolean`: asked when a limit would be crossed; `true` signs anyway. Without it the wallet stops. Ready-made: [`telegramApprover`](#approve-from-your-phone-telegram) |
|
|
73
|
+
| `onOverLimit` | | `async (info) => boolean`: asked when a limit would be crossed; `true` signs anyway. Without it the wallet stops. Ready-made: [`telegramApprover`](#approve-from-your-phone-telegram), [`ac2Approver`](#approve-in-your-own-wallet-ac2) |
|
|
74
74
|
| `onSpend` | | `(entry) => void` after each signed spend, e.g. for a log |
|
|
75
75
|
| `store` | in memory | Where spending is kept; `fileStore(path)` from `presign-guard-wallet/file-store`, or your own |
|
|
76
76
|
|
|
@@ -164,6 +164,31 @@ These limits live in your agent's software: they stop a confused or manipulated
|
|
|
164
164
|
|
|
165
165
|
Only the chat you name (or the `allowedUserIds` you list) can answer; anyone else's tap is refused. No server is needed: the wallet asks Telegram for your tap itself (long polling), so the bot must not have a webhook, and one bot serves one agent process at a time (a second process polling the same bot makes Telegram refuse both; the request then fails and nothing is signed). If Telegram cannot be reached, the wallet stops (`limit_unavailable`) rather than signing.
|
|
166
166
|
|
|
167
|
+
### Approve in your own wallet (AC2)
|
|
168
|
+
|
|
169
|
+
`onOverLimit` can also ask you in your own wallet app over [AC2](https://github.com/algorandfoundation/ac2), the Algorand Foundation's protocol for agents to ask their owner for a signature. When a signature would cross a limit, your AC2 wallet shows what the agent wants to sign, why it is over the limit and presign-guard's verdict. You approve with your passkey (Face ID, a fingerprint), and the wallet **signs** the approval with your Algorand account key. The agent checks that the signature is your account's before it goes on, and the signed approval comes with the spend in `onSpend` (`approval`), as proof of who approved what.
|
|
170
|
+
|
|
171
|
+
1. Install and start the AC2 service on the machine where the agent runs, and pair your wallet (AC2 Wallet on your phone): see [ac2-cli](https://github.com/algorandfoundation/ac2/tree/master/packages/ac2-cli), then `ac2 pair` and scan the code.
|
|
172
|
+
2. Use it:
|
|
173
|
+
```js
|
|
174
|
+
import { ac2Approver } from "presign-guard-wallet/ac2";
|
|
175
|
+
|
|
176
|
+
const wallet = guardWallet(walletClient, {
|
|
177
|
+
pay,
|
|
178
|
+
limits: { tokens: { USDC: { perTx: "5", perDay: "20" } } },
|
|
179
|
+
onOverLimit: ac2Approver({
|
|
180
|
+
owner: process.env.OWNER_ALGORAND_ADDRESS, // only this account's signature approves
|
|
181
|
+
label: "research-agent",
|
|
182
|
+
timeoutMs: 10 * 60_000, // no answer in 10 minutes = Deny
|
|
183
|
+
}),
|
|
184
|
+
onSpend: (entry) => console.log(entry.amount, entry.approval?.signature ?? "within the limit"),
|
|
185
|
+
});
|
|
186
|
+
```
|
|
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 no wallet is paired, 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
|
+
|
|
190
|
+
`verifyApproval(owner, payload, signature)` checks a stored approval again later.
|
|
191
|
+
|
|
167
192
|
### Say what is being bought
|
|
168
193
|
|
|
169
194
|
Wrap a purchase in `withPurchase` to record what it is for. The URL and description then show up:
|
package/ac2.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { OverLimitInfo } from "./index.js";
|
|
2
|
+
|
|
3
|
+
export interface Ac2ApproverOptions {
|
|
4
|
+
/** Your Algorand address: only its signature approves. Default: the wallet the AC2 service is paired with, fixed at the first request. */
|
|
5
|
+
owner?: string;
|
|
6
|
+
/** The AC2 service's control socket. Default AC2_DAEMON_SOCKET, else ~/.ac2/ac2d.sock (as ac2-cli). */
|
|
7
|
+
socket?: string;
|
|
8
|
+
/** How long the agent waits for your approval. Default 10 minutes; no answer counts as Deny. */
|
|
9
|
+
timeoutMs?: number;
|
|
10
|
+
/** Name of the agent in the request. Default "Your agent". */
|
|
11
|
+
label?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** What an AC2 approval proves: the owner's Ed25519 signature over the approval text. */
|
|
15
|
+
export interface Ac2ApprovalProof {
|
|
16
|
+
via: "ac2";
|
|
17
|
+
/** The Algorand address that signed. */
|
|
18
|
+
owner: string;
|
|
19
|
+
id: string;
|
|
20
|
+
/** The text that was signed; it starts with "fizzl-approval-v1". */
|
|
21
|
+
payload: string;
|
|
22
|
+
/** Base64 Ed25519 signature by the owner's account key. */
|
|
23
|
+
signature: string;
|
|
24
|
+
signedAt: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** An onOverLimit for guardWallet: asks you in your AC2 wallet and checks that the signature is the owner's. */
|
|
28
|
+
export declare function ac2Approver(options?: Ac2ApproverOptions): (info: OverLimitInfo) => Promise<false | { approved: true; proof: Ac2ApprovalProof }>;
|
|
29
|
+
|
|
30
|
+
/** True when signature (base64) is owner's Ed25519 signature over payload. */
|
|
31
|
+
export declare function verifyApproval(owner: string, payload: string, signature: string): boolean;
|
|
32
|
+
|
|
33
|
+
/** The text the owner signs for an over-limit request. */
|
|
34
|
+
export declare function approvalText(info: OverLimitInfo, options: { label: string; id: string; expiresAt: number }): string;
|
|
35
|
+
|
|
36
|
+
/** The 32-byte public key in an Algorand address, or null when the address or its checksum is wrong. */
|
|
37
|
+
export declare function algorandPublicKey(address: string): Buffer | null;
|
|
38
|
+
|
|
39
|
+
/** The AC2 service's control socket path, as ac2-cli resolves it. */
|
|
40
|
+
export declare function defaultSocketPath(env?: Record<string, string | undefined>, platform?: string): string;
|
package/ac2.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
// Approve over-limit signatures in your own wallet app, over AC2 (the Algorand Foundation's Agentic
|
|
2
|
+
// Communication and Control protocol, github.com/algorandfoundation/ac2).
|
|
3
|
+
//
|
|
4
|
+
// import { ac2Approver } from "presign-guard-wallet/ac2";
|
|
5
|
+
// guardWallet(walletClient, { pay, limits, onOverLimit: ac2Approver({ owner: "YOUR…ALGORAND…ADDRESS" }) });
|
|
6
|
+
//
|
|
7
|
+
// When a signature would cross a limit, your AC2 wallet (AC2 Wallet on your phone) shows what the agent wants
|
|
8
|
+
// to sign, why it is over the limit and presign-guard's verdict. You approve with your passkey, and the wallet
|
|
9
|
+
// signs that approval with your Algorand account key. A decline, no answer in time (default 10 minutes) or a
|
|
10
|
+
// signature that isn't from the owner's account counts as Deny. The signed approval goes along with the spend
|
|
11
|
+
// (onSpend's approval), as proof of who approved what.
|
|
12
|
+
//
|
|
13
|
+
// What is signed is a text that starts with "fizzl-approval-v1", never a transaction: Algorand signs
|
|
14
|
+
// transactions over "TX" + the transaction, so a signed approval can't be used as a payment.
|
|
15
|
+
//
|
|
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. If the
|
|
18
|
+
// service isn't running or no wallet is paired, the wallet stops (limit_unavailable) rather than signing.
|
|
19
|
+
|
|
20
|
+
import { connect as netConnect } from "node:net";
|
|
21
|
+
import { createHash, createPublicKey, randomBytes, verify } from "node:crypto";
|
|
22
|
+
import { homedir } from "node:os";
|
|
23
|
+
import { join } from "node:path";
|
|
24
|
+
|
|
25
|
+
const PREFIX = "fizzl-approval-v1";
|
|
26
|
+
const SCHEMA = "fizzl/over-limit-approval/v1";
|
|
27
|
+
const SPKI_ED25519 = Buffer.from("302a300506032b6570032100", "hex");
|
|
28
|
+
const B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
29
|
+
|
|
30
|
+
// The AC2 service's control socket, as ac2-cli resolves it.
|
|
31
|
+
export function defaultSocketPath(env = process.env, platform = process.platform) {
|
|
32
|
+
const override = env.AC2_DAEMON_SOCKET?.trim();
|
|
33
|
+
if (override) return override;
|
|
34
|
+
if (platform === "win32") {
|
|
35
|
+
const home = env.AC2_HOME?.trim();
|
|
36
|
+
return home ? `\\\\.\\pipe\\ac2-daemon-${createHash("sha256").update(home).digest("hex").slice(0, 12)}` : "\\\\.\\pipe\\ac2-daemon";
|
|
37
|
+
}
|
|
38
|
+
return join(env.AC2_HOME?.trim() || join(homedir(), ".ac2"), "ac2d.sock");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// The 32-byte Ed25519 public key in an Algorand address (base32 of key + 4-byte checksum), or null.
|
|
42
|
+
export function algorandPublicKey(address) {
|
|
43
|
+
if (typeof address !== "string" || !/^[A-Z2-7]{58}$/.test(address)) return null;
|
|
44
|
+
let bits = 0, value = 0;
|
|
45
|
+
const out = [];
|
|
46
|
+
for (const c of address) {
|
|
47
|
+
value = (value << 5) | B32.indexOf(c);
|
|
48
|
+
bits += 5;
|
|
49
|
+
if (bits >= 8) { out.push((value >>> (bits - 8)) & 0xff); bits -= 8; }
|
|
50
|
+
}
|
|
51
|
+
const bytes = Buffer.from(out.slice(0, 36));
|
|
52
|
+
const key = bytes.subarray(0, 32);
|
|
53
|
+
const sum = createHash("sha512-256").update(key).digest().subarray(28);
|
|
54
|
+
return sum.equals(bytes.subarray(32, 36)) ? key : null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// True when signature (base64) is the owner's Ed25519 signature over payload.
|
|
58
|
+
export function verifyApproval(owner, payload, signature) {
|
|
59
|
+
const key = algorandPublicKey(owner);
|
|
60
|
+
const sig = typeof signature === "string" ? Buffer.from(signature, "base64") : null;
|
|
61
|
+
if (!key || !sig || sig.length !== 64) return false;
|
|
62
|
+
try {
|
|
63
|
+
return verify(null, Buffer.from(payload), createPublicKey({ key: Buffer.concat([SPKI_ED25519, key]), format: "der", type: "spki" }), sig);
|
|
64
|
+
} catch {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// One request to the AC2 service: newline-delimited JSON, answered on the same connection.
|
|
70
|
+
function controlRequest(path, method, params, { timeoutMs, connect }) {
|
|
71
|
+
return new Promise((resolve, reject) => {
|
|
72
|
+
const sock = connect(path);
|
|
73
|
+
let buf = "";
|
|
74
|
+
const done = (fn, arg) => { clearTimeout(timer); sock.destroy(); fn(arg); };
|
|
75
|
+
const timer = setTimeout(() => done(reject, Object.assign(new Error(`the AC2 service did not answer ${method} in time`), { code: "timeout" })), timeoutMs);
|
|
76
|
+
sock.setEncoding("utf8");
|
|
77
|
+
sock.on("error", (err) => done(reject, Object.assign(new Error(`can't reach the AC2 service at ${path} (${err.code ?? err.message}): start it and pair your wallet with \`ac2 pair\``), { code: "unreachable" })));
|
|
78
|
+
sock.on("connect", () => sock.write(`${JSON.stringify({ id: 1, method, params })}\n`));
|
|
79
|
+
sock.on("data", (chunk) => {
|
|
80
|
+
buf += chunk;
|
|
81
|
+
for (let nl = buf.indexOf("\n"); nl >= 0; nl = buf.indexOf("\n")) {
|
|
82
|
+
const line = buf.slice(0, nl);
|
|
83
|
+
buf = buf.slice(nl + 1);
|
|
84
|
+
let frame;
|
|
85
|
+
try { frame = JSON.parse(line); } catch { continue; }
|
|
86
|
+
if (frame.id !== 1) continue; // events and other replies
|
|
87
|
+
if (frame.error) return done(reject, Object.assign(new Error(`AC2 service: ${frame.error.message ?? frame.error.code}`), { code: frame.error.code }));
|
|
88
|
+
return done(resolve, frame.result);
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// The text the owner signs: everything they approve, starting with the prefix, ending with id and expiry.
|
|
95
|
+
export function approvalText(info, { label, id, expiresAt }) {
|
|
96
|
+
const r = info.request ?? {};
|
|
97
|
+
const lines = [PREFIX, `${label} wants to sign something over your limit`, String(info.summary ?? "")];
|
|
98
|
+
if (info.purchase?.description) lines.push(`for: ${info.purchase.description}`);
|
|
99
|
+
if (info.purchase?.url) lines.push(`url: ${info.purchase.url}`);
|
|
100
|
+
lines.push(`${info.method} · chain ${r.chainId ?? "?"}${r.to ? ` · to ${r.to}` : ""}`);
|
|
101
|
+
const v = info.verdict?.verdict;
|
|
102
|
+
const codes = (info.verdict?.reasons ?? []).filter((x) => x.severity !== "info").map((x) => x.code).join(", ");
|
|
103
|
+
lines.push(v ? `presign-guard: ${v}${codes ? ` (${codes})` : ""}` : "presign-guard: no verdict for this one");
|
|
104
|
+
const spent = (info.spending ?? []).map((s) => `${s.token} ${s.used}${s.perDay ? ` / ${s.perDay}` : ""}`).join(" · ");
|
|
105
|
+
if (spent) lines.push(`spent this window: ${spent}`);
|
|
106
|
+
lines.push(`id: ${id}`, `expires: ${new Date(expiresAt).toISOString()}`);
|
|
107
|
+
return lines.join("\n");
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* An onOverLimit for guardWallet that asks you in your AC2 wallet, and checks your signature.
|
|
112
|
+
* @param {object} [o]
|
|
113
|
+
* @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
|
+
* @param {string} [o.socket] the AC2 service's socket (default ~/.ac2/ac2d.sock or AC2_DAEMON_SOCKET)
|
|
115
|
+
* @param {number} [o.timeoutMs] how long the agent waits for you (default 10 minutes); no answer = deny
|
|
116
|
+
* @param {string} [o.label] name of the agent in the request (default "Your agent")
|
|
117
|
+
*/
|
|
118
|
+
export function ac2Approver({ owner, socket = defaultSocketPath(), timeoutMs = 600_000, label = "Your agent", connect = netConnect, now = () => Date.now() } = {}) {
|
|
119
|
+
if (owner !== undefined && !algorandPublicKey(owner)) throw new TypeError("owner must be an Algorand address (58 characters, with a valid checksum)");
|
|
120
|
+
if (!(timeoutMs > 0)) throw new TypeError("timeoutMs must be a positive number of milliseconds");
|
|
121
|
+
let pinned = owner ?? null;
|
|
122
|
+
const ask = (method, params, ms = 10_000) => controlRequest(socket, method, params, { timeoutMs: ms, connect });
|
|
123
|
+
|
|
124
|
+
return async function onOverLimit(info) {
|
|
125
|
+
if (!pinned) {
|
|
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;
|
|
136
|
+
try {
|
|
137
|
+
result = await ask("agent.request", {
|
|
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);
|
|
152
|
+
} catch (err) {
|
|
153
|
+
if (err.code === "timeout" || /timed? ?out/i.test(err.message)) return false; // no answer in time
|
|
154
|
+
throw err;
|
|
155
|
+
}
|
|
156
|
+
if (result?.status === "unavailable") throw Object.assign(new Error(`the AC2 service can't ask your wallet (${result.reason})`), { code: result.reason });
|
|
157
|
+
const msg = result?.message;
|
|
158
|
+
if (result?.status !== "response" || msg?.type !== "ac2/SigningResponse") return false; // declined
|
|
159
|
+
if (now() > expiresAt) return false;
|
|
160
|
+
if (!verifyApproval(pinned, text, msg.body?.signature)) {
|
|
161
|
+
console.warn("[presign-guard-wallet] AC2 approval refused: the signature is not from the owner's account");
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
return { approved: true, proof: { via: "ac2", owner: pinned, id, payload: text, signature: msg.body.signature, signedAt: new Date(now()).toISOString() } };
|
|
165
|
+
};
|
|
166
|
+
}
|
package/index.d.ts
CHANGED
|
@@ -120,6 +120,8 @@ export interface SpendEntry {
|
|
|
120
120
|
verdict: PresignVerdict | null;
|
|
121
121
|
receiptId: string | null;
|
|
122
122
|
purchase: Purchase | null;
|
|
123
|
+
/** Proof of an over-limit approval, from an approver that gives one (ac2Approver), else null. */
|
|
124
|
+
approval?: { via: string; [key: string]: unknown } | null;
|
|
123
125
|
}
|
|
124
126
|
|
|
125
127
|
/** Where spending is kept. amount is a decimal string at 18 decimals. */
|
|
@@ -190,8 +192,8 @@ export interface GuardOptions {
|
|
|
190
192
|
authority?: string | null;
|
|
191
193
|
/** Spending limits per token, checked after presign-guard's verdict and before signing. */
|
|
192
194
|
limits?: SpendingLimits;
|
|
193
|
-
/** Asked when a limit would be crossed (e.g. ask the user on their phone). true = sign anyway. Without it, the wallet stops. */
|
|
194
|
-
onOverLimit?: (info: OverLimitInfo) => boolean | Promise<boolean>;
|
|
195
|
+
/** Asked when a limit would be crossed (e.g. ask the user on their phone). true, or { approved: true, proof }, = sign anyway; the proof goes to onSpend. Without it, the wallet stops. */
|
|
196
|
+
onOverLimit?: (info: OverLimitInfo) => boolean | { approved: true; proof?: object } | Promise<boolean | { approved: true; proof?: object }>;
|
|
195
197
|
/** Called after each signed spend, e.g. for a log. */
|
|
196
198
|
onSpend?: (entry: SpendEntry) => void;
|
|
197
199
|
/** Where spending is kept. Default in memory (gone on a restart); fileStore from "presign-guard-wallet/file-store" for a file. */
|
package/index.js
CHANGED
|
@@ -219,7 +219,7 @@ function cleanPurchase(info) {
|
|
|
219
219
|
* @param {string[]} [options.signers]
|
|
220
220
|
* @param {string|null} [options.authority]
|
|
221
221
|
* @param {object} [options.limits] spending limits: { tokens: { USDC: { perTx, perDay }, … }, unknownTokens, allow, window }
|
|
222
|
-
* @param {(info: object) => boolean|Promise<boolean>} [options.onOverLimit] asked when a limit would be crossed; true = sign anyway
|
|
222
|
+
* @param {(info: object) => boolean|{approved: true, proof?: object}|Promise<boolean|{approved: true, proof?: object}>} [options.onOverLimit] asked when a limit would be crossed; true (or { approved: true, proof }) = sign anyway
|
|
223
223
|
* @param {(entry: object) => void} [options.onSpend] after each signed spend
|
|
224
224
|
* @param {{url: string, key: string}} [options.server] a wallet server (fizzl wallet-server) keeps the limits, budget and approvals for all your agents
|
|
225
225
|
* @param {object} [options.store] where spending is kept (default in memory; fileStore from presign-guard-wallet/file-store)
|
|
@@ -342,7 +342,7 @@ export function guardWallet(wallet, {
|
|
|
342
342
|
await limiter.release(booked.entries, { purchaseId: booked.purchaseId, error: err.message }).catch((e) => console.warn(`[presign-guard-wallet] could not give back spending: ${e.message}`));
|
|
343
343
|
throw err;
|
|
344
344
|
}
|
|
345
|
-
limiter.spent(booked.entries, result, { verdict, purchase, purchaseId: booked.purchaseId });
|
|
345
|
+
limiter.spent(booked.entries, result, { verdict, purchase, purchaseId: booked.purchaseId, approval: booked.approval ?? null });
|
|
346
346
|
return result;
|
|
347
347
|
}
|
|
348
348
|
|
package/limits.js
CHANGED
|
@@ -333,21 +333,24 @@ export function createLimiter(limits, { store = memoryStore(), onOverLimit, onSp
|
|
|
333
333
|
const spend = spendFor(info.request, info.verdict);
|
|
334
334
|
const used = await usedNow();
|
|
335
335
|
const result = evaluate(policy, spend, used);
|
|
336
|
+
let approval = null;
|
|
336
337
|
if (result.reasons.length) {
|
|
337
338
|
const summary = result.reasons.map((r) => r.message).join("; ");
|
|
338
339
|
if (result.hardStop || !onOverLimit) return { ok: false, ...result, summary };
|
|
339
|
-
|
|
340
|
-
|
|
340
|
+
// true, or { approved: true, proof } from an approver that can prove the approval (ac2Approver).
|
|
341
|
+
const answer = await onOverLimit({ method: info.method, request: info.request, verdict: info.verdict, reasons: result.reasons, summary, spending: await summarize(used), purchase: info.purchase ?? null });
|
|
342
|
+
if (answer !== true && answer?.approved !== true) return { ok: false, ...result, summary, asked: true };
|
|
343
|
+
approval = answer === true ? null : answer.proof ?? null;
|
|
341
344
|
}
|
|
342
345
|
const entries = result.charges.filter((c) => c.amount > 0n).map((c) => ({ id: newId(), at: now(), budget: c.budget, amount: c.amount.toString(), method: info.method, chainId: info.request.chainId, to: spend.items[0]?.to ?? info.request.to ?? null }));
|
|
343
346
|
for (const e of entries) await store.add(e);
|
|
344
|
-
return { ok: true, entries };
|
|
347
|
+
return { ok: true, entries, ...(approval ? { approval } : {}) };
|
|
345
348
|
}),
|
|
346
349
|
release: async (entries) => { for (const e of entries) await store.remove(e.id); },
|
|
347
350
|
spent(entries, result, info) {
|
|
348
351
|
if (!onSpend) return;
|
|
349
352
|
for (const e of entries) {
|
|
350
|
-
try { onSpend({ ...e, amount: formatUnits(BigInt(e.amount), SCALE), result, verdict: info.verdict ?? null, receiptId: info.verdict?.receipt?.request_id ?? null, purchase: info.purchase ?? null }); } catch (err) { console.warn(`[presign-guard-wallet] onSpend threw: ${err.message}`); }
|
|
353
|
+
try { onSpend({ ...e, amount: formatUnits(BigInt(e.amount), SCALE), result, verdict: info.verdict ?? null, receiptId: info.verdict?.receipt?.request_id ?? null, purchase: info.purchase ?? null, approval: info.approval ?? null }); } catch (err) { console.warn(`[presign-guard-wallet] onSpend threw: ${err.message}`); }
|
|
351
354
|
}
|
|
352
355
|
},
|
|
353
356
|
spending: async () => summarize(await usedNow()),
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "presign-guard-wallet",
|
|
3
|
-
"version": "0.
|
|
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.",
|
|
3
|
+
"version": "0.20.0",
|
|
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": {
|
|
7
7
|
".": {
|
|
@@ -16,6 +16,10 @@
|
|
|
16
16
|
"types": "./telegram.d.ts",
|
|
17
17
|
"default": "./telegram.js"
|
|
18
18
|
},
|
|
19
|
+
"./ac2": {
|
|
20
|
+
"types": "./ac2.d.ts",
|
|
21
|
+
"default": "./ac2.js"
|
|
22
|
+
},
|
|
19
23
|
"./limits": {
|
|
20
24
|
"default": "./limits.js"
|
|
21
25
|
}
|
|
@@ -34,6 +38,8 @@
|
|
|
34
38
|
"algorand.js",
|
|
35
39
|
"solana.js",
|
|
36
40
|
"telegram.d.ts",
|
|
41
|
+
"ac2.js",
|
|
42
|
+
"ac2.d.ts",
|
|
37
43
|
"README.md",
|
|
38
44
|
"LICENSE"
|
|
39
45
|
],
|
|
@@ -72,6 +78,8 @@
|
|
|
72
78
|
"spending-limits",
|
|
73
79
|
"budget",
|
|
74
80
|
"telegram",
|
|
81
|
+
"ac2",
|
|
82
|
+
"passkey",
|
|
75
83
|
"human-in-the-loop"
|
|
76
84
|
],
|
|
77
85
|
"repository": {
|