import { OwnerAmountActionAuthorization } from "../interfaces"; import { type BorrowerAuthorizationPrimaryType } from "../constants/borrower-authorization-types"; /** * Trust anchors + candidate identity for the Safe-agent withdrawal arm * (2026-08-05 safe-withdrawal-delegation hardening; source design plan * §3.2/§3.3, execution plan step 4/step 5). * * `module` is the candidate `AgentModule` address the recovered signer * claims to be bound to — an unverified claim, exactly like `recovered` * itself; the four conditions in `checkSafeAgentWithdrawAuthorization` test * it, so it is safe for a caller to supply. * * `factory` and `registry` are DIFFERENT: they are trust anchors and MUST be * resolved by the caller through `resolveSecurityCriticalAddresses` / * `resolveAgentPathAddresses` (`modules/pinned-addresses.ts`) on enforced * chains, never taken directly from `jsParams` (source plan §3.3 — "the * conditions above are worthless if the addresses they are evaluated * against arrive in jsParams"). Either being `undefined` (a chain with no * pin, e.g. mainnet has no AgentModuleFactory yet — decision D-1) is the * DEFAULT, fail-closed state: `checkSafeAgentWithdrawAuthorization` refuses * without attempting any chain read, never falling through to a * caller-supplied value. */ export interface SafeAgentWithdrawPath { /** Candidate AgentModule address the recovered signer claims to be bound to. */ module: string; /** Pinned AgentModuleFactory address for this chain, or undefined if unpinned. */ factory?: string; /** Pinned AgentDelegationRegistry address for this chain, or undefined if unpinned. */ registry?: string; /** Populated on success so the caller can enforce the floor against the withdrawal amount. */ outcome?: { effectiveFloorBps: number; }; } /** * The EIP-712 encoding of a borrower authorization, built by a verifier's * closure alongside the legacy packed hash (EIP-712 borrower-authorization * cutover, phase 2 — dual-accept). * * `domain`/`types`/`message` are the exact arguments the SDK hands to * `signer.signTypedData(...)`; the verifier rebuilds them from the SAME wire * fields the legacy preimage already binds, so the two digests are two * encodings of one authorization — never two authorizations. That identity is * what makes try-both (no caller-controlled scheme selector) safe. */ export interface TypedAuthorizationMessage { domain: { name: string; version: string; chainId: number; verifyingContract: string; }; types: Record>; primaryType: BorrowerAuthorizationPrimaryType; message: Record; } /** * What a verifier's `buildMessage` closure returns. * * A bare string is the legacy packed hash alone — the pre-cutover contract, * still used verbatim by the BTCSpendAuthorizer-domain verifiers * (`verifyRecoveryAuthorization`, `verifyBtcExecutionAuthorization`), which * are out of the EIP-712 scope. The object form adds the typed encoding. */ export type BuiltAuthorizationMessage = string | { legacy: string; typed?: TypedAuthorizationMessage; }; /** * Opt-in request for the typed-data arm, passed by the four loan verifiers. * * `verifyingContract` is the resolved LoanOperationsManagerModule address the * validator already holds (via `resolveSecurityCriticalAddresses`). On pinned * chains `buildBorrowerAuthorizationDomain` CHECKS it against the pin and * throws on contradiction; on unpinned chains (hardhat) it supplies the * domain. Omitting the field on an unpinned chain makes domain construction * throw — fail fast, never a silent legacy-only downgrade. */ export interface TypedArmRequest { primaryType: BorrowerAuthorizationPrimaryType; verifyingContract?: string; } /** * Authorization Module * * Validates that LIT Action callers are authorized to perform operations. * * RESTORED PRODUCTION-GRADE DESIGN (from b2794c9): * - Quantum timestamp prevents replay across different quantums * - Waits for safe quantum moment before validation * - Validates timestamp is within current quantum window * - Signature proves caller identity * - Contract verification proves ownership * * Authorization Flow: * 1. Wait for safe quantum moment (if in dead zone) * 2. Verify timestamp is within valid quantum window * 3. Build message hash from parameters (positionId, timestamp, chainId, amount, action) * 4. Recover signer address from signature (EIP-191 standard) * 5. Verify recovered signer === position owner (from contract) * * Security Properties: * - Quantum timing enforces 100-second windows with dead zone protection * - Smart contract only accepts one operation per quantum per position * - Signature proves caller owns the signing address * - Contract verification proves signer is position owner * - chainId prevents cross-chain replay attacks * - Mode controls whether dev environments (hardhat/regtest) are allowed * * Example: mintUCD * - Message: keccak256(positionId, timestamp, chainId, amount, actionHash) * - User signs with wallet (EIP-191) * - LIT Action WAITS for safe quantum moment * - LIT Action VALIDATES quantum timestamp * - LIT Action recovers signer address * - LIT Action verifies signer is position owner (via contract) */ /** * Authorization Module * * Provides methods to verify caller authorization for LIT Actions */ export declare class AuthorizationModule { /** * Verify auth structure for amount/position/action operations. * * Validates that all required fields are present and have correct types: * - positionId (string, required) * - chainId (number, required) * - timestamp (number, required) * - amount (required, any type that can convert to bigint) * - action (string, required) * - signature (string, required) * * NOTE: the legacy `mode` field was removed (audit C-1). Security policy * is derived from `chain` via `modules/chain-policy.ts`; the field is no * longer read, and callers can stop sending it. * * @param auth - Authorization object to validate (untyped) * @returns Typed OwnerAmountActionAuthorization object after validation * @throws Error if any validation fails */ static verifyAmountPositionActionAuthorizationStructure(auth: any): OwnerAmountActionAuthorization; /** * Recover signer address from signature * * Uses EIP-191 standard (Ethereum Signed Message) * * @param messageHash - Keccak256 hash of the message * @param signature - Signature to verify * @returns Recovered signer address */ static recoverSigner(messageHash: string, signature: string): Promise; /** * Agnostic authorization verification * * Verifies authorization for any action by: * 1. Waiting for safe quantum moment * 2. Validating quantum timestamp * 3. Building message hash using provided buildMessage function * 4. Recovering signer from signature * 5. Checking authorization using provided isAuthorized function * * @param auth - Authorization parameters (timestamp, signature, mode) * @param buildMessage - Function to build message hash (caller has context/closure) * @param isAuthorized - Function to check if recovered address is authorized (caller has context/closure) * @returns True if authorized */ /** * Verify an EIP-1271 signature from a smart contract wallet * * Calls `isValidSignature(bytes32,bytes)` on the contract and checks for the magic value. * Returns false if the call fails (e.g. the address is not a contract or doesn't implement EIP-1271). * * @param contractAddress - The smart contract wallet address (e.g. Safe) * @param messageHash - The raw message hash (NOT EIP-191 prefixed) * @param signature - The packed signature bytes * @param provider - Ethers provider for the target chain */ static checkEIP1271(contractAddress: string, messageHash: string, signature: string, provider: any): Promise; /** * Verify the recovered signer matches the borrower-registered delegate for a * position. * * Reads `positionDelegate(positionId)` on the supplied PositionDelegateRegistry * contract and returns true when the stored delegate is non-zero and matches * `recovered` (case-insensitive). Used as the third recovery arm after the * EOA `position.borrower` check and the EIP-1271 smart-account fallback — * lets a Safe-as-borrower register an agent EOA without making it a Safe * owner. Returns false on any RPC error or if no delegate is registered. */ static checkPositionDelegate(positionId: string, recovered: string, registryAddress: string, provider: any): Promise; /** * Scoped agent-delegation check against `AgentDelegationRegistry` (Phase B). * * Replaces the all-or-nothing `checkPositionDelegate` arm for the LOAN * validators (extend / payment / mint): the registry's `canRenew` / * `canRepay` / `canMint` gates bind the recovered signer to the borrower's * registered agent AND to the specific operation's grant (scope bit, TTL, * caps, pause). `canMint` additionally returns the EFFECTIVE post-mint * collateral-ratio floor (grant floor clamped by the governance minimum), * which the mint validator must enforce before signing. * * Fail-closed: any RPC error, absent registry, or deny reason returns * `{ ok: false }` — mirroring `checkPositionDelegate`'s error posture. */ static checkAgentDelegationGrant(positionId: string, recovered: string, op: "renew" | "repay" | "mint", registryAddress: string, provider: any): Promise<{ ok: boolean; effectiveFloorBps: number; }>; /** * The Safe-agent withdrawal discriminator (2026-08-05 hardening; source * design plan §3.2, execution plan step 4). Answers "has THIS Safe's * owner-set consented to THIS module, and is the recovered signer the * agent that module admits?" — not "is this a well-formed Safe delegation" * (every predicate below is public on-chain data on its own; see E-5). * * Four conditions, evaluated IN THIS ORDER, ALL required: * 1. `ISafe(owner).isModuleEnabled(module)` — the wallet's own switch. * The ONLY condition that carries owner consent: enabling a module on * a Safe requires a k-of-n `execTransaction`, so it is the one thing * an attacker cannot manufacture. Evaluated FIRST and independently — * conditions 2 and 3 are FREE to forge in isolation (E-5: * `AgentModuleFactory.deploy` is permissionless and performs no code * check on `safe`; anyone can mint a factory-vouched module whose * `safe()` is any address, including an ordinary EOA). * 2. `factory.isFromFactory(module) && module.safe() == owner` — * anti-phishing provenance: the module's protocol targets are * factory immutables, so an enabled-but-hostile look-alike cannot * redirect calls. * 3. `module.agent() == recovered` — the module names its own agent; * the signer must be it. * 4. `registry.canWithdraw(positionId, agent)` — the registry reports * the WITHDRAW permission active for this position and this agent. * Three returns `(bool ok, uint8 reason, uint32 effectiveFloorBps)` — * NOT the two-return `canWithdraw` fragment in * `agent-module-authorization.module.ts`, which answers a different * question (on-chain `AgentModule.execute` authority) and is out of * scope for this change. * * Deliberately NOT "owner has code" as the wallet-type test — that is not * one: an EIP-7702 account keeps its private key and would pass, and it * says nothing about threshold (E-5 / source plan §0.2). * * Fail-closed, deliberately WITHOUT a swallowing try/catch (unlike * `checkPositionDelegate` / `checkAgentDelegationGrant` above): a missing * trust anchor refuses synchronously before any chain read; a genuine read * failure (revert, undecodable return, RPC error) on any of the four * checks PROPAGATES as a thrown error instead of collapsing to `false`, so * it surfaces distinguishably from an ordinary "not authorized" denial * rather than silently reading as one. */ static checkSafeAgentWithdrawAuthorization(positionId: string, recovered: string, owner: string, path: SafeAgentWithdrawPath, provider: any): Promise; static verifyActionAuthorization(auth: { timestamp: number; signature: string; }, buildMessage: () => BuiltAuthorizationMessage, isAuthorized: (recovered: string, messageHash: string, signature: string) => boolean | Promise, options?: { strictCurrentQuantum?: boolean; }): Promise; /** * Verify position owner authorization for any amount-based position action * * AGNOSTIC BASE FUNCTION - verifies authorization without checking action string * Specific action verification functions should validate action string before calling this. * * RESTORED PRODUCTION-GRADE QUANTUM VALIDATION: * - STEP 1: Waits for safe quantum moment (avoids dead zone) * - STEP 2: Validates timestamp is within current quantum window * - STEP 3: Builds message hash from parameters * - STEP 4: Recovers signer from signature * - STEP 5: Verifies signer matches position owner * * Message contains: positionId, timestamp, chainId, amount, action * NO callerAddress in message (recovered from signature via ecrecover) * * @param auth - Authorization parameters (positionId, timestamp, chainId, amount, action, signature, mode) * @param positionOwner - Position owner address from contract * @returns True if authorized */ static verifyAmountPositionActionAuthorization(auth: { positionId: string; timestamp: number; chainId: number; amount: string | bigint; action: string; signature: string; }, positionOwner: string, targetChainId: number, provider?: any, positionDelegateRegistry?: string, agentGrant?: { registry: string; op: "renew" | "repay" | "mint"; /** Filled by the delegate arm when authorization went via the agent grant. */ outcome?: { viaAgent: boolean; effectiveFloorBps: number; }; }, typedArm?: TypedArmRequest): Promise; /** * Verify position owner authorization for mintUCD action * * Validates action string is "mint-ucd" then delegates to base function. * * @param auth - Authorization parameters (positionId, timestamp, chainId, amount, action, signature, mode) * @param positionOwner - Position owner address from contract * @returns True if authorized */ static verifyMintAuthorization(auth: { positionId: string; timestamp: number; chainId: number; amount: string | bigint; action: string; signature: string; }, positionOwner: string, targetChainId: number, provider?: any, positionDelegateRegistry?: string, agentGrant?: { registry: string; op: "renew" | "repay" | "mint"; outcome?: { viaAgent: boolean; effectiveFloorBps: number; }; }, /** Resolved LOM address for the EIP-712 domain (required on unpinned chains). */ typedVerifyingContract?: string): Promise; /** * Verify position owner authorization for partial-payment action. * * Audit CRIT-5: the payment validator previously called the agnostic base * function (`verifyAmountPositionActionAuthorization`) directly, with * `auth.action` taken from the request body and never pinned. That meant a * signature collected under a different `action` string could be replayed * to the payment validator — the base function's docstring explicitly * warns "Specific action verification functions should validate action * string before calling this." This wrapper pins the action string before * delegating, matching the mint / withdraw / extend pattern. */ static verifyPaymentAuthorization(auth: { positionId: string; timestamp: number; chainId: number; amount: string | bigint; action: string; signature: string; }, positionOwner: string, targetChainId: number, provider?: any, positionDelegateRegistry?: string, agentGrant?: { registry: string; op: "renew" | "repay" | "mint"; outcome?: { viaAgent: boolean; effectiveFloorBps: number; }; }, /** Resolved LOM address for the EIP-712 domain (required on unpinned chains). */ typedVerifyingContract?: string): Promise; /** * Verify position owner authorization for withdrawBTC action * * Validates action string is "withdraw-btc" and includes destinationAddress in message. * Unlike mint/repay, withdrawal requires destination address to prevent unauthorized redirection. * * Message contains: positionId, timestamp, chainId, amount, destinationAddress, action * * @param auth - Authorization parameters (positionId, timestamp, chainId, amount, destinationAddress, action, signature, mode) * @param positionOwner - Position owner address from contract * @returns True if authorized */ static verifyWithdrawAuthorization(auth: { positionId: string; timestamp: number; chainId: number; amount: string | bigint; destinationAddress: string; action: string; signature: string; }, positionOwner: string, targetChainId: number, provider?: any, /** * Safe-agent withdrawal arm (2026-08-05 hardening). Optional and, at * every current call site, unsupplied — the arm exists and is unit * tested but is not yet wired into `btc-withdrawal.ts` (the caller must * first resolve `module`/`factory`/`registry` via * `resolveAgentPathAddresses`, which is a later wiring step). Omitting * it reproduces today's exact borrower/EIP-1271-only behaviour. */ safeAgentPath?: SafeAgentWithdrawPath, /** Resolved LOM address for the EIP-712 domain (required on unpinned chains). */ typedVerifyingContract?: string): Promise; /** * Verify position owner authorization for stale-spend recovery (audit #62210 Phase 2). * * Bound by `RECOVERY_INVALIDATE_ACTION_STRING` so a leaked withdraw / payment / mint * signature cannot be replayed here, and vice versa. The signed message includes the * UTXO identifiers so a single recovery signature is tied to exactly one (positionId, * utxoTxid, utxoVout) — pre-signing a generic recovery is not possible. * * Message: keccak256(positionId, timestamp, chainId, utxoTxid, utxoVout, actionHash) */ static verifyRecoveryAuthorization(auth: { positionId: string; timestamp: number; chainId: number; utxoTxid: string; utxoVout: number; action: string; signature: string; }, positionOwner: string, targetChainId: number, provider?: any): Promise; /** * Verify auth structure for term/position/action operations * * Validates that all required fields are present and have correct types: * - positionId (string, required) * - chainId (number, required) * - timestamp (number, required) * - newTerm (number, required) * - action (string, required) * - signature (string, required) * - mode ("dev" or "prod", required) * * @param auth - Authorization object to validate (untyped) * @returns Typed OwnerTermActionAuthorization object after validation * @throws Error if any validation fails */ static verifyTermPositionActionAuthorizationStructure(auth: any): { positionId: string; timestamp: number; chainId: number; newTerm: number; action: string; signature: string; }; /** * Verify position owner authorization for term-based position action * * AGNOSTIC BASE FUNCTION - verifies authorization without checking action string * Specific action verification functions should validate action string before calling this. * * Message contains: positionId, timestamp, chainId, newTerm, action * * @param auth - Authorization parameters (positionId, timestamp, chainId, newTerm, action, signature, mode) * @param positionOwner - Position owner address from contract * @returns True if authorized */ static verifyTermPositionActionAuthorization(auth: { positionId: string; timestamp: number; chainId: number; newTerm: number; action: string; signature: string; }, positionOwner: string, targetChainId: number, provider?: any, positionDelegateRegistry?: string, agentGrant?: { registry: string; op: "renew" | "repay" | "mint"; outcome?: { viaAgent: boolean; effectiveFloorBps: number; }; }, typedArm?: TypedArmRequest): Promise; /** * Verify position owner authorization for extendPosition action * * Validates action string is "extend-position" then delegates to base function. * * @param auth - Authorization parameters (positionId, timestamp, chainId, newTerm, action, signature, mode) * @param positionOwner - Position owner address from contract * @returns True if authorized */ static verifyExtendAuthorization(auth: { positionId: string; timestamp: number; chainId: number; newTerm: number; action: string; signature: string; }, positionOwner: string, targetChainId: number, provider?: any, positionDelegateRegistry?: string, agentGrant?: { registry: string; op: "renew" | "repay" | "mint"; outcome?: { viaAgent: boolean; effectiveFloorBps: number; }; }, /** Resolved LOM address for the EIP-712 domain (required on unpinned chains). */ typedVerifyingContract?: string): Promise; /** * Verify position owner authorization for BTC withdrawal execution * * Validates action string is "execute-btc-withdrawal" and includes UTXO identifier and networkFee in message. * This prevents operator from changing execution parameters after user authorization. * * Message contains: positionId, timestamp, chainId, utxoIdentifier (txid:vout), networkFee, action * * @param auth - Authorization parameters (positionId, timestamp, chainId, utxoIdentifier, networkFee, action, signature, mode) * @param positionOwner - Position owner address from contract * @returns True if authorized */ static verifyBtcExecutionAuthorization(auth: { positionId: string; timestamp: number; chainId: number; utxoIdentifier: string; networkFee: number; /** * Audit CRIT-1: bound into the user signature alongside the UTXO so the * caller cannot supply destination/amount values that disagree with what * the user intended. The caller (btc-transaction-signer) MUST then assert * these match the on-chain `BTCSpendAuthorizer` record for the same UTXO. */ targetAddress: string; /** Accept string/number/bigint — JSON numbers from the controller arrive * as `number`, the SDK envelope passes `number`, and the signature- * hash builder uses string form. */ targetAmount: string | number | bigint; /** * Remediation P6/#8: canonical hash of the FULL input set the signer is * about to spend (see `modules/bitcoin/utxo-set-hash.ts`). The caller * (btc-transaction-signer) computes this from its actual `utxos[]`, so * an operator appending vault inputs beyond the borrower-signed set * fails signature verification here. */ utxosHash: string; action: string; signature: string; }, positionOwner: string, targetChainId: number, provider?: any, /** * Safe-agent withdrawal arm (2026-08-05 hardening). Optional and, at * every current call site, unsupplied — see the matching parameter on * `verifyWithdrawAuthorization` for the full rationale. Omitting it * reproduces today's exact borrower/EIP-1271-only behaviour. */ safeAgentPath?: SafeAgentWithdrawPath): Promise; /** * Audit C-1 (2026-05-27): pin the PKP-signed on-chain `paymentAmount` field * to the user-signed `authMessage.paymentAmount`. * * The user signs an EIP-191 envelope carrying `authMessage.paymentAmount`; * the LIT Action later builds an EIP-712 digest carrying `paymentAmount` and * has the PKP sign it. Without this cross-binding, a caller could submit * `globalThis.paymentAmount = Y` while the borrower only authorized * `authMessage.paymentAmount = X`, and the PKP would emit a valid on-chain * proof for an amount the user never approved. * * Throws if the two values disagree. Callers must invoke this immediately * AFTER `verifyPaymentAuthorization` succeeds (otherwise the authMessage is * untrusted input). */ static assertPaymentAmountMatchesAuth(globalThisAmount: bigint, authMessageAmount: string | bigint | number): void; /** * Audit C-2 (2026-05-27): pin the PKP-signed on-chain `selectedTerm` field * to the user-signed `auth.newTerm`. Same shape as * {@link assertPaymentAmountMatchesAuth} but for term extensions. * * Callers must invoke this immediately AFTER `verifyExtendAuthorization` * succeeds. */ static assertSelectedTermMatchesAuth(globalThisTerm: number, authNewTerm: number | string): void; } //# sourceMappingURL=authorization.module.d.ts.map