presign-guard-wallet 0.3.0 → 0.4.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 CHANGED
@@ -65,7 +65,7 @@ try {
65
65
  | `signers` | presign-guard's published signer | Accepted signer addresses |
66
66
  | `authority` | the Fizzl payout wallet | Wallet whose certificates also make a signer trusted (key rotation); `null` accepts only `signers` |
67
67
  | `limits` | | Spending limits per token, see [Spending limits](#spending-limits) |
68
- | `onOverLimit` | | `async (info) => boolean`: asked when a limit would be crossed; `true` signs anyway. Without it the wallet stops |
68
+ | `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) |
69
69
  | `onSpend` | | `(entry) => void` after each signed spend, e.g. for a log |
70
70
  | `store` | in memory | Where spending is kept; `fileStore(path)` from `presign-guard-wallet/file-store`, or your own |
71
71
 
@@ -128,6 +128,33 @@ Other contract calls (a swap that uses an allowance you already gave) spend noth
128
128
 
129
129
  These limits live in your agent's software: they stop a confused or manipulated agent, not someone who has the private key. For limits the chain enforces, use a smart account with session keys; the same budget can then be set there.
130
130
 
131
+ ### Approve from your phone (Telegram)
132
+
133
+ `onOverLimit` can be a Telegram bot: when a signature would cross a limit, you get a message with what the agent wants to sign, why it is over the limit and presign-guard's verdict, with **Approve** and **Deny** buttons. The agent waits for your tap.
134
+
135
+ 1. In Telegram, talk to [@BotFather](https://t.me/BotFather), send `/newbot` and keep the token it gives you secret (an environment variable, never in code).
136
+ 2. Send your new bot `/start`, then find your chat id:
137
+ ```bash
138
+ TELEGRAM_BOT_TOKEN=... node -e 'import("presign-guard-wallet/telegram").then(async (t) => console.log(await t.findTelegramChats({ token: process.env.TELEGRAM_BOT_TOKEN })))'
139
+ ```
140
+ 3. Use it:
141
+ ```js
142
+ import { telegramApprover } from "presign-guard-wallet/telegram";
143
+
144
+ const wallet = guardWallet(walletClient, {
145
+ pay,
146
+ limits: { tokens: { USDC: { perTx: "5", perDay: "20" } } },
147
+ onOverLimit: telegramApprover({
148
+ token: process.env.TELEGRAM_BOT_TOKEN,
149
+ chatId: process.env.TELEGRAM_CHAT_ID,
150
+ label: "research-agent",
151
+ timeoutMs: 10 * 60_000, // no answer in 10 minutes = Deny
152
+ }),
153
+ });
154
+ ```
155
+
156
+ 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.
157
+
131
158
  ## Signed verdicts
132
159
 
133
160
  presign-guard signs every paid verdict (EIP-191 over canonical JSON, with a hash of your request inside the signed body; see [Signed verdicts](https://github.com/Fizzl13/presign-guard#signed-verdicts)). The wallet checks that signature before it acts:
package/index.js CHANGED
@@ -35,7 +35,7 @@ export { memoryStore };
35
35
  export const PRESIGN_URL = "https://presign-guard.fizzl.eu";
36
36
  export const PRESIGN_SIGNERS = ["0xf084Ea47Ca4D99BB4De3ECB0332b316bE6521EaE"];
37
37
  export const SUPPORTED_CHAINS = [1, 10, 56, 137, 8453, 42161];
38
- export const VERSION = "0.3.0";
38
+ export const VERSION = "0.4.0";
39
39
  export const CREDIT_HEADER = "x-credit-key";
40
40
  const ROUTE = "POST /v1/check";
41
41
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "presign-guard-wallet",
3
- "version": "0.3.0",
4
- "description": "A viem wallet for AI agents that asks presign-guard ($0.01 over x402) before every transaction, contract write and typed-data signature, refuses to sign red, and keeps to per-token spending limits.",
3
+ "version": "0.4.0",
4
+ "description": "A viem wallet for AI agents that asks presign-guard ($0.01 over x402) before every transaction, contract write and typed-data signature, refuses to sign red, and keeps to per-token spending limits, with approval from your phone over the limit.",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": {
@@ -11,6 +11,10 @@
11
11
  "./file-store": {
12
12
  "types": "./file-store.d.ts",
13
13
  "default": "./file-store.js"
14
+ },
15
+ "./telegram": {
16
+ "types": "./telegram.d.ts",
17
+ "default": "./telegram.js"
14
18
  }
15
19
  },
16
20
  "main": "./index.js",
@@ -21,6 +25,8 @@
21
25
  "limits.js",
22
26
  "file-store.js",
23
27
  "file-store.d.ts",
28
+ "telegram.js",
29
+ "telegram.d.ts",
24
30
  "README.md",
25
31
  "LICENSE"
26
32
  ],
@@ -53,7 +59,9 @@
53
59
  "drainer",
54
60
  "usdc",
55
61
  "spending-limits",
56
- "budget"
62
+ "budget",
63
+ "telegram",
64
+ "human-in-the-loop"
57
65
  ],
58
66
  "repository": {
59
67
  "type": "git",
package/telegram.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { OverLimitInfo } from "./index.js";
2
+
3
+ export interface TelegramApproverOptions {
4
+ /** Bot token from @BotFather. A secret: keep it in an environment variable. */
5
+ token: string;
6
+ /** Your chat with the bot: send it /start, then findTelegramChats({ token }). */
7
+ chatId: string | number;
8
+ /** Telegram user ids allowed to answer. Default: chatId (you, in a private chat). */
9
+ allowedUserIds?: Array<string | number>;
10
+ /** How long the agent waits for your tap. Default 10 minutes; no answer counts as Deny. */
11
+ timeoutMs?: number;
12
+ /** Name of the agent in the message. Default "Your agent". */
13
+ label?: string;
14
+ fetch?: typeof globalThis.fetch;
15
+ api?: string;
16
+ }
17
+
18
+ /** An onOverLimit for guardWallet: asks you on Telegram with Approve and Deny buttons. */
19
+ export declare function telegramApprover(options: TelegramApproverOptions): (info: OverLimitInfo) => Promise<boolean>;
20
+
21
+ /** The chats that sent your bot a message (send it /start first). */
22
+ export declare function findTelegramChats(options: { token: string; fetch?: typeof globalThis.fetch; api?: string }): Promise<Array<{ chatId: number; type: string; name: string; username: string | null }>>;
package/telegram.js ADDED
@@ -0,0 +1,152 @@
1
+ // Approve over-limit signatures from your phone, with a Telegram bot.
2
+ //
3
+ // import { telegramApprover } from "presign-guard-wallet/telegram";
4
+ // guardWallet(walletClient, { pay, limits, onOverLimit: telegramApprover({ token, chatId }) });
5
+ //
6
+ // When a signature would cross a limit, the bot sends you a message with what
7
+ // the agent wants to sign, why it is over the limit and presign-guard's verdict,
8
+ // with Approve and Deny buttons. The agent waits for your tap (default 10
9
+ // minutes); no answer in time counts as Deny. Only the people you allow
10
+ // (default: the chat itself, i.e. you in a private chat) can answer.
11
+ //
12
+ // No server needed: the wallet asks Telegram for button taps itself (long
13
+ // polling, getUpdates). So the bot must not have a webhook, and only one
14
+ // process at a time can poll one bot: give each agent process its own bot.
15
+ // The bot token is a secret: keep it in an environment variable.
16
+
17
+ const API = "https://api.telegram.org";
18
+ const escape = (s) => String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
19
+ const nonce = () => Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
20
+
21
+ function client(token, fetchImpl, api) {
22
+ if (typeof token !== "string" || !/^\d+:[A-Za-z0-9_-]{20,}$/.test(token)) throw new TypeError("token must be a Telegram bot token (123456:ABC…), from @BotFather");
23
+ return async (method, body, signal) => {
24
+ const res = await fetchImpl(`${api}/bot${token}/${method}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body ?? {}), signal });
25
+ const data = await res.json().catch(() => null);
26
+ if (!data?.ok) {
27
+ const err = new Error(`Telegram ${method} failed: ${data?.description ?? `HTTP ${res.status}`}`);
28
+ err.status = data?.error_code ?? res.status;
29
+ throw err;
30
+ }
31
+ return data.result;
32
+ };
33
+ }
34
+
35
+ // One poller per bot token in this process, shared by every waiting request.
36
+ const pollers = new Map();
37
+ function poller(token, call) {
38
+ let p = pollers.get(token);
39
+ if (p) return p;
40
+ p = { waiters: new Map(), offset: undefined, running: false, abort: null };
41
+ pollers.set(token, p);
42
+ p.start = () => {
43
+ if (p.running) return;
44
+ p.running = true;
45
+ (async () => {
46
+ while (p.waiters.size) {
47
+ p.abort = new AbortController();
48
+ let updates;
49
+ try {
50
+ updates = await call("getUpdates", { offset: p.offset, timeout: 25, allowed_updates: ["callback_query"] }, p.abort.signal);
51
+ } catch (err) {
52
+ if (!p.waiters.size) break; // aborted because nobody waits any more
53
+ if (err.status === 409 || err.status === 401 || err.status === 404) {
54
+ // A webhook, another process polling this bot, or a bad token: nobody can answer.
55
+ for (const w of p.waiters.values()) w.fail(err);
56
+ p.waiters.clear();
57
+ break;
58
+ }
59
+ await new Promise((ok) => setTimeout(ok, 2000)); // network hiccup: try again
60
+ continue;
61
+ }
62
+ for (const u of updates) {
63
+ p.offset = u.update_id + 1;
64
+ const q = u.callback_query;
65
+ const m = /^pgw:([a-z0-9]+):(y|n)$/.exec(q?.data ?? "");
66
+ const w = m && p.waiters.get(m[1]);
67
+ if (!w) { if (q?.id && m) call("answerCallbackQuery", { callback_query_id: q.id, text: "This request has already been decided or expired." }).catch(() => {}); continue; }
68
+ if (!w.allowed(q)) { call("answerCallbackQuery", { callback_query_id: q.id, text: "You are not allowed to answer this." }).catch(() => {}); continue; }
69
+ w.decide(m[2] === "y", q);
70
+ }
71
+ }
72
+ p.running = false;
73
+ if (p.waiters.size) p.start(); // someone started waiting while this loop was ending
74
+ })();
75
+ };
76
+ p.stopIfIdle = () => { if (!p.waiters.size) p.abort?.abort(); };
77
+ return p;
78
+ }
79
+
80
+ function messageFor(info, label) {
81
+ const lines = [`<b>${escape(label)} wants to sign something over your limit</b>`, ""];
82
+ lines.push(escape(info.summary));
83
+ const r = info.request ?? {};
84
+ lines.push("", `<code>${escape(info.method)}</code> · chain ${escape(r.chainId)}${r.to ? ` · to <code>${escape(r.to)}</code>` : ""}`);
85
+ const v = info.verdict?.verdict;
86
+ if (v) {
87
+ const codes = (info.verdict.reasons ?? []).filter((x) => x.severity !== "info").map((x) => x.code).join(", ");
88
+ lines.push(`presign-guard: <b>${escape(v)}</b>${codes ? ` (${escape(codes)})` : ""}`);
89
+ } else lines.push("presign-guard: no verdict for this one");
90
+ const spent = (info.spending ?? []).map((s) => `${escape(s.token)} ${escape(s.used)}${s.perDay ? ` / ${escape(s.perDay)}` : ""}`).join(" · ");
91
+ if (spent) lines.push(`spent this window: ${spent}`);
92
+ return lines.join("\n");
93
+ }
94
+
95
+ /**
96
+ * An onOverLimit for guardWallet that asks you on Telegram.
97
+ * @param {object} o
98
+ * @param {string} o.token bot token from @BotFather (keep it in an env var)
99
+ * @param {string|number} o.chatId your chat with the bot (see findTelegramChats)
100
+ * @param {Array<string|number>} [o.allowedUserIds] who may answer (default: chatId)
101
+ * @param {number} [o.timeoutMs] how long the agent waits (default 10 minutes); no answer = deny
102
+ * @param {string} [o.label] name of the agent in the message (default "Your agent")
103
+ * @param {typeof fetch} [o.fetch]
104
+ * @param {string} [o.api]
105
+ */
106
+ export function telegramApprover({ token, chatId, allowedUserIds, timeoutMs = 600_000, label = "Your agent", fetch: fetchImpl = globalThis.fetch, api = API } = {}) {
107
+ const call = client(token, fetchImpl, api);
108
+ if (chatId === undefined || chatId === null || chatId === "") throw new TypeError("chatId is required (send /start to your bot, then findTelegramChats({ token }))");
109
+ if (!(timeoutMs > 0)) throw new TypeError("timeoutMs must be a positive number of milliseconds");
110
+ const allowedIds = new Set((allowedUserIds ?? [chatId]).map(String));
111
+
112
+ return async function onOverLimit(info) {
113
+ const id = nonce();
114
+ const sent = await call("sendMessage", {
115
+ chat_id: chatId,
116
+ text: messageFor(info, label),
117
+ parse_mode: "HTML",
118
+ disable_web_page_preview: true,
119
+ reply_markup: { inline_keyboard: [[{ text: "Approve", callback_data: `pgw:${id}:y` }, { text: "Deny", callback_data: `pgw:${id}:n` }]] },
120
+ });
121
+ const p = poller(token, call);
122
+ const answer = await new Promise((resolve, reject) => {
123
+ const timer = setTimeout(() => { p.waiters.delete(id); p.stopIfIdle(); resolve({ ok: false, timeout: true }); }, timeoutMs);
124
+ p.waiters.set(id, {
125
+ allowed: (q) => allowedIds.has(String(q.from?.id)) && String(q.message?.chat?.id) === String(chatId),
126
+ decide: (ok, q) => { clearTimeout(timer); p.waiters.delete(id); p.stopIfIdle(); resolve({ ok, q }); },
127
+ fail: (err) => { clearTimeout(timer); reject(err); },
128
+ });
129
+ p.start();
130
+ });
131
+ const who = answer.q?.from?.username ? `@${answer.q.from.username}` : answer.q?.from?.first_name ?? "you";
132
+ const outcome = answer.timeout ? `<b>No answer in ${Math.round(timeoutMs / 60_000) || 1} min: not signed.</b>` : answer.ok ? `<b>Approved by ${escape(who)}: signing.</b>` : `<b>Denied by ${escape(who)}: not signed.</b>`;
133
+ if (answer.q?.id) call("answerCallbackQuery", { callback_query_id: answer.q.id, text: answer.ok ? "Approved" : "Denied" }).catch(() => {});
134
+ call("editMessageText", { chat_id: chatId, message_id: sent.message_id, text: `${messageFor(info, label)}\n\n${outcome}`, parse_mode: "HTML", disable_web_page_preview: true }).catch(() => {});
135
+ return answer.ok === true;
136
+ };
137
+ }
138
+
139
+ /**
140
+ * The chats that sent your bot a message (send it /start first). Use the chatId of yours.
141
+ * @returns {Promise<Array<{chatId: number, type: string, name: string, username: string|null}>>}
142
+ */
143
+ export async function findTelegramChats({ token, fetch: fetchImpl = globalThis.fetch, api = API } = {}) {
144
+ const call = client(token, fetchImpl, api);
145
+ const updates = await call("getUpdates", { timeout: 0, allowed_updates: ["message"] });
146
+ const chats = new Map();
147
+ for (const u of updates) {
148
+ const c = u.message?.chat;
149
+ if (c) chats.set(c.id, { chatId: c.id, type: c.type, name: [c.first_name, c.last_name].filter(Boolean).join(" ") || c.title || "", username: c.username ?? null });
150
+ }
151
+ return [...chats.values()];
152
+ }