@oracle-agent/oracle 0.24.5 → 0.24.7

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.
@@ -1,4 +1 @@
1
- import{createCipheriv as X,createDecipheriv as Z,randomBytes as v,scryptSync as K}from"node:crypto";import s from"node:fs";import m from"node:path";var R="ORACLE-LOCAL-VAULT",F=1,x=Object.freeze({N:1<<17,r:8,p:1}),Q=256*1024*1024,ee=16*1024;function O(e,r,n,{max:t=r}={}){if(typeof e!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(`local-vault: invalid ${n} encoding`);let i=Buffer.from(e,"base64");if(i.toString("base64")!==e||i.length<r||i.length>t)throw new Error(`local-vault: invalid ${n} length`);return i}function j(e,r,n=x){let t=String(e??"");if(t.length<12)throw new Error("local-vault: passphrase must be at least 12 characters");return K(t,r,32,{...n,maxmem:Q})}function Oe(e,r,n={}){let t=Buffer.isBuffer(e)?Buffer.from(e):Buffer.from(String(e));if(!t.length)throw new Error("local-vault: refusing empty key material");let i=v(32),o=v(12),a={magic:R,version:F,kdf:{name:"scrypt",...x,salt:i.toString("base64")},cipher:{name:"aes-256-gcm",iv:o.toString("base64")},meta:{address:n.address?String(n.address).toLowerCase():null,kind:n.kind||"evm",createdAt:new Date().toISOString()}},c=j(r,i);try{let u=X("aes-256-gcm",c,o);u.setAAD(Buffer.from(JSON.stringify(a)));let f=Buffer.concat([u.update(t),u.final()]);return{...a,ciphertext:f.toString("base64"),tag:u.getAuthTag().toString("base64")}}finally{c.fill(0),t.fill(0)}}function ve(e,r){if(e?.magic!==R||e?.version!==F)throw new Error("local-vault: unsupported vault file");if(e?.kdf?.name!=="scrypt"||e?.cipher?.name!=="aes-256-gcm")throw new Error("local-vault: unsupported cryptography");if(e.kdf.N!==x.N||e.kdf.r!==x.r||e.kdf.p!==x.p)throw new Error("local-vault: unsupported KDF parameters");if(Object.keys(e.kdf).sort().join(",")!=="N,name,p,r,salt"||Object.keys(e.cipher).sort().join(",")!=="iv,name")throw new Error("local-vault: unexpected cryptography field");if(!e.meta||Object.keys(e.meta).some(d=>!["address","kind","createdAt"].includes(d))||String(e.meta.kind||"").length>16||String(e.meta.address||"").length>128||!Number.isFinite(Date.parse(e.meta.createdAt)))throw new Error("local-vault: invalid metadata");let n=["magic","version","kdf","cipher","meta","ciphertext","tag"];if(Object.keys(e).some(d=>!n.includes(d)))throw new Error("local-vault: unexpected vault field");let t=O(e.kdf.salt,32,"salt"),i=O(e.cipher.iv,12,"iv"),o=O(e.tag,16,"tag"),a=O(e.ciphertext,1,"ciphertext",{max:ee}),{ciphertext:c,tag:u,...f}=e,l=j(r,t);try{let d=Z("aes-256-gcm",l,i);return d.setAAD(Buffer.from(JSON.stringify(f))),d.setAuthTag(o),Buffer.concat([d.update(a),d.final()])}catch{throw new Error("local-vault: wrong passphrase or tampered vault")}finally{l.fill(0)}}function U(e){let r=s.lstatSync(e);if(r.isSymbolicLink())throw new Error("local-vault: refusing symlink");if(!r.isFile())throw new Error("local-vault: secret source must be a regular file");if(r.uid!==process.getuid?.())throw new Error("local-vault: secret source must be owned by this user");if(r.nlink!==1)throw new Error("local-vault: refusing hard-linked secret source");if((r.mode&63)!==0)throw new Error("local-vault: secret source must be owner-only (0600)")}function $(e){let r=m.dirname(e),n=s.lstatSync(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("local-vault: unsafe destination directory");if(n.uid!==process.getuid?.())throw new Error("local-vault: destination directory must be owned by this user");try{let t=s.lstatSync(e);if(t.isSymbolicLink())throw new Error("local-vault: refusing symlink destination");if(!t.isFile()||t.uid!==process.getuid?.()||t.nlink!==1)throw new Error("local-vault: unsafe destination file");if(t.dev!==n.dev)throw new Error("local-vault: destination device mismatch")}catch(t){if(t.code!=="ENOENT")throw t}}function w(e){let r=s.lstatSync(e);U(e);let n=s.openSync(e,s.constants.O_RDONLY|s.constants.O_NOFOLLOW);try{let t=s.fstatSync(n);if(r.dev!==t.dev||r.ino!==t.ino||t.size>1024*1024)throw new Error("local-vault: secret source changed or is too large");return s.readFileSync(n,"utf8").replace(/[\r\n]+$/,"")}finally{s.closeSync(n)}}function be(e){return U(e),JSON.parse(s.readFileSync(e,"utf8"))}function Ne(e,r){s.mkdirSync(m.dirname(e),{recursive:!0,mode:448}),$(e);let n=m.join(m.dirname(e),`.${m.basename(e)}.${process.pid}.${v(6).toString("hex")}.tmp`),t;try{t=s.openSync(n,s.constants.O_CREAT|s.constants.O_EXCL|s.constants.O_WRONLY|s.constants.O_NOFOLLOW,384),s.writeFileSync(t,JSON.stringify(r,null,2)+`
2
- `),s.fsyncSync(t),s.closeSync(t),t=void 0;let i=s.openSync(n,s.constants.O_RDONLY|s.constants.O_NOFOLLOW),o;try{o=s.fstatSync(i)}finally{s.closeSync(i)}let a=s.lstatSync(m.dirname(e));if(o.nlink!==1||o.dev!==a.dev||o.uid!==process.getuid?.())throw new Error("local-vault: unsafe temporary file");s.renameSync(n,e),s.chmodSync(e,384);let c=s.openSync(m.dirname(e),"r");try{s.fsyncSync(c)}finally{s.closeSync(c)}}catch(i){if(t!==void 0)try{s.closeSync(t)}catch{}try{s.unlinkSync(n)}catch{}throw i}return e}function B(e,r){s.mkdirSync(m.dirname(e),{recursive:!0,mode:448}),$(e);let n=m.join(m.dirname(e),`.${m.basename(e)}.${process.pid}.${v(6).toString("hex")}.tmp`);try{let t=s.openSync(n,s.constants.O_CREAT|s.constants.O_EXCL|s.constants.O_WRONLY|s.constants.O_NOFOLLOW,384);try{s.writeFileSync(t,String(r)),s.fsyncSync(t)}finally{s.closeSync(t)}s.renameSync(n,e),s.chmodSync(e,384);let i=s.openSync(m.dirname(e),"r");try{s.fsyncSync(i)}finally{s.closeSync(i)}}catch(t){try{s.unlinkSync(n)}catch{}throw t}}import{createHash as oe,randomBytes as ie,timingSafeEqual as se}from"node:crypto";var W=new Set(["evm","evm-swap","evm-bridge","btc","sol"]),G=Object.freeze({swap:5,bridge:5,perps:0,nft:0}),b=(e,r,n=256)=>{if(typeof e!="string"||!e||e.length>n)throw new Error(`envelope: bounded ${r} required`);return e},S=(e,r)=>{try{let n=BigInt(e);if(n<0n)throw 0;return n}catch{throw new Error(`envelope: ${r} must be a non-negative integer`)}},re=(e,r)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${r} allowlist is empty`);return e},h=(e,r,n)=>{if(!re(r,n).map(t=>String(t).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${n} not allowed`)};function te(e,{localsWaiver:r=!1}={}){if(!(e in G))throw new Error("fee: unknown action");return r?0:G[e]}function C(e,r,{nowMs:n=Date.now()}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let t=b(e.surface,"surface",16);if(!W.has(t))throw new Error("envelope: unsupported public surface");let i=b(e.action,"action",32);if(h(t,r.surfaces,"surface"),h(i,r.actions,"action"),h(e.owner,r.owners,"owner"),h(e.destination,r.destinations,"destination"),!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=n||e.expiresAtMs-n>Number(r.maxTtlMs))throw new Error("policy: TTL outside bounds");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>Number(r.maxSlippageBps))throw new Error("policy: slippage exceeds cap");let o=e.artifact;if(!o||typeof o!="object"||Array.isArray(o))throw new Error("envelope: structured artifact required");if(t.startsWith("evm")){h(Number(o.chainId),r.chains,"chain");let c=String(o.data||"0x").slice(0,10).toLowerCase();if(h(c,r.selectors,"selector"),String(o.to).toLowerCase()!==String(e.destination).toLowerCase())throw new Error("envelope: destination mismatch");if(S(o.value??0,"value")>S(r.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let u=S(o.gasLimit,"gasLimit"),f=S(o.maxFeePerGas??o.gasPrice,"feePerGas");if(u>S(r.maxGasLimit,"maxGasLimit")||u*f>S(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: gas/fee exceeds cap")}else if(t==="btc"){if(b(o.psbt,"PSBT",1e5),h(o.network,r.chains,"chain"),!Array.isArray(o.outputs)||o.outputs.length===0||o.outputs.some(c=>!c.address||S(c.valueSats,"output value")<0n))throw new Error("envelope: bounded BTC outputs required")}else if(t==="sol"){if(b(o.messageBase64,"Solana message",1e5),h(o.cluster,r.chains,"chain"),!Array.isArray(o.programIds)||o.programIds.length===0)throw new Error("envelope: Solana program ids required");for(let c of o.programIds)h(c,r.programs,"program")}else throw new Error("envelope: unsupported public surface");let a=te(i,{localsWaiver:e.fee?.waiver==="locals-only-verified"});if(Number(e.fee?.oracleFeeBps)!==a)throw new Error("fee: final artifact fee mismatch");return!0}var ne=Object.freeze([...W]);function Le(e={}){let r={};for(let n of ne){let t=e[n];if(t){if(typeof t.sign!="function"||typeof t.broadcast!="function")throw new Error(`adapter: ${n} requires sign and broadcast functions`);r[n]=Object.freeze({sign:(i,o)=>t.sign(structuredClone(i),structuredClone(o)),broadcast:(i,o,a)=>t.broadcast(i,structuredClone(o),structuredClone(a))})}}return Object.freeze(r)}function Te(e,r){let n=e?.surface||"evm",t=r?.[n];if(!t)throw new Error(`adapter: ${n} is not configured on this self-host`);return t}var N=e=>String(e||"").toLowerCase(),y=(e,r)=>{try{let n=BigInt(e??0);if(n<0n)throw 0;return n}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},A=(e,r,n,t=String)=>{if(!Array.isArray(r)||r.length===0)throw new Error(`policy: ${n} allowlist is empty`);if(!r.map(t).includes(t(e)))throw new Error(`policy: ${n} not allowed`)};function g(e){return oe("sha256").update(JSON.stringify(e)).digest("hex")}function ae(e){let r=String(e||"").toLowerCase();return!r.startsWith("0x095ea7b3")||r.length!==138?null:{spender:`0x${r.slice(34,74)}`,amount:BigInt(`0x${r.slice(74)}`)}}function H(e,r,{nowMs:n=Date.now()}={}){if(!e||!r)throw new Error("policy: artifact and policy required");A(Number(e.chainId),r.chains,"chain",Number),A(e.to,r.destinations,"destination",N),A(String(e.data||"0x").slice(0,10),r.selectors,"selector",a=>String(a).toLowerCase()),A(e.from,r.owners,"owner",N);let t=ae(e.data);if(String(e.data||"").slice(0,10).toLowerCase()==="0x095ea7b3"){if(!t)throw new Error("policy: malformed approval calldata");if(A(t.spender,r.spenders,"spender",N),t.amount>y(r.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap")}if(y(e.value,"value")>y(r.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let i=y(e.gasLimit,"gasLimit");if(i>y(r.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");if(y(e.maxFeePerGas??e.gasPrice,"feePerGas")*i>y(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>Number(r.maxSlippageBps))throw new Error("policy: slippage attestation exceeds cap");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=n)throw new Error("policy: artifact expired");return!0}var _=class{#e=new Map;constructor({now:r=Date.now}={}){this.now=r}issue({artifact:r,owner:n,ttlMs:t=6e4}){if(t<=0||t>12e4)throw new Error("confirmation: ttl out of range");let i=ie(32).toString("hex");return this.#e.set(i,{digest:g(r),owner:N(n),expiresAtMs:this.now()+t}),i}consume(r,n){let t=this.#e.get(String(r));if(!t)throw new Error("confirmation: used or unknown nonce");if(t.expiresAtMs<=this.now())throw this.#e.delete(String(r)),new Error("confirmation: expired nonce");let i=Buffer.from(t.digest,"hex"),o=Buffer.from(g(n),"hex");if(!se(i,o))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(r)),t}clear(){this.#e.clear()}};function ce(e={},r={}){let n={};for(let t of new Set([...Object.keys(e),...Object.keys(r)]))n[t]=(BigInt(r[t]??0)-BigInt(e[t]??0)).toString();return n}async function J(e,r,n){if(!n.isArmed())throw new Error("signer: disarmed");let t=e?.version===1&&e?.surface?e:null,i=t?t.artifact:e,o=typeof n.readPolicy=="function"?n.readPolicy():n.policy,a=o?.confirmationMode||"exact-human";if(n.autonomous===!0){if(n.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(typeof n.verifyTriggerAttestation!="function"||await n.verifyTriggerAttestation(t?.triggerAttestation,e)!==!0)throw new Error("signer: autonomous trigger attestation required")}else if(a==="exact-human")n.confirmations.consume(r,e);else if(a!=="auto-within-rails")throw new Error("signer: unsupported confirmation mode");let c=g(e),u=()=>typeof n.nowMs=="function"?n.nowMs():n.nowMs??Date.now();t?C(t,o,{nowMs:u()}):H(e,o,{nowMs:u()}),typeof n.reserveLedger=="function"&&n.reserveLedger(t||e,o);let f=await n.sign(i,t);if(!n.isArmed())throw new Error("signer: disarmed before broadcast");if(g(e)!==c)throw new Error("signer: artifact mutated after signing");o=typeof n.readPolicy=="function"?n.readPolicy():n.policy,t?C(t,o,{nowMs:u()}):H(e,o,{nowMs:u()});let l=await n.broadcast(f,i,t),d=l?.status,T=d===1||d==="0x1"?"success":d===0||d==="0x0"?"failed":"pending",k=l?.verifiedBefore??l?.before,I=l?.verifiedAfter??l?.after;return{prepared:e,signed:f,receipt:{transactionHash:l?.hash||l?.transactionHash||null,status:T,balanceDeltaVerified:!!(l?.verifiedBefore&&l?.verifiedAfter),delta:ce(k,I)}}}import ue from"node:http";import{timingSafeEqual as fe}from"node:crypto";var q=new Set(["127.0.0.1","::1","localhost"]),le=(e,r)=>{let n=Buffer.from(String(e)),t=Buffer.from(String(r));return n.length===t.length&&fe(n,t)},p=(e,r,n)=>{let t=JSON.stringify(n);e.writeHead(r,{"content-type":"application/json","cache-control":"no-store","content-length":Buffer.byteLength(t)}),e.end(t)},V=e=>new Promise((r,n)=>{let t=0,i=[],o=!1;e.on("data",a=>{t+=a.length,t>64*1024&&!o?(o=!0,n(new Error("request refused")),e.resume()):o||i.push(a)}),e.on("end",()=>{if(!o)try{r(JSON.parse(Buffer.concat(i).toString()||"{}"))}catch{n(new Error("request refused"))}}),e.on("error",n)});function Re(e={}){let r=e.host||"127.0.0.1";if(!q.has(r))throw new Error("signer: loopback bind required");if(String(e.token||"").length<32)throw new Error("signer: strong auth token required");let n=e.confirmations||new _,t=e.origin||`http://${r}`;return ue.createServer(async(o,a)=>{try{let c=String(o.headers.authorization||"").replace(/^Bearer /i,"");if(!le(c,e.token))return p(a,401,{error:"unauthorized"});let u=String(o.headers.host||"").replace(/^\[|\](?=:|$)/g,"").split(":")[0];if(!q.has(u))return p(a,403,{error:"host refused"});if(o.headers.origin&&o.headers.origin!==t)return p(a,403,{error:"origin refused"});if(o.method==="GET"&&o.url==="/status")return p(a,200,{ok:!0,armed:e.isArmed?.()===!0,sessionExpiresAtMs:e.sessionExpiresAtMs||null});if(o.method==="POST"&&o.url==="/disarm")return e.disarm?.(),n.clear(),p(a,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(o.method))return p(a,405,{error:"request refused"});if(o.method==="POST"&&String(o.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return p(a,415,{error:"request refused"});if(o.method==="POST"&&o.url==="/confirm"){let f=await V(o),l=g(f.artifact);if(e.autonomous!==!0){if(typeof e.confirmArtifact!="function")return p(a,403,{error:"local human confirmation unavailable"});if(await e.confirmArtifact(f.artifact,l)!==!0)return p(a,400,{error:"exact human confirmation refused"})}return p(a,200,{confirmationNonce:n.issue({artifact:f.artifact,owner:f.artifact?.from,ttlMs:f.ttlMs})})}if(o.method==="POST"&&o.url==="/execute"){let f=await V(o),l=await J(f.artifact,f.confirmationNonce,{...e,confirmations:n});return p(a,200,l)}return p(a,404,{error:"not found"})}catch(c){return e.onError?.(String(c?.message||c)),p(a,400,{error:"request refused"})}})}import{createHmac as pe,timingSafeEqual as me}from"node:crypto";import{homedir as D}from"node:os";import{join as M}from"node:path";var z=process.env.ORACLE_PUBLIC_DESKTOP==="1",de=z?process.env.ORACLE_CONFIG_DIR||M(D(),".config","oracle"):M(D(),".config","oracle"),$e=z?de:M(D(),".config","mad-desk");var qe="0".repeat(64),Ve=Object.freeze({PREPARE:"exec.prepare",SIGN:"exec.sign",BROADCAST:"exec.broadcast",POLICY_REJECT:"policy.reject",AUTH_GRANT:"auth.grant",AUTH_OK:"auth.verify.ok",AUTH_FAIL:"auth.verify.fail"});function L(e){return e==null?"null":typeof e!="object"?JSON.stringify(e):Array.isArray(e)?"["+e.map(L).join(",")+"]":"{"+Object.keys(e).sort().map(n=>JSON.stringify(n)+":"+L(e[n])).join(",")+"}"}var ze=Promise.resolve();var he=864e5,E=(e,r)=>pe("sha256",r).update(L(e)).digest("hex"),P=(e,r)=>{let n=Buffer.from(String(e)),t=Buffer.from(String(r));return n.length===t.length&&me(n,t)};function ge(e,r){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("policy: object required");return{policy:e,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:E(e,r)}}}function we(e,r){if(e?.integrity?.algorithm!=="hmac-sha256-canonical-json-v1"||!P(e.integrity.mac,E(e.policy,r)))throw new Error("policy: integrity verification failed");return structuredClone(e.policy)}function er(e,r){let n=w(r),t;try{t=JSON.parse(w(e))}catch(i){throw new Error(`policy: cannot read sealed policy: ${i?.message||i}`)}return we(t,n)}function Se(e,r,n){try{let t=JSON.parse(w(e));if(!P(t?.integrity?.mac,E(t.ledger,r)))throw new Error("integrity verification failed");let i=t.ledger;if(!Number.isFinite(i?.windowStartMs)||!Array.isArray(i?.entries))throw new Error("invalid ledger");return n-i.windowStartMs>=he?{windowStartMs:n,entries:[]}:i}catch(t){if(t?.code==="ENOENT")return{windowStartMs:n,entries:[]};throw new Error(`ledger: corrupt or unreadable: ${t?.message||t}`)}}function Y(e,r){return e.reduce((n,t)=>n+BigInt(t[r]??0),0n)}function rr({file:e,keyFile:r,tradeId:n,value:t=0,notional:i=0,policy:o,nowMs:a=Date.now()}){if(!/^[A-Za-z0-9._:-]{1,128}$/.test(String(n||"")))throw new Error("ledger: bounded tradeId required");let c=w(r),u=Se(e,c,a);if(u.entries.some(I=>I.tradeId===n))throw new Error("ledger: replayed tradeId");let f=BigInt(t),l=BigInt(i),d=BigInt(o.maxDailyValueWei),T=BigInt(o.maxDailyNotional??o.maxDailyValueWei),k=BigInt(o.maxPerTrade??o.maxValueWei);if(f<0n||l<0n||l>k)throw new Error("ledger: per-trade cap exceeded");if(Y(u.entries,"value")+f>d||Y(u.entries,"notional")+l>T)throw new Error("ledger: daily cap exceeded");return u.entries.push({tradeId:String(n),value:f.toString(),notional:l.toString(),atMs:a}),B(e,JSON.stringify({ledger:u,integrity:{algorithm:"hmac-sha256-canonical-json-v1",mac:E(u,c)}})+`
3
- `),structuredClone(u)}function tr(e,r,n){let t=w(r);B(e,JSON.stringify(ge(n,t),null,2)+`
4
- `)}function nr(e,r,n){let t={triggerId:String(r.triggerId),issuedAtMs:Number(r.issuedAtMs),expiresAtMs:Number(r.expiresAtMs),artifactDigest:g(e)};return{...t,algorithm:"hmac-sha256-canonical-json-v1",mac:E(t,n)}}function or(e,r,n,t=Date.now()){if(e?.algorithm!=="hmac-sha256-canonical-json-v1"||!/^[A-Za-z0-9._:-]{1,128}$/.test(String(e?.triggerId||""))||!Number.isFinite(e.issuedAtMs)||!Number.isFinite(e.expiresAtMs)||e.issuedAtMs>t||e.expiresAtMs<=t||e.expiresAtMs-e.issuedAtMs>12e4)return!1;let i={triggerId:e.triggerId,issuedAtMs:e.issuedAtMs,expiresAtMs:e.expiresAtMs,artifactDigest:g(r)};return P(e.mac,E(i,w(n)))}import{spawnSync as ye}from"node:child_process";function ar(e="oracle-local-signer",r=process.env.USER||process.env.USERNAME||"oracle"){let n,t;if(process.platform==="darwin")n="/usr/bin/security",t=["find-generic-password","-s",e,"-a",r,"-w"];else if(process.platform==="linux")n="secret-tool",t=["lookup","service",e,"account",r];else throw new Error("signer: OS credential lookup is supported on macOS and Linux; use a protected passphrase file on this platform");let i=ye(n,t,{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:{PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,LOGNAME:process.env.LOGNAME,DBUS_SESSION_BUS_ADDRESS:process.env.DBUS_SESSION_BUS_ADDRESS}}),o=String(i.stdout||"").replace(/[\r\n]+$/,"");if(i.status!==0||o.length<12)throw new Error("signer: OS credential passphrase unavailable");return o}export{_ as ConfirmationStore,ne as PUBLIC_SIGNER_SURFACES,x as SCRYPT,R as VAULT_MAGIC,F as VAULT_VERSION,g as artifactDigest,H as assertExactPolicy,Re as createSignerServer,Le as createSurfaceAdapters,nr as createTriggerAttestation,ve as decryptVault,Oe as encryptVault,J as executeConfirmedArtifact,we as openPolicy,te as publicFeeBps,ar as readCredentialPassphrase,w as readProtectedSecretFile,er as readSealedPolicy,be as readVault,rr as reserveLedger,ge as sealPolicy,Te as surfaceAdapterFor,C as validateSurfaceEnvelope,or as verifyTriggerAttestation,B as writeProtectedTextAtomic,tr as writeSealedPolicy,Ne as writeVaultAtomic};
1
+ import{createHash as De,randomBytes as Pe,timingSafeEqual as Ve}from"node:crypto";import{Interface as Te,MaxUint256 as $r,isAddress as Br,keccak256 as Lr,toUtf8Bytes as kr}from"ethers";import{Interface as ye,isAddress as dr}from"ethers";import{isAddress as ar}from"ethers";import{createHash as he,createHmac as ge,timingSafeEqual as be}from"node:crypto";import{readFileSync as pe}from"node:fs";import{homedir as me}from"node:os";import{join as M}from"node:path";function le(){if(process.env.ORACLE_TEST_ISOLATE_SECRETS==="1"){let t=(process.env.ORACLE_EXEC_ENV_FILE||"").trim();return t?[t]:[]}let e=(process.env.ORACLE_EXEC_ENV_FILE||process.env.MAD_EXEC_ENV_FILE||"").trim(),r=me();if(process.env.ORACLE_PUBLIC_DESKTOP==="1"){let t=(process.env.ORACLE_CONFIG_DIR||M(r,".config","oracle")).trim();return[e,M(t,"exec.env")].filter(Boolean)}return[e,M(r,".config","oracle","exec.env"),M(r,".config","mad-desk","exec.env")].filter(Boolean)}function C(e,r,t){let o=e??process.env[r]??process.env[t];if(!String(o||"").trim())for(let a of le())try{let n=pe(a,"utf8"),i=n.match(new RegExp(`^${r}=(.*)$`,"m"))||n.match(new RegExp(`^${t}=(.*)$`,"m"));if(i&&(o=i[1].trim(),o))break}catch{}if(!String(o||"").trim())throw new Error(`${r} required for attestation. Set it in the environment, or place ${r}=<value> in ~/.config/oracle/exec.env`);return o}function y(e,r,t="guard"){let o=Number(r);if(r==null||!Number.isFinite(o))throw new Error(`${t}: current time must be a finite number (got ${we(r)})`);let a=Number(e?.issuedAtMs),n=Number(e?.expiresAtMs);if(!Number.isFinite(n))throw new Error(`${t}: expiresAtMs is required and must be a finite number`);if(o>n)throw new Error(`${t} expired at ${n}, now ${o}`);if(e?.issuedAtMs!=null){if(!Number.isFinite(a))throw new Error(`${t}: issuedAtMs must be a finite number when present`);if(n<=a)throw new Error(`${t}: expiry must be after issuance`)}return{now:o,issuedAtMs:a,expiresAtMs:n}}function we(e){return e===null?"null":e===void 0?"undefined":typeof e=="number"?String(e):`${typeof e} ${JSON.stringify(String(e)).slice(0,24)}`}var ee=100;function P(e){return Array.isArray(e)?`[${e.map(P).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(r=>`${JSON.stringify(r)}:${P(e[r])}`).join(",")}}`:JSON.stringify(e??null)}function xe(e,{required:r=!1}={}){try{return C(e,"ORACLE_ROUTE_ATTESTATION_SECRET","MAD_ROUTE_ATTESTATION_SECRET")}catch(t){if(r)throw t;return null}}function Ee(e){let{signature:r,...t}=e;return t}function ve(e){let r=String(e||"").toLowerCase();if(!/^0x[0-9a-f]+$/.test(r)||r.length<10||r.length%2!==0)throw new Error("auto-slippage calldata must be even-length hex with a selector");return he("sha256").update(Buffer.from(r.slice(2),"hex")).digest("hex")}function Se(e,r){let t=Buffer.from(String(e??""),"utf8"),o=Buffer.from(String(r??""),"utf8");return t.length!==o.length||t.length===0?!1:be(t,o)}function Ae(e){let r=String(e||"");if(!/^0x[0-9a-fA-F]+$/.test(r)||r.length<10||r.length%2!==0)return null;let t=r.slice(0,10).toLowerCase(),o=[];for(let n=10;n+64<=r.length;n+=64)o.push(r.slice(n,n+64));let a=n=>o[n]==null?null:BigInt("0x"+o[n]);switch(t){case"0x414bf389":return a(6);case"0x04e45aaf":return a(5);case"0xc04b8d59":{let n=a(0);if(n==null)return null;let i=Number(n)/32;return!Number.isInteger(i)||i<0?null:a(i+4)}case"0xb858183f":{let n=a(0);if(n==null)return null;let i=Number(n)/32;return!Number.isInteger(i)||i<0?null:a(i+3)}case"0xa026383e":return a(6);case"0x38ed1739":case"0x5c11d795":return a(1);case"0x7ff36ab5":case"0xb6f9de95":return a(0);case"0x18cbafe5":case"0x791ac947":return a(1);default:return null}}function V(e,{nowMs:r=Date.now(),chainId:t,venue:o,secret:a,tx:n,requireSigned:i=!1}={}){if(!e||e.mode!=="auto")throw new Error("bounded auto-slippage guard required");let m=xe(a,{required:i});if(i&&!m)throw new Error("auto-slippage attestation secret required for signing or broadcast");if(m){let u=ge("sha256",m).update(P(Ee(e))).digest("hex");if(!Se(e.signature,u))throw new Error("auto-slippage guard signature mismatch \u2014 the guard was not issued by this Oracle")}else if(e.signature)throw new Error("auto-slippage guard carries a signature but no attestation secret is configured");let c=Number(e.selectedBps),s=Number(e.capBps);if(!Number.isInteger(c)||c<0||c>ee)throw new Error("auto-slippage selected tolerance exceeds hard 100 bps cap");if(!Number.isInteger(s)||s<0||s>ee||c>s)throw new Error("auto-slippage cap exceeds hard 100 bps cap");try{y({expiresAtMs:e.expiresAtMs,issuedAtMs:e.quotedAtMs},r,"auto-slippage quote")}catch(u){throw new Error(`${u.message}; re-quote before signing`)}if(t!=null&&Number(e.chainId)!==Number(t))throw new Error("auto-slippage guard chain mismatch");if(o&&String(e.venue).toLowerCase()!==String(o).toLowerCase())throw new Error("auto-slippage guard venue mismatch");let l=BigInt(e.quoteAmountOut??0),w=BigInt(e.minAmountOut??0);if(l<=0n||w<=0n)throw new Error("auto-slippage guard amounts must be positive");let E=l*BigInt(1e4-c)/10000n;if(w<E)throw new Error("auto-slippage guard is under-protected relative to its fresh quote");if(n?.data&&e.minAmountOut!=null)if(e.calldataHash!=null){if(String(e.calldataHash)!==ve(n.data))throw new Error("auto-slippage guard is not bound to this call: calldata hash mismatch")}else{let u=Ae(n.data);if(u==null){let d=String(n.data).slice(0,10);throw new Error(`auto-slippage: cannot verify the output floor encoded by selector ${d}; refusing rather than trusting unbound calldata at an allowlisted venue`)}if(u!==BigInt(e.minAmountOut))throw new Error(`auto-slippage guard is not bound to this call: guard minAmountOut ${e.minAmountOut} but calldata encodes ${u}`)}return!0}var wr=new ye(["function approve(address spender,uint256 amount) returns (bool)"]);import{Interface as Oe,isAddress as br}from"ethers";var Sr=new Oe(["function approve(address spender,uint256 amount) returns (bool)"]),Ar=Object.freeze({42161:"0x1c3fa76e6e1088bce750f23a5bfcffa1efef6a41",43114:"0x8f550e53dfe96c055d5bdb267c21f268fcaf63b2"});var Pr=new Te(["function approve(address spender,uint256 amount) returns (bool)"]);var G=new Set(["0x095ea7b3","0x39509351","0x61f49ed6","0xeb5625d9","0xf9255c1f","0x87517c45","0xd505accf","0x8fcbaf0c","0x2b67b570","0x2a2d80d1"]);var te=new Set(["evm","evm-swap","evm-bridge","btc","sol"]),re=Object.freeze({swap:5,bridge:5,perps:0,nft:0}),oe=new Set(["evm-swap","evm-bridge"]),Ie=new Set(["0x0000000000000000000000000000000000000000","0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"]),j=Object.freeze({"0x04e45aaf":{provider:"uniswap-v3",action:"swap",layout:"router02-exact-input-single"},"0x414bf389":{provider:"uniswap-v3",action:"swap",layout:"swap-router-exact-input-single"},"0x7b939232":{provider:"across-v3",action:"bridge",layout:"across-deposit-v3"}}),Ce=new Set(["0x04e45aaf","0x414bf389","0xc04b8d59","0xb858183f","0xa026383e","0x38ed1739","0x5c11d795","0x7ff36ab5","0xb6f9de95","0x18cbafe5","0x791ac947"]),_e=new Set(["0xa9059cbb","0x23b872dd","0x42842e0e","0xb88d4fde","0xf242432a","0x2eb2c2d6","0xa22cb465","0xd0e30db0","0x2e1a7d4d","0x3593564c","0x24856bc3","0xac9650d8","0x5ae401dc"]),U=(e,r,t=256)=>{if(typeof e!="string"||!e||e.length>t)throw new Error(`envelope: bounded ${r} required`);return e},p=(e,r)=>{try{let t=BigInt(e);if(t<0n)throw 0;return t}catch{throw new Error(`envelope: ${r} must be a non-negative integer`)}},$e=(e,r)=>{if(!Array.isArray(e)||e.length===0)throw new Error(`policy: ${r} allowlist is empty`);return e},b=(e,r,t)=>{if(!$e(r,t).map(o=>String(o).toLowerCase()).includes(String(e).toLowerCase()))throw new Error(`policy: ${t} not allowed`)},_=(e,r)=>{let t=String(e||"").toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(t))throw new Error(`envelope: ${r} must be a 20-byte address`);return t},O=e=>String(e||"0x").slice(0,10).toLowerCase();function W(e){return G.has(O(e))}function H(e){let r=O(e);return Ce.has(r)||_e.has(r)||Object.hasOwn(j,r)||G.has(r)}function J(e,r,t,{dynamicTail:o=!1}={}){let a=String(e||"").toLowerCase();if(!/^0x[0-9a-f]*$/.test(a)||a.length<10+r*64)throw new Error(`envelope: malformed ${t} calldata`);if(!o&&a.length!==10+r*64)throw new Error(`envelope: malformed ${t} calldata`);return{hex:a,word:n=>a.slice(10+n*64,10+(n+1)*64)}}function v(e,r){if(!/^0{24}[0-9a-f]{40}$/.test(e))throw new Error(`envelope: malformed ${r} address`);return`0x${e.slice(24)}`}function A(e,r){try{return BigInt(`0x${e}`)}catch{throw new Error(`envelope: malformed ${r} integer`)}}function Be(e){if(O(e)!=="0x095ea7b3")return null;let r=J(e,2,"approval");return{kind:"approval",spender:v(r.word(0),"approval spender"),amount:A(r.word(1),"approval amount")}}function Le(e,r){let t=r==="router02-exact-input-single"?7:8,o=J(e,t,"Uniswap v3 exactInputSingle"),a=t===7?4:5;return{kind:"action",action:"swap",inputToken:v(o.word(0),"input token"),outputToken:v(o.word(1),"output token"),recipient:v(o.word(3),"recipient"),amountIn:A(o.word(a),"amountIn"),minimumOut:A(o.word(a+1),"amountOutMinimum")}}function ke(e){let r=J(e,12,"Across depositV3",{dynamicTail:!0}),t=A(r.word(11),"message offset");if(t!==384n)throw new Error("envelope: malformed Across depositV3 message offset");let o=10+Number(t)*2;if(r.hex.length<o+64)throw new Error("envelope: malformed Across depositV3 message");let a=Number(BigInt(`0x${r.hex.slice(o,o+64)}`));if(!Number.isSafeInteger(a))throw new Error("envelope: malformed Across depositV3 message length");let n=Math.ceil(a/32)*64;if(r.hex.length!==o+64+n)throw new Error("envelope: malformed Across depositV3 trailing bytes");return{kind:"action",action:"bridge",depositor:v(r.word(0),"depositor"),recipient:v(r.word(1),"recipient"),inputToken:v(r.word(2),"input token"),outputToken:v(r.word(3),"output token"),amountIn:A(r.word(4),"inputAmount"),minimumOut:A(r.word(5),"outputAmount"),destinationChainId:A(r.word(6),"destinationChainId")}}function Me(e,r){let t=O(e),o=j[t];if(!o)throw new Error("envelope: opaque or unsupported EVM swap/bridge calldata");if(String(r).toLowerCase()!==o.provider)throw new Error("envelope: provider does not match reviewed selector");if(o.action==="swap")return{...Le(e,o.layout),selector:t,provider:o.provider};if(o.action==="bridge")return{...ke(e),selector:t,provider:o.provider};throw new Error("envelope: unsupported reviewed EVM action")}function q(e){let r=e?.artifact;if(Array.isArray(r?.transactions))return r.transactions;if(r?.transaction&&typeof r.transaction=="object")return[r.transaction];if(r?.data)return[r];throw new Error("envelope: ordered EVM transaction batch required")}function R(e,r,{nowMs:t=Date.now(),routeAttestationSecret:o}={}){let a=String(e?.surface||"");if(!oe.has(a))throw new Error("envelope: strict EVM swap/bridge surface required");let n=U(e.provider,"provider",64).toLowerCase();b(n,r.providers,"provider");let i=_(e.owner,"owner"),m=e.artifact,c=Number(m?.chainId);if(!Number.isSafeInteger(c)||c<=0)throw new Error("envelope: explicit batch chainId required");if(b(c,r.chains,"chain"),_(m?.owner,"batch owner")!==i)throw new Error("envelope: explicit batch owner mismatch");let s=q(e);if(!s.length||s.length>8)throw new Error("envelope: bounded EVM transaction batch required");let l=0n,w=0n,E=0n,u=[],d=-1;for(let g=0;g<s.length;g++){let h=s[g];if(!h||typeof h!="object"||Array.isArray(h))throw new Error("envelope: structured EVM transaction required");if(Number(h.chainId)!==c)throw new Error("envelope: every batch leg must use the same chain");if(_(h.from,"transaction owner")!==i)throw new Error("envelope: every batch leg must use the same owner");let de=O(h.data);b(de,r.selectors,"selector");let L=Be(h.data),D;if(L){if(d!==-1)throw new Error("envelope: approval must be before action");let Y=_(h.to,"approval token");if(b(Y,r.tokens,"token"),b(L.spender,r.spenders,"spender"),L.amount>p(r.maxApproval,"maxApproval"))throw new Error("policy: approval exceeds cap");D={...L,token:Y,index:g}}else{if(d!==-1)throw new Error("envelope: exactly one swap/bridge action is supported per batch");b(h.to,r.destinations,"destination"),D={...Me(h.data,n),target:_(h.to,"action target"),index:g},d=g}let Z=p(h.value??0,"value"),k=p(h.gasLimit,"gasLimit"),Q=p(h.maxFeePerGas??h.gasPrice,"feePerGas");l+=Z,w+=k,E+=k*Q,u.push({...D,value:Z,gas:k,fee:k*Q})}if(d<0)throw new Error("envelope: reviewed swap/bridge action required");if(l>p(r.maxValueWei,"maxValueWei"))throw new Error("policy: aggregate value exceeds cap");if(w>p(r.maxGasLimit,"maxGasLimit"))throw new Error("policy: aggregate gas exceeds cap");if(E>p(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: aggregate fee exceeds cap");let f=u[d],B=a==="evm-swap"?"swap":"bridge";if(f.action!==B||e.action!==B)throw new Error("envelope: surface/action/calldata mismatch");if(f.recipient!==i)throw new Error("envelope: decoded recipient must equal owner");if(f.depositor&&f.depositor!==i)throw new Error("envelope: decoded bridge depositor must equal owner");if(b(f.inputToken,r.tokens,"input token"),b(f.outputToken,r.tokens,"output token"),f.amountIn<=0n||f.amountIn>p(r.maxPerTrade,"maxPerTrade"))throw new Error("policy: decoded amount exceeds per-trade cap");if(f.minimumOut<=0n)throw new Error("policy: decoded minimum output must be positive");if(V(e.autoSlippage,{nowMs:t,chainId:c,venue:n,tx:s[d],secret:o,requireSigned:!0}),Number(e.slippageBps)!==Number(e.autoSlippage.selectedBps))throw new Error("policy: slippageBps must equal the authenticated quote selectedBps");if(f.minimumOut!==p(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"))throw new Error("policy: decoded minimum output does not match authenticated quote");if(f.action==="bridge"&&p(e.toChainId,"toChainId")!==f.destinationChainId)throw new Error("envelope: decoded bridge destination chain mismatch");let N=u.filter(g=>g.kind==="approval");if(Ie.has(f.inputToken)){if(N.length)throw new Error("envelope: native-value action must not include token approval")}else{if(N.length!==1)throw new Error("envelope: exactly one approval is required before action");let g=N[0];if(g.index>=d)throw new Error("envelope: approval must be before action");if(g.token!==f.inputToken)throw new Error("envelope: approval token does not match decoded input token");if(g.spender!==f.target)throw new Error("envelope: approval spender does not match decoded action target");if(g.amount!==f.amountIn)throw new Error("envelope: approval amount must exactly match decoded action amount")}let fe=Object.freeze({quoteAmountOut:p(e.autoSlippage.quoteAmountOut,"authenticated quote amountOut"),minAmountOut:p(e.autoSlippage.minAmountOut,"authenticated quote minAmountOut"),selectedBps:Number(e.autoSlippage.selectedBps),quotedAtMs:Number(e.autoSlippage.quotedAtMs),expiresAtMs:Number(e.autoSlippage.expiresAtMs)});return{transactions:s,decoded:u,action:f,totalValue:l,totalGas:w,totalFee:E,chainId:c,owner:i,provider:n,authenticatedQuote:fe}}function ne(e,{localsWaiver:r=!1}={}){if(!(e in re))throw new Error("fee: unknown action");return r?0:re[e]}function z(e,r,{nowMs:t=Date.now(),routeAttestationSecret:o}={}){if(!e||e.version!==1)throw new Error("envelope: version 1 required");let a=U(e.surface,"surface",16);if(!te.has(a))throw new Error("envelope: unsupported public surface");let n=U(e.action,"action",32);if(b(a,r.surfaces,"surface"),b(n,r.actions,"action"),b(e.owner,r.owners,"owner"),b(e.destination,r.destinations,"destination"),!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=t||e.expiresAtMs-t>Number(r.maxTtlMs))throw new Error("policy: TTL outside bounds");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>Number(r.maxSlippageBps))throw new Error("policy: slippage exceeds cap");let i=e.artifact;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("envelope: structured artifact required");if(oe.has(a))R(e,r,{nowMs:t,routeAttestationSecret:o});else if(a==="evm"){if(W(i.data))throw new Error("envelope: approval requires a strict decoded surface");if(n==="swap"||n==="bridge"||H(i.data))throw new Error("envelope: strict EVM swap/bridge surface required");b(Number(i.chainId),r.chains,"chain");let c=O(i.data);if(b(c,r.selectors,"selector"),String(i.from).toLowerCase()!==String(e.owner).toLowerCase())throw new Error("envelope: owner mismatch");if(String(i.to).toLowerCase()!==String(e.destination).toLowerCase())throw new Error("envelope: destination mismatch");if(p(i.value??0,"value")>p(r.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let s=p(i.gasLimit,"gasLimit"),l=p(i.maxFeePerGas??i.gasPrice,"feePerGas");if(s>p(r.maxGasLimit,"maxGasLimit")||s*l>p(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: gas/fee exceeds cap")}else throw a==="btc"||a==="sol"?new Error("envelope: btc/sol require decoded payload; caller-authored outputs and programIds are refused"):new Error("envelope: unsupported public surface");let m=ne(n,{localsWaiver:e.fee?.waiver==="locals-only-verified"});if(Number(e.fee?.oracleFeeBps)!==m)throw new Error("fee: final artifact fee mismatch");return!0}var ae=Object.freeze([...te]),qe=Object.freeze({...j});function Re(e={}){let r={};for(let t of ae){let o=e[t];if(o){if(typeof o.sign!="function"||typeof o.broadcast!="function")throw new Error(`adapter: ${t} requires sign and broadcast functions`);r[t]=Object.freeze({sign:(a,n)=>o.sign(structuredClone(a),structuredClone(n)),broadcast:(a,n,i)=>o.broadcast(a,structuredClone(n),structuredClone(i))})}}return Object.freeze(r)}function Fe(e,r){let t=e?.surface||"evm",o=r?.[t];if(!o)throw new Error(`adapter: ${t} is not configured on this self-host`);return o}var K=e=>String(e||"").toLowerCase(),T=(e,r)=>{try{let t=BigInt(e??0);if(t<0n)throw 0;return t}catch{throw new Error(`policy: ${r} must be a non-negative integer`)}},F=(e,r,t,o=String)=>{if(!Array.isArray(r)||r.length===0)throw new Error(`policy: ${t} allowlist is empty`);if(!r.map(o).includes(o(e)))throw new Error(`policy: ${t} not allowed`)};function S(e){return De("sha256").update(JSON.stringify(e)).digest("hex")}function ie(e,r,{nowMs:t=Date.now()}={}){if(!e||!r)throw new Error("policy: artifact and policy required");if(W(e.data))throw new Error("envelope: approval requires a strict decoded surface");if(H(e.data))throw new Error("envelope: strict EVM swap/bridge surface required");if(F(Number(e.chainId),r.chains,"chain",Number),F(e.to,r.destinations,"destination",K),F(String(e.data||"0x").slice(0,10),r.selectors,"selector",n=>String(n).toLowerCase()),F(e.from,r.owners,"owner",K),T(e.value,"value")>T(r.maxValueWei,"maxValueWei"))throw new Error("policy: value exceeds cap");let o=T(e.gasLimit,"gasLimit");if(o>T(r.maxGasLimit,"maxGasLimit"))throw new Error("policy: gas exceeds cap");if(T(e.maxFeePerGas??e.gasPrice,"feePerGas")*o>T(r.maxFeeWei,"maxFeeWei"))throw new Error("policy: fee exceeds cap");if(!Number.isFinite(e.slippageBps)||e.slippageBps<0||e.slippageBps>Number(r.maxSlippageBps))throw new Error("policy: slippage attestation exceeds cap");if(!Number.isFinite(e.expiresAtMs)||e.expiresAtMs<=t)throw new Error("policy: artifact expired");return!0}var $=class{#e=new Map;constructor({now:r=Date.now}={}){this.now=r}issue({artifact:r,owner:t,ttlMs:o=6e4}){if(o<=0||o>12e4)throw new Error("confirmation: ttl out of range");let a=Pe(32).toString("hex");return this.#e.set(a,{digest:S(r),owner:K(t),expiresAtMs:this.now()+o}),a}consume(r,t){let o=this.#e.get(String(r));if(!o)throw new Error("confirmation: used or unknown nonce");if(o.expiresAtMs<=this.now())throw this.#e.delete(String(r)),new Error("confirmation: expired nonce");let a=Buffer.from(o.digest,"hex"),n=Buffer.from(S(t),"hex");if(!Ve(a,n))throw new Error("confirmation: artifact mismatch");return this.#e.delete(String(r)),o}clear(){this.#e.clear()}};function Ge(e={},r={}){let t={};for(let o of new Set([...Object.keys(e||{}),...Object.keys(r||{})]))t[o]=(BigInt(r?.[o]??0)-BigInt(e?.[o]??0)).toString();return t}function Ue(e){let r=e?.status,t=r===1||r==="0x1"?"success":r===0||r==="0x0"?"failed":"pending",o=e?.verifiedBefore??e?.before,a=e?.verifiedAfter??e?.after;return{transactionHash:e?.hash||e?.transactionHash||null,status:t,balanceDeltaVerified:!!(e?.verifiedBefore&&e?.verifiedAfter),delta:Ge(o,a)}}function se(e){return e?.surface==="evm-swap"||e?.surface==="evm-bridge"}function I(e,r,t=Date.now(),{routeAttestationSecret:o}={}){let a=e?.version===1&&e?.surface?e:null;return a?(z(a,r,{nowMs:t,routeAttestationSecret:o}),se(a)?R(a,r,{nowMs:t,routeAttestationSecret:o}):null):(ie(e,r,{nowMs:t}),null)}async function X(e,r,t){if(!t.isArmed())throw new Error("signer: disarmed");let o=e?.version===1&&e?.surface?e:null,a=()=>typeof t.nowMs=="function"?t.nowMs():t.nowMs??Date.now(),n=typeof t.readPolicy=="function"?t.readPolicy():t.policy,i=n?.confirmationMode||"exact-human";if(t.autonomous===!0){if(t.env?.ORACLE_AUTONOMOUS_TRADING!=="1")throw new Error("signer: autonomous execution requires ORACLE_AUTONOMOUS_TRADING=1");if(typeof t.verifyTriggerAttestation!="function"||await t.verifyTriggerAttestation(o?.triggerAttestation,e)!==!0)throw new Error("signer: autonomous trigger attestation required")}else{if(i==="auto-within-rails")throw new Error("signer: auto-within-rails requires autonomous trading with authenticated trigger attestation");if(i!=="exact-human")throw new Error("signer: unsupported confirmation mode");if(!t.confirmations||typeof t.confirmations.consume!="function")throw new Error("signer: exact confirmation store required");t.confirmations.consume(r,e)}let m=S(e),c=I(e,n,a(),{routeAttestationSecret:t.routeAttestationSecret});typeof t.reserveLedger=="function"&&t.reserveLedger(o||e,n,c);let s=o&&se(o)?q(o):[o?o.artifact:e],l=[],w=[];for(let d=0;d<s.length;d++){if(!t.isArmed())throw new Error("signer: disarmed before signing");if(S(e)!==m)throw new Error("signer: artifact mutated before signing");d>0&&(n=typeof t.readPolicy=="function"?t.readPolicy():t.policy,c=I(e,n,a(),{routeAttestationSecret:t.routeAttestationSecret}));let f=await t.sign(s[d],o);if(l.push(f),!t.isArmed())throw new Error("signer: disarmed before broadcast");if(S(e)!==m)throw new Error("signer: artifact mutated before broadcast");n=typeof t.readPolicy=="function"?t.readPolicy():t.policy,c=I(e,n,a(),{routeAttestationSecret:t.routeAttestationSecret});let B=await t.broadcast(f,s[d],o),N=Ue(B);if(w.push(N),N.status!=="success")break}let E=w.length===s.length&&w.every(d=>d.status==="success")?"success":w.some(d=>d.status==="failed")?"failed":"pending",u={prepared:e,signed:s.length===1?l[0]:l,receipt:w[0]||null,receipts:w,status:E};return o?.surface==="evm-bridge"&&(u.originStatus=E,u.destinationStatus="unverified",u.destinationSuccess=!1,u.note="Origin-chain receipts do not prove destination-chain settlement."),u}import je from"node:http";import{timingSafeEqual as We}from"node:crypto";var ce=new Set(["127.0.0.1","::1","localhost"]),He=(e,r)=>{let t=Buffer.from(String(e)),o=Buffer.from(String(r));return t.length===o.length&&We(t,o)},x=(e,r,t)=>{let o=JSON.stringify(t);e.writeHead(r,{"content-type":"application/json","cache-control":"no-store","content-length":Buffer.byteLength(o)}),e.end(o)},ue=e=>new Promise((r,t)=>{let o=0,a=[],n=!1;e.on("data",i=>{o+=i.length,o>64*1024&&!n?(n=!0,t(new Error("request refused")),e.resume()):n||a.push(i)}),e.on("end",()=>{if(!n)try{r(JSON.parse(Buffer.concat(a).toString()||"{}"))}catch{t(new Error("request refused"))}}),e.on("error",t)});function Je(e={}){let r=e.host||"127.0.0.1";if(!ce.has(r))throw new Error("signer: loopback bind required");if(String(e.token||"").length<32)throw new Error("signer: strong auth token required");let t=e.confirmations||new $,o=e.origin||`http://${r}`;return je.createServer(async(n,i)=>{try{let m=String(n.headers.authorization||"").replace(/^Bearer /i,"");if(!He(m,e.token))return x(i,401,{error:"unauthorized"});let c=String(n.headers.host||"").replace(/^\[|\](?=:|$)/g,"").split(":")[0];if(!ce.has(c))return x(i,403,{error:"host refused"});if(n.headers.origin&&n.headers.origin!==o)return x(i,403,{error:"origin refused"});if(n.method==="GET"&&n.url==="/status")return x(i,200,{ok:!0,armed:e.isArmed?.()===!0,sessionExpiresAtMs:e.sessionExpiresAtMs||null});if(n.method==="POST"&&n.url==="/disarm")return e.disarm?.(),t.clear(),x(i,200,{ok:!0,armed:!1});if(!["GET","POST"].includes(n.method))return x(i,405,{error:"request refused"});if(n.method==="POST"&&String(n.headers["content-type"]||"").split(";",1)[0].trim().toLowerCase()!=="application/json")return x(i,415,{error:"request refused"});if(n.method==="POST"&&n.url==="/confirm"){let s=await ue(n),l=S(s.artifact);if(e.autonomous!==!0){if(typeof e.confirmArtifact!="function")return x(i,403,{error:"local human confirmation unavailable"});let w=typeof e.readPolicy=="function"?e.readPolicy():e.policy,E=typeof e.nowMs=="function"?e.nowMs():e.nowMs??Date.now(),u=I(s.artifact,w,E);if(await e.confirmArtifact(s.artifact,l,u)!==!0)return x(i,400,{error:"exact human confirmation refused"})}return x(i,200,{confirmationNonce:t.issue({artifact:s.artifact,owner:s.artifact?.from,ttlMs:s.ttlMs})})}if(n.method==="POST"&&n.url==="/execute"){let s=await ue(n),l=await X(s.artifact,s.confirmationNonce,{...e,confirmations:t});return x(i,200,l)}return x(i,404,{error:"not found"})}catch(m){return e.onError?.(String(m?.message||m)),x(i,400,{error:"request refused"})}})}export{$ as ConfirmationStore,ae as PUBLIC_SIGNER_SURFACES,qe as REVIEWED_EVM_SELECTORS,S as artifactDigest,ie as assertExactPolicy,Je as createSignerServer,Re as createSurfaceAdapters,q as evmTransactions,X as executeConfirmedArtifact,I as inspectArtifactForConfirmation,R as inspectEvmBatch,ne as publicFeeBps,Fe as surfaceAdapterFor,z as validateSurfaceEnvelope};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oracle-agent/oracle",
3
- "version": "0.24.5",
3
+ "version": "0.24.7",
4
4
  "description": "Oracle: standalone multichain agent control plane with an optional encrypted, loopback-only self-hosted signer.",
5
5
  "license": "BUSL-1.1",
6
6
  "type": "module",