@morpho-org/calldata-verifier 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +97 -2
- package/lib/cjs/actionProof.d.ts +6 -0
- package/lib/cjs/actionProof.js +215 -0
- package/lib/cjs/blue.d.ts +18 -0
- package/lib/cjs/blue.js +395 -0
- package/lib/cjs/checks.d.ts +80 -0
- package/lib/cjs/checks.js +172 -0
- package/lib/cjs/errors.d.ts +42 -0
- package/lib/cjs/errors.js +59 -0
- package/lib/cjs/index.d.ts +3 -0
- package/lib/cjs/index.js +15 -0
- package/lib/cjs/midnight.d.ts +27 -0
- package/lib/cjs/midnight.js +546 -0
- package/lib/cjs/midnightOffers.d.ts +23 -0
- package/lib/cjs/midnightOffers.js +108 -0
- package/lib/cjs/package.json +1 -0
- package/lib/cjs/types.d.ts +362 -0
- package/lib/cjs/types.js +2 -0
- package/lib/cjs/vault.d.ts +13 -0
- package/lib/cjs/vault.js +339 -0
- package/lib/cjs/verifyCalldata.d.ts +76 -0
- package/lib/cjs/verifyCalldata.js +152 -0
- package/lib/cjs/version.d.ts +2 -0
- package/lib/cjs/version.js +6 -0
- package/lib/esm/actionProof.d.ts +6 -0
- package/lib/esm/actionProof.js +212 -0
- package/lib/esm/blue.d.ts +18 -0
- package/lib/esm/blue.js +392 -0
- package/lib/esm/checks.d.ts +80 -0
- package/lib/esm/checks.js +156 -0
- package/lib/esm/errors.d.ts +42 -0
- package/lib/esm/errors.js +47 -0
- package/lib/esm/index.d.ts +3 -0
- package/lib/esm/index.js +2 -0
- package/lib/esm/midnight.d.ts +27 -0
- package/lib/esm/midnight.js +543 -0
- package/lib/esm/midnightOffers.d.ts +23 -0
- package/lib/esm/midnightOffers.js +105 -0
- package/lib/esm/package.json +1 -0
- package/lib/esm/types.d.ts +362 -0
- package/lib/esm/types.js +1 -0
- package/lib/esm/vault.d.ts +13 -0
- package/lib/esm/vault.js +336 -0
- package/lib/esm/verifyCalldata.d.ts +76 -0
- package/lib/esm/verifyCalldata.js +149 -0
- package/lib/esm/version.d.ts +2 -0
- package/lib/esm/version.js +3 -0
- package/package.json +50 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Morpho Association
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,98 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Calldata verifier
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Verify Morpho Actions API calls against the user's original intent before signing. Supports Vault V1/V2, Morpho Blue and Midnight market actions.
|
|
4
|
+
|
|
5
|
+
## Scope
|
|
6
|
+
|
|
7
|
+
`verifyCalldata` is a static check, not an execution verifier. It uses only calldata, intent, and the local chain registry to check targets and selectors, vault or market, requested amounts where comparable, encoded owners and recipients, and encoded referral fees against `max_fee_bps`. Unknown, malformed, or unexpected calls are rejected.
|
|
8
|
+
|
|
9
|
+
When a referral fee is requested, the verifier checks its recipient and caps the encoded fee at the lower of `referral_fee.bps` and `max_fee_bps`.
|
|
10
|
+
|
|
11
|
+
Use [`@morpho-org/evm-simulation`](../evm-simulation) for execution-dependent checks. Outside the static scope:
|
|
12
|
+
|
|
13
|
+
- Whether Vault share-price bounds match `slippage_bps`. Regardless of whether it is supplied, the verifier rejects Vault V1/V2 deposit ceilings of zero or `maxUint256` and exact-asset Vault V2 force-withdraw floors of zero. To enforce the tolerance, derive a RAY-scaled bound from trusted vault data at a pinned block. For deposits, take the projection deadline from your original request or local policy, not the API response, and reject decoded `args[6]` if it is later than that deadline. Follow the [SDK calculation](../morpho-sdk/src/helpers/slippage.ts): deduct any referral fee, use the lower of the current and deadline-accrued share previews (both rounded down), and require decoded `args[2]` to be at most the resulting ceiling. A raw share-price ratio can be too strict, especially at zero slippage.
|
|
14
|
+
- For exact-asset Vault V2 force withdrawals, use the public Morpho SDK's `client.morpho.vaultV2(vault, chainId).forceWithdraw(...).buildTx()` to derive an independent floor without signing or sending anything. Use pinned vault data, the block timestamp as `now`, and the exit amount, signer, slippage tolerance, and deadline from your request or local policy. To rely on this floor comparison, set `slippage_bps` explicitly in your request instead of relying on a default. Pass `BigInt(slippage_bps) * 10n ** 14n` as the SDK's WAD-scaled `slippageTolerance`. Compare decoded `args[3]` with `tx.action.args.minSharePriceE27` and reject a lower floor or a later decoded deadline (`args[7]`). The SDK's internal quote accounts for deallocation penalties and net shares burned: fee shares minted to the signer as a management or performance fee recipient offset shares burned. The public `computeVaultV2ForceWithdrawFeeSharesMinted` helper projects those mints to the trusted deadline but does not compute the floor. The bundle skips its onchain floor check when `totalSharesBurnt == 0`; do not rely on the floor if the SDK rejects the projection because fee mints can erase the burn.
|
|
15
|
+
- Vault V2 penalty rates and whether they meet `max_penalty_bps`.
|
|
16
|
+
- For `vault_v2.redeem_in_kind`, the verifier does not check the optional `max_penalty_bps` cap, and `@morpho-org/evm-simulation` rejects `quote.penalty` for in-kind redemption. If `max_penalty_bps !== undefined`, read the vault's WAD-scaled `forceDeallocatePenalty(adapter)` at a pinned block before signing and require `penalty <= BigInt(max_penalty_bps) * 10n ** 14n`. An omitted cap skips this comparison; a cap of `0` requires zero penalty. This read checks the rate only at that block: the calldata carries no penalty limit, so the vault charges the rate in effect when the transaction executes. If you need the cap to hold at execution, also watch for pending penalty changes or limit how long a signed transaction can wait before inclusion. Separately, use minimum `quote.positions` (Blue supply shares) or `quote.assetsReceived` (idle assets paid to the wallet), accounting for simulation tolerance, to bound proceeds; these bounds do not verify the penalty rate.
|
|
17
|
+
- For `vault_v2.force_withdraw` with `amount.unit: "all"`, the verifier checks that `forceDeallocate` legs are well-formed, use the requested account, and encode positive amounts. To check the rate cap before signing, read the vault's WAD-scaled `forceDeallocatePenalty(adapter)` at a pinned block for each adapter in the verified legs and require `penalty <= BigInt(max_penalty_bps) * 10n ** 14n`. This read checks the rate only at that block: the calldata carries no penalty limit, so the vault charges the rate in effect when the transaction executes. If you need the cap to hold at execution, also watch for pending penalty changes or limit how long a signed transaction can wait before inclusion. Separately, simulation's `quote.penalty` bounds total penalty assets and `quote.deallocations` bounds amounts by observed Blue market, accounting for simulation tolerance; neither checks the penalty rate. If a leg emits no matching Blue `Withdraw` event (for example, a Vault V1 adapter or a non-Blue leg with empty adapter data), simulation fails closed when `quote.deallocations` is supplied; use `quote.penalty` to bound the penalty cost across all legs, or derive your own per-leg limits.
|
|
18
|
+
- Actual balances and amounts derived for `amount.unit: "all"`.
|
|
19
|
+
- Whether the caller-supplied Vault `asset` matches the actual `vault.asset()`. Read `vault.asset()` at the pinned block and compare it with `asset`. For deposits and standard withdrawals or redemptions, typed-input simulation can establish an exact match if you pass a canonical ERC-20 address as the token override (`assetPaid` for deposits, `assetReceived` for exits). Simulation also accepts `ethAddress` for a vault whose asset is the chain's wrapped-native token, so use the pinned read if your source might supply a native alias. Force withdrawals, force redemptions, and in-kind redemptions do not support typed inputs; use the pinned read for those. Quote-only limits can accept a token override without comparing it with `vault.asset()`.
|
|
20
|
+
- Whether existing onchain allowances suffice and whether a call succeeds or reverts.
|
|
21
|
+
- Blue ERC-20 repay by shares or for all debt: before signing, compare the decoded `maxRepayAssets`, which is `args[3]` of the verified `blueBundlesV1RepayAndWithdrawCollateral` call, against an independently chosen funding cap. Apply this check whenever that call's `value` is zero, including for requests that allowed native funding, because such requests don't have to use it. Simulating net spend does not bound the upfront pull because unused funds can be refunded.
|
|
22
|
+
- Blue public-allocator reallocations: the verifier checks zero penalty, the destination market and loan token, positive amounts, and route structure and uniqueness. Simulation checks whether a reallocation is needed and whether its source and amount are appropriate.
|
|
23
|
+
- Blue embedded Morpho authorizations: the verifier checks signature structure. The bundle supplies the transaction sender and its own address as the authorizer and authorized spender; signature validity, nonce and expiry are execution checks.
|
|
24
|
+
- Midnight full direct repays, and units-target lends, market repays and `midnight.take_lend` takes: compare the decoded `maxBuyerAssets` against an independently chosen upfront funding cap before signing. For full direct repays, this applies to ERC-20, native, and auto funding: when ETH is sent, the bundle wraps it to the signer's balance and then pulls the encoded `maxBuyerAssets` from that wrapped-native balance. `max_native_assets` caps only the ETH sent, not the token pull. For the units-target cases, you can instead set a `max_assets` guard to enforce the upfront funding cap. Simulation's `assetsPaid` measures net spend after refunds, not the upfront pull.
|
|
25
|
+
- Midnight buy bundles for lend, market repay, and `midnight.take_lend`: the verifier does not bound the encoded `maxContinuousFee`. Compare it with an independently chosen ceiling. To check the market's actual fee against that ceiling, read Midnight's `continuousFee(marketId)` at the simulation block or use a simulation `assertBefore` view call.
|
|
26
|
+
- Midnight fill prices under a `slippage` guard: the secondary bound and offer ticks depend on the onchain price. Check the resulting fill price in simulation.
|
|
27
|
+
- Midnight borrow takes withdraw available existing credit first and may succeed without filling the requested offer. If a fill is required, verify it in simulation.
|
|
28
|
+
- Midnight offer ratification: the verifier does not check roots, proofs, or ratifier data. Midnight checks ratification at execution.
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { verifyCalldata } from "@morpho-org/calldata-verifier";
|
|
34
|
+
|
|
35
|
+
verifyCalldata(
|
|
36
|
+
{
|
|
37
|
+
...requestBody,
|
|
38
|
+
action: "vault_v2.deposit",
|
|
39
|
+
chain_id: 8453,
|
|
40
|
+
vault,
|
|
41
|
+
asset,
|
|
42
|
+
max_fee_bps: 0,
|
|
43
|
+
},
|
|
44
|
+
response.data.calls,
|
|
45
|
+
);
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Pass the original request body, not values copied from the response. A successful check returns the decoded calls; a mismatch throws.
|
|
49
|
+
|
|
50
|
+
Every Vault intent requires `asset`, the underlying token address from a source independent of the calldata response. The verifier checks it against deposit approvals (including zero resets), the chain's wrapped native token for native deposits, and any encoded Blue market loan token in in-kind redemptions and force-redeem deallocation legs. Standard withdrawals, exact-asset force withdrawals, and empty adapter data do not encode the underlying token. Deposit bundle arguments and ERC-2612 or Permit2 payloads do not encode a token address either; the bundle reads `vault.asset()` at execution.
|
|
51
|
+
|
|
52
|
+
For Blue and Midnight, pass the market ID as `market` and the chain separately as `chain_id`. Keep the API's chain-qualified `destination_market` in the Blue refinance request body.
|
|
53
|
+
|
|
54
|
+
- Submit only the verified calls, in order, from `account` on `chain_id`. Calldata does not identify the signer or the network; some Vault calls pay the caller directly.
|
|
55
|
+
- For `amount.unit: "all"`, the owner and every recipient (including any referral recipient) must be `account`. The verifier does not compare a concrete share or asset amount, so a withdrawal may return less than the full balance.
|
|
56
|
+
- An approval's spender must match the main call's target. A positive approval included in the response must cover the encoded pull where the amount is available: at least the encoded assets on Vault deposits, or at least the encoded shares on share-unit and `"all"` Vault withdrawals. An unlimited approval is accepted. A zero reset must immediately precede a positive approval for the same token and spender.
|
|
57
|
+
- Nonzero native value must be authorized by the request's `funding.max_native_assets`. The verifier does not require a native-capable request to use native funds.
|
|
58
|
+
- Blue reallocations with a nonzero penalty are rejected.
|
|
59
|
+
- Midnight accepts `slippage` or no guard, and checks explicit `min_units`/`max_assets` on buys and `max_units`/`min_assets` on sells and direct withdrawals. Unknown and wrong-side guards throw `CalldataUnsupportedError`.
|
|
60
|
+
- For Midnight, an approval, if included, must cover the encoded loan-token or collateral pull.
|
|
61
|
+
- Midnight `min_rate` and `max_rate` guards throw `CalldataUnsupportedError`: the rate is not encoded directly in the bundle, and its conversion depends on the quote and execution context.
|
|
62
|
+
- Midnight core withdrawals transfer one loan asset per unit withdrawn after the contract updates the account's credit for losses. The verifier accepts exact asset and exact unit requests for this route.
|
|
63
|
+
- The verifier does not check slippage, expiry or attribution tags, or verify typed-data signing requests.
|
|
64
|
+
|
|
65
|
+
### Authenticate an Actions API response
|
|
66
|
+
|
|
67
|
+
Pass `{ proof }` as the optional third argument to require a valid `Morpho-Action-Proof` header. Fetch the JWKS yourself from `/.well-known/morpho-actions-jwks.json` on your independently trusted Actions origin. The verifier never fetches keys. The expected issuer defaults to `https://api.morpho.org/v0/actions`; override it only for a different trusted environment.
|
|
68
|
+
|
|
69
|
+
Follow Morpho's [response verification guide](https://docs.morpho.org/api/actions/verify-responses/): send requests to your keyed origin without following redirects, cache its JWKS for at most 60 seconds, and refetch on an unknown `kid`. The wallet integration must check the action's `expires_at` separately from the proof expiry. This verifier does not handle signature-required continuations or typed-data signatures.
|
|
70
|
+
|
|
71
|
+
Retain the exact request body bytes as sent and the response body bytes after HTTP decompression, before parsing JSON. Do not reserialize either body. Pass the exact request path and content type, response status and content type, response `X-Request-Id`, and the current time in Unix seconds as `now`. The verifier does not read the clock. For example, given your original `intent`, sent `request`, received `response`, and `trustedJwks`:
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
const responseBytes = new Uint8Array(await response.arrayBuffer());
|
|
75
|
+
const { data } = JSON.parse(new TextDecoder().decode(responseBytes));
|
|
76
|
+
const verified = verifyCalldata(intent, data.calls, {
|
|
77
|
+
proof: {
|
|
78
|
+
header: response.headers.get("Morpho-Action-Proof") ?? "",
|
|
79
|
+
jwks: trustedJwks,
|
|
80
|
+
now: Math.floor(Date.now() / 1000),
|
|
81
|
+
request, // { method, path, contentType, body: Uint8Array }
|
|
82
|
+
response: {
|
|
83
|
+
status: response.status,
|
|
84
|
+
contentType: response.headers.get("Content-Type") ?? "",
|
|
85
|
+
requestId: response.headers.get("X-Request-Id") ?? "",
|
|
86
|
+
body: responseBytes,
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Verification stays synchronous and throws `CalldataProofError` if the signature, freshness, exchange, or supplied calls do not match, or if the signed response is not prepared with a successful simulation and an approved decision. The signed response must include a `chain_id` matching the intent. A valid proof authenticates the bytes as attested by Morpho; it does not bind the host or prevent replay within the proof's short validity window. It does not establish transaction safety or current chain state. Proof mode still runs the static checks; use simulation and independent state-dependent bounds before signing.
|
|
93
|
+
|
|
94
|
+
### Midnight offers
|
|
95
|
+
|
|
96
|
+
- For takes, pass `group` from the original path and `market_id` from the request. Group IDs are scoped to a maker: without `maker`, the group alone does not identify the offer, and the verifier only checks that all fills use one maker. Takes without a caller-known market ID or with a reduce-only maker fill throw `CalldataUnsupportedError`. Use an explicit amount guard to enforce a minimum or maximum on the other side of the trade.
|
|
97
|
+
- Funding withdrawals must pay `account` from the original `funding_address` and `funding_market`. The request has no amount: the verifier checks for a positive share withdrawal, not that it empties the position.
|
|
98
|
+
- The four `midnight.make_*` actions throw `CalldataUnsupportedError` in v1. Verifying them would require decoding the compressed offer payload and checking its commitment against the root the call activates.
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.authenticateCalls = authenticateCalls;
|
|
4
|
+
const p256_1 = require("@noble/curves/p256");
|
|
5
|
+
const viem_1 = require("viem");
|
|
6
|
+
const errors_js_1 = require("./errors.js");
|
|
7
|
+
const algorithm = "ES256";
|
|
8
|
+
const proofType = "morpho-action-proof+jwt";
|
|
9
|
+
const productionIssuer = "https://api.morpho.org/v0/actions";
|
|
10
|
+
const audience = "morpho-actions-client";
|
|
11
|
+
const jwkFields = ["kty", "crv", "x", "y", "alg", "kid", "key_ops", "use"];
|
|
12
|
+
const callFields = ["id", "kind", "to", "data", "value"];
|
|
13
|
+
const clockTolerance = 5;
|
|
14
|
+
const maxTokenAge = 60;
|
|
15
|
+
const maxLifetime = 300;
|
|
16
|
+
const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
|
|
17
|
+
function isObject(value) {
|
|
18
|
+
return value != null && typeof value === "object" && !Array.isArray(value);
|
|
19
|
+
}
|
|
20
|
+
function isUint8Array(value) {
|
|
21
|
+
return (Reflect.get(typedArrayPrototype, Symbol.toStringTag, value) === "Uint8Array");
|
|
22
|
+
}
|
|
23
|
+
function base64url(bytes) {
|
|
24
|
+
return btoa(String.fromCharCode(...bytes))
|
|
25
|
+
.replaceAll("+", "-")
|
|
26
|
+
.replaceAll("/", "_")
|
|
27
|
+
.replace(/=+$/, "");
|
|
28
|
+
}
|
|
29
|
+
function decodeBase64url(value) {
|
|
30
|
+
if (!/^[A-Za-z0-9_-]+$/.test(value)) {
|
|
31
|
+
throw new errors_js_1.CalldataProofError("proof.encoding");
|
|
32
|
+
}
|
|
33
|
+
return Uint8Array.from(atob(value.replaceAll("-", "+").replaceAll("_", "/")), (character) => character.charCodeAt(0));
|
|
34
|
+
}
|
|
35
|
+
function parseObject(bytes, field) {
|
|
36
|
+
const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
37
|
+
if (!isObject(value)) {
|
|
38
|
+
throw new errors_js_1.CalldataProofError(field);
|
|
39
|
+
}
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
function publicKey(jwks, kid) {
|
|
43
|
+
const keys = isObject(jwks) && Array.isArray(jwks.keys)
|
|
44
|
+
? jwks.keys.filter((entry) => isObject(entry) && entry.kid === kid)
|
|
45
|
+
: [];
|
|
46
|
+
const [key] = keys;
|
|
47
|
+
if (keys.length !== 1 ||
|
|
48
|
+
!isObject(key) ||
|
|
49
|
+
Object.keys(key).some((field) => !jwkFields.includes(field)) ||
|
|
50
|
+
key.kty !== "EC" ||
|
|
51
|
+
key.crv !== "P-256" ||
|
|
52
|
+
typeof key.x !== "string" ||
|
|
53
|
+
!/^[A-Za-z0-9_-]{43}$/.test(key.x) ||
|
|
54
|
+
typeof key.y !== "string" ||
|
|
55
|
+
!/^[A-Za-z0-9_-]{43}$/.test(key.y) ||
|
|
56
|
+
(key.alg !== undefined && key.alg !== algorithm) ||
|
|
57
|
+
(key.use !== undefined && key.use !== "sig") ||
|
|
58
|
+
(key.key_ops !== undefined &&
|
|
59
|
+
(!Array.isArray(key.key_ops) ||
|
|
60
|
+
key.key_ops.length !== 1 ||
|
|
61
|
+
key.key_ops[0] !== "verify"))) {
|
|
62
|
+
throw new errors_js_1.CalldataProofError("proof.jwks");
|
|
63
|
+
}
|
|
64
|
+
const point = new Uint8Array(65);
|
|
65
|
+
point[0] = 4;
|
|
66
|
+
point.set(decodeBase64url(key.x), 1);
|
|
67
|
+
point.set(decodeBase64url(key.y), 33);
|
|
68
|
+
return point;
|
|
69
|
+
}
|
|
70
|
+
function verifyClaims(claims, { issuer, now }) {
|
|
71
|
+
const { iat, exp, nbf, aud } = claims;
|
|
72
|
+
if (claims.iss !== issuer ||
|
|
73
|
+
claims.sub !== "action-response" ||
|
|
74
|
+
!(aud === audience || (Array.isArray(aud) && aud.includes(audience))) ||
|
|
75
|
+
!Number.isSafeInteger(now) ||
|
|
76
|
+
typeof iat !== "number" ||
|
|
77
|
+
!Number.isSafeInteger(iat) ||
|
|
78
|
+
typeof exp !== "number" ||
|
|
79
|
+
!Number.isSafeInteger(exp) ||
|
|
80
|
+
exp <= iat ||
|
|
81
|
+
exp - iat > maxLifetime ||
|
|
82
|
+
iat > now + clockTolerance ||
|
|
83
|
+
now - iat > maxTokenAge + clockTolerance ||
|
|
84
|
+
exp <= now - clockTolerance ||
|
|
85
|
+
(nbf !== undefined &&
|
|
86
|
+
(typeof nbf !== "number" ||
|
|
87
|
+
!Number.isFinite(nbf) ||
|
|
88
|
+
nbf > now + clockTolerance))) {
|
|
89
|
+
throw new errors_js_1.CalldataProofError("proof.claims");
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function responseDecision(data) {
|
|
93
|
+
const simulation = isObject(data.simulation)
|
|
94
|
+
? data.simulation.status
|
|
95
|
+
: undefined;
|
|
96
|
+
if (data.status === "signature_required") {
|
|
97
|
+
return "signature_required";
|
|
98
|
+
}
|
|
99
|
+
if (data.status === "prepared" && simulation === "success") {
|
|
100
|
+
return "approved";
|
|
101
|
+
}
|
|
102
|
+
if (data.status === "simulation_unavailable" &&
|
|
103
|
+
simulation === "unavailable") {
|
|
104
|
+
return "unsimulated";
|
|
105
|
+
}
|
|
106
|
+
return "rejected";
|
|
107
|
+
}
|
|
108
|
+
function verifyExchange({ header, jwks, request, response, issuer = productionIssuer, now, }) {
|
|
109
|
+
if (typeof now !== "number" || !Number.isFinite(now)) {
|
|
110
|
+
throw new errors_js_1.CalldataProofError("proof.now");
|
|
111
|
+
}
|
|
112
|
+
const [protectedPart, payloadPart, signaturePart, ...rest] = header.split(".");
|
|
113
|
+
if (!protectedPart || !payloadPart || !signaturePart || rest.length !== 0) {
|
|
114
|
+
throw new errors_js_1.CalldataProofError("proof.header");
|
|
115
|
+
}
|
|
116
|
+
const { alg, typ, kid, crit, b64 } = parseObject(decodeBase64url(protectedPart), "proof.header");
|
|
117
|
+
if (alg !== algorithm ||
|
|
118
|
+
typ !== proofType ||
|
|
119
|
+
typeof kid !== "string" ||
|
|
120
|
+
kid.length === 0 ||
|
|
121
|
+
(b64 !== undefined && b64 !== true) ||
|
|
122
|
+
(crit !== undefined &&
|
|
123
|
+
(!Array.isArray(crit) ||
|
|
124
|
+
crit.length !== 1 ||
|
|
125
|
+
crit[0] !== "b64" ||
|
|
126
|
+
b64 !== true))) {
|
|
127
|
+
throw new errors_js_1.CalldataProofError("proof.header");
|
|
128
|
+
}
|
|
129
|
+
const signature = decodeBase64url(signaturePart);
|
|
130
|
+
const message = new TextEncoder().encode(`${protectedPart}.${payloadPart}`);
|
|
131
|
+
if (signature.length !== 64 ||
|
|
132
|
+
!p256_1.p256.verify(signature, message, publicKey(jwks, kid), {
|
|
133
|
+
format: "compact",
|
|
134
|
+
lowS: false,
|
|
135
|
+
prehash: true,
|
|
136
|
+
})) {
|
|
137
|
+
throw new errors_js_1.CalldataProofError("proof.signature");
|
|
138
|
+
}
|
|
139
|
+
const claims = parseObject(decodeBase64url(payloadPart), "proof.claims");
|
|
140
|
+
verifyClaims(claims, {
|
|
141
|
+
issuer,
|
|
142
|
+
now: Math.floor(new Date(now * 1000).getTime() / 1000),
|
|
143
|
+
});
|
|
144
|
+
const { request: signedRequest, response: signedResponse } = claims;
|
|
145
|
+
const receivedRequestBody = request.body;
|
|
146
|
+
const receivedResponseBody = response.body;
|
|
147
|
+
if (request.method !== "POST" ||
|
|
148
|
+
!request.path.startsWith("/v0/actions/") ||
|
|
149
|
+
!isUint8Array(receivedRequestBody) ||
|
|
150
|
+
!isUint8Array(receivedResponseBody) ||
|
|
151
|
+
typeof response.requestId !== "string" ||
|
|
152
|
+
claims.request_id !== response.requestId ||
|
|
153
|
+
!isObject(signedRequest) ||
|
|
154
|
+
signedRequest.method !== request.method ||
|
|
155
|
+
signedRequest.target !== request.path ||
|
|
156
|
+
signedRequest.content_type !== request.contentType ||
|
|
157
|
+
!isObject(signedResponse) ||
|
|
158
|
+
signedResponse.status !== response.status ||
|
|
159
|
+
signedResponse.content_type !== response.contentType) {
|
|
160
|
+
throw new errors_js_1.CalldataProofError("proof.exchange");
|
|
161
|
+
}
|
|
162
|
+
const requestBody = new Uint8Array(receivedRequestBody);
|
|
163
|
+
const responseBody = new Uint8Array(receivedResponseBody);
|
|
164
|
+
if (requestBody.length === 0 ||
|
|
165
|
+
signedRequest.body_sha256 !== base64url((0, viem_1.sha256)(requestBody, "bytes")) ||
|
|
166
|
+
signedResponse.body_sha256 !== base64url((0, viem_1.sha256)(responseBody, "bytes"))) {
|
|
167
|
+
throw new errors_js_1.CalldataProofError("proof.exchange");
|
|
168
|
+
}
|
|
169
|
+
const { data } = parseObject(responseBody, "proof.response");
|
|
170
|
+
if (!isObject(data)) {
|
|
171
|
+
throw new errors_js_1.CalldataProofError("proof.response");
|
|
172
|
+
}
|
|
173
|
+
const decision = responseDecision(data);
|
|
174
|
+
if (claims.action_id !== data.action_id ||
|
|
175
|
+
claims.action !== data.action ||
|
|
176
|
+
claims.decision !== decision) {
|
|
177
|
+
throw new errors_js_1.CalldataProofError("proof.response");
|
|
178
|
+
}
|
|
179
|
+
return { data, decision };
|
|
180
|
+
}
|
|
181
|
+
function isCall(value) {
|
|
182
|
+
return (isObject(value) &&
|
|
183
|
+
callFields.every((field) => typeof value[field] === "string"));
|
|
184
|
+
}
|
|
185
|
+
/** @internal */
|
|
186
|
+
function authenticateCalls(proof, { calls, chainId }) {
|
|
187
|
+
try {
|
|
188
|
+
const { data, decision } = verifyExchange(proof);
|
|
189
|
+
if (decision !== "approved") {
|
|
190
|
+
throw new errors_js_1.CalldataProofError("proof.decision");
|
|
191
|
+
}
|
|
192
|
+
if (!Number.isSafeInteger(data.chain_id) || data.chain_id !== chainId) {
|
|
193
|
+
throw new errors_js_1.CalldataProofError("proof.chain_id");
|
|
194
|
+
}
|
|
195
|
+
const signedCalls = data.calls;
|
|
196
|
+
if (!Array.isArray(signedCalls) ||
|
|
197
|
+
!signedCalls.every(isCall) ||
|
|
198
|
+
!Array.isArray(calls) ||
|
|
199
|
+
signedCalls.length !== calls.length ||
|
|
200
|
+
signedCalls.some((signed, index) => {
|
|
201
|
+
const call = calls[index];
|
|
202
|
+
return (!isCall(call) ||
|
|
203
|
+
callFields.some((field) => call[field] !== signed[field]));
|
|
204
|
+
})) {
|
|
205
|
+
throw new errors_js_1.CalldataProofError("proof.calls");
|
|
206
|
+
}
|
|
207
|
+
return signedCalls;
|
|
208
|
+
}
|
|
209
|
+
catch (cause) {
|
|
210
|
+
if (cause instanceof errors_js_1.CalldataProofError) {
|
|
211
|
+
throw cause;
|
|
212
|
+
}
|
|
213
|
+
throw new errors_js_1.CalldataProofError("proof", { cause });
|
|
214
|
+
}
|
|
215
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ChainAddresses } from "@morpho-org/morpho-ts";
|
|
2
|
+
import type { BlueCalldataIntent, CalldataCall, DecodedCalldataCall } from "./types.js";
|
|
3
|
+
type Context = {
|
|
4
|
+
readonly calls: readonly CalldataCall[];
|
|
5
|
+
readonly chain: ChainAddresses;
|
|
6
|
+
};
|
|
7
|
+
declare function verifyBlue(intent: BlueCalldataIntent, context: Context): readonly DecodedCalldataCall[];
|
|
8
|
+
/** @internal */
|
|
9
|
+
export declare const blueRules: {
|
|
10
|
+
"blue.supply": typeof verifyBlue;
|
|
11
|
+
"blue.withdraw": typeof verifyBlue;
|
|
12
|
+
"blue.supply_collateral": typeof verifyBlue;
|
|
13
|
+
"blue.withdraw_collateral": typeof verifyBlue;
|
|
14
|
+
"blue.borrow": typeof verifyBlue;
|
|
15
|
+
"blue.repay": typeof verifyBlue;
|
|
16
|
+
"blue.refinance": typeof verifyBlue;
|
|
17
|
+
};
|
|
18
|
+
export {};
|