presign-guard-wallet 0.8.0 → 0.9.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 CHANGED
@@ -200,6 +200,21 @@ const wallet = guardWallet(walletClient, {
200
200
 
201
201
  If the server can't be reached the wallet stops (`limit_unavailable`); paused on the dashboard means `paused`.
202
202
 
203
+ ## Paying under a mandate
204
+
205
+ A principal can give an agent a signed spending mandate ([x402 `authority` extension draft](https://github.com/x402-foundation/x402/pull/3220), `x402-mandate/1`): "spend up to CAP, to recipients in R, until T". Wrap the payment scheme with `mandatePayer` and each x402 payment is made under it: the EIP-3009 nonce becomes the binding of (mandate, paymentId), so the settled payment proves which grant it used, and the guarded wallet sends the mandate along with the check. presign-guard then makes a payment outside the mandate red (over `perPayment` or `cap`, another recipient, payer or token, expired, bad signature), before anything is signed.
206
+
207
+ ```js
208
+ import { guardWallet, mandatePayer } from "presign-guard-wallet";
209
+ import { ExactEvmScheme } from "@x402/evm/exact/client";
210
+
211
+ const wallet = guardWallet(walletClient, { pay });
212
+ const signer = { address: account.address, signTypedData: (t) => wallet.signTypedData({ account, ...t }) };
213
+ client.register("eip155:8453", mandatePayer(new ExactEvmScheme(signer), mandate)); // mandate = { mandate, alg: "Ed25519", sig }
214
+ ```
215
+
216
+ Only single payments are checked; the cumulative spend against the cap needs the mandate's accountant. Permit2 payments pass through unbound. The draft is still open, so details may change.
217
+
203
218
  ## Signed verdicts
204
219
 
205
220
  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.d.ts CHANGED
@@ -177,3 +177,18 @@ export interface GuardOptions {
177
177
  /** The same wallet client; sendTransaction, writeContract and signTypedData are checked first. */
178
178
  export declare function guardWallet<W extends WalletClient>(wallet: W, options: GuardOptions): W & GuardControls;
179
179
  export declare function checkRequestFor(method: string, args: unknown, options?: { chainId?: number; origin?: string }): CheckRequest | null;
180
+
181
+ /** A principal's signed spending mandate (x402 `authority` extension draft, x402-mandate/1). */
182
+ export interface MandateEnvelope {
183
+ mandate: { v: "x402-mandate/1"; issuer: string; subject: string; asset: string; cap: string; perPayment?: string; recipients: string[]; accountant: string; purpose: string; notAfter: string; nonce: string; parent?: string };
184
+ alg: "Ed25519";
185
+ sig: string;
186
+ }
187
+ /**
188
+ * Wraps an x402 EVM payment scheme (e.g. `new ExactEvmScheme(signer)`) so its EIP-3009 payments are
189
+ * made under `mandate`: the nonce becomes the mandate binding, and a guardWallet() signer sends the
190
+ * mandate to presign-guard, which makes a payment outside it red.
191
+ */
192
+ export function mandatePayer<S extends { scheme?: string; signer: unknown; createPaymentPayload: (...args: any[]) => Promise<unknown> }>(scheme: S, mandate: MandateEnvelope): S;
193
+ export function mandateDigest(mandate: MandateEnvelope["mandate"]): string;
194
+ export function mandateBinding(digest: string, paymentId: string): string;
package/index.js CHANGED
@@ -38,6 +38,8 @@ import { createLimiter, memoryStore } from "./limits.js";
38
38
  import { createRemoteLimiter } from "./remote.js";
39
39
  import { AsyncLocalStorage } from "node:async_hooks";
40
40
 
41
+ import { mandateFor } from "./mandate.js";
42
+ export { mandatePayer, mandateDigest, mandateBinding } from "./mandate.js";
41
43
  export { memoryStore };
42
44
 
43
45
  export const PRESIGN_URL = "https://presign-guard.fizzl.eu";
@@ -49,7 +51,7 @@ export const TEMPO_TOKENS = {
49
51
  42431: ["0x20c0000000000000000000000000000000000000"],
50
52
  };
51
53
  const TEMPO_TRANSFERS = new Set(["transfer", "transferWithMemo"]);
52
- export const VERSION = "0.7.0";
54
+ export const VERSION = "0.9.1";
53
55
  export const CREDIT_HEADER = "x-credit-key";
54
56
  const ROUTE = "POST /v1/check";
55
57
 
@@ -80,7 +82,9 @@ export function checkRequestFor(method, args, { chainId, origin } = {}) {
80
82
  }
81
83
  if (method === "signTypedData") {
82
84
  const { domain, types, primaryType, message } = args;
83
- return { type: "signature", ...base, typedData: { domain, types, primaryType, message } };
85
+ // A payment made by mandatePayer() (mandate.js) is checked against its mandate too.
86
+ const under = primaryType === "TransferWithAuthorization" ? mandateFor(message?.nonce) : null;
87
+ return { type: "signature", ...base, typedData: { domain, types, primaryType, message }, ...(under && { mandate: { ...under.envelope, paymentId: under.paymentId } }) };
84
88
  }
85
89
  return null;
86
90
  }
package/mandate.js ADDED
@@ -0,0 +1,79 @@
1
+ // Paying under a spending mandate (the x402 `authority` extension draft, x402-mandate/1,
2
+ // x402-foundation/x402#3220). The agent's principal signs a bounded grant ("spend up to CAP, to
3
+ // recipients in R, until T"); mandatePayer() wraps the x402 payment scheme so each EIP-3009
4
+ // payment carries the grant's binding as its nonce (§7), and the guarded wallet then sends the
5
+ // mandate along to presign-guard, which turns a payment outside it red before anything is signed.
6
+ import { createHash, randomBytes } from "node:crypto";
7
+
8
+ const TAG = "x402-mandate/1\n";
9
+ const BINDING_TAG = "x402-mandate-binding/1\n";
10
+
11
+ // RFC 8785 (JCS) for the JSON a mandate holds: strings, integers, arrays, objects.
12
+ export function jcs(value) {
13
+ if (value === null || typeof value === "boolean" || typeof value === "string") return JSON.stringify(value);
14
+ if (typeof value === "number") {
15
+ if (!Number.isInteger(value) || Math.abs(value) > 2 ** 52) throw new TypeError("only integers within 2^52 are signed");
16
+ return String(value);
17
+ }
18
+ if (Array.isArray(value)) return `[${value.map(jcs).join(",")}]`;
19
+ if (typeof value === "object") {
20
+ return `{${Object.keys(value).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).map((k) => `${JSON.stringify(k)}:${jcs(value[k])}`).join(",")}}`;
21
+ }
22
+ throw new TypeError("value cannot be canonicalized");
23
+ }
24
+
25
+ export const mandateDigest = (mandate) => `sha256:${createHash("sha256").update(TAG + jcs(mandate)).digest("hex")}`;
26
+ export const mandateBinding = (digest, paymentId) => `0x${createHash("sha256").update(`${BINDING_TAG}${digest}\n${paymentId}`, "utf8").digest("hex")}`;
27
+
28
+ // nonce -> { envelope, paymentId }: how the guarded wallet knows a payment it is asked to sign
29
+ // was made under a mandate (the nonce is the binding, so it cannot be read back from it).
30
+ const bound = new Map();
31
+ export const mandateFor = (nonce) => bound.get(String(nonce ?? "").toLowerCase()) ?? null;
32
+
33
+ function cleanEnvelope(envelope) {
34
+ const m = envelope?.mandate;
35
+ if (!m || typeof m !== "object" || m.v !== "x402-mandate/1") throw new TypeError("mandate must be { mandate: { v: \"x402-mandate/1\", … }, alg: \"Ed25519\", sig }");
36
+ if (envelope.alg !== "Ed25519" || typeof envelope.sig !== "string") throw new TypeError("mandate needs alg \"Ed25519\" and the issuer's sig");
37
+ return { mandate: m, alg: envelope.alg, sig: envelope.sig };
38
+ }
39
+
40
+ /**
41
+ * Wraps an x402 EVM payment scheme (e.g. new ExactEvmScheme(signer) from @x402/evm) so its
42
+ * EIP-3009 payments are made under `mandate`: the nonce becomes the binding of (mandate,
43
+ * paymentId), and a signer that is a guardWallet() wallet sends the mandate to presign-guard.
44
+ * Permit2 payments are passed to the wrapped scheme unchanged (no mandate binding there yet).
45
+ * @param {object} scheme the scheme to wrap; its `signer` signs the payment
46
+ * @param {{mandate: object, alg: "Ed25519", sig: string}} mandate the principal's signed grant
47
+ */
48
+ export function mandatePayer(scheme, mandate) {
49
+ const envelope = cleanEnvelope(mandate);
50
+ const digest = mandateDigest(envelope.mandate);
51
+ // Everything else (scheme name, findDefaultAsset, …) comes from the wrapped scheme.
52
+ return Object.assign(Object.create(scheme), {
53
+ scheme: scheme.scheme ?? "exact",
54
+ async createPaymentPayload(x402Version, requirements, context) {
55
+ if ((requirements.extra?.assetTransferMethod ?? "eip3009") !== "eip3009") return scheme.createPaymentPayload(x402Version, requirements, context);
56
+ if (!requirements.extra?.name || !requirements.extra?.version) throw new Error(`EIP-712 domain (name, version) missing in the payment requirements for ${requirements.asset}`);
57
+ const signer = scheme.signer;
58
+ const paymentId = `pgw-${randomBytes(12).toString("base64url")}`;
59
+ const nonce = mandateBinding(digest, paymentId);
60
+ const now = Math.floor(Date.now() / 1000);
61
+ const authorization = { from: signer.address, to: requirements.payTo, value: String(requirements.amount), validAfter: "0", validBefore: String(now + Number(requirements.maxTimeoutSeconds ?? 300)), nonce };
62
+ bound.set(nonce, { envelope, paymentId });
63
+ try {
64
+ const signature = await signer.signTypedData({
65
+ domain: { name: requirements.extra.name, version: requirements.extra.version, chainId: Number(String(requirements.network).split(":")[1]), verifyingContract: requirements.asset },
66
+ types: { TransferWithAuthorization: [
67
+ { name: "from", type: "address" }, { name: "to", type: "address" }, { name: "value", type: "uint256" },
68
+ { name: "validAfter", type: "uint256" }, { name: "validBefore", type: "uint256" }, { name: "nonce", type: "bytes32" },
69
+ ] },
70
+ primaryType: "TransferWithAuthorization",
71
+ message: { from: authorization.from, to: authorization.to, value: BigInt(authorization.value), validAfter: 0n, validBefore: BigInt(authorization.validBefore), nonce },
72
+ });
73
+ return { x402Version, payload: { authorization, signature } };
74
+ } finally {
75
+ bound.delete(nonce);
76
+ }
77
+ },
78
+ });
79
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "presign-guard-wallet",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
4
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": {
@@ -30,6 +30,7 @@
30
30
  "file-store.d.ts",
31
31
  "telegram.js",
32
32
  "remote.js",
33
+ "mandate.js",
33
34
  "telegram.d.ts",
34
35
  "README.md",
35
36
  "LICENSE"