nirium-avalanche 0.3.0 → 0.4.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/LICENSE +0 -0
- package/README.md +77 -55
- package/package.json +81 -75
- package/policy/evm-policy.mjs +367 -367
- package/policy/rules-policy.mjs +35 -35
- package/policy/x402-fetch.mjs +56 -56
- package/sdk/decision.mjs +108 -108
- package/sdk/index.mjs +14 -12
- package/sdk/networks.mjs +28 -28
- package/sdk/pay.mjs +46 -46
- package/sdk/pq.mjs +58 -0
- package/sdk/receipt.mjs +102 -96
- package/sdk/serve.mjs +106 -106
- package/verify-evm-core.mjs +192 -159
- package/verify-evm-pq.mjs +113 -0
- package/verify-evm-receipt.mjs +38 -38
package/policy/evm-policy.mjs
CHANGED
|
@@ -1,367 +1,367 @@
|
|
|
1
|
-
// Pre-sign policy gate for x402 `exact` payments on EVM chains (Avalanche C-Chain and Fuji).
|
|
2
|
-
//
|
|
3
|
-
// Same contract as the Stellar gate in the `nirium` SDK (x402-policy.ts): the policy engine
|
|
4
|
-
// is asked AFTER the exact authorization is built and BEFORE anything is signed, and only an
|
|
5
|
-
// ALLOW bound to that exact authorization, still valid, reaches the signer. DENY, WAIT, an
|
|
6
|
-
// error, a timeout, a malformed or stale answer, or a bad clock sign nothing.
|
|
7
|
-
//
|
|
8
|
-
// Where it hooks in: @x402/evm 2.32.0 builds the EIP-3009 `TransferWithAuthorization`
|
|
9
|
-
// message inside createPaymentPayload and hands it to `signer.signTypedData`. That call is
|
|
10
|
-
// the only place where amount, destination, token, chain and nonce all exist together, so
|
|
11
|
-
// the gate wraps it. Any other typed data (Permit2, EIP-2612 Permit, anything else) is
|
|
12
|
-
// refused before the policy is consulted: this gate only knows how to read EIP-3009.
|
|
13
|
-
//
|
|
14
|
-
// Not a security boundary against code in the same process: whoever holds the base signer
|
|
15
|
-
// can still call it directly.
|
|
16
|
-
|
|
17
|
-
import { getAddress, hashTypedData, isAddress, sha256, stringToBytes } from "viem";
|
|
18
|
-
|
|
19
|
-
const DEFAULT_TIMEOUT_MS = 5000;
|
|
20
|
-
const HEX32 = /^0x[0-9a-fA-F]{64}$/;
|
|
21
|
-
const SIG65 = /^0x[0-9a-fA-F]{130}$/;
|
|
22
|
-
|
|
23
|
-
// The exact EIP-3009 type @x402/evm signs (field order matters for the EIP-712 hash).
|
|
24
|
-
const TRANSFER_WITH_AUTHORIZATION = [
|
|
25
|
-
{ name: "from", type: "address" },
|
|
26
|
-
{ name: "to", type: "address" },
|
|
27
|
-
{ name: "value", type: "uint256" },
|
|
28
|
-
{ name: "validAfter", type: "uint256" },
|
|
29
|
-
{ name: "validBefore", type: "uint256" },
|
|
30
|
-
{ name: "nonce", type: "bytes32" },
|
|
31
|
-
];
|
|
32
|
-
|
|
33
|
-
/** @typedef {'ALLOW'|'DENY'|'WAIT'} X402PolicyVerdict */
|
|
34
|
-
/**
|
|
35
|
-
* @typedef {Object} X402PaymentRequirementsView
|
|
36
|
-
* @property {string} scheme
|
|
37
|
-
* @property {string} network CAIP-2, e.g. "eip155:43113"
|
|
38
|
-
* @property {string} asset ERC-20 contract (EIP-3009 token)
|
|
39
|
-
* @property {string} payTo
|
|
40
|
-
* @property {string} amount atomic units, decimal string
|
|
41
|
-
* @property {number} maxTimeoutSeconds
|
|
42
|
-
* @property {{name?: string, version?: string}} [extra] EIP-712 domain the server asked for
|
|
43
|
-
*/
|
|
44
|
-
/**
|
|
45
|
-
* @typedef {Object} X402PolicyDecision
|
|
46
|
-
* @property {X402PolicyVerdict} decision
|
|
47
|
-
* @property {string} [contextHash] required on ALLOW, must equal the context's
|
|
48
|
-
* @property {string} [reason]
|
|
49
|
-
* @property {string} [policyVersion] required on ALLOW when `currentVersion` is set
|
|
50
|
-
* @property {number} [expiresAt] epoch ms; equality counts as expired
|
|
51
|
-
* @property {string} [decisionId]
|
|
52
|
-
*/
|
|
53
|
-
/**
|
|
54
|
-
* @typedef {Object} X402PolicyHook
|
|
55
|
-
* @property {(ctx: object, opts: {signal: AbortSignal}) => Promise<X402PolicyDecision>} evaluate
|
|
56
|
-
* @property {(ctx: object, opts: {signal: AbortSignal}) => Promise<string>} [currentVersion]
|
|
57
|
-
* @property {number} [timeoutMs] default 5000, never more than half of maxTimeoutSeconds
|
|
58
|
-
* @property {boolean} [requireExpiry] an ALLOW without expiresAt is unsignable
|
|
59
|
-
* @property {(record: object) => void} [onDecision] observer; cannot change the outcome
|
|
60
|
-
* @property {() => number} [now] injectable clock (epoch ms), for tests
|
|
61
|
-
*/
|
|
62
|
-
|
|
63
|
-
/** Outcomes that mean no signature was released. */
|
|
64
|
-
export const REFUSALS = Object.freeze([
|
|
65
|
-
"SIGNER_ERROR", "DENY", "WAIT", "TIMEOUT", "ENGINE_ERROR", "EXPIRED", "UNBOUND", "MALFORMED",
|
|
66
|
-
"CONTEXT_MISMATCH", "STALE", "VERSION_UNAVAILABLE", "SIGNER_CHANGED", "CLOCK_INVALID",
|
|
67
|
-
]);
|
|
68
|
-
|
|
69
|
-
export class X402PolicyError extends Error {
|
|
70
|
-
constructor(outcome, message, extra = {}) {
|
|
71
|
-
super(`x402 policy ${outcome}: ${message}`);
|
|
72
|
-
this.name = "X402PolicyError";
|
|
73
|
-
this.outcome = outcome;
|
|
74
|
-
this.decision = extra.decision;
|
|
75
|
-
this.contextHash = extra.contextHash;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
const sha256hex = (s) => sha256(stringToBytes(s)).slice(2);
|
|
80
|
-
const nonempty = (v) => typeof v === "string" && v.trim().length > 0;
|
|
81
|
-
|
|
82
|
-
/** Validates a policy hook when it is configured, so bad config fails before any payment. */
|
|
83
|
-
export function assertValidPolicyHook(policy) {
|
|
84
|
-
if (!policy || typeof policy !== "object" || typeof policy.evaluate !== "function") {
|
|
85
|
-
throw new Error("policy: `evaluate` must be a function.");
|
|
86
|
-
}
|
|
87
|
-
if (policy.currentVersion !== undefined && typeof policy.currentVersion !== "function") {
|
|
88
|
-
throw new Error("policy: `currentVersion`, when set, must be a function.");
|
|
89
|
-
}
|
|
90
|
-
if (policy.timeoutMs !== undefined && (!Number.isSafeInteger(policy.timeoutMs) || policy.timeoutMs <= 0)) {
|
|
91
|
-
throw new Error("policy: `timeoutMs` must be a positive integer (ms).");
|
|
92
|
-
}
|
|
93
|
-
if (policy.now !== undefined && typeof policy.now !== "function") {
|
|
94
|
-
throw new Error("policy: `now`, when set, must be a function returning epoch milliseconds.");
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
function chainIdOf(network) {
|
|
99
|
-
const m = /^eip155:(\d+)$/.exec(String(network));
|
|
100
|
-
if (!m) throw new X402PolicyError("CONTEXT_MISMATCH", `not an EVM network: ${network}`);
|
|
101
|
-
return BigInt(m[1]);
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function toBigInt(v, field) {
|
|
105
|
-
try {
|
|
106
|
-
if (typeof v === "bigint") return v;
|
|
107
|
-
if (typeof v === "number" && Number.isSafeInteger(v)) return BigInt(v);
|
|
108
|
-
if (typeof v === "string" && /^(0x[0-9a-fA-F]+|\d+)$/.test(v)) return BigInt(v);
|
|
109
|
-
} catch { /* falls through */ }
|
|
110
|
-
throw new X402PolicyError("CONTEXT_MISMATCH", `${field} is not an integer`);
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
function sameAddress(a, b) {
|
|
114
|
-
return isAddress(String(a)) && isAddress(String(b)) && getAddress(a) === getAddress(b);
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* Decodes the typed data about to be signed and checks it describes exactly the payment x402
|
|
119
|
-
* selected. This is not policy (that belongs to the engine): it is context integrity, so that
|
|
120
|
-
* what the engine evaluates is what gets signed.
|
|
121
|
-
*/
|
|
122
|
-
export function describeAuthorization(typedData, requirements, signerAddress) {
|
|
123
|
-
if (!typedData || typeof typedData !== "object") {
|
|
124
|
-
throw new X402PolicyError("CONTEXT_MISMATCH", "no typed data to sign");
|
|
125
|
-
}
|
|
126
|
-
const { domain, types, primaryType, message } = typedData;
|
|
127
|
-
if (primaryType !== "TransferWithAuthorization") {
|
|
128
|
-
throw new X402PolicyError("CONTEXT_MISMATCH", `unsupported primaryType ${String(primaryType)} (only EIP-3009 TransferWithAuthorization is gated)`);
|
|
129
|
-
}
|
|
130
|
-
if (!types || typeof types !== "object") throw new X402PolicyError("CONTEXT_MISMATCH", "typed data has no types");
|
|
131
|
-
const extraTypes = Object.keys(types).filter((k) => k !== "EIP712Domain" && k !== "TransferWithAuthorization");
|
|
132
|
-
if (extraTypes.length) throw new X402PolicyError("CONTEXT_MISMATCH", `unexpected extra types: ${extraTypes.join(", ")}`);
|
|
133
|
-
const fields = types.TransferWithAuthorization;
|
|
134
|
-
const sameFields = Array.isArray(fields) && fields.length === TRANSFER_WITH_AUTHORIZATION.length
|
|
135
|
-
&& fields.every((f, i) => f && f.name === TRANSFER_WITH_AUTHORIZATION[i].name && f.type === TRANSFER_WITH_AUTHORIZATION[i].type);
|
|
136
|
-
if (!sameFields) throw new X402PolicyError("CONTEXT_MISMATCH", "TransferWithAuthorization fields differ from EIP-3009");
|
|
137
|
-
if (!domain || typeof domain !== "object" || !message || typeof message !== "object") {
|
|
138
|
-
throw new X402PolicyError("CONTEXT_MISMATCH", "typed data has no domain or message");
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
const chainId = chainIdOf(requirements.network);
|
|
142
|
-
if (toBigInt(domain.chainId, "domain.chainId") !== chainId) {
|
|
143
|
-
throw new X402PolicyError("CONTEXT_MISMATCH", "domain.chainId differs from requirements.network");
|
|
144
|
-
}
|
|
145
|
-
if (!sameAddress(domain.verifyingContract, requirements.asset)) {
|
|
146
|
-
throw new X402PolicyError("CONTEXT_MISMATCH", "token contract differs from requirements.asset");
|
|
147
|
-
}
|
|
148
|
-
const extra = requirements.extra || {};
|
|
149
|
-
if (!nonempty(extra.name) || !nonempty(extra.version)) {
|
|
150
|
-
throw new X402PolicyError("CONTEXT_MISMATCH", "requirements.extra has no EIP-712 name/version");
|
|
151
|
-
}
|
|
152
|
-
if (domain.name !== extra.name || domain.version !== extra.version) {
|
|
153
|
-
throw new X402PolicyError("CONTEXT_MISMATCH", "EIP-712 domain name/version differ from requirements.extra");
|
|
154
|
-
}
|
|
155
|
-
if (!sameAddress(message.to, requirements.payTo)) {
|
|
156
|
-
throw new X402PolicyError("CONTEXT_MISMATCH", "destination differs from requirements.payTo");
|
|
157
|
-
}
|
|
158
|
-
const value = toBigInt(message.value, "value");
|
|
159
|
-
if (value !== toBigInt(requirements.amount, "requirements.amount")) {
|
|
160
|
-
throw new X402PolicyError("CONTEXT_MISMATCH", "amount differs from requirements.amount");
|
|
161
|
-
}
|
|
162
|
-
if (!sameAddress(message.from, signerAddress)) {
|
|
163
|
-
throw new X402PolicyError("CONTEXT_MISMATCH", "from differs from signer address");
|
|
164
|
-
}
|
|
165
|
-
if (typeof message.nonce !== "string" || !HEX32.test(message.nonce)) {
|
|
166
|
-
throw new X402PolicyError("CONTEXT_MISMATCH", "nonce is not bytes32");
|
|
167
|
-
}
|
|
168
|
-
const validAfter = toBigInt(message.validAfter, "validAfter");
|
|
169
|
-
const validBefore = toBigInt(message.validBefore, "validBefore");
|
|
170
|
-
|
|
171
|
-
let payloadHash;
|
|
172
|
-
try {
|
|
173
|
-
payloadHash = hashTypedData({ domain, types, primaryType, message }).slice(2).toLowerCase();
|
|
174
|
-
} catch (e) {
|
|
175
|
-
throw new X402PolicyError("CONTEXT_MISMATCH", `typed data does not hash (${e?.shortMessage ?? e?.message})`);
|
|
176
|
-
}
|
|
177
|
-
return Object.freeze({
|
|
178
|
-
primaryType,
|
|
179
|
-
payloadHash,
|
|
180
|
-
chainId: chainId.toString(),
|
|
181
|
-
verifyingContract: getAddress(domain.verifyingContract),
|
|
182
|
-
domainName: domain.name,
|
|
183
|
-
domainVersion: domain.version,
|
|
184
|
-
from: getAddress(message.from),
|
|
185
|
-
to: getAddress(message.to),
|
|
186
|
-
amount: value.toString(),
|
|
187
|
-
validAfter: validAfter.toString(),
|
|
188
|
-
validBefore: validBefore.toString(),
|
|
189
|
-
nonce: message.nonce.toLowerCase(),
|
|
190
|
-
});
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
/** min(timeoutMs ?? 5000, maxTimeoutSeconds * 1000 / 2): a slow engine must not eat the payment window. */
|
|
194
|
-
export function effectiveTimeoutMs(policy, maxTimeoutSeconds) {
|
|
195
|
-
const base = policy.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
196
|
-
if (typeof maxTimeoutSeconds === "number" && Number.isFinite(maxTimeoutSeconds) && maxTimeoutSeconds > 0) {
|
|
197
|
-
return Math.max(1, Math.min(base, Math.floor((maxTimeoutSeconds * 1000) / 2)));
|
|
198
|
-
}
|
|
199
|
-
return base;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
/** sha256 of {v, url, method, payloadHash}: the value an ALLOW must echo back. */
|
|
203
|
-
export function computeContextHash(url, method, payloadHash) {
|
|
204
|
-
return sha256hex(JSON.stringify({ v: 1, url, method, payloadHash }));
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
/**
|
|
208
|
-
* Wraps an EVM signer ({ address, signTypedData }) so it only signs with a current ALLOW bound
|
|
209
|
-
* to this exact authorization. Anything else ends without a signature.
|
|
210
|
-
*
|
|
211
|
-
* `getCall` supplies the per-call context (URL, method, requirements): create one gated signer
|
|
212
|
-
* per payment so two concurrent payments never share state. `onRefused` receives the error
|
|
213
|
-
* before it is thrown, because @x402/fetch re-wraps errors and loses their class.
|
|
214
|
-
*/
|
|
215
|
-
export function createPolicyGatedSigner(base, policy, getCall, onRefused) {
|
|
216
|
-
assertValidPolicyHook(policy);
|
|
217
|
-
if (!base || typeof base.signTypedData !== "function" || !isAddress(String(base.address))) {
|
|
218
|
-
throw new Error("createPolicyGatedSigner: base signer needs an address and signTypedData().");
|
|
219
|
-
}
|
|
220
|
-
// Identity is fixed here. If the base signer changes address mid-payment, nothing is signed.
|
|
221
|
-
const account = getAddress(base.address);
|
|
222
|
-
const now = policy.now ?? Date.now;
|
|
223
|
-
|
|
224
|
-
const report = (r) => {
|
|
225
|
-
try {
|
|
226
|
-
const out = policy.onDecision?.(r);
|
|
227
|
-
if (out !== null && (typeof out === "object" || typeof out === "function")) {
|
|
228
|
-
Promise.resolve(out).catch(() => { /* an observer decides nothing */ });
|
|
229
|
-
}
|
|
230
|
-
} catch { /* an observer decides nothing */ }
|
|
231
|
-
};
|
|
232
|
-
const refuse = (outcome, msg, context, decision) => {
|
|
233
|
-
report({ outcome, context, decision, error: msg });
|
|
234
|
-
const err = new X402PolicyError(outcome, msg, { decision, contextHash: context?.contextHash });
|
|
235
|
-
try { onRefused?.(err); } catch { /* idem */ }
|
|
236
|
-
throw err;
|
|
237
|
-
};
|
|
238
|
-
// A clock that does not return a finite number closes: NaN makes every comparison false.
|
|
239
|
-
const readClock = (context, decision) => {
|
|
240
|
-
let t;
|
|
241
|
-
try { t = now(); } catch (e) {
|
|
242
|
-
return refuse("CLOCK_INVALID", `clock threw (${e?.message ?? String(e)})`, context, decision);
|
|
243
|
-
}
|
|
244
|
-
if (typeof t !== "number" || !Number.isFinite(t)) {
|
|
245
|
-
return refuse("CLOCK_INVALID", `clock returned ${String(t)}, not epoch milliseconds`, context, decision);
|
|
246
|
-
}
|
|
247
|
-
return t;
|
|
248
|
-
};
|
|
249
|
-
|
|
250
|
-
const signTypedData = async (typedData) => {
|
|
251
|
-
const call = getCall();
|
|
252
|
-
if (!call || !call.requirements) refuse("CONTEXT_MISMATCH", "no payment requirements bound to this signing call");
|
|
253
|
-
if (!sameAddress(base.address, account)) refuse("SIGNER_CHANGED", "base signer address changed after the gate was created");
|
|
254
|
-
|
|
255
|
-
let authorization;
|
|
256
|
-
try {
|
|
257
|
-
authorization = describeAuthorization(typedData, call.requirements, account);
|
|
258
|
-
} catch (e) {
|
|
259
|
-
return refuse(e instanceof X402PolicyError ? e.outcome : "CONTEXT_MISMATCH", e?.message ?? String(e));
|
|
260
|
-
}
|
|
261
|
-
const contextHash = computeContextHash(call.url, call.method, authorization.payloadHash);
|
|
262
|
-
// Frozen: the engine reads, it does not rewrite what gets signed.
|
|
263
|
-
const context = Object.freeze({
|
|
264
|
-
contextVersion: 1,
|
|
265
|
-
url: call.url,
|
|
266
|
-
method: call.method,
|
|
267
|
-
requirements: Object.freeze({ ...call.requirements, extra: Object.freeze({ ...(call.requirements.extra || {}) }) }),
|
|
268
|
-
authorization,
|
|
269
|
-
signer: account,
|
|
270
|
-
contextHash,
|
|
271
|
-
});
|
|
272
|
-
|
|
273
|
-
const timeoutMs = effectiveTimeoutMs(policy, call.requirements.maxTimeoutSeconds);
|
|
274
|
-
const controller = new AbortController();
|
|
275
|
-
// One deadline for the whole pre-sign phase (evaluate + currentVersion).
|
|
276
|
-
const deadline = readClock(context) + timeoutMs;
|
|
277
|
-
let timer;
|
|
278
|
-
const TIMED_OUT = Symbol("timeout");
|
|
279
|
-
const timeout = new Promise((_, reject) => {
|
|
280
|
-
timer = setTimeout(() => { controller.abort(); reject(TIMED_OUT); }, timeoutMs);
|
|
281
|
-
});
|
|
282
|
-
timeout.catch(() => { /* observed by each race */ });
|
|
283
|
-
|
|
284
|
-
try {
|
|
285
|
-
let decision;
|
|
286
|
-
try {
|
|
287
|
-
decision = await Promise.race([
|
|
288
|
-
Promise.resolve().then(() => policy.evaluate(context, { signal: controller.signal })),
|
|
289
|
-
timeout,
|
|
290
|
-
]);
|
|
291
|
-
} catch (e) {
|
|
292
|
-
if (e === TIMED_OUT) return refuse("TIMEOUT", `no decision within ${timeoutMs} ms`, context);
|
|
293
|
-
return refuse("ENGINE_ERROR", e?.message ?? String(e), context);
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
// Anything that is not a well-formed ALLOW closes.
|
|
297
|
-
if (!decision || typeof decision !== "object") return refuse("MALFORMED", "engine returned no decision object", context);
|
|
298
|
-
if (decision.decision === "DENY") return refuse("DENY", decision.reason ?? "denied", context, decision);
|
|
299
|
-
if (decision.decision === "WAIT") return refuse("WAIT", decision.reason ?? "wait", context, decision);
|
|
300
|
-
if (decision.decision !== "ALLOW") return refuse("MALFORMED", `unknown verdict ${String(decision.decision)}`, context, decision);
|
|
301
|
-
// Copied before any await: mutating the engine's object later changes nothing.
|
|
302
|
-
const allow = Object.freeze({ ...decision });
|
|
303
|
-
if (allow.contextHash !== contextHash) return refuse("UNBOUND", "ALLOW is not bound to this authorization", context, allow);
|
|
304
|
-
if (allow.expiresAt !== undefined && (typeof allow.expiresAt !== "number" || !Number.isFinite(allow.expiresAt))) {
|
|
305
|
-
return refuse("MALFORMED", "expiresAt must be epoch milliseconds", context, allow);
|
|
306
|
-
}
|
|
307
|
-
if (allow.expiresAt === undefined && policy.requireExpiry) {
|
|
308
|
-
return refuse("EXPIRED", "ALLOW without expiresAt while requireExpiry is set", context, allow);
|
|
309
|
-
}
|
|
310
|
-
const checkClock = () => {
|
|
311
|
-
const t = readClock(context, allow);
|
|
312
|
-
if (t >= deadline) refuse("TIMEOUT", "decision arrived after the deadline", context, allow);
|
|
313
|
-
if (allow.expiresAt !== undefined && t >= allow.expiresAt) refuse("EXPIRED", "ALLOW expired before signing", context, allow);
|
|
314
|
-
};
|
|
315
|
-
if (policy.currentVersion && !nonempty(allow.policyVersion)) {
|
|
316
|
-
return refuse("MALFORMED", "ALLOW has no policyVersion to check against currentVersion", context, allow);
|
|
317
|
-
}
|
|
318
|
-
checkClock();
|
|
319
|
-
|
|
320
|
-
// The observer runs HERE, not next to the signer: whatever it changes (the clock, the
|
|
321
|
-
// policy version, the signer's address) is seen by the checks that follow.
|
|
322
|
-
report({ outcome: "ALLOWED", context, decision: allow });
|
|
323
|
-
|
|
324
|
-
if (policy.currentVersion) {
|
|
325
|
-
let current;
|
|
326
|
-
try {
|
|
327
|
-
current = await Promise.race([
|
|
328
|
-
Promise.resolve().then(() => policy.currentVersion(context, { signal: controller.signal })),
|
|
329
|
-
timeout,
|
|
330
|
-
]);
|
|
331
|
-
} catch (e) {
|
|
332
|
-
if (e === TIMED_OUT) return refuse("TIMEOUT", `no current policy version within ${timeoutMs} ms`, context, allow);
|
|
333
|
-
return refuse("VERSION_UNAVAILABLE", `currentVersion failed (${e?.message ?? String(e)})`, context, allow);
|
|
334
|
-
}
|
|
335
|
-
if (!nonempty(current)) return refuse("VERSION_UNAVAILABLE", "currentVersion returned no version", context, allow);
|
|
336
|
-
if (current !== allow.policyVersion) {
|
|
337
|
-
return refuse("STALE", `ALLOW was issued under policy ${allow.policyVersion}, current is ${current}`, context, allow);
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
// Final checks, always, with no await before the signer.
|
|
342
|
-
checkClock();
|
|
343
|
-
if (!sameAddress(base.address, account)) return refuse("SIGNER_CHANGED", "base signer address changed while the policy was evaluated", context, allow);
|
|
344
|
-
if (timer) clearTimeout(timer);
|
|
345
|
-
let signature;
|
|
346
|
-
try {
|
|
347
|
-
// The original object, not a copy someone could have touched.
|
|
348
|
-
signature = await base.signTypedData(typedData);
|
|
349
|
-
} catch (e) {
|
|
350
|
-
report({ outcome: "SIGNER_ERROR", context, decision: allow, error: e?.message ?? String(e) });
|
|
351
|
-
throw e;
|
|
352
|
-
}
|
|
353
|
-
if (typeof signature !== "string" || !SIG65.test(signature)) {
|
|
354
|
-
return refuse("SIGNER_ERROR", "signer returned no 65-byte signature", context, allow);
|
|
355
|
-
}
|
|
356
|
-
report({ outcome: "SIGNED", context, decision: allow });
|
|
357
|
-
return signature;
|
|
358
|
-
} finally {
|
|
359
|
-
if (timer) clearTimeout(timer);
|
|
360
|
-
}
|
|
361
|
-
};
|
|
362
|
-
|
|
363
|
-
// Read-only chain access may be forwarded; no other signing method is exposed.
|
|
364
|
-
const gated = { address: account, signTypedData };
|
|
365
|
-
if (typeof base.readContract === "function") gated.readContract = (args) => base.readContract(args);
|
|
366
|
-
return Object.freeze(gated);
|
|
367
|
-
}
|
|
1
|
+
// Pre-sign policy gate for x402 `exact` payments on EVM chains (Avalanche C-Chain and Fuji).
|
|
2
|
+
//
|
|
3
|
+
// Same contract as the Stellar gate in the `nirium` SDK (x402-policy.ts): the policy engine
|
|
4
|
+
// is asked AFTER the exact authorization is built and BEFORE anything is signed, and only an
|
|
5
|
+
// ALLOW bound to that exact authorization, still valid, reaches the signer. DENY, WAIT, an
|
|
6
|
+
// error, a timeout, a malformed or stale answer, or a bad clock sign nothing.
|
|
7
|
+
//
|
|
8
|
+
// Where it hooks in: @x402/evm 2.32.0 builds the EIP-3009 `TransferWithAuthorization`
|
|
9
|
+
// message inside createPaymentPayload and hands it to `signer.signTypedData`. That call is
|
|
10
|
+
// the only place where amount, destination, token, chain and nonce all exist together, so
|
|
11
|
+
// the gate wraps it. Any other typed data (Permit2, EIP-2612 Permit, anything else) is
|
|
12
|
+
// refused before the policy is consulted: this gate only knows how to read EIP-3009.
|
|
13
|
+
//
|
|
14
|
+
// Not a security boundary against code in the same process: whoever holds the base signer
|
|
15
|
+
// can still call it directly.
|
|
16
|
+
|
|
17
|
+
import { getAddress, hashTypedData, isAddress, sha256, stringToBytes } from "viem";
|
|
18
|
+
|
|
19
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
20
|
+
const HEX32 = /^0x[0-9a-fA-F]{64}$/;
|
|
21
|
+
const SIG65 = /^0x[0-9a-fA-F]{130}$/;
|
|
22
|
+
|
|
23
|
+
// The exact EIP-3009 type @x402/evm signs (field order matters for the EIP-712 hash).
|
|
24
|
+
const TRANSFER_WITH_AUTHORIZATION = [
|
|
25
|
+
{ name: "from", type: "address" },
|
|
26
|
+
{ name: "to", type: "address" },
|
|
27
|
+
{ name: "value", type: "uint256" },
|
|
28
|
+
{ name: "validAfter", type: "uint256" },
|
|
29
|
+
{ name: "validBefore", type: "uint256" },
|
|
30
|
+
{ name: "nonce", type: "bytes32" },
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
/** @typedef {'ALLOW'|'DENY'|'WAIT'} X402PolicyVerdict */
|
|
34
|
+
/**
|
|
35
|
+
* @typedef {Object} X402PaymentRequirementsView
|
|
36
|
+
* @property {string} scheme
|
|
37
|
+
* @property {string} network CAIP-2, e.g. "eip155:43113"
|
|
38
|
+
* @property {string} asset ERC-20 contract (EIP-3009 token)
|
|
39
|
+
* @property {string} payTo
|
|
40
|
+
* @property {string} amount atomic units, decimal string
|
|
41
|
+
* @property {number} maxTimeoutSeconds
|
|
42
|
+
* @property {{name?: string, version?: string}} [extra] EIP-712 domain the server asked for
|
|
43
|
+
*/
|
|
44
|
+
/**
|
|
45
|
+
* @typedef {Object} X402PolicyDecision
|
|
46
|
+
* @property {X402PolicyVerdict} decision
|
|
47
|
+
* @property {string} [contextHash] required on ALLOW, must equal the context's
|
|
48
|
+
* @property {string} [reason]
|
|
49
|
+
* @property {string} [policyVersion] required on ALLOW when `currentVersion` is set
|
|
50
|
+
* @property {number} [expiresAt] epoch ms; equality counts as expired
|
|
51
|
+
* @property {string} [decisionId]
|
|
52
|
+
*/
|
|
53
|
+
/**
|
|
54
|
+
* @typedef {Object} X402PolicyHook
|
|
55
|
+
* @property {(ctx: object, opts: {signal: AbortSignal}) => Promise<X402PolicyDecision>} evaluate
|
|
56
|
+
* @property {(ctx: object, opts: {signal: AbortSignal}) => Promise<string>} [currentVersion]
|
|
57
|
+
* @property {number} [timeoutMs] default 5000, never more than half of maxTimeoutSeconds
|
|
58
|
+
* @property {boolean} [requireExpiry] an ALLOW without expiresAt is unsignable
|
|
59
|
+
* @property {(record: object) => void} [onDecision] observer; cannot change the outcome
|
|
60
|
+
* @property {() => number} [now] injectable clock (epoch ms), for tests
|
|
61
|
+
*/
|
|
62
|
+
|
|
63
|
+
/** Outcomes that mean no signature was released. */
|
|
64
|
+
export const REFUSALS = Object.freeze([
|
|
65
|
+
"SIGNER_ERROR", "DENY", "WAIT", "TIMEOUT", "ENGINE_ERROR", "EXPIRED", "UNBOUND", "MALFORMED",
|
|
66
|
+
"CONTEXT_MISMATCH", "STALE", "VERSION_UNAVAILABLE", "SIGNER_CHANGED", "CLOCK_INVALID",
|
|
67
|
+
]);
|
|
68
|
+
|
|
69
|
+
export class X402PolicyError extends Error {
|
|
70
|
+
constructor(outcome, message, extra = {}) {
|
|
71
|
+
super(`x402 policy ${outcome}: ${message}`);
|
|
72
|
+
this.name = "X402PolicyError";
|
|
73
|
+
this.outcome = outcome;
|
|
74
|
+
this.decision = extra.decision;
|
|
75
|
+
this.contextHash = extra.contextHash;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const sha256hex = (s) => sha256(stringToBytes(s)).slice(2);
|
|
80
|
+
const nonempty = (v) => typeof v === "string" && v.trim().length > 0;
|
|
81
|
+
|
|
82
|
+
/** Validates a policy hook when it is configured, so bad config fails before any payment. */
|
|
83
|
+
export function assertValidPolicyHook(policy) {
|
|
84
|
+
if (!policy || typeof policy !== "object" || typeof policy.evaluate !== "function") {
|
|
85
|
+
throw new Error("policy: `evaluate` must be a function.");
|
|
86
|
+
}
|
|
87
|
+
if (policy.currentVersion !== undefined && typeof policy.currentVersion !== "function") {
|
|
88
|
+
throw new Error("policy: `currentVersion`, when set, must be a function.");
|
|
89
|
+
}
|
|
90
|
+
if (policy.timeoutMs !== undefined && (!Number.isSafeInteger(policy.timeoutMs) || policy.timeoutMs <= 0)) {
|
|
91
|
+
throw new Error("policy: `timeoutMs` must be a positive integer (ms).");
|
|
92
|
+
}
|
|
93
|
+
if (policy.now !== undefined && typeof policy.now !== "function") {
|
|
94
|
+
throw new Error("policy: `now`, when set, must be a function returning epoch milliseconds.");
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function chainIdOf(network) {
|
|
99
|
+
const m = /^eip155:(\d+)$/.exec(String(network));
|
|
100
|
+
if (!m) throw new X402PolicyError("CONTEXT_MISMATCH", `not an EVM network: ${network}`);
|
|
101
|
+
return BigInt(m[1]);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function toBigInt(v, field) {
|
|
105
|
+
try {
|
|
106
|
+
if (typeof v === "bigint") return v;
|
|
107
|
+
if (typeof v === "number" && Number.isSafeInteger(v)) return BigInt(v);
|
|
108
|
+
if (typeof v === "string" && /^(0x[0-9a-fA-F]+|\d+)$/.test(v)) return BigInt(v);
|
|
109
|
+
} catch { /* falls through */ }
|
|
110
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", `${field} is not an integer`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function sameAddress(a, b) {
|
|
114
|
+
return isAddress(String(a)) && isAddress(String(b)) && getAddress(a) === getAddress(b);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Decodes the typed data about to be signed and checks it describes exactly the payment x402
|
|
119
|
+
* selected. This is not policy (that belongs to the engine): it is context integrity, so that
|
|
120
|
+
* what the engine evaluates is what gets signed.
|
|
121
|
+
*/
|
|
122
|
+
export function describeAuthorization(typedData, requirements, signerAddress) {
|
|
123
|
+
if (!typedData || typeof typedData !== "object") {
|
|
124
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "no typed data to sign");
|
|
125
|
+
}
|
|
126
|
+
const { domain, types, primaryType, message } = typedData;
|
|
127
|
+
if (primaryType !== "TransferWithAuthorization") {
|
|
128
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", `unsupported primaryType ${String(primaryType)} (only EIP-3009 TransferWithAuthorization is gated)`);
|
|
129
|
+
}
|
|
130
|
+
if (!types || typeof types !== "object") throw new X402PolicyError("CONTEXT_MISMATCH", "typed data has no types");
|
|
131
|
+
const extraTypes = Object.keys(types).filter((k) => k !== "EIP712Domain" && k !== "TransferWithAuthorization");
|
|
132
|
+
if (extraTypes.length) throw new X402PolicyError("CONTEXT_MISMATCH", `unexpected extra types: ${extraTypes.join(", ")}`);
|
|
133
|
+
const fields = types.TransferWithAuthorization;
|
|
134
|
+
const sameFields = Array.isArray(fields) && fields.length === TRANSFER_WITH_AUTHORIZATION.length
|
|
135
|
+
&& fields.every((f, i) => f && f.name === TRANSFER_WITH_AUTHORIZATION[i].name && f.type === TRANSFER_WITH_AUTHORIZATION[i].type);
|
|
136
|
+
if (!sameFields) throw new X402PolicyError("CONTEXT_MISMATCH", "TransferWithAuthorization fields differ from EIP-3009");
|
|
137
|
+
if (!domain || typeof domain !== "object" || !message || typeof message !== "object") {
|
|
138
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "typed data has no domain or message");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const chainId = chainIdOf(requirements.network);
|
|
142
|
+
if (toBigInt(domain.chainId, "domain.chainId") !== chainId) {
|
|
143
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "domain.chainId differs from requirements.network");
|
|
144
|
+
}
|
|
145
|
+
if (!sameAddress(domain.verifyingContract, requirements.asset)) {
|
|
146
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "token contract differs from requirements.asset");
|
|
147
|
+
}
|
|
148
|
+
const extra = requirements.extra || {};
|
|
149
|
+
if (!nonempty(extra.name) || !nonempty(extra.version)) {
|
|
150
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "requirements.extra has no EIP-712 name/version");
|
|
151
|
+
}
|
|
152
|
+
if (domain.name !== extra.name || domain.version !== extra.version) {
|
|
153
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "EIP-712 domain name/version differ from requirements.extra");
|
|
154
|
+
}
|
|
155
|
+
if (!sameAddress(message.to, requirements.payTo)) {
|
|
156
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "destination differs from requirements.payTo");
|
|
157
|
+
}
|
|
158
|
+
const value = toBigInt(message.value, "value");
|
|
159
|
+
if (value !== toBigInt(requirements.amount, "requirements.amount")) {
|
|
160
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "amount differs from requirements.amount");
|
|
161
|
+
}
|
|
162
|
+
if (!sameAddress(message.from, signerAddress)) {
|
|
163
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "from differs from signer address");
|
|
164
|
+
}
|
|
165
|
+
if (typeof message.nonce !== "string" || !HEX32.test(message.nonce)) {
|
|
166
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", "nonce is not bytes32");
|
|
167
|
+
}
|
|
168
|
+
const validAfter = toBigInt(message.validAfter, "validAfter");
|
|
169
|
+
const validBefore = toBigInt(message.validBefore, "validBefore");
|
|
170
|
+
|
|
171
|
+
let payloadHash;
|
|
172
|
+
try {
|
|
173
|
+
payloadHash = hashTypedData({ domain, types, primaryType, message }).slice(2).toLowerCase();
|
|
174
|
+
} catch (e) {
|
|
175
|
+
throw new X402PolicyError("CONTEXT_MISMATCH", `typed data does not hash (${e?.shortMessage ?? e?.message})`);
|
|
176
|
+
}
|
|
177
|
+
return Object.freeze({
|
|
178
|
+
primaryType,
|
|
179
|
+
payloadHash,
|
|
180
|
+
chainId: chainId.toString(),
|
|
181
|
+
verifyingContract: getAddress(domain.verifyingContract),
|
|
182
|
+
domainName: domain.name,
|
|
183
|
+
domainVersion: domain.version,
|
|
184
|
+
from: getAddress(message.from),
|
|
185
|
+
to: getAddress(message.to),
|
|
186
|
+
amount: value.toString(),
|
|
187
|
+
validAfter: validAfter.toString(),
|
|
188
|
+
validBefore: validBefore.toString(),
|
|
189
|
+
nonce: message.nonce.toLowerCase(),
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** min(timeoutMs ?? 5000, maxTimeoutSeconds * 1000 / 2): a slow engine must not eat the payment window. */
|
|
194
|
+
export function effectiveTimeoutMs(policy, maxTimeoutSeconds) {
|
|
195
|
+
const base = policy.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
196
|
+
if (typeof maxTimeoutSeconds === "number" && Number.isFinite(maxTimeoutSeconds) && maxTimeoutSeconds > 0) {
|
|
197
|
+
return Math.max(1, Math.min(base, Math.floor((maxTimeoutSeconds * 1000) / 2)));
|
|
198
|
+
}
|
|
199
|
+
return base;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** sha256 of {v, url, method, payloadHash}: the value an ALLOW must echo back. */
|
|
203
|
+
export function computeContextHash(url, method, payloadHash) {
|
|
204
|
+
return sha256hex(JSON.stringify({ v: 1, url, method, payloadHash }));
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Wraps an EVM signer ({ address, signTypedData }) so it only signs with a current ALLOW bound
|
|
209
|
+
* to this exact authorization. Anything else ends without a signature.
|
|
210
|
+
*
|
|
211
|
+
* `getCall` supplies the per-call context (URL, method, requirements): create one gated signer
|
|
212
|
+
* per payment so two concurrent payments never share state. `onRefused` receives the error
|
|
213
|
+
* before it is thrown, because @x402/fetch re-wraps errors and loses their class.
|
|
214
|
+
*/
|
|
215
|
+
export function createPolicyGatedSigner(base, policy, getCall, onRefused) {
|
|
216
|
+
assertValidPolicyHook(policy);
|
|
217
|
+
if (!base || typeof base.signTypedData !== "function" || !isAddress(String(base.address))) {
|
|
218
|
+
throw new Error("createPolicyGatedSigner: base signer needs an address and signTypedData().");
|
|
219
|
+
}
|
|
220
|
+
// Identity is fixed here. If the base signer changes address mid-payment, nothing is signed.
|
|
221
|
+
const account = getAddress(base.address);
|
|
222
|
+
const now = policy.now ?? Date.now;
|
|
223
|
+
|
|
224
|
+
const report = (r) => {
|
|
225
|
+
try {
|
|
226
|
+
const out = policy.onDecision?.(r);
|
|
227
|
+
if (out !== null && (typeof out === "object" || typeof out === "function")) {
|
|
228
|
+
Promise.resolve(out).catch(() => { /* an observer decides nothing */ });
|
|
229
|
+
}
|
|
230
|
+
} catch { /* an observer decides nothing */ }
|
|
231
|
+
};
|
|
232
|
+
const refuse = (outcome, msg, context, decision) => {
|
|
233
|
+
report({ outcome, context, decision, error: msg });
|
|
234
|
+
const err = new X402PolicyError(outcome, msg, { decision, contextHash: context?.contextHash });
|
|
235
|
+
try { onRefused?.(err); } catch { /* idem */ }
|
|
236
|
+
throw err;
|
|
237
|
+
};
|
|
238
|
+
// A clock that does not return a finite number closes: NaN makes every comparison false.
|
|
239
|
+
const readClock = (context, decision) => {
|
|
240
|
+
let t;
|
|
241
|
+
try { t = now(); } catch (e) {
|
|
242
|
+
return refuse("CLOCK_INVALID", `clock threw (${e?.message ?? String(e)})`, context, decision);
|
|
243
|
+
}
|
|
244
|
+
if (typeof t !== "number" || !Number.isFinite(t)) {
|
|
245
|
+
return refuse("CLOCK_INVALID", `clock returned ${String(t)}, not epoch milliseconds`, context, decision);
|
|
246
|
+
}
|
|
247
|
+
return t;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
const signTypedData = async (typedData) => {
|
|
251
|
+
const call = getCall();
|
|
252
|
+
if (!call || !call.requirements) refuse("CONTEXT_MISMATCH", "no payment requirements bound to this signing call");
|
|
253
|
+
if (!sameAddress(base.address, account)) refuse("SIGNER_CHANGED", "base signer address changed after the gate was created");
|
|
254
|
+
|
|
255
|
+
let authorization;
|
|
256
|
+
try {
|
|
257
|
+
authorization = describeAuthorization(typedData, call.requirements, account);
|
|
258
|
+
} catch (e) {
|
|
259
|
+
return refuse(e instanceof X402PolicyError ? e.outcome : "CONTEXT_MISMATCH", e?.message ?? String(e));
|
|
260
|
+
}
|
|
261
|
+
const contextHash = computeContextHash(call.url, call.method, authorization.payloadHash);
|
|
262
|
+
// Frozen: the engine reads, it does not rewrite what gets signed.
|
|
263
|
+
const context = Object.freeze({
|
|
264
|
+
contextVersion: 1,
|
|
265
|
+
url: call.url,
|
|
266
|
+
method: call.method,
|
|
267
|
+
requirements: Object.freeze({ ...call.requirements, extra: Object.freeze({ ...(call.requirements.extra || {}) }) }),
|
|
268
|
+
authorization,
|
|
269
|
+
signer: account,
|
|
270
|
+
contextHash,
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
const timeoutMs = effectiveTimeoutMs(policy, call.requirements.maxTimeoutSeconds);
|
|
274
|
+
const controller = new AbortController();
|
|
275
|
+
// One deadline for the whole pre-sign phase (evaluate + currentVersion).
|
|
276
|
+
const deadline = readClock(context) + timeoutMs;
|
|
277
|
+
let timer;
|
|
278
|
+
const TIMED_OUT = Symbol("timeout");
|
|
279
|
+
const timeout = new Promise((_, reject) => {
|
|
280
|
+
timer = setTimeout(() => { controller.abort(); reject(TIMED_OUT); }, timeoutMs);
|
|
281
|
+
});
|
|
282
|
+
timeout.catch(() => { /* observed by each race */ });
|
|
283
|
+
|
|
284
|
+
try {
|
|
285
|
+
let decision;
|
|
286
|
+
try {
|
|
287
|
+
decision = await Promise.race([
|
|
288
|
+
Promise.resolve().then(() => policy.evaluate(context, { signal: controller.signal })),
|
|
289
|
+
timeout,
|
|
290
|
+
]);
|
|
291
|
+
} catch (e) {
|
|
292
|
+
if (e === TIMED_OUT) return refuse("TIMEOUT", `no decision within ${timeoutMs} ms`, context);
|
|
293
|
+
return refuse("ENGINE_ERROR", e?.message ?? String(e), context);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// Anything that is not a well-formed ALLOW closes.
|
|
297
|
+
if (!decision || typeof decision !== "object") return refuse("MALFORMED", "engine returned no decision object", context);
|
|
298
|
+
if (decision.decision === "DENY") return refuse("DENY", decision.reason ?? "denied", context, decision);
|
|
299
|
+
if (decision.decision === "WAIT") return refuse("WAIT", decision.reason ?? "wait", context, decision);
|
|
300
|
+
if (decision.decision !== "ALLOW") return refuse("MALFORMED", `unknown verdict ${String(decision.decision)}`, context, decision);
|
|
301
|
+
// Copied before any await: mutating the engine's object later changes nothing.
|
|
302
|
+
const allow = Object.freeze({ ...decision });
|
|
303
|
+
if (allow.contextHash !== contextHash) return refuse("UNBOUND", "ALLOW is not bound to this authorization", context, allow);
|
|
304
|
+
if (allow.expiresAt !== undefined && (typeof allow.expiresAt !== "number" || !Number.isFinite(allow.expiresAt))) {
|
|
305
|
+
return refuse("MALFORMED", "expiresAt must be epoch milliseconds", context, allow);
|
|
306
|
+
}
|
|
307
|
+
if (allow.expiresAt === undefined && policy.requireExpiry) {
|
|
308
|
+
return refuse("EXPIRED", "ALLOW without expiresAt while requireExpiry is set", context, allow);
|
|
309
|
+
}
|
|
310
|
+
const checkClock = () => {
|
|
311
|
+
const t = readClock(context, allow);
|
|
312
|
+
if (t >= deadline) refuse("TIMEOUT", "decision arrived after the deadline", context, allow);
|
|
313
|
+
if (allow.expiresAt !== undefined && t >= allow.expiresAt) refuse("EXPIRED", "ALLOW expired before signing", context, allow);
|
|
314
|
+
};
|
|
315
|
+
if (policy.currentVersion && !nonempty(allow.policyVersion)) {
|
|
316
|
+
return refuse("MALFORMED", "ALLOW has no policyVersion to check against currentVersion", context, allow);
|
|
317
|
+
}
|
|
318
|
+
checkClock();
|
|
319
|
+
|
|
320
|
+
// The observer runs HERE, not next to the signer: whatever it changes (the clock, the
|
|
321
|
+
// policy version, the signer's address) is seen by the checks that follow.
|
|
322
|
+
report({ outcome: "ALLOWED", context, decision: allow });
|
|
323
|
+
|
|
324
|
+
if (policy.currentVersion) {
|
|
325
|
+
let current;
|
|
326
|
+
try {
|
|
327
|
+
current = await Promise.race([
|
|
328
|
+
Promise.resolve().then(() => policy.currentVersion(context, { signal: controller.signal })),
|
|
329
|
+
timeout,
|
|
330
|
+
]);
|
|
331
|
+
} catch (e) {
|
|
332
|
+
if (e === TIMED_OUT) return refuse("TIMEOUT", `no current policy version within ${timeoutMs} ms`, context, allow);
|
|
333
|
+
return refuse("VERSION_UNAVAILABLE", `currentVersion failed (${e?.message ?? String(e)})`, context, allow);
|
|
334
|
+
}
|
|
335
|
+
if (!nonempty(current)) return refuse("VERSION_UNAVAILABLE", "currentVersion returned no version", context, allow);
|
|
336
|
+
if (current !== allow.policyVersion) {
|
|
337
|
+
return refuse("STALE", `ALLOW was issued under policy ${allow.policyVersion}, current is ${current}`, context, allow);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// Final checks, always, with no await before the signer.
|
|
342
|
+
checkClock();
|
|
343
|
+
if (!sameAddress(base.address, account)) return refuse("SIGNER_CHANGED", "base signer address changed while the policy was evaluated", context, allow);
|
|
344
|
+
if (timer) clearTimeout(timer);
|
|
345
|
+
let signature;
|
|
346
|
+
try {
|
|
347
|
+
// The original object, not a copy someone could have touched.
|
|
348
|
+
signature = await base.signTypedData(typedData);
|
|
349
|
+
} catch (e) {
|
|
350
|
+
report({ outcome: "SIGNER_ERROR", context, decision: allow, error: e?.message ?? String(e) });
|
|
351
|
+
throw e;
|
|
352
|
+
}
|
|
353
|
+
if (typeof signature !== "string" || !SIG65.test(signature)) {
|
|
354
|
+
return refuse("SIGNER_ERROR", "signer returned no 65-byte signature", context, allow);
|
|
355
|
+
}
|
|
356
|
+
report({ outcome: "SIGNED", context, decision: allow });
|
|
357
|
+
return signature;
|
|
358
|
+
} finally {
|
|
359
|
+
if (timer) clearTimeout(timer);
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
// Read-only chain access may be forwarded; no other signing method is exposed.
|
|
364
|
+
const gated = { address: account, signTypedData };
|
|
365
|
+
if (typeof base.readContract === "function") gated.readContract = (args) => base.readContract(args);
|
|
366
|
+
return Object.freeze(gated);
|
|
367
|
+
}
|