Verify Action API responses
Check simulation results and verify the signed proof before signing typed data or sending Action API calls.
The Morpho Action API returns calls for the user's wallet to send. Morpho does not submit transactions. Verify the proof and inspect the response before signing typed data or sending calls.
Check the response
| Field | What to check |
|---|---|
data.status | prepared contains wallet calls. Send them only after proof verification and a successful final simulation. signature_required asks for typed-data signatures, not call execution. Verify that response before asking the user to sign. |
data.chain_id, data.account, data.action | Match the user's chain, account, and requested action. |
data.expires_at | Reject an expired action and request it again. This off-chain validity timestamp does not control transaction inclusion. |
data.simulation.status | Require success before sending calls. A simulation_failed response contains no wallet calls. Inspect simulation.failure.code and simulation.failure.message instead. |
data.simulation.wallet_changes | Compare each asset and signed difference, in asset base units, with the expected spendable balance change. |
data.simulation.position_changes | Compare protocol position changes with the user's intent. For a vault deposit, vault_shares is the signed change in share base units. |
data.simulation.effects | Check the action-specific effects. For a Vault V2 deposit, these include gross_assets, referral_fee_assets, and net_assets. |
For signature_required, show the user each signatures[].typed_data and sign only with their consent. Check its domain chain against the requested chain. Post the returned continuation and collected signatures to the same action endpoint, then verify the new response. The TypeScript helper below limits this to three signature rounds and refuses to sign with 60 seconds or less remaining.
A live Vault V2 deposit response
This trimmed response was captured on Base for a deposit of 1000000 asset base units into vault 0x050cE30b927Da55177A4914EC73480238BAD56f0. Fields not shown, including calls, are omitted.
{
"data": {
"status": "prepared",
"action": "vault_v2.deposit",
"chain_id": 8453,
"simulation": {
"status": "success",
"block": { "number": "55647340", "timestamp": 1794319843 },
"wallet_changes": [
{
"asset": {
"type": "erc20",
"address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
},
"difference": "-1000000"
}
],
"position_changes": { "vault_shares": "953246207399607626" },
"effects": {
"gross_assets": "1000000",
"referral_fee_assets": "0",
"net_assets": "1000000"
}
}
}
}The final ordered calls, including prerequisite calls and collected signatures, are the authoritative simulation input. The attestor does not accept caller-selected state overrides. A successful simulation is a point-in-time check, not a guarantee of inclusion or of unchanged state when the wallet sends the calls. It does not prove the wallet can send them: wallets have their own gas estimates, batch limits, and atomic-batching support.
A proof reports what the attestor checked at that time. It does not make a transaction safe after its on-chain protections expire.
Send calls from the wallet
Send every call's to, data, and value unchanged, from the action's account, on its chain_id, in the returned order. Treat these fields as opaque. Do not set gas limits or gas prices from the simulation: the wallet estimates gas and applies its own size and gas limits.
- Atomic batch: use EIP-5792
wallet_sendCallsonly when the wallet reportsatomicsupport for that chain, or send one ERC-4337 user operation. All calls apply together or none do. - Sequential transactions: otherwise send one call at a time and await its receipt before sending the next. Check
expires_atbefore each call. Stop on the first rejection, failure, or expiry. Already-confirmed approvals and authorizations remain in place; the API does not revoke them. Show the user what was confirmed. Request the action again to retry instead of sending the remaining calls, so the new response reflects the confirmed state. - Typed-data support: if the wallet cannot sign EIP-712 typed data with
signature_mode: "auto", request the action again withsignature_mode: "none". Tell the user before sending that the replacement approval or authorization calls can grant more than the signature would have, including an unlimited approval.
If a transaction may have been sent but its outcome is unknown, check its receipt or the wallet's history before retrying. Do not assume that an unconfirmed transaction failed.
Retry or rebuild
Treat HTTP 503 state, request, and verification errors as retryable. On HTTP 429, honor Retry-After; no JSON error body is specified for that response. SIGNATURE_REFRESH_REQUIRED and ACTION_CONTINUATION_INVALID mean restarting the action without its continuation.
If the API is unavailable or rejects a request, integrators can build the transaction with the Morpho SDK using their own RPC, or call the protocol contracts directly. The Blue transaction tutorial and Midnight borrow tutorial retain SDK and contract alternatives. Re-read current state and apply the relevant simulation, authorization, and user-consent checks; do not execute calls from a rejected response.
Verify the signed proof
Read the Morpho-Action-Proof response header. It is an ES256 compact JWT with protected header typ: morpho-action-proof+jwt and a kid identifying the verification key.
Send requests only to your keyed origin under /v0/actions/, with x-api-key, and do not follow redirects. The proof binds the path, not the host; a request sent elsewhere could be relayed with a genuine response.
Download Morpho's public signing keys from the same address you send requests to: https://private.api.morpho.org/.well-known/morpho-actions-jwks.json. This download needs no API key. Pin that address in your verifier. Do not accept a remote key source nominated by a proof header.
Cache JWKS for at most 60 seconds, as its Cache-Control header specifies, so removed keys stop being trusted quickly. Refetch when a proof's kid is absent from the cached set. Require a nonempty kid that identifies exactly one key. The TypeScript helper reloads an expired cache and refreshes an unknown kid subject to JOSE's cooldown; it rejects the proof if the key still does not resolve uniquely. The other helpers accept JWKS bytes, so their callers must implement this cache and refresh policy.
| Check | Expected value |
|---|---|
| Algorithm | ES256 |
Protected typ | morpho-action-proof+jwt |
iss | https://api.morpho.org/v0/actions, the production issuer, not the private request origin |
aud | morpho-actions-client |
sub | action-response |
| Time | Require safe-integer iat and exp, with exp > iat and exp - iat <= 300 seconds. Reject expired proofs and an iat in the future or more than 60 seconds old, allowing 5 seconds of clock tolerance. |
Keep the exact request bytes sent and response bytes received. Hash those bytes with SHA-256 and encode the digest as unpadded base64url. Do not parse and reserialize JSON before hashing. Clients such as fetch that decode compression hash the decoded bytes.
| Signed binding | Compare with |
|---|---|
request.method, request.target | The sent HTTP method and path, including the query string when present |
request.content_type, request.body_sha256 | The sent content type and hash of the exact request body |
response.status, response.content_type, response.body_sha256 | The received HTTP status, content type, and hash of the exact response body |
request_id | The x-request-id response header |
action_id, action | data.action_id and data.action |
decision | The decision derived from the response below |
Derive the decision independently and require the signed decision to match:
| Decision | Response | Allowed wallet operation |
|---|---|---|
signature_required | data.status === "signature_required" | Request user-approved typed-data signatures, not call execution. |
approved | data.status === "prepared" and data.simulation.status === "success" | Send calls only after the response, chain, expiry, and consent checks. |
rejected | Any other result | Do not send calls. |
Stop on a missing proof, failed signature verification, expired proof, or mismatched binding. A valid signature alone does not mean the action was approved. The proof does not prevent the same unchanged response from being presented again before it expires.
Verification samples
Keep the API key server-side. Browser apps should call through their own backend, leaving signing and sending to the user's wallet.
The TypeScript sample uses jose and reads MORPHO_API_KEY from the environment. Its postAction verifies the exchange; runAction also checks chain and expiry and handles signature continuations. Its abstract wallet adapter does not implement capability detection, sequential sending, receipt tracking, or retries: implement the sending rules above in that adapter. Inspect the simulated changes, match the sending account, and obtain user consent in your integration before wallet operations.
The Python, Java, and Go helpers below are the published verification helpers without changes. They accept raw request and response metadata and bytes plus JWKS bytes; they do not send requests or wallet calls. Use PyJWT with cryptography for Python, Nimbus JOSE JWT for Java, and github.com/go-jose/go-jose/v4 for Go.
For those helpers, this shell example captures the raw exchange using an environment variable. Save the JSON request body as request.json first. Pass the printed HTTP status, response headers, exact file bytes, POST, the path below, and application/json to the helper. Treat non-success HTTP responses as errors; gateway errors may not be JSON.
export MORPHO_API_KEY='your-issued-key'
ORIGIN=https://private.api.morpho.org
PATHNAME=/v0/actions/vaults-v2/8453:0x050cE30b927Da55177A4914EC73480238BAD56f0/deposit
curl --silent --show-error --request POST "$ORIGIN$PATHNAME" \
--header "x-api-key: ${MORPHO_API_KEY:?Set MORPHO_API_KEY}" \
--header 'Content-Type: application/json' \
--data-binary @request.json --dump-header response.headers \
--output response.json --write-out '%{http_code}\n'
curl --fail --silent --show-error \
"$ORIGIN/.well-known/morpho-actions-jwks.json" --output jwks.jsonimport { base64url, createRemoteJWKSet, jwtVerify } from "jose";
const API_ORIGIN = "https://private.api.morpho.org";
// Current Morpho-issued usage-plan keys are not origin-restricted: keep them server-side.
// Browser apps should call through their own backend.
const API_KEY = process.env.MORPHO_API_KEY!;
// The environment's canonical issuer, not the host you call.
const PROOF_ISSUER = "https://api.morpho.org/v0/actions";
// Stop instead of signing forever if responses keep asking for signatures.
const MAX_SIGNATURE_ROUNDS = 3;
// The API finalizes a signature-required action only with more than 60 seconds left.
const MIN_SIGNING_SECONDS = 60;
const jwks = createRemoteJWKSet(
new URL("/.well-known/morpho-actions-jwks.json", API_ORIGIN),
{ cacheMaxAge: 60_000 },
);
const sha256 = async (bytes: Uint8Array<ArrayBuffer>) =>
base64url.encode(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)));
interface ProofBinding {
method?: string;
target?: string;
status?: number;
content_type?: string;
body_sha256?: string;
}
export interface ActionCall {
to: `0x${string}`;
data: `0x${string}`;
value: string;
}
export interface ActionWallet {
// Must show the EIP-712 typed data to the user and sign only after they approve it.
signTypedData: (typedData: any) => Promise<string>;
sendCalls: (chainId: number, calls: ActionCall[]) => Promise<unknown>;
}
// Returns the response data only when its Morpho-Action-Proof covers this exact exchange.
export const postAction = async (path: string, payload: unknown) => {
const url = new URL(path, API_ORIGIN);
if (url.origin !== API_ORIGIN || !url.pathname.startsWith("/v0/actions/")) {
throw new Error("Not a Morpho action endpoint");
}
const contentType = "application/json";
const requestBody = new TextEncoder().encode(JSON.stringify(payload));
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": contentType, "x-api-key": API_KEY },
body: requestBody,
redirect: "error",
});
const responseBody = new Uint8Array(await response.arrayBuffer());
const responseText = new TextDecoder().decode(responseBody);
if (!response.ok) {
// Gateway errors such as 429 or 502 may not use the JSON error envelope.
const isJson = response.headers.get("Content-Type")?.startsWith("application/json");
throw new Error(
(isJson && JSON.parse(responseText).error?.message) ||
`Morpho action request failed with HTTP ${response.status}`,
);
}
const json = JSON.parse(responseText);
const proof = response.headers.get("Morpho-Action-Proof");
if (!proof) throw new Error("Missing Morpho-Action-Proof header");
const { payload: claims } = await jwtVerify(proof, async (header, token) => {
if (typeof header.kid !== "string" || !header.kid) {
throw new Error("Missing proof key ID");
}
if (!jwks.fresh) await jwks.reload();
const matchingKeys = () => jwks.jwks()!.keys.filter((key) => key.kid === header.kid);
if (matchingKeys().length === 0 && !jwks.coolingDown) await jwks.reload();
if (matchingKeys().length !== 1) {
throw new Error("Proof key ID must identify exactly one key");
}
return jwks(header, token);
}, {
algorithms: ["ES256"],
typ: "morpho-action-proof+jwt",
issuer: PROOF_ISSUER,
audience: "morpho-actions-client",
subject: "action-response",
requiredClaims: ["exp"],
maxTokenAge: 60,
clockTolerance: 5,
});
if (
!Number.isSafeInteger(claims.iat) ||
!Number.isSafeInteger(claims.exp) ||
claims.exp! <= claims.iat! ||
claims.exp! - claims.iat! > 300
) {
throw new Error("Invalid proof lifetime");
}
const { data } = json;
const decision =
data.status === "signature_required"
? "signature_required"
: data.status === "prepared" && data.simulation.status === "success"
? "approved"
: "rejected";
const request = (claims.request ?? {}) as ProofBinding;
const signed = (claims.response ?? {}) as ProofBinding;
const checks: [unknown, unknown][] = [
[claims.request_id, response.headers.get("X-Request-Id")],
[claims.action_id, data.action_id],
[claims.action, data.action],
[claims.decision, decision],
[request.method, "POST"],
[request.target, url.pathname],
[request.content_type, contentType],
[request.body_sha256, await sha256(requestBody)],
[signed.status, response.status],
[signed.content_type, response.headers.get("Content-Type")],
[signed.body_sha256, await sha256(responseBody)],
];
if (checks.some(([claimed, actual]) => claimed !== actual)) {
throw new Error("Morpho-Action-Proof does not match this response");
}
return { data, decision };
};
// Runs an action on chainId: verifies every response before the wallet signs
// or sends anything, and sends the calls only for an approved proof.
export const runAction = async (
wallet: ActionWallet,
{ chainId, path, body }: { chainId: number; path: string; body: unknown },
) => {
const checkChain = (data: any) => {
const chains = [data.chain_id, ...(data.signatures ?? []).map(
({ typed_data }: any) => Number(typed_data.domain.chainId),
)];
if (chains.some((id) => id !== chainId)) {
throw new Error(`Action is not on chain ${chainId}`);
}
// Rejects a stale action; it does not control when a transaction is included.
if (Date.now() / 1000 >= data.expires_at) {
throw new Error("Action expired, request it again");
}
};
let { data, decision } = await postAction(path, body);
for (let round = 1; decision === "signature_required"; round++) {
if (round > MAX_SIGNATURE_ROUNDS) throw new Error("Too many signature rounds");
checkChain(data);
const signatures = [];
for (const { id, typed_data } of data.signatures) {
if (data.expires_at - Date.now() / 1000 <= MIN_SIGNING_SECONDS) {
throw new Error("Action expires too soon to sign, request it again");
}
signatures.push({ id, signature: await wallet.signTypedData(typed_data) });
}
({ data, decision } = await postAction(path, {
continuation: data.continuation,
signatures,
}));
}
if (decision !== "approved") {
throw new Error(data.simulation?.failure?.message ?? "Action was not approved");
}
checkChain(data);
return wallet.sendCalls(chainId, data.calls);
};import base64
import hashlib
import json
import re
import time
from typing import Any
import jwt
ALGORITHM = "ES256"
PROOF_TYPE = "morpho-action-proof+jwt"
ISSUER = "https://api.morpho.org/v0/actions"
AUDIENCE = "morpho-actions-client"
SUBJECT = "action-response"
MAX_TOKEN_AGE_SECONDS = 60
CLOCK_TOLERANCE_SECONDS = 5
def _reject(reason: str) -> None:
raise ValueError(f"Invalid action proof: {reason}")
def _header(headers: dict[str, str], name: str) -> str | None:
return next(
(value for key, value in headers.items() if key.lower() == name),
None,
)
def _public_key(jwks: Any, kid: str) -> dict[str, Any]:
if not isinstance(jwks, dict) or not isinstance(jwks.get("keys"), list):
_reject("JWKS has no keys array")
keys = [key for key in jwks["keys"] if isinstance(key, dict) and key.get("kid") == kid]
if len(keys) != 1:
_reject("key ID must identify exactly one key")
for key in keys:
if not isinstance(key, dict) or key.get("kid") != kid:
continue
allowed = {"kty", "crv", "x", "y", "alg", "kid", "key_ops", "use"}
if (
set(key) - allowed
or key.get("kty") != "EC"
or key.get("crv") != "P-256"
or ("alg" in key and key["alg"] != ALGORITHM)
or ("use" in key and key["use"] != "sig")
or ("key_ops" in key and key["key_ops"] != ["verify"])
or not isinstance(key.get("x"), str)
or not isinstance(key.get("y"), str)
):
_reject("JWK is not a public ES256 verification key")
for coordinate in (key["x"], key["y"]):
if not re.fullmatch(r"[A-Za-z0-9_-]{43}", coordinate):
_reject("JWK coordinate is not canonical base64url")
try:
decoded = base64.urlsafe_b64decode(coordinate + "=")
except Exception as error:
raise ValueError("JWK coordinate is not base64url") from error
if (
len(decoded) != 32
or base64.urlsafe_b64encode(decoded).decode("ascii").rstrip("=")
!= coordinate
):
_reject("JWK coordinate is not a P-256 coordinate")
return key
_reject("verification key is unknown")
def verify_action_proof(
method: str,
path: str,
content_type: str,
request_body: bytes,
status: int,
headers: dict[str, str],
response_body: bytes,
jwks_json: bytes,
now: int | None = None,
*,
issuer: str = ISSUER,
) -> dict[str, Any]:
if now is None:
now = int(time.time())
jwks = json.loads(jwks_json)
if not path.startswith("/v0/actions/") or method != "POST":
_reject("request is outside the Actions API")
proof = _header(headers, "morpho-action-proof")
if not proof:
_reject("proof header is missing")
parts = proof.split(".")
if len(parts) != 3:
_reject("proof is not a compact JWS")
try:
protected = json.loads(base64.urlsafe_b64decode(parts[0] + "=="))
except Exception as error:
raise ValueError("protected header is invalid") from error
if (
not isinstance(protected, dict)
or protected["alg"] != ALGORITHM
or protected["typ"] != PROOF_TYPE
or not isinstance(protected["kid"], str)
):
_reject("protected header is not the required ES256 proof header")
key = _public_key(jwks, protected["kid"])
try:
body = json.loads(response_body)
except Exception as error:
raise ValueError("response body is invalid JSON") from error
if not isinstance(body, dict) or not isinstance(body.get("data"), dict):
_reject("response body does not contain data")
try:
claims = jwt.decode(
proof,
jwt.algorithms.ECAlgorithm.from_jwk(json.dumps(key)),
algorithms=[ALGORITHM],
issuer=issuer,
audience=AUDIENCE,
options={
"require": ["iss", "aud", "sub", "iat", "exp"],
"verify_exp": False,
"verify_iat": False,
},
)
except Exception as error:
raise ValueError("signature or registered claims are invalid") from error
if claims.get("sub") != SUBJECT:
_reject("subject is invalid")
issued_at, expires_at = claims.get("iat"), claims.get("exp")
if (
type(issued_at) not in (int, float)
or type(expires_at) not in (int, float)
or not -9007199254740991 <= issued_at <= 9007199254740991
or not -9007199254740991 <= expires_at <= 9007199254740991
or issued_at != int(issued_at)
or expires_at != int(expires_at)
or not 0 < expires_at - issued_at <= 300
or issued_at - CLOCK_TOLERANCE_SECONDS > now
or now - issued_at > MAX_TOKEN_AGE_SECONDS + CLOCK_TOLERANCE_SECONDS
or expires_at <= now - CLOCK_TOLERANCE_SECONDS
):
_reject("proof is outside its age window")
data = body["data"]
simulation = data.get("simulation")
decision = (
"signature_required"
if data.get("status") == "signature_required"
else "approved"
if data.get("status") == "prepared"
and isinstance(simulation, dict)
and simulation.get("status") == "success"
else "rejected"
)
request_claims = claims.get("request")
response_claims = claims.get("response")
request_id = _header(headers, "x-request-id")
response_content_type = _header(headers, "content-type")
if (
request_id is None
or claims.get("request_id") != request_id
or claims.get("action_id") != data.get("action_id")
or claims.get("action") != data.get("action")
or claims.get("decision") != decision
or not isinstance(request_claims, dict)
or request_claims.get("method") != method
or request_claims.get("target") != path
or request_claims.get("content_type") != content_type
or request_claims.get("body_sha256")
!= base64.urlsafe_b64encode(hashlib.sha256(request_body).digest())
.decode("ascii")
.rstrip("=")
or not isinstance(response_claims, dict)
or response_claims.get("status") != status
or response_claims.get("content_type") != response_content_type
or response_claims.get("body_sha256")
!= base64.urlsafe_b64encode(hashlib.sha256(response_body).digest())
.decode("ascii")
.rstrip("=")
):
_reject("proof does not bind this request and response")
return {
"decision": decision,
"execute_calls": (
decision == "approved"
and data.get("status") == "prepared"
and isinstance(simulation, dict)
and simulation.get("status") == "success"
),
"data": data,
}import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.crypto.ECDSAVerifier;
import com.nimbusds.jose.jwk.ECKey;
import com.nimbusds.jose.util.JSONObjectUtils;
import com.nimbusds.jwt.JWTClaimsSet;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Map;
import java.util.Set;
public final class ActionProof {
private static final String PROOF_TYPE = "morpho-action-proof+jwt";
private static final String ISSUER = "https://api.morpho.org/v0/actions";
private static final String AUDIENCE = "morpho-actions-client";
private static final String SUBJECT = "action-response";
private static final Set<String> JWK_FIELDS =
Set.of("kty", "crv", "x", "y", "alg", "kid", "key_ops", "use");
public static Map<String, Object> verify(
String method, String path, String contentType, byte[] requestBody,
int status, Map<String, String> headers, byte[] responseBody,
byte[] jwksJson, String expectedIssuer, Long nowSeconds) throws Exception {
if (expectedIssuer == null) expectedIssuer = ISSUER;
long now = nowSeconds == null ? java.time.Instant.now().getEpochSecond() : nowSeconds;
Map<String, Object> jwks = JSONObjectUtils.parse(new String(jwksJson, StandardCharsets.UTF_8));
if (!path.startsWith("/v0/actions/") || !"POST".equals(method)) {
throw new IllegalArgumentException("request is outside the Actions API");
}
String proof = header(headers, "morpho-action-proof");
if (proof == null) throw new IllegalArgumentException("proof header is missing");
String[] parts = proof.split("\\.", -1);
if (parts.length != 3) throw new IllegalArgumentException("proof is not compact JWS");
Map<String, Object> protectedHeader =
JSONObjectUtils.parse(new String(Base64.getUrlDecoder().decode(parts[0]), StandardCharsets.UTF_8));
if (!"ES256".equals(protectedHeader.get("alg"))
|| !PROOF_TYPE.equals(protectedHeader.get("typ"))
|| !(protectedHeader.get("kid") instanceof String)) {
throw new IllegalArgumentException("invalid protected header");
}
String kid = (String) protectedHeader.get("kid");
Map<String, Object> jwk = findKey(jwks, kid);
ECKey publicJwk = ECKey.parse(jwk);
if (!publicJwk.getCurve().equals(com.nimbusds.jose.jwk.Curve.P_256)
|| publicJwk.isPrivate()) {
throw new IllegalArgumentException("JWK is not a public P-256 key");
}
JWSObject jws = JWSObject.parse(proof);
if (!JWSAlgorithm.ES256.equals(jws.getHeader().getAlgorithm())
|| !kid.equals(jws.getHeader().getKeyID())
|| !PROOF_TYPE.equals(jws.getHeader().getType().toString())
|| !jws.verify(new ECDSAVerifier(publicJwk.toECPublicKey()))) {
throw new IllegalArgumentException("signature or proof header is invalid");
}
Map<String, Object> rawClaims = JSONObjectUtils.parse(
new String(jws.getPayload().toBytes(), StandardCharsets.UTF_8));
long issuedAtSeconds = timestamp(rawClaims.get("iat"));
long expiresAtSeconds = timestamp(rawClaims.get("exp"));
if (expiresAtSeconds <= issuedAtSeconds || expiresAtSeconds - issuedAtSeconds > 300) {
throw new IllegalArgumentException("invalid token lifetime");
}
JWTClaimsSet claims = JWTClaimsSet.parse(rawClaims);
if (!expectedIssuer.equals(claims.getIssuer())
|| !claims.getAudience().contains(AUDIENCE)
|| !SUBJECT.equals(claims.getSubject())) {
throw new IllegalArgumentException("registered claims are invalid");
}
if (issuedAtSeconds - 5 > now
|| now - issuedAtSeconds > 65
|| expiresAtSeconds <= now - 5) {
throw new IllegalArgumentException("proof is outside its age window");
}
Map<String, Object> body =
JSONObjectUtils.parse(new String(responseBody, StandardCharsets.UTF_8));
Map<String, Object> data = map(body.get("data"));
Object simulation = data.get("simulation");
String simulationStatus =
simulation instanceof Map<?, ?> ? (String) map(simulation).get("status") : null;
String decision =
"signature_required".equals(data.get("status"))
? "signature_required"
: "prepared".equals(data.get("status")) && "success".equals(simulationStatus)
? "approved"
: "rejected";
Map<String, Object> requestClaims = map(claims.getClaim("request"));
Map<String, Object> responseClaims = map(claims.getClaim("response"));
String requestId = header(headers, "x-request-id");
String responseContentType = header(headers, "content-type");
if (requestId == null
|| !requestId.equals(claims.getClaim("request_id"))
|| !data.get("action_id").equals(claims.getClaim("action_id"))
|| !data.get("action").equals(claims.getClaim("action"))
|| !decision.equals(claims.getClaim("decision"))
|| !method.equals(requestClaims.get("method"))
|| !path.equals(requestClaims.get("target"))
|| !contentType.equals(requestClaims.get("content_type"))
|| !hash(requestBody).equals(requestClaims.get("body_sha256"))
|| status
!= ((Number) responseClaims.get("status")).intValue()
|| !responseContentType.equals(responseClaims.get("content_type"))
|| !hash(responseBody).equals(responseClaims.get("body_sha256"))) {
throw new IllegalArgumentException("proof does not bind this request and response");
}
boolean executeCalls =
"approved".equals(decision)
&& "prepared".equals(data.get("status"))
&& "success".equals(simulationStatus);
return Map.of("data", data, "decision", decision, "execute_calls", executeCalls);
}
private static Map<String, Object> findKey(Map<String, Object> jwks, String kid) {
var keys = (java.util.List<Map<String, Object>>) jwks.get("keys");
if (keys.stream().filter(key -> kid.equals(key.get("kid"))).count() != 1) {
throw new IllegalArgumentException("key ID must identify exactly one key");
}
for (Map<String, Object> key : keys) {
if (!kid.equals(key.get("kid"))) continue;
if (!JWK_FIELDS.containsAll(key.keySet())
|| !"EC".equals(key.get("kty"))
|| !"P-256".equals(key.get("crv"))
|| (key.containsKey("alg") && !"ES256".equals(key.get("alg")))
|| (key.containsKey("use") && !"sig".equals(key.get("use")))
|| (key.containsKey("key_ops")
&& !java.util.List.of("verify").equals(key.get("key_ops")))
|| !key.containsKey("x")
|| !key.containsKey("y")) {
throw new IllegalArgumentException("JWK is not a public ES256 verification key");
}
return key;
}
throw new IllegalArgumentException("verification key is unknown");
}
private static long timestamp(Object value) {
if (!(value instanceof Number number)
|| !Double.isFinite(number.doubleValue())
|| Math.abs(number.doubleValue()) > 9007199254740991L
|| Math.rint(number.doubleValue()) != number.doubleValue()) {
throw new IllegalArgumentException("invalid timestamp");
}
return number.longValue();
}
private static String hash(byte[] value) throws Exception {
return Base64.getUrlEncoder()
.withoutPadding()
.encodeToString(MessageDigest.getInstance("SHA-256").digest(value));
}
private static String header(Map<String, String> headers, String name) {
return headers.entrySet().stream()
.filter(entry -> entry.getKey().equalsIgnoreCase(name))
.map(Map.Entry::getValue)
.findFirst()
.orElse(null);
}
private static Map<String, Object> map(Object value) {
return (Map<String, Object>) value;
}
}package actionproof
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"math"
"strings"
"time"
jose "github.com/go-jose/go-jose/v4"
)
const (
proofType = "morpho-action-proof+jwt"
issuer = "https://api.morpho.org/v0/actions"
audience = "morpho-actions-client"
subject = "action-response"
)
type Result struct {
Data map[string]any
Decision string
ExecuteCalls bool
}
// Verify returns data only after verification. Empty issuer and zero now use production defaults.
func Verify(method, path, contentType string, requestBody []byte, status int,
headers map[string]string, responseBody, jwksBytes []byte, expectedIssuer string, now time.Time,
) (Result, error) {
if expectedIssuer == "" {
expectedIssuer = issuer
}
if now.IsZero() {
now = time.Now()
}
if !strings.HasPrefix(path, "/v0/actions/") || method != "POST" {
return Result{}, errors.New("request is outside the Actions API")
}
proof := header(headers, "morpho-action-proof")
if proof == "" {
return Result{}, errors.New("missing action proof")
}
parts := strings.Split(proof, ".")
if len(parts) != 3 {
return Result{}, errors.New("proof is not compact JWS")
}
protectedBytes, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return Result{}, err
}
var protected map[string]any
if err := json.Unmarshal(protectedBytes, &protected); err != nil {
return Result{}, err
}
if protected["alg"] != "ES256" || protected["typ"] != proofType {
return Result{}, errors.New("invalid protected header")
}
kid, ok := protected["kid"].(string)
if !ok {
return Result{}, errors.New("missing key ID")
}
key, err := publicKey(jwksBytes, kid)
if err != nil {
return Result{}, err
}
token, err := jose.ParseSigned(proof, []jose.SignatureAlgorithm{jose.ES256})
if err != nil {
return Result{}, err
}
if len(token.Signatures) != 1 ||
token.Signatures[0].Protected.Algorithm != "ES256" ||
token.Signatures[0].Protected.ExtraHeaders[jose.HeaderType] != proofType ||
token.Signatures[0].Protected.KeyID != kid {
return Result{}, errors.New("invalid proof header")
}
payloadBytes, err := token.Verify(key.Key)
if err != nil {
return Result{}, err
}
var claims map[string]any
if err := json.Unmarshal(payloadBytes, &claims); err != nil {
return Result{}, err
}
if claims["iss"] != expectedIssuer || claims["sub"] != subject || !hasAudience(claims["aud"], audience) {
return Result{}, errors.New("invalid registered claims")
}
iatValue, iatOK := claims["iat"].(float64)
expValue, expOK := claims["exp"].(float64)
if !iatOK || !expOK || math.Abs(iatValue) > 9007199254740991 || math.Abs(expValue) > 9007199254740991 ||
math.Trunc(iatValue) != iatValue || math.Trunc(expValue) != expValue ||
expValue <= iatValue || expValue-iatValue > 300 {
return Result{}, errors.New("invalid token lifetime")
}
iat, exp := int64(iatValue), int64(expValue)
age := now.Unix() - iat
if iat-5 > now.Unix() || age > 65 || exp <= now.Unix()-5 {
return Result{}, errors.New("proof is outside its age window")
}
var body map[string]any
if err := json.Unmarshal(responseBody, &body); err != nil {
return Result{}, err
}
data, ok := body["data"].(map[string]any)
if !ok {
return Result{}, errors.New("response has no data object")
}
simulation, _ := data["simulation"].(map[string]any)
decision := "rejected"
if data["status"] == "signature_required" {
decision = "signature_required"
} else if data["status"] == "prepared" && simulation["status"] == "success" {
decision = "approved"
}
requestClaims, _ := claims["request"].(map[string]any)
responseClaims, _ := claims["response"].(map[string]any)
requestID := header(headers, "x-request-id")
responseContentType := header(headers, "content-type")
if requestID == "" ||
claims["request_id"] != requestID ||
claims["action_id"] != data["action_id"] ||
claims["action"] != data["action"] ||
claims["decision"] != decision ||
requestClaims["method"] != method ||
requestClaims["target"] != path ||
requestClaims["content_type"] != contentType ||
requestClaims["body_sha256"] != hash(requestBody) ||
number(responseClaims["status"]) != float64(status) ||
responseClaims["content_type"] != responseContentType ||
responseClaims["body_sha256"] != hash(responseBody) {
return Result{}, errors.New("proof does not bind this request and response")
}
return Result{
Data: data,
Decision: decision,
ExecuteCalls: decision == "approved" &&
data["status"] == "prepared" &&
simulation["status"] == "success",
}, nil
}
func publicKey(jwksBytes []byte, kid string) (jose.JSONWebKey, error) {
var set struct {
Keys []map[string]any `json:"keys"`
}
if err := json.Unmarshal(jwksBytes, &set); err != nil {
return jose.JSONWebKey{}, err
}
allowed := map[string]bool{
"kty": true, "crv": true, "x": true, "y": true, "alg": true,
"kid": true, "key_ops": true, "use": true,
}
matching := 0
for _, raw := range set.Keys {
if raw["kid"] == kid {
matching++
}
}
if matching != 1 {
return jose.JSONWebKey{}, errors.New("key ID must identify exactly one key")
}
for _, raw := range set.Keys {
if raw["kid"] != kid {
continue
}
for name := range raw {
if !allowed[name] {
return jose.JSONWebKey{}, errors.New("JWK has an unsupported member")
}
}
opsValue, hasOps := raw["key_ops"]
ops, opsAreArray := opsValue.([]any)
if raw["kty"] != "EC" || raw["crv"] != "P-256" ||
(hasAlg(raw) && raw["alg"] != "ES256") ||
(hasUse(raw) && raw["use"] != "sig") ||
(hasOps && (!opsAreArray || len(ops) != 1 || ops[0] != "verify")) {
return jose.JSONWebKey{}, errors.New("JWK is not a public ES256 verification key")
}
encoded, _ := json.Marshal(raw)
var key jose.JSONWebKey
if err := json.Unmarshal(encoded, &key); err != nil {
return jose.JSONWebKey{}, err
}
public, ok := key.Key.(*ecdsa.PublicKey)
if !ok || public.Curve != elliptic.P256() {
return jose.JSONWebKey{}, errors.New("JWK is not an EC P-256 public key")
}
return key, nil
}
return jose.JSONWebKey{}, fmt.Errorf("unknown key ID %q", kid)
}
func hasAlg(key map[string]any) bool {
_, ok := key["alg"]
return ok
}
func hasUse(key map[string]any) bool {
_, ok := key["use"]
return ok
}
func hash(value []byte) string {
digest := sha256.Sum256(value)
return base64.RawURLEncoding.EncodeToString(digest[:])
}
func header(values map[string]string, name string) string {
for key, value := range values {
if strings.EqualFold(key, name) {
return value
}
}
return ""
}
func number(value any) float64 {
switch value := value.(type) {
case float64:
return value
case int:
return float64(value)
default:
return 0
}
}
func hasAudience(value any, expected string) bool {
switch value := value.(type) {
case string:
return value == expected
case []any:
for _, item := range value {
if item == expected {
return true
}
}
}
return false
}GETGet curator details
Resolve curator details using the selector <chain_id>:<curator_address>, where the address is the vault's on-chain curator role.
POSTBuild Midnight repayment calls
Builds calls that repay Midnight debt in one of two ways selected by type. direct repays exact loan assets at face value now, or the complete debt with…