From 45c6da4d526f10dc893c2e8a7b9f4fc33a271851 Mon Sep 17 00:00:00 2001 From: Ethan Konkolowicz Date: Wed, 11 Feb 2026 19:19:23 -0500 Subject: [PATCH 1/7] added encrypted bundle caching + escrow key injection --- .../dist/bundle.2ddbc9eacea08f1f698a.js | 3 - .../dist/bundle.2ddbc9eacea08f1f698a.js.map | 1 - .../dist/bundle.8ccdeed719db48416e34.js | 3 + ...undle.8ccdeed719db48416e34.js.LICENSE.txt} | 0 .../dist/bundle.8ccdeed719db48416e34.js.map | 1 + export-and-sign/dist/index.html | 2 +- export-and-sign/index.test.js | 795 ++++++++++++++++++ export-and-sign/src/event-handlers.js | 473 +++++++++-- export-and-sign/src/turnkey-core.js | 8 + shared/turnkey-core.js | 56 ++ 10 files changed, 1249 insertions(+), 93 deletions(-) delete mode 100644 export-and-sign/dist/bundle.2ddbc9eacea08f1f698a.js delete mode 100644 export-and-sign/dist/bundle.2ddbc9eacea08f1f698a.js.map create mode 100644 export-and-sign/dist/bundle.8ccdeed719db48416e34.js rename export-and-sign/dist/{bundle.2ddbc9eacea08f1f698a.js.LICENSE.txt => bundle.8ccdeed719db48416e34.js.LICENSE.txt} (100%) create mode 100644 export-and-sign/dist/bundle.8ccdeed719db48416e34.js.map diff --git a/export-and-sign/dist/bundle.2ddbc9eacea08f1f698a.js b/export-and-sign/dist/bundle.2ddbc9eacea08f1f698a.js deleted file mode 100644 index 3a14fd8..0000000 --- a/export-and-sign/dist/bundle.2ddbc9eacea08f1f698a.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! For license information please see bundle.2ddbc9eacea08f1f698a.js.LICENSE.txt */ -(()=>{var e,t,r,n,o,a={560:(e,t,r)=>{"use strict";var n=r(598),o=r(443),a=r(566);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function c(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function u(e){for(var t=1;t3?(o=y===n)&&(u=a[(c=a[4])?5:(c=3,3)],a[4]=a[5]=e):a[0]<=p&&((o=r<2&&pn||n>y)&&(a[4]=r,a[5]=n,d.n=y,c=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){a||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,a){if(c||(o="next"),t=a[o]){if(!(t=t.call(a,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=a.return)&&t.call(a),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);a=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){a=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var d=[][n]?t(t([][n]())):(l(t={},n,function(){return this}),t),p=s.prototype=c.prototype=Object.create(d);function y(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,l(e,o,"GeneratorFunction")),e.prototype=Object.create(p),e}return u.prototype=s,l(p,"constructor",s),l(s,"constructor",u),u.displayName="GeneratorFunction",l(s,o,"GeneratorFunction"),l(p),l(p,o,"Generator"),l(p,n,function(){return this}),l(p,"toString",function(){return"[object Generator]"}),(f=function(){return{w:a,m:y}})()}function l(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}l=function(e,t,r,n){function a(t,r){l(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},l(e,t,r,n)}function d(e){return function(e){if(Array.isArray(e))return y(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||p(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e,t){if(e){if("string"==typeof e)return y(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?y(e,t):void 0}}function y(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1:window.parent!==window.top}function S(){return(S=b(f().m(function e(t){var r;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=w()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,r.importKey("raw",t,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function O(){return(O=b(f().m(function e(){return f().w(function(e){for(;;)switch(e.n){case 0:if(!E()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,P();case 2:if(null!==e.v){e.n=4;break}return e.n=3,k();case 3:x(e.v);case 4:return e.a(2)}},e)}))).apply(this,arguments)}function k(){return j.apply(this,arguments)}function j(){return(j=b(f().m(function e(){var t,r;return f().w(function(e){for(;;)switch(e.n){case 0:if(t=w()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,t.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return r=e.v,e.n=3,t.exportKey("jwk",r.privateKey);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function P(){var e=T(m);return e?JSON.parse(e):null}function x(e){_(m,JSON.stringify(e),1728e5)}function _(e,t,r){var n={value:t,expiry:(new Date).getTime()+r};window.localStorage.setItem(e,JSON.stringify(n))}function T(e){var t=window.localStorage.getItem(e);if(!t)return null;var r=JSON.parse(t);return Object.prototype.hasOwnProperty.call(r,"expiry")&&Object.prototype.hasOwnProperty.call(r,"value")?(new Date).getTime()>r.expiry?(window.localStorage.removeItem(e),null):r.value:(window.localStorage.removeItem(e),null)}function I(e){if(!e||"string"!=typeof e)throw new Error("cannot create uint8array from invalid hex string");var t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0||!/^[0-9A-Fa-f]+$/.test(t))throw new Error("cannot create uint8array from invalid hex string");return new Uint8Array(t.match(/../g).map(function(e){return parseInt(e,16)}))}function A(e){return d(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function D(e,t){var r=Array.from(new Uint8Array(e)),n=Array.from(new Uint8Array(t));return new Uint8Array([].concat(r,n))}function N(e){var t=document.getElementById("message-log");if(t){var r=document.createElement("p");r.innerText=e,t.appendChild(r)}}function R(e){return M.apply(this,arguments)}function M(){return(M=b(f().m(function e(t){var r,n,o,a;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=w()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return delete(n=u({},t)).d,n.key_ops=["verify"],e.n=2,r.importKey("jwk",n,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return o=e.v,e.n=3,r.exportKey("raw",o);case 3:return a=e.v,e.a(2,new Uint8Array(a))}},e)}))).apply(this,arguments)}function K(e){for(var t="",r=[0],n=0;n0;)r.push(o%58),o=o/58|0}for(var i=0;i0;){var c=r[i];a=(c=void 0===c?a:58*c+a)>>8,r[i]=c%256,i++}}var u=n.concat(r.reverse());return new Uint8Array(u)}function G(){return(G=b(f().m(function e(t,r,n){var o,a;return f().w(function(e){for(;;)switch(e.n){case 0:a=r,e.n="SOLANA"===a?1:"HEXADECIMAL"===a?5:6;break;case 1:if(n){e.n=2;break}throw new Error("public key must be specified for SOLANA key format");case 2:if(32===t.length){e.n=3;break}throw new Error("invalid private key length. Expected 32 bytes. Got ".concat(t.length,"."));case 3:if(32===n.length){e.n=4;break}throw new Error("invalid public key length. Expected 32 bytes. Got ".concat(n.length,"."));case 4:return(o=new Uint8Array(64)).set(t,0),o.set(n,32),e.a(2,K(o));case 5:return e.a(2,"0x"+A(t));case 6:return console.warn("invalid key format: ".concat(r,". Defaulting to HEXADECIMAL.")),e.a(2,"0x"+A(t));case 7:return e.a(2)}},e)}))).apply(this,arguments)}function C(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function a(r,n,o,a){var u=n&&n.prototype instanceof c?n:c,s=Object.create(u.prototype);return B(s,"_invoke",function(r,n,o){var a,c,u,s=0,f=o||[],l=!1,d={p:0,n:0,v:e,a:p,f:p.bind(e,4),d:function(t,r){return a=t,c=0,u=e,d.n=r,i}};function p(r,n){for(c=r,u=n,t=0;!l&&s&&!o&&t3?(o=y===n)&&(u=a[(c=a[4])?5:(c=3,3)],a[4]=a[5]=e):a[0]<=p&&((o=r<2&&pn||n>y)&&(a[4]=r,a[5]=n,d.n=y,c=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){a||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,a){if(c||(o="next"),t=a[o]){if(!(t=t.call(a,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=a.return)&&t.call(a),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);a=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){a=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(B(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,B(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,B(l,"constructor",s),B(s,"constructor",u),u.displayName="GeneratorFunction",B(s,o,"GeneratorFunction"),B(l),B(l,o,"Generator"),B(l,n,function(){return this}),B(l,"toString",function(){return"[object Generator]"}),(C=function(){return{w:a,m:d}})()}function B(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}B=function(e,t,r,n){function a(t,r){B(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},B(e,t,r,n)}function L(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r]*$',color:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",labelColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",backgroundColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",width:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",height:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",maxWidth:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",maxHeight:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",lineHeight:"^(\\d+(\\.\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$",boxShadow:"^(none|(\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)) ?(inset)?)$",textAlign:"^(left|right|center|justify|initial|inherit)$",overflowWrap:"^(normal|break-word|anywhere)$",wordWrap:"^(normal|break-word)$",resize:"^(none|both|horizontal|vertical|block|inline)$"};return Object.entries(e).forEach(function(e){var t,o,a=(o=2,function(e){if(Array.isArray(e))return e}(t=e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,a,i,c=[],u=!0,s=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=a.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,o=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw o}}return c}}(t,o)||p(t,o)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),i=a[0],c=a[1],u=i.trim();if(0===u.length)throw new Error("css style property cannot be empty");var s=n[u];if(!s)throw new Error('invalid or unsupported css style property: "'.concat(u,'"'));var f=new RegExp(s),l=c.trim();if(0==l.length)throw new Error('css style for "'.concat(u,'" is empty'));if(!f.test(l))throw new Error('invalid css style value for property "'.concat(u,'"'));r[u]=l}),r},q=E,W=function(e){return S.apply(this,arguments)};function X(){return(X=H(C().m(function e(){return C().w(function(e){for(;;)switch(e.n){case 0:if(!q()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,Y();case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function V(){return(V=H(C().m(function e(t,r,n){var o,i,c,u,s,f,l,d;return C().w(function(e){for(;;)switch(e.n){case 0:if(o={prod:"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569",preprod:"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212"},i=null,"undefined"!=typeof document&&(c=document.querySelector('meta[name="turnkey-signer-environment"]'))&&c.content&&"__TURNKEY_SIGNER_ENVIRONMENT__"!==c.content&&(i=c.content),i||"undefined"==typeof window||(i=window.__TURNKEY_SIGNER_ENVIRONMENT__),void 0!==(u=o[i])){e.n=1;break}throw new Error("Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined");case 1:if(t===u){e.n=2;break}throw new Error("enclave quorum public keys from client and bundle do not match. Client: ".concat(u,". Bundle: ").concat(t,"."));case 2:return s=new Uint8Array(J(u)),e.n=3,W(s);case 3:if(f=e.v){e.n=4;break}throw new Error("failed to load quorum key");case 4:return l=(0,a.g8)(r),d=J(n),e.n=5,crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},f,l,d);case 5:return e.a(2,e.v)}},e)}))).apply(this,arguments)}var Q={initEmbeddedKey:function(){return X.apply(this,arguments)},generateTargetKey:k,setItemWithExpiry:_,getItemWithExpiry:T,getEmbeddedKey:P,setEmbeddedKey:x,onResetEmbeddedKey:function(){window.localStorage.removeItem(m),window.localStorage.removeItem("TURNKEY_EMBEDDED_KEY_ORIGIN")},p256JWKPrivateToPublic:R,base58Encode:K,base58Decode:U,encodeKey:function(e,t,r){return G.apply(this,arguments)},sendMessageUp:function(e,t,r){var n={type:e,value:t};r&&(n.requestId=r),h?h.postMessage(n):window.parent!==window&&window.parent.postMessage({type:e,value:t},"*"),N("⬆️ Sent message ".concat(e,": ").concat(t))},logMessage:N,uint8arrayFromHexString:J,uint8arrayToHexString:A,setParentFrameMessageChannelPort:function(e){h=e},normalizePadding:function(e,t){var r=t-e.length;if(r>0){var n=new Uint8Array(r).fill(0);return new Uint8Array([].concat(d(n),d(e)))}if(r<0){for(var o=-1*r,a=0,i=0;i3?(o=y===n)&&(u=a[(c=a[4])?5:(c=3,3)],a[4]=a[5]=e):a[0]<=p&&((o=r<2&&pn||n>y)&&(a[4]=r,a[5]=n,d.n=y,c=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){a||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,a){if(c||(o="next"),t=a[o]){if(!(t=t.call(a,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=a.return)&&t.call(a),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);a=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){a=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(ae(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,ae(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,ae(l,"constructor",s),ae(s,"constructor",u),u.displayName="GeneratorFunction",ae(s,o,"GeneratorFunction"),ae(l),ae(l,o,"Generator"),ae(l,n,function(){return this}),ae(l,"toString",function(){return"[object Generator]"}),(oe=function(){return{w:a,m:d}})()}function ae(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}ae=function(e,t,r,n){function a(t,r){ae(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},ae(e,t,r,n)}function ie(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,a,i,c=[],u=!0,s=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=a.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,o=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw o}}return c}}(e,t)||function(e,t){if(e){if("string"==typeof e)return ce(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ce(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function ce(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r= v2.0.0 to pass "organizationId" for security purposes.');case 8:if(c.organizationId&&c.organizationId===r){e.n=9;break}throw new Error("organization id does not match expected value. Expected: ".concat(r,". Found: ").concat(c.organizationId,"."));case 9:if(c.encappedPublic){e.n=10;break}throw new Error('missing "encappedPublic" in bundle signed data');case 10:if(c.ciphertext){e.n=11;break}throw new Error('missing "ciphertext" in bundle signed data');case 11:return o=Q.uint8arrayFromHexString(c.encappedPublic),a=Q.uint8arrayFromHexString(c.ciphertext),e.a(3,13);case 12:throw new Error("unsupported version: ".concat(i.version));case 13:return e.n=14,Q.getEmbeddedKey();case 14:return u=e.v,e.n=15,n({ciphertextBuf:a,encappedKeyBuf:o,receiverPrivJwk:u});case 15:return e.a(2,e.v)}},e)})),ye.apply(this,arguments)}function ve(e){return be.apply(this,arguments)}function be(){return(be=se(oe().m(function e(t){var r,n,o;return oe().w(function(e){for(;;)switch(e.n){case 0:if(r=Q.getEmbeddedKey()){e.n=1;break}return Q.sendMessageUp("EMBEDDED_PUBLIC_KEY","",t),e.a(2);case 1:return e.n=2,Q.p256JWKPrivateToPublic(r);case 2:n=e.v,o=Q.uint8arrayToHexString(n),Q.sendMessageUp("EMBEDDED_PUBLIC_KEY",o,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function me(e,t,r,n,o,a){return ge.apply(this,arguments)}function ge(){return ge=se(oe().m(function e(t,r,n,o,a,i){var c,u,s,f,l,d,p;return oe().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,pe(n,r,i);case 1:if(c=e.v,s=new Uint8Array(c),"SOLANA"!==o){e.n=3;break}return f=Q.uint8arrayToHexString(s.subarray(0,32)),l=Q.getEd25519PublicKey(f),e.n=2,Q.encodeKey(s,o,l);case 2:u=e.v,e.n=5;break;case 3:return e.n=4,Q.encodeKey(s,o);case 4:u=e.v;case 5:if(d=a||"default","SOLANA"!==o){e.n=6;break}p=Z.AX.fromSecretKey(Q.base58Decode(u)),e.n=8;break;case 6:if("HEXADECIMAL"!==o){e.n=8;break}return e.n=7,xe(Array.from(Q.uint8arrayFromHexString(u)));case 7:p=e.v;case 8:fe=re(re({},fe),{},ne({},d,{organizationId:r,privateKey:u,format:o,expiry:(new Date).getTime()+864e5,keypair:p})),Q.sendMessageUp("BUNDLE_INJECTED",!0,t);case 9:return e.a(2)}},e)})),ge.apply(this,arguments)}function he(e,t){return we.apply(this,arguments)}function we(){return(we=se(oe().m(function e(t,r){var n;return oe().w(function(e){for(;;)switch(e.n){case 0:n=Q.applySettings(t),Q.setSettings(n),Q.sendMessageUp("SETTINGS_APPLIED",!0,r);case 1:return e.a(2)}},e)}))).apply(this,arguments)}function Ee(e,t,r){return Se.apply(this,arguments)}function Se(){return(Se=se(oe().m(function e(t,r,n){var o,a,i,c,u,s,f,l,d;return oe().w(function(e){for(;;)switch(e.n){case 0:if(Ie(a=fe[o=n||"default"],o)){e.n=1;break}return e.a(2);case 1:return e.n=2,Ae(a);case 2:if(i=e.v,c=JSON.parse(r),u=c.transaction,"SOLANA"!==c.type){e.n=3;break}f=Q.uint8arrayFromHexString(u),(l=Z.Kt.deserialize(f)).sign([i]),s=l.serialize(),e.n=4;break;case 3:throw new Error("unsupported transaction type");case 4:d=Q.uint8arrayToHexString(s),Q.sendMessageUp("TRANSACTION_SIGNED",d,t);case 5:return e.a(2)}},e)}))).apply(this,arguments)}function Oe(e,t,r){return ke.apply(this,arguments)}function ke(){return ke=se(oe().m(function e(t,r,a){var i,c,u,s,f,l,d,p,y,v;return oe().w(function(e){for(;;)switch(e.n){case 0:if(Ie(c=fe[i=a||"default"],i)){e.n=1;break}return e.a(2);case 1:return u=JSON.parse(r),s=u.message,f=u.type,l=le.encode(s),e.n=2,Ae(c);case 2:if(p=e.v,"SOLANA"!==f){e.n=3;break}n.jn.sha512Sync=function(){var e;return o.Zf((e=n.jn).concatBytes.apply(e,arguments))},y=p.secretKey.slice(0,32),v=n._S(l,y),d=Q.uint8arrayToHexString(v),e.n=4;break;case 3:return Q.sendMessageUp("ERROR","unsupported message type",t),e.a(2);case 4:Q.sendMessageUp("MESSAGE_SIGNED",d,t);case 5:return e.a(2)}},e)})),ke.apply(this,arguments)}function je(e,t){return Pe.apply(this,arguments)}function Pe(){return(Pe=se(oe().m(function e(t,r){return oe().w(function(e){for(;;)switch(e.n){case 0:if(r){e.n=1;break}return fe={},Q.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t),e.a(2);case 1:if(fe[r]){e.n=2;break}return Q.sendMessageUp("ERROR",new Error("key not found for address ".concat(r,". Note that address is case sensitive.")).toString(),t),e.a(2);case 2:delete fe[r],Q.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function xe(e){return _e.apply(this,arguments)}function _e(){return(_e=se(oe().m(function e(t){var r,n;return oe().w(function(e){for(;;)switch(e.n){case 0:if(32!==(r=Q.parsePrivateKey(t)).length){e.n=1;break}n=Z.AX.fromSeed(r),e.n=3;break;case 1:if(64!==r.length){e.n=2;break}n=Z.AX.fromSecretKey(r),e.n=3;break;case 2:throw new Error("Invalid private key length: ".concat(r.length,". Expected 32 or 64 bytes."));case 3:return e.a(2,n)}},e)}))).apply(this,arguments)}function Te(e){fe[e]&&delete fe[e]}function Ie(e,t){if(!e)throw new Error("key bytes not found. Please re-inject export bundle for address ".concat(t," into iframe. Note that address is case sensitive.")).toString();if((new Date).getTime()>=e.expiry)throw function(){for(var e=(new Date).getTime(),t=[],r=0,n=Object.entries(fe);r=i.expiry&&t.push(a)}for(var c=0,u=t;c3?(o=y===n)&&(u=a[(c=a[4])?5:(c=3,3)],a[4]=a[5]=e):a[0]<=p&&((o=r<2&&pn||n>y)&&(a[4]=r,a[5]=n,d.n=y,c=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){a||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,a){if(c||(o="next"),t=a[o]){if(!(t=t.call(a,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=a.return)&&t.call(a),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);a=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){a=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(Ue(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,Ue(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,Ue(l,"constructor",s),Ue(s,"constructor",u),u.displayName="GeneratorFunction",Ue(s,o,"GeneratorFunction"),Ue(l),Ue(l,o,"Generator"),Ue(l,n,function(){return this}),Ue(l,"toString",function(){return"[object Generator]"}),(Ke=function(){return{w:a,m:d}})()}function Ue(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}Ue=function(e,t,r,n){function a(t,r){Ue(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},Ue(e,t,r,n)}function Ge(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function Ce(e){for(var t=1;t3?(o=y===n)&&(u=a[(c=a[4])?5:(c=3,3)],a[4]=a[5]=e):a[0]<=p&&((o=r<2&&pn||n>y)&&(a[4]=r,a[5]=n,d.n=y,c=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){a||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,a){if(c||(o="next"),t=a[o]){if(!(t=t.call(a,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=a.return)&&t.call(a),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);a=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){a=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):($e(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,$e(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,$e(l,"constructor",s),$e(s,"constructor",u),u.displayName="GeneratorFunction",$e(s,o,"GeneratorFunction"),$e(l),$e(l,o,"Generator"),$e(l,n,function(){return this}),$e(l,"toString",function(){return"[object Generator]"}),(Je=function(){return{w:a,m:d}})()}function $e(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}$e=function(e,t,r,n){function a(t,r){$e(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},$e(e,t,r,n)}function ze(e,t,r,n,o,a,i){try{var c=e[a](i),u=c.value}catch(e){return void r(e)}c.done?t(u):Promise.resolve(u).then(n,o)}function qe(e){return function(){var t=this,r=arguments;return new Promise(function(n,o){var a=e.apply(t,r);function i(e){ze(a,n,o,i,c,"next",e)}function c(e){ze(a,n,o,i,c,"throw",e)}i(void 0)})}}window.TKHQ=Q,document.addEventListener("DOMContentLoaded",qe(Je().m(function e(){var t,r,n,o;return Je().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,Q.initEmbeddedKey();case 1:return e.n=2,Q.getEmbeddedKey();case 2:return t=e.v,e.n=3,Q.p256JWKPrivateToPublic(t);case 3:r=e.v,n=Q.uint8arrayToHexString(r),document.getElementById("embedded-key").value=n,Ne(He),(o=Q.getSettings())&&Q.applySettings(o),Q.sendMessageUp("PUBLIC_KEY_READY",n);case 4:return e.a(2)}},e)})))},790:()=>{},846:e=>{"use strict";e.exports=crypto}},i={};function c(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={id:e,loaded:!1,exports:{}};return a[e].call(r.exports,r,r.exports,c),r.loaded=!0,r.exports}c.m=a,e=[],c.O=(t,r,n,o)=>{if(!r){var a=1/0;for(f=0;f=o)&&Object.keys(c.O).every(e=>c.O[e](r[u]))?r.splice(u--,1):(i=!1,o0&&e[f-1][2]>o;f--)e[f]=e[f-1];e[f]=[r,n,o]},c.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return c.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,c.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var o=Object.create(null);c.r(o);var a={};t=t||[null,r({}),r([]),r(r)];for(var i=2&n&&e;("object"==typeof i||"function"==typeof i)&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach(t=>a[t]=()=>e[t]);return a.default=()=>e,c.d(o,a),o},c.d=(e,t)=>{for(var r in t)c.o(t,r)&&!c.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},c.f={},c.e=e=>Promise.all(Object.keys(c.f).reduce((t,r)=>(c.f[r](e,t),t),[])),c.u=e=>"bundle."+{291:"3eaea85f4001b9cc63c3",825:"aaba32bf7338e3d0f1cc"}[e]+".js",c.miniCssF=e=>{},c.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),c.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},o="export-and-sign:",c.l=(e,t,r,a)=>{if(n[e])n[e].push(t);else{var i,u;if(void 0!==r)for(var s=document.getElementsByTagName("script"),f=0;f{i.onerror=i.onload=null,clearTimeout(p);var o=n[e];if(delete n[e],i.parentNode&&i.parentNode.removeChild(i),o&&o.forEach(e=>e(r)),t)return t(r)},p=setTimeout(d.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=d.bind(null,i.onerror),i.onload=d.bind(null,i.onload),u&&document.head.appendChild(i)}},c.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),c.p="/",c.sriHashes={291:"sha384-G5pDFEAG9UZITbluyje/R/rWohZTUJf+Vu3ZIh0rsnLFLTw3SP/ca/XVNZVtv48f",825:"sha384-R9OIdd42i5GcdtZiHJuQgIUVvqyqJ0s7eaBnJHAfGllpi4YwbF7NSkjIRwOPUtsP"},(()=>{var e={792:0};c.f.j=(t,r)=>{var n=c.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[2]);else{var o=new Promise((r,o)=>n=e[t]=[r,o]);r.push(n[2]=o);var a=c.p+c.u(t),i=new Error;c.l(a,r=>{if(c.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var o=r&&("load"===r.type?"missing":r.type),a=r&&r.target&&r.target.src;i.message="Loading chunk "+t+" failed.\n("+o+": "+a+")",i.name="ChunkLoadError",i.type=o,i.request=a,n[1](i)}},"chunk-"+t,t)}},c.O.j=t=>0===e[t];var t=(t,r)=>{var n,o,[a,i,u]=r,s=0;if(a.some(t=>0!==e[t])){for(n in i)c.o(i,n)&&(c.m[n]=i[n]);if(u)var f=u(c)}for(t&&t(r);sc(560));u=c.O(u)})(); -//# sourceMappingURL=bundle.2ddbc9eacea08f1f698a.js.map \ No newline at end of file diff --git a/export-and-sign/dist/bundle.2ddbc9eacea08f1f698a.js.map b/export-and-sign/dist/bundle.2ddbc9eacea08f1f698a.js.map deleted file mode 100644 index 8a92319..0000000 --- a/export-and-sign/dist/bundle.2ddbc9eacea08f1f698a.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bundle.2ddbc9eacea08f1f698a.js","mappings":";UAAIA,ECCAC,EADAC,ECAAC,EACAC,E,svCCAJ,IAAAC,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,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AASA,EAAMmI,QAAUnI,EAAMmI,OAAOd,IACpD3O,EAAMlJ,QAAU,iBAAmB4W,EAAU,cAAgBwC,EAAY,KAAOC,EAAU,IAC1FnQ,EAAM3O,KAAO,iBACb2O,EAAM/B,KAAOiS,EACblQ,EAAMoQ,QAAUD,EAChBJ,EAAmB,GAAG/P,EACvB,GAGuC,SAAW0N,EAASA,EAE/D,GAYH1B,EAAoBM,EAAErU,EAAKyV,GAA0C,IAA7BoC,EAAgBpC,GAGxD,IAAI2C,EAAuB,CAACC,EAA4BlP,KACvD,IAGI6K,EAAUyB,GAHTnB,EAAUgE,EAAaC,GAAWpP,EAGhB/S,EAAI,EAC3B,GAAGke,EAASkE,KAAMtE,GAAgC,IAAxB2D,EAAgB3D,IAAa,CACtD,IAAIF,KAAYsE,EACZvE,EAAoB7d,EAAEoiB,EAAatE,KACrCD,EAAoB7b,EAAE8b,GAAYsE,EAAYtE,IAGhD,GAAGuE,EAAS,IAAI1Y,EAAS0Y,EAAQxE,EAClC,CAEA,IADGsE,GAA4BA,EAA2BlP,GACrD/S,EAAIke,EAASld,OAAQhB,IACzBqf,EAAUnB,EAASle,GAChB2d,EAAoB7d,EAAE2hB,EAAiBpC,IAAYoC,EAAgBpC,IACrEoC,EAAgBpC,GAAS,KAE1BoC,EAAgBpC,GAAW,EAE5B,OAAO1B,EAAoBM,EAAExU,IAG1B4Y,EAAqBC,KAAkC,4BAAIA,KAAkC,6BAAK,GACtGD,EAAmBtV,QAAQiV,EAAqBjhB,KAAK,KAAM,IAC3DshB,EAAmBxY,KAAOmY,EAAqBjhB,KAAK,KAAMshB,EAAmBxY,KAAK9I,KAAKshB,G,KClFvF,IAAIE,EAAsB5E,EAAoBM,OAAE5Z,EAAW,CAAC,IAAK,IAAOsZ,EAAoB,MAC5F4E,EAAsB5E,EAAoBM,EAAEsE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/../shared/turnkey-core.js","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/../shared/crypto-utils.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/external var \"crypto\"","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/global","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/compat","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t\tif (script.src.indexOf(window.location.origin + '/') !== 0) {\n\t\t\tscript.crossOrigin = \"anonymous\";\n\t\t}\n\t\tscript.integrity = __webpack_require__.sriHashes[chunkId];\n\t\tscript.crossOrigin = \"anonymous\";\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n};\n","import * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\nimport { fromDerSignature } from \"@turnkey/crypto\";\nimport * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n initEmbeddedKey: sharedInitEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n additionalAssociatedData,\n getSettings,\n setSettings,\n parsePrivateKey,\n validateStyles,\n isDoublyIframed,\n loadQuorumKey,\n} = SharedTKHQ;\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n return await sharedInitEmbeddedKey();\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Read environment from meta tag (templated at deploy time), fall back to window variable (for testing)\n let environment = null;\n if (typeof document !== \"undefined\") {\n const meta = document.querySelector(\n 'meta[name=\"turnkey-signer-environment\"]'\n );\n if (\n meta &&\n meta.content &&\n meta.content !== \"__TURNKEY_SIGNER_ENVIRONMENT__\"\n ) {\n environment = meta.content;\n }\n }\n if (!environment && typeof window !== \"undefined\") {\n environment = window.__TURNKEY_SIGNER_ENVIRONMENT__;\n }\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n let encappedKeyBuf;\n let ciphertextBuf;\n let verified;\n\n // Parse the import bundle\n const bundleObj = JSON.parse(bundle);\n switch (bundleObj.version) {\n case \"v1.0.0\":\n // Validate fields exist\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n // Verify enclave signature\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(`failed to verify enclave signature: ${bundle}`);\n }\n\n // Parse the signed data. The data is produced by JSON encoding followed by hex encoding. We reverse this here.\n {\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n // Validate fields match\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n }\n break;\n default:\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n\n // Decrypt the ciphertext\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: embeddedKeyJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Parse the decrypted key bytes\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n // Set in memory\n // If no address provided, use a default key\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair, // Cache the keypair for performance\n },\n };\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Set up sha512 for nobleEd25519 (required for signing)\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n\n // Extract the 32-byte private key from the 64-byte secretKey\n // Solana keypair.secretKey format: [32-byte private key][32-byte public key]\n const privateKey = keypair.secretKey.slice(0, 32);\n // Sign the message using nobleEd25519\n const signature = nobleEd25519.sign(messageBytes, privateKey);\n\n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error(\n `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`\n ).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n undefined, // keyFormat - default to HEXADECIMAL\n undefined, // address - default to \"default\"\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"@shared/crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n","module.exports = crypto;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","\n__webpack_require__.sriHashes = {\"291\":\"*-*-*-CHUNK-SRI-HASH-r3NPGwA4ft5fHgGXhVIptCiDVf06qPa+sxzG6L+8GwPuhn89e/\",\"825\":\"*-*-*-CHUNK-SRI-HASH-mfog3UJdGPOmSk4QZbKxsxHPFZtt298WnZNc1aQ1MCgc6YirFj\"};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(560)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","parentFrameMessageChannelPort","getSubtleCrypto","globalThis","crypto","subtle","window","global","isDoublyIframed","undefined","location","ancestorOrigins","parent","top","_loadQuorumKey","_callee","quorumPublic","_context","Error","importKey","namedCurve","_initEmbeddedKey","_callee3","_context3","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee4","p256key","_context4","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","key","ttl","item","expiry","Date","getTime","localStorage","setItem","itemStr","getItem","hasOwnProperty","removeItem","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","concat","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","p256JWKPrivateToPublic","_x6","_p256JWKPrivateToPublic","_callee6","jwkPrivate","jwkPrivateCopy","publicKey","_context6","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","push","k","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee9","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_t2","_context9","set","console","warn","sharedInitEmbeddedKey","SharedTKHQ","validateStyles","styles","element","validStyles","cssValidationRegex","padding","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref","_ref2","_arrayWithHoles","next","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","loadQuorumKey","_x","_verifyEnclaveSignature","_callee2","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","meta","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context2","prod","preprod","querySelector","__TURNKEY_SIGNER_ENVIRONMENT__","fromDerSignature","verify","hash","TKHQ","initEmbeddedKey","onResetEmbeddedKey","encodeKey","_x0","_x1","_x10","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","normalizePadding","byteArray","targetLength","paddingLength","fill","expectedZeroCount","zeroCount","verifyEnclaveSignature","_x2","_x3","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","style","getSettings","setSettings","parsePrivateKey","error","_slicedToArray","inMemoryKeys","textEncoder","TextEncoder","textDecoder","TextDecoder","decryptBundle","_decryptBundle","_callee8","bundle","organizationId","HpkeDecrypt","encappedKeyBuf","ciphertextBuf","bundleObj","embeddedKeyJwk","_t8","_context8","version","data","dataSignature","decode","encappedPublic","ciphertext","receiverPrivJwk","onGetPublicEmbeddedKey","_x4","_onGetPublicEmbeddedKey","targetPubBuf","targetPubHex","onInjectKeyBundle","_x5","_x7","_x8","_x9","_onInjectKeyBundle","_callee0","address","keyBytes","keyAddress","cachedKeypair","_context0","subarray","Keypair","fromSecretKey","createSolanaKeypair","_defineProperty","format","keypair","onApplySettings","_onApplySettings","_callee1","_context1","onSignTransaction","_x11","_x12","_x13","_onSignTransaction","_callee10","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context10","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x14","_x15","_x16","_onSignMessage","_callee11","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context11","encode","secretKey","onClearEmbeddedPrivateKey","_x17","_x18","_onClearEmbeddedPrivateKey","_callee12","_context12","_x19","_createSolanaKeypair","_callee13","_context13","fromSeed","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x20","_getOrCreateKeypair","_callee14","_context14","initEventHandlers","messageEventListener","_messageEventListener","event","_t","_t3","_t4","_t5","_t6","_t7","_x26","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","preventDefault","_x21","_x22","_ref3","_x23","_ref4","_x24","injectWalletBtn","_ref5","_callee5","_context5","_x25","addDOMEventListeners","capture","signal","_ref6","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x27","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","_HpkeDecrypt","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","styleSettings","module","exports","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","g","Function","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","crossOrigin","integrity","sriHashes","onScriptComplete","prev","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/dist/bundle.8ccdeed719db48416e34.js b/export-and-sign/dist/bundle.8ccdeed719db48416e34.js new file mode 100644 index 0000000..17101ab --- /dev/null +++ b/export-and-sign/dist/bundle.8ccdeed719db48416e34.js @@ -0,0 +1,3 @@ +/*! For license information please see bundle.8ccdeed719db48416e34.js.LICENSE.txt */ +(()=>{var e,t,r,n,a,o={560:(e,t,r)=>{"use strict";var n=r(598),a=r(443),o=r(566);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function c(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function u(e){for(var t=1;t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,d.n=y,c=0))}if(a||r>1)return i;throw l=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){o||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var d=[][n]?t(t([][n]())):(l(t={},n,function(){return this}),t),p=s.prototype=c.prototype=Object.create(d);function y(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,l(e,a,"GeneratorFunction")),e.prototype=Object.create(p),e}return u.prototype=s,l(p,"constructor",s),l(s,"constructor",u),u.displayName="GeneratorFunction",l(s,a,"GeneratorFunction"),l(p),l(p,a,"Generator"),l(p,n,function(){return this}),l(p,"toString",function(){return"[object Generator]"}),(f=function(){return{w:o,m:y}})()}function l(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}l=function(e,t,r,n){function o(t,r){l(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},l(e,t,r,n)}function d(e){return function(e){if(Array.isArray(e))return y(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||p(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e,t){if(e){if("string"==typeof e)return y(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?y(e,t):void 0}}function y(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1:window.parent!==window.top}function O(){return(O=b(f().m(function e(t){var r;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=E()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,r.importKey("raw",t,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function k(){return(k=b(f().m(function e(){return f().w(function(e){for(;;)switch(e.n){case 0:if(!S()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,_();case 2:if(null!==e.v){e.n=4;break}return e.n=3,P();case 3:I(e.v);case 4:return e.a(2)}},e)}))).apply(this,arguments)}function P(){return j.apply(this,arguments)}function j(){return(j=b(f().m(function e(){var t,r;return f().w(function(e){for(;;)switch(e.n){case 0:if(t=E()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,t.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return r=e.v,e.n=3,t.exportKey("jwk",r.privateKey);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function _(){var e=A(g);return e?JSON.parse(e):null}function I(e){T(g,JSON.stringify(e),1728e5)}function x(){var e=window.localStorage.getItem(h);return e?JSON.parse(e):null}function T(e,t,r){var n={value:t,expiry:(new Date).getTime()+r};window.localStorage.setItem(e,JSON.stringify(n))}function A(e){var t=window.localStorage.getItem(e);if(!t)return null;var r=JSON.parse(t);return Object.prototype.hasOwnProperty.call(r,"expiry")&&Object.prototype.hasOwnProperty.call(r,"value")?(new Date).getTime()>r.expiry?(window.localStorage.removeItem(e),null):r.value:(window.localStorage.removeItem(e),null)}function R(e){if(!e||"string"!=typeof e)throw new Error("cannot create uint8array from invalid hex string");var t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0||!/^[0-9A-Fa-f]+$/.test(t))throw new Error("cannot create uint8array from invalid hex string");return new Uint8Array(t.match(/../g).map(function(e){return parseInt(e,16)}))}function D(e){return d(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function N(e,t){var r=Array.from(new Uint8Array(e)),n=Array.from(new Uint8Array(t));return new Uint8Array([].concat(r,n))}function M(e){var t=document.getElementById("message-log");if(t){var r=document.createElement("p");r.innerText=e,t.appendChild(r)}}function U(e){return K.apply(this,arguments)}function K(){return(K=b(f().m(function e(t){var r,n,a,o;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=E()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return delete(n=u({},t)).d,n.key_ops=["verify"],e.n=2,r.importKey("jwk",n,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return a=e.v,e.n=3,r.exportKey("raw",a);case 3:return o=e.v,e.a(2,new Uint8Array(o))}},e)}))).apply(this,arguments)}function C(e){for(var t="",r=[0],n=0;n0;)r.push(a%58),a=a/58|0}for(var i=0;i0;){var c=r[i];o=(c=void 0===c?o:58*c+o)>>8,r[i]=c%256,i++}}var u=n.concat(r.reverse());return new Uint8Array(u)}function L(){return(L=b(f().m(function e(t,r,n){var a,o;return f().w(function(e){for(;;)switch(e.n){case 0:o=r,e.n="SOLANA"===o?1:"HEXADECIMAL"===o?5:6;break;case 1:if(n){e.n=2;break}throw new Error("public key must be specified for SOLANA key format");case 2:if(32===t.length){e.n=3;break}throw new Error("invalid private key length. Expected 32 bytes. Got ".concat(t.length,"."));case 3:if(32===n.length){e.n=4;break}throw new Error("invalid public key length. Expected 32 bytes. Got ".concat(n.length,"."));case 4:return(a=new Uint8Array(64)).set(t,0),a.set(n,32),e.a(2,C(a));case 5:return e.a(2,"0x"+D(t));case 6:return console.warn("invalid key format: ".concat(r,". Defaulting to HEXADECIMAL.")),e.a(2,"0x"+D(t));case 7:return e.a(2)}},e)}))).apply(this,arguments)}function G(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",a=r.toStringTag||"@@toStringTag";function o(r,n,a,o){var u=n&&n.prototype instanceof c?n:c,s=Object.create(u.prototype);return F(s,"_invoke",function(r,n,a){var o,c,u,s=0,f=a||[],l=!1,d={p:0,n:0,v:e,a:p,f:p.bind(e,4),d:function(t,r){return o=t,c=0,u=e,d.n=r,i}};function p(r,n){for(c=r,u=n,t=0;!l&&s&&!a&&t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,d.n=y,c=0))}if(a||r>1)return i;throw l=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){o||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(F(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,F(e,a,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,F(l,"constructor",s),F(s,"constructor",u),u.displayName="GeneratorFunction",F(s,a,"GeneratorFunction"),F(l),F(l,a,"Generator"),F(l,n,function(){return this}),F(l,"toString",function(){return"[object Generator]"}),(G=function(){return{w:o,m:d}})()}function F(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}F=function(e,t,r,n){function o(t,r){F(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},F(e,t,r,n)}function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r]*$',color:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",labelColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",backgroundColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",width:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",height:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",maxWidth:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",maxHeight:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",lineHeight:"^(\\d+(\\.\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$",boxShadow:"^(none|(\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)) ?(inset)?)$",textAlign:"^(left|right|center|justify|initial|inherit)$",overflowWrap:"^(normal|break-word|anywhere)$",wordWrap:"^(normal|break-word)$",resize:"^(none|both|horizontal|vertical|block|inline)$"};return Object.entries(e).forEach(function(e){var t,a,o=(a=2,function(e){if(Array.isArray(e))return e}(t=e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,a,o,i,c=[],u=!0,s=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=o.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,a=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw a}}return c}}(t,a)||p(t,a)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),i=o[0],c=o[1],u=i.trim();if(0===u.length)throw new Error("css style property cannot be empty");var s=n[u];if(!s)throw new Error('invalid or unsupported css style property: "'.concat(u,'"'));var f=new RegExp(s),l=c.trim();if(0==l.length)throw new Error('css style for "'.concat(u,'" is empty'));if(!f.test(l))throw new Error('invalid css style value for property "'.concat(u,'"'));r[u]=l}),r},X=S,V=function(e){return O.apply(this,arguments)},Q=x;function Z(){return(Z=J(G().m(function e(){return G().w(function(e){for(;;)switch(e.n){case 0:if(!X()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,q();case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function ee(){return(ee=J(G().m(function e(t,r,n){var a,i,c,u,s,f,l,d;return G().w(function(e){for(;;)switch(e.n){case 0:if(a={prod:"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569",preprod:"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212"},i=null,"undefined"!=typeof document&&(c=document.querySelector('meta[name="turnkey-signer-environment"]'))&&c.content&&"__TURNKEY_SIGNER_ENVIRONMENT__"!==c.content&&(i=c.content),i||"undefined"==typeof window||(i=window.__TURNKEY_SIGNER_ENVIRONMENT__),void 0!==(u=a[i])){e.n=1;break}throw new Error("Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined");case 1:if(t===u){e.n=2;break}throw new Error("enclave quorum public keys from client and bundle do not match. Client: ".concat(u,". Bundle: ").concat(t,"."));case 2:return s=new Uint8Array(z(u)),e.n=3,V(s);case 3:if(f=e.v){e.n=4;break}throw new Error("failed to load quorum key");case 4:return l=(0,o.g8)(r),d=z(n),e.n=5,crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},f,l,d);case 5:return e.a(2,e.v)}},e)}))).apply(this,arguments)}var te={initEmbeddedKey:function(){return Z.apply(this,arguments)},generateTargetKey:P,setItemWithExpiry:T,getItemWithExpiry:A,getEmbeddedKey:_,setEmbeddedKey:I,onResetEmbeddedKey:function(){window.localStorage.removeItem(g),window.localStorage.removeItem("TURNKEY_EMBEDDED_KEY_ORIGIN")},p256JWKPrivateToPublic:U,base58Encode:C,base58Decode:B,encodeKey:function(e,t,r){return L.apply(this,arguments)},sendMessageUp:function(e,t,r){var n={type:e,value:t};r&&(n.requestId=r),w?w.postMessage(n):window.parent!==window&&window.parent.postMessage({type:e,value:t},"*"),M("⬆️ Sent message ".concat(e,": ").concat(t))},logMessage:M,uint8arrayFromHexString:z,uint8arrayToHexString:D,setParentFrameMessageChannelPort:function(e){w=e},normalizePadding:function(e,t){var r=t-e.length;if(r>0){var n=new Uint8Array(r).fill(0);return new Uint8Array([].concat(d(n),d(e)))}if(r<0){for(var a=-1*r,o=0,i=0;i3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,d.n=y,c=0))}if(a||r>1)return i;throw l=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){o||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(ue(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,ue(e,a,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,ue(l,"constructor",s),ue(s,"constructor",u),u.displayName="GeneratorFunction",ue(s,a,"GeneratorFunction"),ue(l),ue(l,a,"Generator"),ue(l,n,function(){return this}),ue(l,"toString",function(){return"[object Generator]"}),(ce=function(){return{w:o,m:d}})()}function ue(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}ue=function(e,t,r,n){function o(t,r){ue(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},ue(e,t,r,n)}function se(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,a,o,i,c=[],u=!0,s=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=o.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,a=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw a}}return c}}(e,t)||function(e,t){if(e){if("string"==typeof e)return fe(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?fe(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function fe(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r= v2.0.0 to pass "organizationId" for security purposes.');case 8:if(a.organizationId&&a.organizationId===r){e.n=9;break}throw new Error("organization id does not match expected value. Expected: ".concat(r,". Found: ").concat(a.organizationId,"."));case 9:if(a.encappedPublic){e.n=10;break}throw new Error('missing "encappedPublic" in bundle signed data');case 10:if(a.ciphertext){e.n=11;break}throw new Error('missing "ciphertext" in bundle signed data');case 11:return e.a(2,a)}},e)}))).apply(this,arguments)}function he(e,t,r){return we.apply(this,arguments)}function we(){return we=de(ce().m(function e(t,r,n){var a,o,i,c;return ce().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,ge(t,r);case 1:return a=e.v,o=te.uint8arrayFromHexString(a.encappedPublic),i=te.uint8arrayFromHexString(a.ciphertext),e.n=2,te.getEmbeddedKey();case 2:return c=e.v,e.n=3,n({ciphertextBuf:i,encappedKeyBuf:o,receiverPrivJwk:c});case 3:return e.a(2,e.v)}},e)})),we.apply(this,arguments)}function Ee(e){return Se.apply(this,arguments)}function Se(){return(Se=de(ce().m(function e(t){var r,n,a;return ce().w(function(e){for(;;)switch(e.n){case 0:if(r=te.getEmbeddedKey()){e.n=1;break}return te.sendMessageUp("EMBEDDED_PUBLIC_KEY","",t),e.a(2);case 1:return e.n=2,te.p256JWKPrivateToPublic(r);case 2:n=e.v,a=te.uint8arrayToHexString(n),te.sendMessageUp("EMBEDDED_PUBLIC_KEY",a,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function Oe(e,t,r,n){return ke.apply(this,arguments)}function ke(){return(ke=de(ce().m(function e(t,r,n,a){var o,i,c,u,s,f;return ce().w(function(e){for(;;)switch(e.n){case 0:if(i=new Uint8Array(r),"SOLANA"!==n){e.n=2;break}return c=te.uint8arrayToHexString(i.subarray(0,32)),u=te.getEd25519PublicKey(c),e.n=1,te.encodeKey(i,n,u);case 1:o=e.v,e.n=4;break;case 2:return e.n=3,te.encodeKey(i,n);case 3:o=e.v;case 4:if(s=t||"default","SOLANA"!==n){e.n=5;break}f=re.AX.fromSecretKey(te.base58Decode(o)),e.n=7;break;case 5:if("HEXADECIMAL"!==n){e.n=7;break}return e.n=6,Ye(Array.from(te.uint8arrayFromHexString(o)));case 6:f=e.v;case 7:pe=oe(oe({},pe),{},ie({},s,{organizationId:a,privateKey:o,format:n,expiry:(new Date).getTime()+864e5,keypair:f}));case 8:return e.a(2)}},e)}))).apply(this,arguments)}function Pe(e,t,r,n,a,o){return je.apply(this,arguments)}function je(){return je=de(ce().m(function e(t,r,n,a,o,i){var c;return ce().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,he(n,r,i);case 1:return c=e.v,e.n=2,Oe(o,c,a,r);case 2:te.sendMessageUp("BUNDLE_INJECTED",!0,t);case 3:return e.a(2)}},e)})),je.apply(this,arguments)}function _e(e,t){return Ie.apply(this,arguments)}function Ie(){return(Ie=de(ce().m(function e(t,r){var n;return ce().w(function(e){for(;;)switch(e.n){case 0:n=te.applySettings(t),te.setSettings(n),te.sendMessageUp("SETTINGS_APPLIED",!0,r);case 1:return e.a(2)}},e)}))).apply(this,arguments)}function xe(e,t,r){return Te.apply(this,arguments)}function Te(){return(Te=de(ce().m(function e(t,r,n){var a,o,i,c,u,s,f,l,d;return ce().w(function(e){for(;;)switch(e.n){case 0:if(ze(o=pe[a=n||"default"],a)){e.n=1;break}return e.a(2);case 1:return e.n=2,$e(o);case 2:if(i=e.v,c=JSON.parse(r),u=c.transaction,"SOLANA"!==c.type){e.n=3;break}f=te.uint8arrayFromHexString(u),(l=re.Kt.deserialize(f)).sign([i]),s=l.serialize(),e.n=4;break;case 3:throw new Error("unsupported transaction type");case 4:d=te.uint8arrayToHexString(s),te.sendMessageUp("TRANSACTION_SIGNED",d,t);case 5:return e.a(2)}},e)}))).apply(this,arguments)}function Ae(e,t,r){return Re.apply(this,arguments)}function Re(){return Re=de(ce().m(function e(t,r,o){var i,c,u,s,f,l,d,p,y,v;return ce().w(function(e){for(;;)switch(e.n){case 0:if(ze(c=pe[i=o||"default"],i)){e.n=1;break}return e.a(2);case 1:return u=JSON.parse(r),s=u.message,f=u.type,l=ve.encode(s),e.n=2,$e(c);case 2:if(p=e.v,"SOLANA"!==f){e.n=3;break}n.jn.sha512Sync=function(){var e;return a.Zf((e=n.jn).concatBytes.apply(e,arguments))},y=p.secretKey.slice(0,32),v=n._S(l,y),d=te.uint8arrayToHexString(v),e.n=4;break;case 3:return te.sendMessageUp("ERROR","unsupported message type",t),e.a(2);case 4:te.sendMessageUp("MESSAGE_SIGNED",d,t);case 5:return e.a(2)}},e)})),Re.apply(this,arguments)}function De(e,t){return Ne.apply(this,arguments)}function Ne(){return(Ne=de(ce().m(function e(t,r){return ce().w(function(e){for(;;)switch(e.n){case 0:if(r){e.n=1;break}return pe={},te.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t),e.a(2);case 1:if(pe[r]){e.n=2;break}return te.sendMessageUp("ERROR",new Error("key not found for address ".concat(r,". Note that address is case sensitive.")).toString(),t),e.a(2);case 2:delete pe[r],te.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function Me(e,t,r,n,a,o){return Ue.apply(this,arguments)}function Ue(){return Ue=de(ce().m(function e(t,r,n,a,o,i){var c,u,s,f,l;return ce().w(function(e){for(;;)switch(e.n){case 0:if(o){e.n=1;break}throw new Error("address is required for STORE_ENCRYPTED_BUNDLE");case 1:return e.n=2,ge(n,r);case 2:if(c=e.v,u=a||"HEXADECIMAL",te.setEncryptedBundle(o,{encappedPublic:c.encappedPublic,ciphertext:c.ciphertext,organizationId:r,keyFormat:u}),!ye||!i){e.n=4;break}return s=te.uint8arrayFromHexString(c.encappedPublic),f=te.uint8arrayFromHexString(c.ciphertext),e.n=3,i({ciphertextBuf:f,encappedKeyBuf:s,receiverPrivJwk:ye});case 3:return l=e.v,e.n=4,Oe(o,l,u,r);case 4:te.sendMessageUp("ENCRYPTED_BUNDLE_STORED",!0,t);case 5:return e.a(2)}},e)})),Ue.apply(this,arguments)}function Ke(e){return Ce.apply(this,arguments)}function Ce(){return(Ce=de(ce().m(function e(t){var r,n,a;return ce().w(function(e){for(;;)switch(e.n){case 0:if(32===t.length){e.n=1;break}throw new Error("invalid decryption key length: expected 32 bytes, got ".concat(t.length));case 1:return r=new Uint8Array([48,65,2,1,0,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,4,39,48,37,2,1,1,4,32]),(n=new Uint8Array(r.length+32)).set(r),n.set(t,r.length),e.n=2,crypto.subtle.importKey("pkcs8",n,{name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return a=e.v,e.n=3,crypto.subtle.exportKey("jwk",a);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function Be(e,t,r,n){return Le.apply(this,arguments)}function Le(){return Le=de(ce().m(function e(t,r,n,a){var o,i,c,u,s,f,l,d,p,y,v,b,g;return ce().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.n=1,he(n,r,a);case 1:return o=e.v,e.n=2,Ke(new Uint8Array(o));case 2:if(i=e.v,ye=i,c=te.getEncryptedBundles(),u=0,!c){e.n=9;break}s=Object.keys(c),f=0,l=s;case 3:if(!(f=e.expiry)throw function(){for(var e=(new Date).getTime(),t=[],r=0,n=Object.entries(pe);r=i.expiry&&t.push(o)}for(var c=0,u=t;c3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,d.n=y,c=0))}if(a||r>1)return i;throw l=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){o||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(et(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,et(e,a,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,et(l,"constructor",s),et(s,"constructor",u),u.displayName="GeneratorFunction",et(s,a,"GeneratorFunction"),et(l),et(l,a,"Generator"),et(l,n,function(){return this}),et(l,"toString",function(){return"[object Generator]"}),(Ze=function(){return{w:o,m:d}})()}function et(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}et=function(e,t,r,n){function o(t,r){et(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},et(e,t,r,n)}function tt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function rt(e){for(var t=1;t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,d.n=y,c=0))}if(a||r>1)return i;throw l=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){o||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(st(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,st(e,a,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,st(l,"constructor",s),st(s,"constructor",u),u.displayName="GeneratorFunction",st(s,a,"GeneratorFunction"),st(l),st(l,a,"Generator"),st(l,n,function(){return this}),st(l,"toString",function(){return"[object Generator]"}),(ut=function(){return{w:o,m:d}})()}function st(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}st=function(e,t,r,n){function o(t,r){st(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},st(e,t,r,n)}function ft(e,t,r,n,a,o,i){try{var c=e[o](i),u=c.value}catch(e){return void r(e)}c.done?t(u):Promise.resolve(u).then(n,a)}function lt(e){return function(){var t=this,r=arguments;return new Promise(function(n,a){var o=e.apply(t,r);function i(e){ft(o,n,a,i,c,"next",e)}function c(e){ft(o,n,a,i,c,"throw",e)}i(void 0)})}}window.TKHQ=te,document.addEventListener("DOMContentLoaded",lt(ut().m(function e(){var t,r,n,a;return ut().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,te.initEmbeddedKey();case 1:return e.n=2,te.getEmbeddedKey();case 2:return t=e.v,e.n=3,te.p256JWKPrivateToPublic(t);case 3:r=e.v,n=te.uint8arrayToHexString(r),document.getElementById("embedded-key").value=n,Xe(it),(a=te.getSettings())&&te.applySettings(a),te.sendMessageUp("PUBLIC_KEY_READY",n);case 4:return e.a(2)}},e)})))},790:()=>{},846:e=>{"use strict";e.exports=crypto}},i={};function c(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={id:e,loaded:!1,exports:{}};return o[e].call(r.exports,r,r.exports,c),r.loaded=!0,r.exports}c.m=o,e=[],c.O=(t,r,n,a)=>{if(!r){var o=1/0;for(f=0;f=a)&&Object.keys(c.O).every(e=>c.O[e](r[u]))?r.splice(u--,1):(i=!1,a0&&e[f-1][2]>a;f--)e[f]=e[f-1];e[f]=[r,n,a]},c.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return c.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,c.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var a=Object.create(null);c.r(a);var o={};t=t||[null,r({}),r([]),r(r)];for(var i=2&n&&e;("object"==typeof i||"function"==typeof i)&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach(t=>o[t]=()=>e[t]);return o.default=()=>e,c.d(a,o),a},c.d=(e,t)=>{for(var r in t)c.o(t,r)&&!c.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},c.f={},c.e=e=>Promise.all(Object.keys(c.f).reduce((t,r)=>(c.f[r](e,t),t),[])),c.u=e=>"bundle."+{291:"3eaea85f4001b9cc63c3",825:"aaba32bf7338e3d0f1cc"}[e]+".js",c.miniCssF=e=>{},c.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),c.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},a="export-and-sign:",c.l=(e,t,r,o)=>{if(n[e])n[e].push(t);else{var i,u;if(void 0!==r)for(var s=document.getElementsByTagName("script"),f=0;f{i.onerror=i.onload=null,clearTimeout(p);var a=n[e];if(delete n[e],i.parentNode&&i.parentNode.removeChild(i),a&&a.forEach(e=>e(r)),t)return t(r)},p=setTimeout(d.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=d.bind(null,i.onerror),i.onload=d.bind(null,i.onload),u&&document.head.appendChild(i)}},c.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),c.p="/",c.sriHashes={291:"sha384-G5pDFEAG9UZITbluyje/R/rWohZTUJf+Vu3ZIh0rsnLFLTw3SP/ca/XVNZVtv48f",825:"sha384-R9OIdd42i5GcdtZiHJuQgIUVvqyqJ0s7eaBnJHAfGllpi4YwbF7NSkjIRwOPUtsP"},(()=>{var e={792:0};c.f.j=(t,r)=>{var n=c.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[2]);else{var a=new Promise((r,a)=>n=e[t]=[r,a]);r.push(n[2]=a);var o=c.p+c.u(t),i=new Error;c.l(o,r=>{if(c.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var a=r&&("load"===r.type?"missing":r.type),o=r&&r.target&&r.target.src;i.message="Loading chunk "+t+" failed.\n("+a+": "+o+")",i.name="ChunkLoadError",i.type=a,i.request=o,n[1](i)}},"chunk-"+t,t)}},c.O.j=t=>0===e[t];var t=(t,r)=>{var n,a,[o,i,u]=r,s=0;if(o.some(t=>0!==e[t])){for(n in i)c.o(i,n)&&(c.m[n]=i[n]);if(u)var f=u(c)}for(t&&t(r);sc(560));u=c.O(u)})(); +//# sourceMappingURL=bundle.8ccdeed719db48416e34.js.map \ No newline at end of file diff --git a/export-and-sign/dist/bundle.2ddbc9eacea08f1f698a.js.LICENSE.txt b/export-and-sign/dist/bundle.8ccdeed719db48416e34.js.LICENSE.txt similarity index 100% rename from export-and-sign/dist/bundle.2ddbc9eacea08f1f698a.js.LICENSE.txt rename to export-and-sign/dist/bundle.8ccdeed719db48416e34.js.LICENSE.txt diff --git a/export-and-sign/dist/bundle.8ccdeed719db48416e34.js.map b/export-and-sign/dist/bundle.8ccdeed719db48416e34.js.map new file mode 100644 index 0000000..f7fc11f --- /dev/null +++ b/export-and-sign/dist/bundle.8ccdeed719db48416e34.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bundle.8ccdeed719db48416e34.js","mappings":";UAAIA,ECCAC,EADAC,ECAAC,EACAC,E,svCCAJ,IAAAC,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IAAAE,EAAAC,EAAAG,EAAAI,EAAA,EAAAC,EAAAX,GAAA,GAAAY,GAAA,EAAAC,EAAA,CAAAF,EAAA,EAAAb,EAAA,EAAAgB,EAAApB,EAAAqB,EAAAC,EAAAN,EAAAM,EAAAC,KAAAvB,EAAA,GAAAsB,EAAA,SAAArB,EAAAC,GAAA,OAAAM,EAAAP,EAAAQ,EAAA,EAAAG,EAAAZ,EAAAmB,EAAAf,EAAAF,EAAAmB,CAAA,YAAAC,EAAApB,EAAAE,GAAA,IAAAK,EAAAP,EAAAU,EAAAR,EAAAH,EAAA,GAAAiB,GAAAF,IAAAV,GAAAL,EAAAgB,EAAAO,OAAAvB,IAAA,KAAAK,EAAAE,EA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AO1B,EAAoBM,EAAEpY,IAG1Bwc,EAAqBC,KAAkC,4BAAIA,KAAkC,6BAAK,GACtGD,EAAmBlZ,QAAQ6Y,EAAqBhlB,KAAK,KAAM,IAC3DqlB,EAAmBpc,KAAO+b,EAAqBhlB,KAAK,KAAMqlB,EAAmBpc,KAAKjJ,KAAKqlB,G,KClFvF,IAAIE,EAAsB5E,EAAoBM,OAAE1d,EAAW,CAAC,IAAK,IAAOod,EAAoB,MAC5F4E,EAAsB5E,EAAoBM,EAAEsE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/../shared/turnkey-core.js","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/../shared/crypto-utils.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/external var \"crypto\"","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/global","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/compat","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t\tif (script.src.indexOf(window.location.origin + '/') !== 0) {\n\t\t\tscript.crossOrigin = \"anonymous\";\n\t\t}\n\t\tscript.integrity = __webpack_require__.sriHashes[chunkId];\n\t\tscript.crossOrigin = \"anonymous\";\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n return data ? JSON.parse(data) : null;\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * @param {string} address - The wallet address to remove\n */\nfunction removeEncryptedBundle(address) {\n const bundles = getEncryptedBundles();\n if (bundles && bundles[address]) {\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n }\n}\n\n/**\n * Removes all encrypted bundles from localStorage.\n */\nfunction clearAllEncryptedBundles() {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\nimport { fromDerSignature } from \"@turnkey/crypto\";\nimport * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n initEmbeddedKey: sharedInitEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n additionalAssociatedData,\n getSettings,\n setSettings,\n parsePrivateKey,\n validateStyles,\n isDoublyIframed,\n loadQuorumKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n} = SharedTKHQ;\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n return await sharedInitEmbeddedKey();\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Read environment from meta tag (templated at deploy time), fall back to window variable (for testing)\n let environment = null;\n if (typeof document !== \"undefined\") {\n const meta = document.querySelector(\n 'meta[name=\"turnkey-signer-environment\"]'\n );\n if (\n meta &&\n meta.content &&\n meta.content !== \"__TURNKEY_SIGNER_ENVIRONMENT__\"\n ) {\n environment = meta.content;\n }\n }\n if (!environment && typeof window !== \"undefined\") {\n environment = window.__TURNKEY_SIGNER_ENVIRONMENT__;\n }\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\n// Decryption key -- held in memory only, never persisted to localStorage.\n// This is a P-256 private key in JWK format used to decrypt stored bundles.\nlet decryptionKey = null;\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Verifies the enclave signature on a v1.0.0 bundle and returns the parsed signed data.\n * @param {string} bundle - JSON-stringified bundle\n * @param {string} organizationId - Expected organization ID\n * @returns {Promise} - The parsed signed data {organizationId, encappedPublic, ciphertext}\n */\nasync function verifyAndParseBundleData(bundle, organizationId) {\n const bundleObj = JSON.parse(bundle);\n\n if (bundleObj.version !== \"v1.0.0\") {\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n const verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(`failed to verify enclave signature: ${bundle}`);\n }\n\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n\n return signedData;\n}\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n // Decrypt the ciphertext\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: embeddedKeyJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Encodes raw key bytes and loads them into the in-memory key store.\n * @param {string} address - Wallet address (case-sensitive)\n * @param {ArrayBuffer} keyBytes - Raw decrypted private key bytes\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} organizationId - Organization ID\n */\nasync function loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId) {\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair,\n },\n };\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Load decrypted key into memory\n await loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId);\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Set up sha512 for nobleEd25519 (required for signing)\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n\n // Extract the 32-byte private key from the 64-byte secretKey\n // Solana keypair.secretKey format: [32-byte private key][32-byte public key]\n const privateKey = keypair.secretKey.slice(0, 32);\n // Sign the message using nobleEd25519\n const signature = nobleEd25519.sign(messageBytes, privateKey);\n\n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n/**\n * Handler for STORE_ENCRYPTED_BUNDLE events.\n * Verifies the enclave signature on an encrypted bundle and stores\n * the encrypted payload in localStorage for later decryption.\n * If the decryption key is already in memory, also decrypts and loads\n * the key into memory immediately.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle JSON\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} address - Wallet address\n * @param {Function} HpkeDecrypt\n */\nasync function onStoreEncryptedBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n if (!address) {\n throw new Error(\"address is required for STORE_ENCRYPTED_BUNDLE\");\n }\n\n // Verify enclave signature and parse the signed data\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const resolvedKeyFormat = keyFormat || \"HEXADECIMAL\";\n\n // Store the encrypted fields in localStorage (just what's needed for decryption)\n TKHQ.setEncryptedBundle(address, {\n encappedPublic: signedData.encappedPublic,\n ciphertext: signedData.ciphertext,\n organizationId: organizationId,\n keyFormat: resolvedKeyFormat,\n });\n\n // If the decryption key is already in memory, decrypt and load immediately\n if (decryptionKey && HpkeDecrypt) {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n await loadKeyIntoMemory(address, keyBytes, resolvedKeyFormat, organizationId);\n }\n\n TKHQ.sendMessageUp(\"ENCRYPTED_BUNDLE_STORED\", true, requestId);\n}\n\n/**\n * Converts raw P-256 private key bytes (32-byte scalar) to a JWK.\n * Constructs a PKCS8 wrapper around the raw bytes, imports via WebCrypto\n * (which derives the public key), then exports as JWK.\n * @param {Uint8Array} rawPrivateKeyBytes - 32-byte P-256 private key scalar\n * @returns {Promise} - Full P-256 ECDH private key JWK\n */\nasync function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) {\n if (rawPrivateKeyBytes.length !== 32) {\n throw new Error(\n `invalid decryption key length: expected 32 bytes, got ${rawPrivateKeyBytes.length}`\n );\n }\n\n // PKCS8 DER prefix for a P-256 private key (without optional public key field)\n // SEQUENCE {\n // INTEGER 0 (version)\n // SEQUENCE { OID ecPublicKey, OID P-256 }\n // OCTET STRING { SEQUENCE { INTEGER 1, OCTET STRING(32) } }\n // }\n const pkcs8Prefix = new Uint8Array([\n 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48,\n 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03,\n 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20,\n ]);\n\n const pkcs8 = new Uint8Array(pkcs8Prefix.length + 32);\n pkcs8.set(pkcs8Prefix);\n pkcs8.set(rawPrivateKeyBytes, pkcs8Prefix.length);\n\n const cryptoKey = await crypto.subtle.importKey(\n \"pkcs8\",\n pkcs8,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"]\n );\n\n return await crypto.subtle.exportKey(\"jwk\", cryptoKey);\n}\n\n/**\n * Handler for INJECT_DECRYPTION_KEY_BUNDLE events.\n * Decrypts the P-256 private key using the iframe's embedded key,\n * then iterates all stored encrypted bundles, HPKE-decrypts each one\n * with the key, and loads them into inMemoryKeys.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle containing the private key\n * @param {Function} HpkeDecrypt\n */\nasync function onInjectDecryptionKeyBundle(\n requestId,\n organizationId,\n bundle,\n HpkeDecrypt\n) {\n // Decrypt the private key using the iframe's embedded key.\n // The decrypted payload is a raw 32-byte P-256 private key scalar.\n const keyBytes = await decryptBundle(\n bundle,\n organizationId,\n HpkeDecrypt\n );\n\n // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto)\n const keyJwk = await rawP256PrivateKeyToJwk(\n new Uint8Array(keyBytes)\n );\n\n // Store in module-level variable (memory only)\n decryptionKey = keyJwk;\n\n // Iterate all stored encrypted bundles and decrypt each one\n const storedBundles = TKHQ.getEncryptedBundles();\n let decryptedCount = 0;\n\n if (storedBundles) {\n const addresses = Object.keys(storedBundles);\n\n for (const addr of addresses) {\n const bundleData = storedBundles[addr];\n\n try {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n bundleData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(\n bundleData.ciphertext\n );\n\n // HPKE-decrypt using the key\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n // Load the decrypted key into memory\n await loadKeyIntoMemory(\n addr,\n keyBytes,\n bundleData.keyFormat,\n bundleData.organizationId\n );\n\n decryptedCount++;\n } catch (e) {\n TKHQ.logMessage(\n `Failed to decrypt bundle for address ${addr}: ${e.toString()}`\n );\n }\n }\n }\n\n TKHQ.sendMessageUp(\"DECRYPTION_KEY_INJECTED\", decryptedCount, requestId);\n}\n\n/**\n * Handler for BURN_SESSION events.\n * Clears the decryption key and all in-memory wallet keys.\n * Encrypted bundles in localStorage are preserved for the next session.\n * @param {string} requestId\n */\nfunction onBurnSession(requestId) {\n decryptionKey = null;\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"SESSION_BURNED\", true, requestId);\n}\n\n/**\n * Handler for GET_STORED_WALLET_ADDRESSES events.\n * Returns a JSON array of all wallet addresses that have encrypted bundles in localStorage.\n * @param {string} requestId\n */\nfunction onGetStoredWalletAddresses(requestId) {\n const bundles = TKHQ.getEncryptedBundles();\n const addresses = bundles ? Object.keys(bundles) : [];\n TKHQ.sendMessageUp(\n \"STORED_WALLET_ADDRESSES\",\n JSON.stringify(addresses),\n requestId\n );\n}\n\n/**\n * Handler for CLEAR_STORED_BUNDLES events.\n * Removes encrypted bundles from localStorage AND the corresponding\n * in-memory keys. If address is provided, removes only that address.\n * If no address, removes ALL encrypted bundles and ALL in-memory keys.\n * @param {string} requestId\n * @param {string|undefined} address - Optional wallet address\n */\nfunction onClearStoredBundles(requestId, address) {\n if (address) {\n TKHQ.removeEncryptedBundle(address);\n delete inMemoryKeys[address];\n } else {\n TKHQ.clearAllEncryptedBundles();\n inMemoryKeys = {};\n }\n TKHQ.sendMessageUp(\"STORED_BUNDLES_CLEARED\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error(\n `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`\n ).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n undefined, // keyFormat - default to HEXADECIMAL\n undefined, // address - default to \"default\"\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"STORE_ENCRYPTED_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n await onStoreEncryptedBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_DECRYPTION_KEY_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}`\n );\n try {\n await onInjectDecryptionKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"BURN_SESSION\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onBurnSession(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_STORED_WALLET_ADDRESSES\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onGetStoredWalletAddresses(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_STORED_BUNDLES\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n onClearStoredBundles(event.data[\"requestId\"], event.data[\"address\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n onStoreEncryptedBundle,\n onInjectDecryptionKeyBundle,\n onBurnSession,\n onGetStoredWalletAddresses,\n onClearStoredBundles,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"@shared/crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n","module.exports = crypto;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","\n__webpack_require__.sriHashes = {\"291\":\"*-*-*-CHUNK-SRI-HASH-r3NPGwA4ft5fHgGXhVIptCiDVf06qPa+sxzG6L+8GwPuhn89e/\",\"825\":\"*-*-*-CHUNK-SRI-HASH-mfog3UJdGPOmSk4QZbKxsxHPFZtt298WnZNc1aQ1MCgc6YirFj\"};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(560)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","TURNKEY_ENCRYPTED_BUNDLES","parentFrameMessageChannelPort","getSubtleCrypto","globalThis","crypto","subtle","window","global","isDoublyIframed","undefined","location","ancestorOrigins","parent","top","_loadQuorumKey","_callee","quorumPublic","_context","Error","importKey","namedCurve","_initEmbeddedKey","_callee3","_context3","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee4","p256key","_context4","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","getEncryptedBundles","data","localStorage","getItem","key","ttl","item","expiry","Date","getTime","setItem","itemStr","hasOwnProperty","removeItem","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","concat","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","p256JWKPrivateToPublic","_x6","_p256JWKPrivateToPublic","_callee6","jwkPrivate","jwkPrivateCopy","publicKey","_context6","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","push","k","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee9","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_t2","_context9","set","console","warn","sharedInitEmbeddedKey","SharedTKHQ","validateStyles","styles","element","validStyles","cssValidationRegex","padding","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref","_ref2","_arrayWithHoles","next","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","loadQuorumKey","_x","_verifyEnclaveSignature","_callee2","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","meta","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context2","prod","preprod","querySelector","__TURNKEY_SIGNER_ENVIRONMENT__","fromDerSignature","verify","hash","TKHQ","initEmbeddedKey","onResetEmbeddedKey","encodeKey","_x0","_x1","_x10","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","normalizePadding","byteArray","targetLength","paddingLength","fill","expectedZeroCount","zeroCount","verifyEnclaveSignature","_x2","_x3","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","style","getSettings","setSettings","parsePrivateKey","error","setEncryptedBundle","address","bundleData","bundles","removeEncryptedBundle","keys","clearAllEncryptedBundles","_slicedToArray","inMemoryKeys","decryptionKey","textEncoder","TextEncoder","textDecoder","TextDecoder","verifyAndParseBundleData","_verifyAndParseBundleData","_callee8","bundle","organizationId","bundleObj","_context8","version","dataSignature","decode","encappedPublic","ciphertext","decryptBundle","_x4","_x5","_decryptBundle","HpkeDecrypt","encappedKeyBuf","ciphertextBuf","embeddedKeyJwk","receiverPrivJwk","onGetPublicEmbeddedKey","_onGetPublicEmbeddedKey","_callee0","targetPubBuf","targetPubHex","_context0","loadKeyIntoMemory","_x7","_x8","_x9","_loadKeyIntoMemory","_callee1","keyBytes","keyAddress","cachedKeypair","_context1","subarray","Keypair","fromSecretKey","createSolanaKeypair","_defineProperty","format","keypair","onInjectKeyBundle","_x11","_x12","_x13","_x14","_onInjectKeyBundle","_callee10","_context10","onApplySettings","_x15","_x16","_onApplySettings","_callee11","_context11","onSignTransaction","_x17","_x18","_x19","_onSignTransaction","_callee12","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context12","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x20","_x21","_x22","_onSignMessage","_callee13","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context13","encode","secretKey","onClearEmbeddedPrivateKey","_x23","_x24","_onClearEmbeddedPrivateKey","_callee14","_context14","onStoreEncryptedBundle","_x25","_x26","_x27","_x28","_x29","_x30","_onStoreEncryptedBundle","_callee15","resolvedKeyFormat","_context15","rawP256PrivateKeyToJwk","_x31","_rawP256PrivateKeyToJwk","_callee16","rawPrivateKeyBytes","pkcs8Prefix","pkcs8","cryptoKey","_context16","onInjectDecryptionKeyBundle","_x32","_x33","_x34","_x35","_onInjectDecryptionKeyBundle","_callee17","keyJwk","storedBundles","decryptedCount","addresses","_i3","_addresses","addr","_keyBytes","_t0","_context17","onBurnSession","onGetStoredWalletAddresses","onClearStoredBundles","_x36","_createSolanaKeypair","_callee18","_context18","fromSeed","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x37","_getOrCreateKeypair","_callee19","_context19","initEventHandlers","messageEventListener","_messageEventListener","event","_t","_t3","_t4","_t5","_t6","_t7","_t8","_t9","_x43","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","preventDefault","_x38","_x39","_ref3","_x40","_ref4","_x41","injectWalletBtn","_ref5","_callee5","_context5","_x42","addDOMEventListeners","capture","signal","_ref6","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x44","ownKeys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","_HpkeDecrypt","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","styleSettings","module","exports","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","g","Function","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","crossOrigin","integrity","sriHashes","onScriptComplete","prev","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/dist/index.html b/export-and-sign/dist/index.html index 338cfef..a10ff89 100644 --- a/export-and-sign/dist/index.html +++ b/export-and-sign/dist/index.html @@ -1 +1 @@ -Turnkey Export

Export Key Material

This public key will be sent along with a private key ID or wallet ID inside of a new EXPORT_PRIVATE_KEY or EXPORT_WALLET activity




Inject Key Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).





Inject Wallet Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).




Sign Transaction

Input a serialized transaction to sign.



Sign Message

Input a serialized message to sign.



Message log

Below we display a log of the messages sent / received. The forms above send messages, and the code communicates results by sending events via the postMessage API.

\ No newline at end of file +Turnkey Export

Export Key Material

This public key will be sent along with a private key ID or wallet ID inside of a new EXPORT_PRIVATE_KEY or EXPORT_WALLET activity




Inject Key Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).





Inject Wallet Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).




Sign Transaction

Input a serialized transaction to sign.



Sign Message

Input a serialized message to sign.



Message log

Below we display a log of the messages sent / received. The forms above send messages, and the code communicates results by sending events via the postMessage API.

\ No newline at end of file diff --git a/export-and-sign/index.test.js b/export-and-sign/index.test.js index b4395e8..6e6bd00 100644 --- a/export-and-sign/index.test.js +++ b/export-and-sign/index.test.js @@ -8,6 +8,11 @@ import { onInjectKeyBundle, onSignTransaction, getKeyNotFoundErrorMessage, + onStoreEncryptedBundle, + onInjectDecryptionKeyBundle, + onBurnSession, + onGetStoredWalletAddresses, + onClearStoredBundles, } from "./src/event-handlers.js"; jest.mock("@solana/web3.js", () => { @@ -852,3 +857,793 @@ describe("Event Handler Expiration Flow", () => { } }); }); + +describe("Encryption Escrow", () => { + const requestId = "test-request-id"; + const serializedTransaction = JSON.stringify({ + type: "SOLANA", + transaction: "00", + }); + + let dom; + let TKHQ; + let sendMessageSpy; + + // Mock raw 32-byte P-256 private key (escrow decryption key) + // This is what Turnkey exports after HPKE decryption - raw key bytes, not a JWK. + const mockEscrowKeyBytes = new Uint8Array(32).fill(42); + + function buildBundle(organizationId = "org-test") { + const signedData = { + organizationId, + encappedPublic: "aa", + ciphertext: "bb", + }; + + const signedDataHex = Buffer.from( + JSON.stringify(signedData), + "utf8" + ).toString("hex"); + + return JSON.stringify({ + version: "v1.0.0", + data: signedDataHex, + dataSignature: "30440220773382ac", + enclaveQuorumPublic: "04e479640d6d34", + }); + } + + beforeEach(async () => { + jest.useFakeTimers().setSystemTime(new Date("2025-01-01T00:00:00Z")); + + dom = new JSDOM( + `
`, + { + url: "http://localhost", + } + ); + + global.window = dom.window; + global.document = dom.window.document; + global.localStorage = dom.window.localStorage; + global.TextEncoder = TextEncoder; + global.TextDecoder = TextDecoder; + global.crypto = crypto.webcrypto; + + const module = await import("./src/turnkey-core.js"); + TKHQ = module.TKHQ; + dom.window.TKHQ = TKHQ; + + sendMessageSpy = jest + .spyOn(TKHQ, "sendMessageUp") + .mockImplementation(() => {}); + + jest.spyOn(TKHQ, "verifyEnclaveSignature").mockResolvedValue(true); + TKHQ.setEmbeddedKey({ foo: "bar" }); + jest.spyOn(TKHQ, "onResetEmbeddedKey").mockImplementation(() => {}); + jest.spyOn(TKHQ, "uint8arrayFromHexString").mockImplementation((hex) => { + if (typeof hex !== "string" || hex.length === 0 || hex.length % 2 !== 0) { + throw new Error("cannot create uint8array from invalid hex string"); + } + return new Uint8Array(Buffer.from(hex, "hex")); + }); + jest + .spyOn(TKHQ, "uint8arrayToHexString") + .mockImplementation((bytes) => Buffer.from(bytes).toString("hex")); + jest + .spyOn(TKHQ, "getEd25519PublicKey") + .mockReturnValue(new Uint8Array(32).fill(3)); + jest + .spyOn(TKHQ, "encodeKey") + .mockImplementation(async (keyBytes, format) => { + if (format === "SOLANA") { + return "2P3qgS5A18gGmZJmYHNxYrDYPyfm6S3dJgs8tPW6ki6i2o4yx7K8r5N8CF7JpEtQiW8mx1kSktpgyDG1xuWNzfsM"; + } + return "encoded-key-material"; + }); + jest + .spyOn(TKHQ, "parsePrivateKey") + .mockReturnValue(new Uint8Array(64).fill(5)); + }); + + afterEach(() => { + // Reset module-level state (decryptionKey + inMemoryKeys) + onBurnSession("cleanup"); + jest.useRealTimers(); + jest.restoreAllMocks(); + delete global.window; + delete global.document; + delete global.localStorage; + delete global.crypto; + }); + + describe("Encrypted Bundle Storage (TKHQ helpers)", () => { + it("returns null when no bundles stored", () => { + expect(TKHQ.getEncryptedBundles()).toBeNull(); + }); + + it("stores and retrieves an encrypted bundle", () => { + TKHQ.setEncryptedBundle("addr1", { + encappedPublic: "aa", + ciphertext: "bb", + organizationId: "org1", + keyFormat: "SOLANA", + }); + + const bundles = TKHQ.getEncryptedBundles(); + expect(bundles).not.toBeNull(); + expect(bundles["addr1"]).toEqual({ + encappedPublic: "aa", + ciphertext: "bb", + organizationId: "org1", + keyFormat: "SOLANA", + }); + }); + + it("stores multiple bundles and retrieves all", () => { + TKHQ.setEncryptedBundle("addr1", { + encappedPublic: "aa", + ciphertext: "bb", + organizationId: "org1", + keyFormat: "SOLANA", + }); + TKHQ.setEncryptedBundle("addr2", { + encappedPublic: "cc", + ciphertext: "dd", + organizationId: "org1", + keyFormat: "HEXADECIMAL", + }); + TKHQ.setEncryptedBundle("addr3", { + encappedPublic: "ee", + ciphertext: "ff", + organizationId: "org1", + keyFormat: "SOLANA", + }); + + const bundles = TKHQ.getEncryptedBundles(); + expect(Object.keys(bundles)).toHaveLength(3); + }); + + it("removes a single bundle by address", () => { + TKHQ.setEncryptedBundle("addr1", { + encappedPublic: "aa", + ciphertext: "bb", + organizationId: "org1", + keyFormat: "SOLANA", + }); + TKHQ.setEncryptedBundle("addr2", { + encappedPublic: "cc", + ciphertext: "dd", + organizationId: "org1", + keyFormat: "SOLANA", + }); + + TKHQ.removeEncryptedBundle("addr1"); + + const bundles = TKHQ.getEncryptedBundles(); + expect(bundles["addr1"]).toBeUndefined(); + expect(bundles["addr2"]).toBeDefined(); + }); + + it("clears localStorage key when last bundle removed", () => { + TKHQ.setEncryptedBundle("addr1", { + encappedPublic: "aa", + ciphertext: "bb", + organizationId: "org1", + keyFormat: "SOLANA", + }); + + TKHQ.removeEncryptedBundle("addr1"); + expect(TKHQ.getEncryptedBundles()).toBeNull(); + }); + + it("clears all bundles", () => { + TKHQ.setEncryptedBundle("addr1", { + encappedPublic: "aa", + ciphertext: "bb", + organizationId: "org1", + keyFormat: "SOLANA", + }); + TKHQ.setEncryptedBundle("addr2", { + encappedPublic: "cc", + ciphertext: "dd", + organizationId: "org1", + keyFormat: "SOLANA", + }); + + TKHQ.clearAllEncryptedBundles(); + expect(TKHQ.getEncryptedBundles()).toBeNull(); + }); + }); + + describe("STORE_ENCRYPTED_BUNDLE handler", () => { + it("verifies enclave signature and stores bundle", async () => { + await onStoreEncryptedBundle( + requestId, + "org-test", + buildBundle(), + "SOLANA", + "wallet-addr-1" + ); + + expect(sendMessageSpy).toHaveBeenCalledWith( + "ENCRYPTED_BUNDLE_STORED", + true, + requestId + ); + + const bundles = TKHQ.getEncryptedBundles(); + expect(bundles["wallet-addr-1"]).toBeDefined(); + expect(bundles["wallet-addr-1"].encappedPublic).toBe("aa"); + expect(bundles["wallet-addr-1"].ciphertext).toBe("bb"); + expect(bundles["wallet-addr-1"].organizationId).toBe("org-test"); + expect(bundles["wallet-addr-1"].keyFormat).toBe("SOLANA"); + }); + + it("rejects bundle with invalid enclave signature", async () => { + jest.spyOn(TKHQ, "verifyEnclaveSignature").mockResolvedValue(false); + + await expect( + onStoreEncryptedBundle( + requestId, + "org-test", + buildBundle(), + "SOLANA", + "wallet-addr-1" + ) + ).rejects.toThrow("failed to verify enclave signature"); + }); + + it("requires address parameter", async () => { + await expect( + onStoreEncryptedBundle( + requestId, + "org-test", + buildBundle(), + "SOLANA", + undefined + ) + ).rejects.toThrow("address is required for STORE_ENCRYPTED_BUNDLE"); + }); + + it("defaults keyFormat to HEXADECIMAL when not provided", async () => { + await onStoreEncryptedBundle( + requestId, + "org-test", + buildBundle(), + undefined, + "wallet-addr-1" + ); + + const bundles = TKHQ.getEncryptedBundles(); + expect(bundles["wallet-addr-1"].keyFormat).toBe("HEXADECIMAL"); + }); + + it("auto-decrypts and loads key into memory when decryption key is available", async () => { + // First inject a decryption key so it's in memory + let callCount = 0; + const HpkeDecryptMock = jest.fn().mockImplementation(() => { + callCount++; + if (callCount === 1) { + // Escrow key decryption + return Promise.resolve(mockEscrowKeyBytes); + } + // Wallet bundle decryption + return Promise.resolve(new Uint8Array(64).fill(9)); + }); + + await onInjectDecryptionKeyBundle( + requestId, + "org-test", + buildBundle(), + HpkeDecryptMock + ); + + // Now store a new bundle mid-session with HpkeDecrypt + await onStoreEncryptedBundle( + requestId, + "org-test", + buildBundle(), + "SOLANA", + "new-wallet", + HpkeDecryptMock + ); + + expect(sendMessageSpy).toHaveBeenCalledWith( + "ENCRYPTED_BUNDLE_STORED", + true, + requestId + ); + + // Key should be immediately signable (no need for another INJECT_DECRYPTION_KEY_BUNDLE) + await onSignTransaction(requestId, serializedTransaction, "new-wallet"); + expect(sendMessageSpy).toHaveBeenCalledWith( + "TRANSACTION_SIGNED", + expect.any(String), + requestId + ); + }); + + it("stores without decrypting when no decryption key in memory", async () => { + const HpkeDecryptMock = jest.fn(); + + await onStoreEncryptedBundle( + requestId, + "org-test", + buildBundle(), + "SOLANA", + "wallet-addr-1", + HpkeDecryptMock + ); + + // Bundle stored in localStorage + const bundles = TKHQ.getEncryptedBundles(); + expect(bundles["wallet-addr-1"]).toBeDefined(); + + // HpkeDecrypt should NOT have been called (no decryption key) + expect(HpkeDecryptMock).not.toHaveBeenCalled(); + + // Signing should fail (key not in memory) + try { + await onSignTransaction(requestId, serializedTransaction, "wallet-addr-1"); + } catch (e) { + expect(e.toString()).toContain("key bytes not found"); + } + }); + }); + + describe("INJECT_DECRYPTION_KEY_BUNDLE handler", () => { + it("decrypts escrow key and loads all stored bundles into memory", async () => { + // Pre-store 3 encrypted bundles + TKHQ.setEncryptedBundle("wallet1", { + encappedPublic: "aa", + ciphertext: "bb", + organizationId: "org-test", + keyFormat: "SOLANA", + }); + TKHQ.setEncryptedBundle("wallet2", { + encappedPublic: "cc", + ciphertext: "dd", + organizationId: "org-test", + keyFormat: "SOLANA", + }); + TKHQ.setEncryptedBundle("wallet3", { + encappedPublic: "ee", + ciphertext: "ff", + organizationId: "org-test", + keyFormat: "SOLANA", + }); + + let callCount = 0; + const HpkeDecryptMock = jest.fn().mockImplementation(() => { + callCount++; + if (callCount === 1) { + // First call: decrypting the escrow key bundle -> returns JWK bytes + return Promise.resolve( + mockEscrowKeyBytes + ); + } + // Subsequent calls: decrypting wallet bundles -> returns key bytes + return Promise.resolve(new Uint8Array(64).fill(9)); + }); + + await onInjectDecryptionKeyBundle( + requestId, + "org-test", + buildBundle(), + HpkeDecryptMock + ); + + // 1 call for escrow key + 3 calls for wallet bundles + expect(HpkeDecryptMock).toHaveBeenCalledTimes(4); + + expect(sendMessageSpy).toHaveBeenCalledWith( + "DECRYPTION_KEY_INJECTED", + 3, + requestId + ); + + // Verify keys are usable by signing + await onSignTransaction(requestId, serializedTransaction, "wallet1"); + expect(sendMessageSpy).toHaveBeenCalledWith( + "TRANSACTION_SIGNED", + expect.any(String), + requestId + ); + }); + + it("handles empty localStorage gracefully", async () => { + const HpkeDecryptMock = jest.fn().mockResolvedValue( + mockEscrowKeyBytes + ); + + await onInjectDecryptionKeyBundle( + requestId, + "org-test", + buildBundle(), + HpkeDecryptMock + ); + + // Only 1 call for the escrow key, no wallet bundles + expect(HpkeDecryptMock).toHaveBeenCalledTimes(1); + + expect(sendMessageSpy).toHaveBeenCalledWith( + "DECRYPTION_KEY_INJECTED", + 0, + requestId + ); + }); + + it("continues past individual bundle failures", async () => { + TKHQ.setEncryptedBundle("wallet1", { + encappedPublic: "aa", + ciphertext: "bb", + organizationId: "org-test", + keyFormat: "SOLANA", + }); + TKHQ.setEncryptedBundle("wallet2-bad", { + encappedPublic: "cc", + ciphertext: "dd", + organizationId: "org-test", + keyFormat: "SOLANA", + }); + TKHQ.setEncryptedBundle("wallet3", { + encappedPublic: "ee", + ciphertext: "ff", + organizationId: "org-test", + keyFormat: "SOLANA", + }); + + let callCount = 0; + const HpkeDecryptMock = jest.fn().mockImplementation(() => { + callCount++; + if (callCount === 1) { + // First call: escrow key + return Promise.resolve( + mockEscrowKeyBytes + ); + } + // Fail for the second wallet bundle (callCount 3 = wallet2-bad) + if (callCount === 3) { + return Promise.reject(new Error("decryption failed for bad bundle")); + } + return Promise.resolve(new Uint8Array(64).fill(9)); + }); + + await onInjectDecryptionKeyBundle( + requestId, + "org-test", + buildBundle(), + HpkeDecryptMock + ); + + // Should report 2 successful decryptions (wallet1 + wallet3) + expect(sendMessageSpy).toHaveBeenCalledWith( + "DECRYPTION_KEY_INJECTED", + 2, + requestId + ); + }); + + it("rejects invalid escrow key length", async () => { + // Return 16 bytes instead of 32 - invalid P-256 key length + const HpkeDecryptMock = jest + .fn() + .mockResolvedValue(new Uint8Array(16).fill(1)); + + await expect( + onInjectDecryptionKeyBundle( + requestId, + "org-test", + buildBundle(), + HpkeDecryptMock + ) + ).rejects.toThrow("invalid decryption key length"); + }); + }); + + describe("BURN_SESSION handler", () => { + it("clears in-memory keys but preserves localStorage bundles", async () => { + // Store a bundle in localStorage + TKHQ.setEncryptedBundle("wallet1", { + encappedPublic: "aa", + ciphertext: "bb", + organizationId: "org-test", + keyFormat: "SOLANA", + }); + + // Inject a key into memory via normal flow + const HpkeDecryptMock = jest + .fn() + .mockResolvedValue(new Uint8Array(64).fill(9)); + await onInjectKeyBundle( + requestId, + "org-test", + buildBundle(), + "SOLANA", + "wallet1", + HpkeDecryptMock + ); + + // Verify key is usable + await onSignTransaction(requestId, serializedTransaction, "wallet1"); + expect(sendMessageSpy).toHaveBeenCalledWith( + "TRANSACTION_SIGNED", + expect.any(String), + requestId + ); + + // Burn session + onBurnSession(requestId); + expect(sendMessageSpy).toHaveBeenCalledWith( + "SESSION_BURNED", + true, + requestId + ); + + // Signing should fail after burn + try { + await onSignTransaction(requestId, serializedTransaction, "wallet1"); + } catch (e) { + expect(e.toString()).toContain("key bytes not found"); + } + + // Encrypted bundles should still be in localStorage + const bundles = TKHQ.getEncryptedBundles(); + expect(bundles).not.toBeNull(); + expect(bundles["wallet1"]).toBeDefined(); + }); + }); + + describe("GET_STORED_WALLET_ADDRESSES handler", () => { + it("returns stored addresses as JSON array", () => { + TKHQ.setEncryptedBundle("addr1", { + encappedPublic: "aa", + ciphertext: "bb", + organizationId: "org1", + keyFormat: "SOLANA", + }); + TKHQ.setEncryptedBundle("addr2", { + encappedPublic: "cc", + ciphertext: "dd", + organizationId: "org1", + keyFormat: "SOLANA", + }); + TKHQ.setEncryptedBundle("addr3", { + encappedPublic: "ee", + ciphertext: "ff", + organizationId: "org1", + keyFormat: "SOLANA", + }); + + onGetStoredWalletAddresses(requestId); + + expect(sendMessageSpy).toHaveBeenCalledWith( + "STORED_WALLET_ADDRESSES", + JSON.stringify(["addr1", "addr2", "addr3"]), + requestId + ); + }); + + it("returns empty array when no bundles stored", () => { + onGetStoredWalletAddresses(requestId); + + expect(sendMessageSpy).toHaveBeenCalledWith( + "STORED_WALLET_ADDRESSES", + JSON.stringify([]), + requestId + ); + }); + }); + + describe("CLEAR_STORED_BUNDLES handler", () => { + it("clears a single address from localStorage and memory", async () => { + TKHQ.setEncryptedBundle("addr1", { + encappedPublic: "aa", + ciphertext: "bb", + organizationId: "org1", + keyFormat: "SOLANA", + }); + TKHQ.setEncryptedBundle("addr2", { + encappedPublic: "cc", + ciphertext: "dd", + organizationId: "org1", + keyFormat: "SOLANA", + }); + + // Load addr1 into memory via normal key injection + const HpkeDecryptMock = jest + .fn() + .mockResolvedValue(new Uint8Array(64).fill(9)); + await onInjectKeyBundle( + requestId, + "org1", + buildBundle("org1"), + "SOLANA", + "addr1", + HpkeDecryptMock + ); + + // Verify addr1 is signable + await onSignTransaction(requestId, serializedTransaction, "addr1"); + expect(sendMessageSpy).toHaveBeenCalledWith( + "TRANSACTION_SIGNED", + expect.any(String), + requestId + ); + + // Clear addr1 + onClearStoredBundles(requestId, "addr1"); + + expect(sendMessageSpy).toHaveBeenCalledWith( + "STORED_BUNDLES_CLEARED", + true, + requestId + ); + + // localStorage: addr1 gone, addr2 still present + const bundles = TKHQ.getEncryptedBundles(); + expect(bundles["addr1"]).toBeUndefined(); + expect(bundles["addr2"]).toBeDefined(); + + // Memory: signing with addr1 should fail + try { + await onSignTransaction(requestId, serializedTransaction, "addr1"); + } catch (e) { + expect(e.toString()).toContain("key bytes not found"); + } + }); + + it("clears all bundles and all in-memory keys when no address provided", async () => { + TKHQ.setEncryptedBundle("addr1", { + encappedPublic: "aa", + ciphertext: "bb", + organizationId: "org1", + keyFormat: "SOLANA", + }); + TKHQ.setEncryptedBundle("addr2", { + encappedPublic: "cc", + ciphertext: "dd", + organizationId: "org1", + keyFormat: "SOLANA", + }); + + // Load both into memory + const HpkeDecryptMock = jest + .fn() + .mockResolvedValue(new Uint8Array(64).fill(9)); + await onInjectKeyBundle( + requestId, + "org1", + buildBundle("org1"), + "SOLANA", + "addr1", + HpkeDecryptMock + ); + await onInjectKeyBundle( + requestId, + "org1", + buildBundle("org1"), + "SOLANA", + "addr2", + HpkeDecryptMock + ); + + // Clear all + onClearStoredBundles(requestId, undefined); + + expect(sendMessageSpy).toHaveBeenCalledWith( + "STORED_BUNDLES_CLEARED", + true, + requestId + ); + expect(TKHQ.getEncryptedBundles()).toBeNull(); + + // Memory: signing with either address should fail + try { + await onSignTransaction(requestId, serializedTransaction, "addr1"); + } catch (e) { + expect(e.toString()).toContain("key bytes not found"); + } + try { + await onSignTransaction(requestId, serializedTransaction, "addr2"); + } catch (e) { + expect(e.toString()).toContain("key bytes not found"); + } + }); + }); + + describe("Full Escrow Lifecycle", () => { + it("store -> decrypt -> sign -> burn -> re-decrypt -> sign", async () => { + // 1. Store 2 encrypted bundles + await onStoreEncryptedBundle( + requestId, + "org-test", + buildBundle(), + "SOLANA", + "wallet-a" + ); + await onStoreEncryptedBundle( + requestId, + "org-test", + buildBundle(), + "SOLANA", + "wallet-b" + ); + + expect(TKHQ.getEncryptedBundles()).not.toBeNull(); + expect(Object.keys(TKHQ.getEncryptedBundles())).toHaveLength(2); + + // 2. Inject decryption key -> decrypt all bundles + let callCount = 0; + const HpkeDecryptMock = jest.fn().mockImplementation(() => { + callCount++; + if (callCount === 1) { + return Promise.resolve( + mockEscrowKeyBytes + ); + } + return Promise.resolve(new Uint8Array(64).fill(9)); + }); + + await onInjectDecryptionKeyBundle( + requestId, + "org-test", + buildBundle(), + HpkeDecryptMock + ); + + expect(sendMessageSpy).toHaveBeenCalledWith( + "DECRYPTION_KEY_INJECTED", + 2, + requestId + ); + + // 3. Sign a transaction + await onSignTransaction(requestId, serializedTransaction, "wallet-a"); + expect(sendMessageSpy).toHaveBeenCalledWith( + "TRANSACTION_SIGNED", + expect.any(String), + requestId + ); + + // 4. Burn session + onBurnSession(requestId); + expect(sendMessageSpy).toHaveBeenCalledWith( + "SESSION_BURNED", + true, + requestId + ); + + // Signing should fail after burn + try { + await onSignTransaction(requestId, serializedTransaction, "wallet-a"); + } catch (e) { + expect(e.toString()).toContain("key bytes not found"); + } + + // 5. Re-inject decryption key (bundles survived the burn) + callCount = 0; + await onInjectDecryptionKeyBundle( + requestId, + "org-test", + buildBundle(), + HpkeDecryptMock + ); + + expect(sendMessageSpy).toHaveBeenCalledWith( + "DECRYPTION_KEY_INJECTED", + 2, + requestId + ); + + // 6. Sign again - should work + await onSignTransaction(requestId, serializedTransaction, "wallet-b"); + expect(sendMessageSpy).toHaveBeenCalledWith( + "TRANSACTION_SIGNED", + expect.any(String), + requestId + ); + }); + }); +}); diff --git a/export-and-sign/src/event-handlers.js b/export-and-sign/src/event-handlers.js index bbfdf5b..a06e5da 100644 --- a/export-and-sign/src/event-handlers.js +++ b/export-and-sign/src/event-handlers.js @@ -6,12 +6,77 @@ import * as nobleHashes from "@noble/hashes/sha512"; // Persist keys in memory via mapping of { address --> pk } let inMemoryKeys = {}; +// Decryption key -- held in memory only, never persisted to localStorage. +// This is a P-256 private key in JWK format used to decrypt stored bundles. +let decryptionKey = null; + export const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds // Instantiate these once (for perf) const textEncoder = new TextEncoder(); const textDecoder = new TextDecoder(); +/** + * Verifies the enclave signature on a v1.0.0 bundle and returns the parsed signed data. + * @param {string} bundle - JSON-stringified bundle + * @param {string} organizationId - Expected organization ID + * @returns {Promise} - The parsed signed data {organizationId, encappedPublic, ciphertext} + */ +async function verifyAndParseBundleData(bundle, organizationId) { + const bundleObj = JSON.parse(bundle); + + if (bundleObj.version !== "v1.0.0") { + throw new Error(`unsupported version: ${bundleObj.version}`); + } + if (!bundleObj.data) { + throw new Error('missing "data" in bundle'); + } + if (!bundleObj.dataSignature) { + throw new Error('missing "dataSignature" in bundle'); + } + if (!bundleObj.enclaveQuorumPublic) { + throw new Error('missing "enclaveQuorumPublic" in bundle'); + } + + if (!TKHQ.verifyEnclaveSignature) { + throw new Error("method not loaded"); + } + const verified = await TKHQ.verifyEnclaveSignature( + bundleObj.enclaveQuorumPublic, + bundleObj.dataSignature, + bundleObj.data + ); + if (!verified) { + throw new Error(`failed to verify enclave signature: ${bundle}`); + } + + const signedData = JSON.parse( + textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data)) + ); + + if (!organizationId) { + throw new Error( + `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass "organizationId" for security purposes.` + ); + } else if ( + !signedData.organizationId || + signedData.organizationId !== organizationId + ) { + throw new Error( + `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.` + ); + } + + if (!signedData.encappedPublic) { + throw new Error('missing "encappedPublic" in bundle signed data'); + } + if (!signedData.ciphertext) { + throw new Error('missing "ciphertext" in bundle signed data'); + } + + return signedData; +} + /** * Parse and decrypt the export bundle. * The `bundle` param is a JSON string of the encapsulated public @@ -21,73 +86,12 @@ const textDecoder = new TextDecoder(); * @param {Function} HpkeDecrypt */ async function decryptBundle(bundle, organizationId, HpkeDecrypt) { - let encappedKeyBuf; - let ciphertextBuf; - let verified; + const signedData = await verifyAndParseBundleData(bundle, organizationId); - // Parse the import bundle - const bundleObj = JSON.parse(bundle); - switch (bundleObj.version) { - case "v1.0.0": - // Validate fields exist - if (!bundleObj.data) { - throw new Error('missing "data" in bundle'); - } - if (!bundleObj.dataSignature) { - throw new Error('missing "dataSignature" in bundle'); - } - if (!bundleObj.enclaveQuorumPublic) { - throw new Error('missing "enclaveQuorumPublic" in bundle'); - } - - // Verify enclave signature - if (!TKHQ.verifyEnclaveSignature) { - throw new Error("method not loaded"); - } - verified = await TKHQ.verifyEnclaveSignature( - bundleObj.enclaveQuorumPublic, - bundleObj.dataSignature, - bundleObj.data - ); - if (!verified) { - throw new Error(`failed to verify enclave signature: ${bundle}`); - } - - // Parse the signed data. The data is produced by JSON encoding followed by hex encoding. We reverse this here. - { - const signedData = JSON.parse( - textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data)) - ); - - // Validate fields match - if (!organizationId) { - throw new Error( - `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass "organizationId" for security purposes.` - ); - } else if ( - !signedData.organizationId || - signedData.organizationId !== organizationId - ) { - throw new Error( - `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.` - ); - } - - if (!signedData.encappedPublic) { - throw new Error('missing "encappedPublic" in bundle signed data'); - } - if (!signedData.ciphertext) { - throw new Error('missing "ciphertext" in bundle signed data'); - } - encappedKeyBuf = TKHQ.uint8arrayFromHexString( - signedData.encappedPublic - ); - ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext); - } - break; - default: - throw new Error(`unsupported version: ${bundleObj.version}`); - } + const encappedKeyBuf = TKHQ.uint8arrayFromHexString( + signedData.encappedPublic + ); + const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext); // Decrypt the ciphertext const embeddedKeyJwk = await TKHQ.getEmbeddedKey(); @@ -119,26 +123,13 @@ async function onGetPublicEmbeddedKey(requestId) { } /** - * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received. - * @param {string} requestId - * @param {string} organizationId - * @param {string} bundle - * @param {string} keyFormat - * @param {string} address - * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around) + * Encodes raw key bytes and loads them into the in-memory key store. + * @param {string} address - Wallet address (case-sensitive) + * @param {ArrayBuffer} keyBytes - Raw decrypted private key bytes + * @param {string} keyFormat - "SOLANA" | "HEXADECIMAL" + * @param {string} organizationId - Organization ID */ -async function onInjectKeyBundle( - requestId, - organizationId, - bundle, - keyFormat, - address, - HpkeDecrypt -) { - // Decrypt the export bundle - const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt); - - // Parse the decrypted key bytes +async function loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId) { let key; const privateKeyBytes = new Uint8Array(keyBytes); @@ -152,8 +143,6 @@ async function onInjectKeyBundle( key = await TKHQ.encodeKey(privateKeyBytes, keyFormat); } - // Set in memory - // If no address provided, use a default key const keyAddress = address || "default"; // Cache keypair for improved signing perf @@ -173,9 +162,33 @@ async function onInjectKeyBundle( privateKey: key, format: keyFormat, expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS, - keypair: cachedKeypair, // Cache the keypair for performance + keypair: cachedKeypair, }, }; +} + +/** + * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received. + * @param {string} requestId + * @param {string} organizationId + * @param {string} bundle + * @param {string} keyFormat + * @param {string} address + * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around) + */ +async function onInjectKeyBundle( + requestId, + organizationId, + bundle, + keyFormat, + address, + HpkeDecrypt +) { + // Decrypt the export bundle + const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt); + + // Load decrypted key into memory + await loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId); // Send up BUNDLE_INJECTED message TKHQ.sendMessageUp("BUNDLE_INJECTED", true, requestId); @@ -324,6 +337,227 @@ async function onClearEmbeddedPrivateKey(requestId, address) { TKHQ.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED", true, requestId); } +/** + * Handler for STORE_ENCRYPTED_BUNDLE events. + * Verifies the enclave signature on an encrypted bundle and stores + * the encrypted payload in localStorage for later decryption. + * If the decryption key is already in memory, also decrypts and loads + * the key into memory immediately. + * @param {string} requestId + * @param {string} organizationId + * @param {string} bundle - v1.0.0 bundle JSON + * @param {string} keyFormat - "SOLANA" | "HEXADECIMAL" + * @param {string} address - Wallet address + * @param {Function} HpkeDecrypt + */ +async function onStoreEncryptedBundle( + requestId, + organizationId, + bundle, + keyFormat, + address, + HpkeDecrypt +) { + if (!address) { + throw new Error("address is required for STORE_ENCRYPTED_BUNDLE"); + } + + // Verify enclave signature and parse the signed data + const signedData = await verifyAndParseBundleData(bundle, organizationId); + + const resolvedKeyFormat = keyFormat || "HEXADECIMAL"; + + // Store the encrypted fields in localStorage (just what's needed for decryption) + TKHQ.setEncryptedBundle(address, { + encappedPublic: signedData.encappedPublic, + ciphertext: signedData.ciphertext, + organizationId: organizationId, + keyFormat: resolvedKeyFormat, + }); + + // If the decryption key is already in memory, decrypt and load immediately + if (decryptionKey && HpkeDecrypt) { + const encappedKeyBuf = TKHQ.uint8arrayFromHexString( + signedData.encappedPublic + ); + const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext); + + const keyBytes = await HpkeDecrypt({ + ciphertextBuf, + encappedKeyBuf, + receiverPrivJwk: decryptionKey, + }); + + await loadKeyIntoMemory(address, keyBytes, resolvedKeyFormat, organizationId); + } + + TKHQ.sendMessageUp("ENCRYPTED_BUNDLE_STORED", true, requestId); +} + +/** + * Converts raw P-256 private key bytes (32-byte scalar) to a JWK. + * Constructs a PKCS8 wrapper around the raw bytes, imports via WebCrypto + * (which derives the public key), then exports as JWK. + * @param {Uint8Array} rawPrivateKeyBytes - 32-byte P-256 private key scalar + * @returns {Promise} - Full P-256 ECDH private key JWK + */ +async function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) { + if (rawPrivateKeyBytes.length !== 32) { + throw new Error( + `invalid decryption key length: expected 32 bytes, got ${rawPrivateKeyBytes.length}` + ); + } + + // PKCS8 DER prefix for a P-256 private key (without optional public key field) + // SEQUENCE { + // INTEGER 0 (version) + // SEQUENCE { OID ecPublicKey, OID P-256 } + // OCTET STRING { SEQUENCE { INTEGER 1, OCTET STRING(32) } } + // } + const pkcs8Prefix = new Uint8Array([ + 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, + 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, + 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20, + ]); + + const pkcs8 = new Uint8Array(pkcs8Prefix.length + 32); + pkcs8.set(pkcs8Prefix); + pkcs8.set(rawPrivateKeyBytes, pkcs8Prefix.length); + + const cryptoKey = await crypto.subtle.importKey( + "pkcs8", + pkcs8, + { name: "ECDH", namedCurve: "P-256" }, + true, + ["deriveBits"] + ); + + return await crypto.subtle.exportKey("jwk", cryptoKey); +} + +/** + * Handler for INJECT_DECRYPTION_KEY_BUNDLE events. + * Decrypts the P-256 private key using the iframe's embedded key, + * then iterates all stored encrypted bundles, HPKE-decrypts each one + * with the key, and loads them into inMemoryKeys. + * @param {string} requestId + * @param {string} organizationId + * @param {string} bundle - v1.0.0 bundle containing the private key + * @param {Function} HpkeDecrypt + */ +async function onInjectDecryptionKeyBundle( + requestId, + organizationId, + bundle, + HpkeDecrypt +) { + // Decrypt the private key using the iframe's embedded key. + // The decrypted payload is a raw 32-byte P-256 private key scalar. + const keyBytes = await decryptBundle( + bundle, + organizationId, + HpkeDecrypt + ); + + // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto) + const keyJwk = await rawP256PrivateKeyToJwk( + new Uint8Array(keyBytes) + ); + + // Store in module-level variable (memory only) + decryptionKey = keyJwk; + + // Iterate all stored encrypted bundles and decrypt each one + const storedBundles = TKHQ.getEncryptedBundles(); + let decryptedCount = 0; + + if (storedBundles) { + const addresses = Object.keys(storedBundles); + + for (const addr of addresses) { + const bundleData = storedBundles[addr]; + + try { + const encappedKeyBuf = TKHQ.uint8arrayFromHexString( + bundleData.encappedPublic + ); + const ciphertextBuf = TKHQ.uint8arrayFromHexString( + bundleData.ciphertext + ); + + // HPKE-decrypt using the key + const keyBytes = await HpkeDecrypt({ + ciphertextBuf, + encappedKeyBuf, + receiverPrivJwk: decryptionKey, + }); + + // Load the decrypted key into memory + await loadKeyIntoMemory( + addr, + keyBytes, + bundleData.keyFormat, + bundleData.organizationId + ); + + decryptedCount++; + } catch (e) { + TKHQ.logMessage( + `Failed to decrypt bundle for address ${addr}: ${e.toString()}` + ); + } + } + } + + TKHQ.sendMessageUp("DECRYPTION_KEY_INJECTED", decryptedCount, requestId); +} + +/** + * Handler for BURN_SESSION events. + * Clears the decryption key and all in-memory wallet keys. + * Encrypted bundles in localStorage are preserved for the next session. + * @param {string} requestId + */ +function onBurnSession(requestId) { + decryptionKey = null; + inMemoryKeys = {}; + TKHQ.sendMessageUp("SESSION_BURNED", true, requestId); +} + +/** + * Handler for GET_STORED_WALLET_ADDRESSES events. + * Returns a JSON array of all wallet addresses that have encrypted bundles in localStorage. + * @param {string} requestId + */ +function onGetStoredWalletAddresses(requestId) { + const bundles = TKHQ.getEncryptedBundles(); + const addresses = bundles ? Object.keys(bundles) : []; + TKHQ.sendMessageUp( + "STORED_WALLET_ADDRESSES", + JSON.stringify(addresses), + requestId + ); +} + +/** + * Handler for CLEAR_STORED_BUNDLES events. + * Removes encrypted bundles from localStorage AND the corresponding + * in-memory keys. If address is provided, removes only that address. + * If no address, removes ALL encrypted bundles and ALL in-memory keys. + * @param {string} requestId + * @param {string|undefined} address - Optional wallet address + */ +function onClearStoredBundles(requestId, address) { + if (address) { + TKHQ.removeEncryptedBundle(address); + delete inMemoryKeys[address]; + } else { + TKHQ.clearAllEncryptedBundles(); + inMemoryKeys = {}; + } + TKHQ.sendMessageUp("STORED_BUNDLES_CLEARED", true, requestId); +} + // Utility functions async function createSolanaKeypair(privateKey) { const privateKeyBytes = TKHQ.parsePrivateKey(privateKey); @@ -599,6 +833,64 @@ function initMessageEventListener(HpkeDecrypt) { TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); } } + if (event.data && event.data["type"] == "STORE_ENCRYPTED_BUNDLE") { + TKHQ.logMessage( + `⬇️ Received message ${event.data["type"]}: address=${event.data["address"]}` + ); + try { + await onStoreEncryptedBundle( + event.data["requestId"], + event.data["organizationId"], + event.data["value"], + event.data["keyFormat"], + event.data["address"], + HpkeDecrypt + ); + } catch (e) { + TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); + } + } + if (event.data && event.data["type"] == "INJECT_DECRYPTION_KEY_BUNDLE") { + TKHQ.logMessage( + `⬇️ Received message ${event.data["type"]}` + ); + try { + await onInjectDecryptionKeyBundle( + event.data["requestId"], + event.data["organizationId"], + event.data["value"], + HpkeDecrypt + ); + } catch (e) { + TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); + } + } + if (event.data && event.data["type"] == "BURN_SESSION") { + TKHQ.logMessage(`⬇️ Received message ${event.data["type"]}`); + try { + onBurnSession(event.data["requestId"]); + } catch (e) { + TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); + } + } + if (event.data && event.data["type"] == "GET_STORED_WALLET_ADDRESSES") { + TKHQ.logMessage(`⬇️ Received message ${event.data["type"]}`); + try { + onGetStoredWalletAddresses(event.data["requestId"]); + } catch (e) { + TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); + } + } + if (event.data && event.data["type"] == "CLEAR_STORED_BUNDLES") { + TKHQ.logMessage( + `⬇️ Received message ${event.data["type"]}: address=${event.data["address"]}` + ); + try { + onClearStoredBundles(event.data["requestId"], event.data["address"]); + } catch (e) { + TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); + } + } }; } @@ -670,4 +962,9 @@ export { onSignTransaction, onSignMessage, onClearEmbeddedPrivateKey, + onStoreEncryptedBundle, + onInjectDecryptionKeyBundle, + onBurnSession, + onGetStoredWalletAddresses, + onClearStoredBundles, }; diff --git a/export-and-sign/src/turnkey-core.js b/export-and-sign/src/turnkey-core.js index 8c79de7..6b90f04 100644 --- a/export-and-sign/src/turnkey-core.js +++ b/export-and-sign/src/turnkey-core.js @@ -28,6 +28,10 @@ const { validateStyles, isDoublyIframed, loadQuorumKey, + getEncryptedBundles, + setEncryptedBundle, + removeEncryptedBundle, + clearAllEncryptedBundles, } = SharedTKHQ; /** @@ -177,4 +181,8 @@ export const TKHQ = { getSettings, setSettings, parsePrivateKey, + getEncryptedBundles, + setEncryptedBundle, + removeEncryptedBundle, + clearAllEncryptedBundles, }; diff --git a/shared/turnkey-core.js b/shared/turnkey-core.js index 131ca98..8bde880 100644 --- a/shared/turnkey-core.js +++ b/shared/turnkey-core.js @@ -9,6 +9,7 @@ import { bech32 } from "bech32"; const TURNKEY_EMBEDDED_KEY = "TURNKEY_EMBEDDED_KEY"; const TURNKEY_TARGET_EMBEDDED_KEY = "TURNKEY_TARGET_EMBEDDED_KEY"; const TURNKEY_SETTINGS = "TURNKEY_SETTINGS"; +const TURNKEY_ENCRYPTED_BUNDLES = "TURNKEY_ENCRYPTED_BUNDLES"; /** 48 hours in milliseconds */ const TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48; const TURNKEY_EMBEDDED_KEY_ORIGIN = "TURNKEY_EMBEDDED_KEY_ORIGIN"; @@ -214,6 +215,57 @@ function setSettings(settings) { window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings)); } +/** + * Gets all encrypted bundles from localStorage. + * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat} + * or null if no bundles are stored. + * @returns {Object|null} + */ +function getEncryptedBundles() { + const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES); + return data ? JSON.parse(data) : null; +} + +/** + * Stores or updates an encrypted bundle for a given address. + * @param {string} address - The wallet address + * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat} + */ +function setEncryptedBundle(address, bundleData) { + const bundles = getEncryptedBundles() || {}; + bundles[address] = bundleData; + window.localStorage.setItem( + TURNKEY_ENCRYPTED_BUNDLES, + JSON.stringify(bundles) + ); +} + +/** + * Removes a single encrypted bundle by address. + * @param {string} address - The wallet address to remove + */ +function removeEncryptedBundle(address) { + const bundles = getEncryptedBundles(); + if (bundles && bundles[address]) { + delete bundles[address]; + if (Object.keys(bundles).length === 0) { + window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES); + } else { + window.localStorage.setItem( + TURNKEY_ENCRYPTED_BUNDLES, + JSON.stringify(bundles) + ); + } + } +} + +/** + * Removes all encrypted bundles from localStorage. + */ +function clearAllEncryptedBundles() { + window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES); +} + /** * Set an item in localStorage with an expiration time * @param {string} key @@ -931,4 +983,8 @@ export { encodeKey, parsePrivateKey, validateStyles, + getEncryptedBundles, + setEncryptedBundle, + removeEncryptedBundle, + clearAllEncryptedBundles, }; From 1fb0969ddd0bc29e6cdd0cc1da8dba476fe4507c Mon Sep 17 00:00:00 2001 From: Ethan Konkolowicz Date: Wed, 11 Feb 2026 19:50:29 -0500 Subject: [PATCH 2/7] prettier --- .../dist/bundle.8ccdeed719db48416e34.js.map | 2 +- export-and-sign/index.test.js | 22 ++++++++----------- export-and-sign/src/event-handlers.js | 21 ++++++++---------- .../551.bundle.27da59437a4e403e3c24.js.map | 2 +- 4 files changed, 20 insertions(+), 27 deletions(-) diff --git a/export-and-sign/dist/bundle.8ccdeed719db48416e34.js.map b/export-and-sign/dist/bundle.8ccdeed719db48416e34.js.map index f7fc11f..62355ac 100644 --- a/export-and-sign/dist/bundle.8ccdeed719db48416e34.js.map +++ b/export-and-sign/dist/bundle.8ccdeed719db48416e34.js.map @@ -1 +1 @@ -{"version":3,"file":"bundle.8ccdeed719db48416e34.js","mappings":";UAAIA,ECCAC,EADAC,ECAAC,EACAC,E,svCCAJ,IAAAC,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EA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GAHTnB,EAAUgE,EAAaC,GAAW3f,EAGhBvG,EAAI,EAC3B,GAAGiiB,EAASkE,KAAMtE,GAAgC,IAAxB2D,EAAgB3D,IAAa,CACtD,IAAIF,KAAYsE,EACZvE,EAAoB5hB,EAAEmmB,EAAatE,KACrCD,EAAoB5f,EAAE6f,GAAYsE,EAAYtE,IAGhD,GAAGuE,EAAS,IAAItc,EAASsc,EAAQxE,EAClC,CAEA,IADGsE,GAA4BA,EAA2Bzf,GACrDvG,EAAIiiB,EAASjhB,OAAQhB,IACzBojB,EAAUnB,EAASjiB,GAChB0hB,EAAoB5hB,EAAE0lB,EAAiBpC,IAAYoC,EAAgBpC,IACrEoC,EAAgBpC,GAAS,KAE1BoC,EAAgBpC,GAAW,EAE5B,OAAO1B,EAAoBM,EAAEpY,IAG1Bwc,EAAqBC,KAAkC,4BAAIA,KAAkC,6BAAK,GACtGD,EAAmBlZ,QAAQ6Y,EAAqBhlB,KAAK,KAAM,IAC3DqlB,EAAmBpc,KAAO+b,EAAqBhlB,KAAK,KAAMqlB,EAAmBpc,KAAKjJ,KAAKqlB,G,KClFvF,IAAIE,EAAsB5E,EAAoBM,OAAE1d,EAAW,CAAC,IAAK,IAAOod,EAAoB,MAC5F4E,EAAsB5E,EAAoBM,EAAEsE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/../shared/turnkey-core.js","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/../shared/crypto-utils.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/external var \"crypto\"","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/global","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/compat","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t\tif (script.src.indexOf(window.location.origin + '/') !== 0) {\n\t\t\tscript.crossOrigin = \"anonymous\";\n\t\t}\n\t\tscript.integrity = __webpack_require__.sriHashes[chunkId];\n\t\tscript.crossOrigin = \"anonymous\";\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n return data ? JSON.parse(data) : null;\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * @param {string} address - The wallet address to remove\n */\nfunction removeEncryptedBundle(address) {\n const bundles = getEncryptedBundles();\n if (bundles && bundles[address]) {\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n }\n}\n\n/**\n * Removes all encrypted bundles from localStorage.\n */\nfunction clearAllEncryptedBundles() {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\nimport { fromDerSignature } from \"@turnkey/crypto\";\nimport * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n initEmbeddedKey: sharedInitEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n additionalAssociatedData,\n getSettings,\n setSettings,\n parsePrivateKey,\n validateStyles,\n isDoublyIframed,\n loadQuorumKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n} = SharedTKHQ;\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n return await sharedInitEmbeddedKey();\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Read environment from meta tag (templated at deploy time), fall back to window variable (for testing)\n let environment = null;\n if (typeof document !== \"undefined\") {\n const meta = document.querySelector(\n 'meta[name=\"turnkey-signer-environment\"]'\n );\n if (\n meta &&\n meta.content &&\n meta.content !== \"__TURNKEY_SIGNER_ENVIRONMENT__\"\n ) {\n environment = meta.content;\n }\n }\n if (!environment && typeof window !== \"undefined\") {\n environment = window.__TURNKEY_SIGNER_ENVIRONMENT__;\n }\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\n// Decryption key -- held in memory only, never persisted to localStorage.\n// This is a P-256 private key in JWK format used to decrypt stored bundles.\nlet decryptionKey = null;\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Verifies the enclave signature on a v1.0.0 bundle and returns the parsed signed data.\n * @param {string} bundle - JSON-stringified bundle\n * @param {string} organizationId - Expected organization ID\n * @returns {Promise} - The parsed signed data {organizationId, encappedPublic, ciphertext}\n */\nasync function verifyAndParseBundleData(bundle, organizationId) {\n const bundleObj = JSON.parse(bundle);\n\n if (bundleObj.version !== \"v1.0.0\") {\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n const verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(`failed to verify enclave signature: ${bundle}`);\n }\n\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n\n return signedData;\n}\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n // Decrypt the ciphertext\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: embeddedKeyJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Encodes raw key bytes and loads them into the in-memory key store.\n * @param {string} address - Wallet address (case-sensitive)\n * @param {ArrayBuffer} keyBytes - Raw decrypted private key bytes\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} organizationId - Organization ID\n */\nasync function loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId) {\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair,\n },\n };\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Load decrypted key into memory\n await loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId);\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Set up sha512 for nobleEd25519 (required for signing)\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n\n // Extract the 32-byte private key from the 64-byte secretKey\n // Solana keypair.secretKey format: [32-byte private key][32-byte public key]\n const privateKey = keypair.secretKey.slice(0, 32);\n // Sign the message using nobleEd25519\n const signature = nobleEd25519.sign(messageBytes, privateKey);\n\n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n/**\n * Handler for STORE_ENCRYPTED_BUNDLE events.\n * Verifies the enclave signature on an encrypted bundle and stores\n * the encrypted payload in localStorage for later decryption.\n * If the decryption key is already in memory, also decrypts and loads\n * the key into memory immediately.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle JSON\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} address - Wallet address\n * @param {Function} HpkeDecrypt\n */\nasync function onStoreEncryptedBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n if (!address) {\n throw new Error(\"address is required for STORE_ENCRYPTED_BUNDLE\");\n }\n\n // Verify enclave signature and parse the signed data\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const resolvedKeyFormat = keyFormat || \"HEXADECIMAL\";\n\n // Store the encrypted fields in localStorage (just what's needed for decryption)\n TKHQ.setEncryptedBundle(address, {\n encappedPublic: signedData.encappedPublic,\n ciphertext: signedData.ciphertext,\n organizationId: organizationId,\n keyFormat: resolvedKeyFormat,\n });\n\n // If the decryption key is already in memory, decrypt and load immediately\n if (decryptionKey && HpkeDecrypt) {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n await loadKeyIntoMemory(address, keyBytes, resolvedKeyFormat, organizationId);\n }\n\n TKHQ.sendMessageUp(\"ENCRYPTED_BUNDLE_STORED\", true, requestId);\n}\n\n/**\n * Converts raw P-256 private key bytes (32-byte scalar) to a JWK.\n * Constructs a PKCS8 wrapper around the raw bytes, imports via WebCrypto\n * (which derives the public key), then exports as JWK.\n * @param {Uint8Array} rawPrivateKeyBytes - 32-byte P-256 private key scalar\n * @returns {Promise} - Full P-256 ECDH private key JWK\n */\nasync function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) {\n if (rawPrivateKeyBytes.length !== 32) {\n throw new Error(\n `invalid decryption key length: expected 32 bytes, got ${rawPrivateKeyBytes.length}`\n );\n }\n\n // PKCS8 DER prefix for a P-256 private key (without optional public key field)\n // SEQUENCE {\n // INTEGER 0 (version)\n // SEQUENCE { OID ecPublicKey, OID P-256 }\n // OCTET STRING { SEQUENCE { INTEGER 1, OCTET STRING(32) } }\n // }\n const pkcs8Prefix = new Uint8Array([\n 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48,\n 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03,\n 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20,\n ]);\n\n const pkcs8 = new Uint8Array(pkcs8Prefix.length + 32);\n pkcs8.set(pkcs8Prefix);\n pkcs8.set(rawPrivateKeyBytes, pkcs8Prefix.length);\n\n const cryptoKey = await crypto.subtle.importKey(\n \"pkcs8\",\n pkcs8,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"]\n );\n\n return await crypto.subtle.exportKey(\"jwk\", cryptoKey);\n}\n\n/**\n * Handler for INJECT_DECRYPTION_KEY_BUNDLE events.\n * Decrypts the P-256 private key using the iframe's embedded key,\n * then iterates all stored encrypted bundles, HPKE-decrypts each one\n * with the key, and loads them into inMemoryKeys.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle containing the private key\n * @param {Function} HpkeDecrypt\n */\nasync function onInjectDecryptionKeyBundle(\n requestId,\n organizationId,\n bundle,\n HpkeDecrypt\n) {\n // Decrypt the private key using the iframe's embedded key.\n // The decrypted payload is a raw 32-byte P-256 private key scalar.\n const keyBytes = await decryptBundle(\n bundle,\n organizationId,\n HpkeDecrypt\n );\n\n // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto)\n const keyJwk = await rawP256PrivateKeyToJwk(\n new Uint8Array(keyBytes)\n );\n\n // Store in module-level variable (memory only)\n decryptionKey = keyJwk;\n\n // Iterate all stored encrypted bundles and decrypt each one\n const storedBundles = TKHQ.getEncryptedBundles();\n let decryptedCount = 0;\n\n if (storedBundles) {\n const addresses = Object.keys(storedBundles);\n\n for (const addr of addresses) {\n const bundleData = storedBundles[addr];\n\n try {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n bundleData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(\n bundleData.ciphertext\n );\n\n // HPKE-decrypt using the key\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n // Load the decrypted key into memory\n await loadKeyIntoMemory(\n addr,\n keyBytes,\n bundleData.keyFormat,\n bundleData.organizationId\n );\n\n decryptedCount++;\n } catch (e) {\n TKHQ.logMessage(\n `Failed to decrypt bundle for address ${addr}: ${e.toString()}`\n );\n }\n }\n }\n\n TKHQ.sendMessageUp(\"DECRYPTION_KEY_INJECTED\", decryptedCount, requestId);\n}\n\n/**\n * Handler for BURN_SESSION events.\n * Clears the decryption key and all in-memory wallet keys.\n * Encrypted bundles in localStorage are preserved for the next session.\n * @param {string} requestId\n */\nfunction onBurnSession(requestId) {\n decryptionKey = null;\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"SESSION_BURNED\", true, requestId);\n}\n\n/**\n * Handler for GET_STORED_WALLET_ADDRESSES events.\n * Returns a JSON array of all wallet addresses that have encrypted bundles in localStorage.\n * @param {string} requestId\n */\nfunction onGetStoredWalletAddresses(requestId) {\n const bundles = TKHQ.getEncryptedBundles();\n const addresses = bundles ? Object.keys(bundles) : [];\n TKHQ.sendMessageUp(\n \"STORED_WALLET_ADDRESSES\",\n JSON.stringify(addresses),\n requestId\n );\n}\n\n/**\n * Handler for CLEAR_STORED_BUNDLES events.\n * Removes encrypted bundles from localStorage AND the corresponding\n * in-memory keys. If address is provided, removes only that address.\n * If no address, removes ALL encrypted bundles and ALL in-memory keys.\n * @param {string} requestId\n * @param {string|undefined} address - Optional wallet address\n */\nfunction onClearStoredBundles(requestId, address) {\n if (address) {\n TKHQ.removeEncryptedBundle(address);\n delete inMemoryKeys[address];\n } else {\n TKHQ.clearAllEncryptedBundles();\n inMemoryKeys = {};\n }\n TKHQ.sendMessageUp(\"STORED_BUNDLES_CLEARED\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error(\n `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`\n ).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n undefined, // keyFormat - default to HEXADECIMAL\n undefined, // address - default to \"default\"\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"STORE_ENCRYPTED_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n await onStoreEncryptedBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_DECRYPTION_KEY_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}`\n );\n try {\n await onInjectDecryptionKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"BURN_SESSION\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onBurnSession(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_STORED_WALLET_ADDRESSES\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onGetStoredWalletAddresses(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_STORED_BUNDLES\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n onClearStoredBundles(event.data[\"requestId\"], event.data[\"address\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n onStoreEncryptedBundle,\n onInjectDecryptionKeyBundle,\n onBurnSession,\n onGetStoredWalletAddresses,\n onClearStoredBundles,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"@shared/crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n","module.exports = crypto;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","\n__webpack_require__.sriHashes = {\"291\":\"*-*-*-CHUNK-SRI-HASH-r3NPGwA4ft5fHgGXhVIptCiDVf06qPa+sxzG6L+8GwPuhn89e/\",\"825\":\"*-*-*-CHUNK-SRI-HASH-mfog3UJdGPOmSk4QZbKxsxHPFZtt298WnZNc1aQ1MCgc6YirFj\"};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(560)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","TURNKEY_ENCRYPTED_BUNDLES","parentFrameMessageChannelPort","getSubtleCrypto","globalThis","crypto","subtle","window","global","isDoublyIframed","undefined","location","ancestorOrigins","parent","top","_loadQuorumKey","_callee","quorumPublic","_context","Error","importKey","namedCurve","_initEmbeddedKey","_callee3","_context3","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee4","p256key","_context4","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","getEncryptedBundles","data","localStorage","getItem","key","ttl","item","expiry","Date","getTime","setItem","itemStr","hasOwnProperty","removeItem","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","concat","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","p256JWKPrivateToPublic","_x6","_p256JWKPrivateToPublic","_callee6","jwkPrivate","jwkPrivateCopy","publicKey","_context6","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","push","k","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee9","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_t2","_context9","set","console","warn","sharedInitEmbeddedKey","SharedTKHQ","validateStyles","styles","element","validStyles","cssValidationRegex","padding","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref","_ref2","_arrayWithHoles","next","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","loadQuorumKey","_x","_verifyEnclaveSignature","_callee2","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","meta","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context2","prod","preprod","querySelector","__TURNKEY_SIGNER_ENVIRONMENT__","fromDerSignature","verify","hash","TKHQ","initEmbeddedKey","onResetEmbeddedKey","encodeKey","_x0","_x1","_x10","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","normalizePadding","byteArray","targetLength","paddingLength","fill","expectedZeroCount","zeroCount","verifyEnclaveSignature","_x2","_x3","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","style","getSettings","setSettings","parsePrivateKey","error","setEncryptedBundle","address","bundleData","bundles","removeEncryptedBundle","keys","clearAllEncryptedBundles","_slicedToArray","inMemoryKeys","decryptionKey","textEncoder","TextEncoder","textDecoder","TextDecoder","verifyAndParseBundleData","_verifyAndParseBundleData","_callee8","bundle","organizationId","bundleObj","_context8","version","dataSignature","decode","encappedPublic","ciphertext","decryptBundle","_x4","_x5","_decryptBundle","HpkeDecrypt","encappedKeyBuf","ciphertextBuf","embeddedKeyJwk","receiverPrivJwk","onGetPublicEmbeddedKey","_onGetPublicEmbeddedKey","_callee0","targetPubBuf","targetPubHex","_context0","loadKeyIntoMemory","_x7","_x8","_x9","_loadKeyIntoMemory","_callee1","keyBytes","keyAddress","cachedKeypair","_context1","subarray","Keypair","fromSecretKey","createSolanaKeypair","_defineProperty","format","keypair","onInjectKeyBundle","_x11","_x12","_x13","_x14","_onInjectKeyBundle","_callee10","_context10","onApplySettings","_x15","_x16","_onApplySettings","_callee11","_context11","onSignTransaction","_x17","_x18","_x19","_onSignTransaction","_callee12","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context12","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x20","_x21","_x22","_onSignMessage","_callee13","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context13","encode","secretKey","onClearEmbeddedPrivateKey","_x23","_x24","_onClearEmbeddedPrivateKey","_callee14","_context14","onStoreEncryptedBundle","_x25","_x26","_x27","_x28","_x29","_x30","_onStoreEncryptedBundle","_callee15","resolvedKeyFormat","_context15","rawP256PrivateKeyToJwk","_x31","_rawP256PrivateKeyToJwk","_callee16","rawPrivateKeyBytes","pkcs8Prefix","pkcs8","cryptoKey","_context16","onInjectDecryptionKeyBundle","_x32","_x33","_x34","_x35","_onInjectDecryptionKeyBundle","_callee17","keyJwk","storedBundles","decryptedCount","addresses","_i3","_addresses","addr","_keyBytes","_t0","_context17","onBurnSession","onGetStoredWalletAddresses","onClearStoredBundles","_x36","_createSolanaKeypair","_callee18","_context18","fromSeed","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x37","_getOrCreateKeypair","_callee19","_context19","initEventHandlers","messageEventListener","_messageEventListener","event","_t","_t3","_t4","_t5","_t6","_t7","_t8","_t9","_x43","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","preventDefault","_x38","_x39","_ref3","_x40","_ref4","_x41","injectWalletBtn","_ref5","_callee5","_context5","_x42","addDOMEventListeners","capture","signal","_ref6","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x44","ownKeys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","_HpkeDecrypt","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","styleSettings","module","exports","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","g","Function","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","crossOrigin","integrity","sriHashes","onScriptComplete","prev","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"bundle.8ccdeed719db48416e34.js","mappings":";UAAIA,ECCAC,EADAC,ECAAC,EACAC,E,svCCAJ,IAAAC,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAA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gU,QAAUD,EAChBJ,EAAmB,GAAG3T,EACvB,GAGuC,SAAWsR,EAASA,EAE/D,GAYH1B,EAAoBM,EAAEjY,EAAKqZ,GAA0C,IAA7BoC,EAAgBpC,GAGxD,IAAI2C,EAAuB,CAACC,EAA4Bzf,KACvD,IAGIob,EAAUyB,GAHTnB,EAAUgE,EAAaC,GAAW3f,EAGhBvG,EAAI,EAC3B,GAAGiiB,EAASkE,KAAMtE,GAAgC,IAAxB2D,EAAgB3D,IAAa,CACtD,IAAIF,KAAYsE,EACZvE,EAAoB5hB,EAAEmmB,EAAatE,KACrCD,EAAoB5f,EAAE6f,GAAYsE,EAAYtE,IAGhD,GAAGuE,EAAS,IAAItc,EAASsc,EAAQxE,EAClC,CAEA,IADGsE,GAA4BA,EAA2Bzf,GACrDvG,EAAIiiB,EAASjhB,OAAQhB,IACzBojB,EAAUnB,EAASjiB,GAChB0hB,EAAoB5hB,EAAE0lB,EAAiBpC,IAAYoC,EAAgBpC,IACrEoC,EAAgBpC,GAAS,KAE1BoC,EAAgBpC,GAAW,EAE5B,OAAO1B,EAAoBM,EAAEpY,IAG1Bwc,EAAqBC,KAAkC,4BAAIA,KAAkC,6BAAK,GACtGD,EAAmBlZ,QAAQ6Y,EAAqBhlB,KAAK,KAAM,IAC3DqlB,EAAmBpc,KAAO+b,EAAqBhlB,KAAK,KAAMqlB,EAAmBpc,KAAKjJ,KAAKqlB,G,KClFvF,IAAIE,EAAsB5E,EAAoBM,OAAE1d,EAAW,CAAC,IAAK,IAAOod,EAAoB,MAC5F4E,EAAsB5E,EAAoBM,EAAEsE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/../shared/turnkey-core.js","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/../shared/crypto-utils.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/external var \"crypto\"","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/global","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/compat","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t\tif (script.src.indexOf(window.location.origin + '/') !== 0) {\n\t\t\tscript.crossOrigin = \"anonymous\";\n\t\t}\n\t\tscript.integrity = __webpack_require__.sriHashes[chunkId];\n\t\tscript.crossOrigin = \"anonymous\";\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n return data ? JSON.parse(data) : null;\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * @param {string} address - The wallet address to remove\n */\nfunction removeEncryptedBundle(address) {\n const bundles = getEncryptedBundles();\n if (bundles && bundles[address]) {\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n }\n}\n\n/**\n * Removes all encrypted bundles from localStorage.\n */\nfunction clearAllEncryptedBundles() {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\nimport { fromDerSignature } from \"@turnkey/crypto\";\nimport * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n initEmbeddedKey: sharedInitEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n additionalAssociatedData,\n getSettings,\n setSettings,\n parsePrivateKey,\n validateStyles,\n isDoublyIframed,\n loadQuorumKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n} = SharedTKHQ;\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n return await sharedInitEmbeddedKey();\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Read environment from meta tag (templated at deploy time), fall back to window variable (for testing)\n let environment = null;\n if (typeof document !== \"undefined\") {\n const meta = document.querySelector(\n 'meta[name=\"turnkey-signer-environment\"]'\n );\n if (\n meta &&\n meta.content &&\n meta.content !== \"__TURNKEY_SIGNER_ENVIRONMENT__\"\n ) {\n environment = meta.content;\n }\n }\n if (!environment && typeof window !== \"undefined\") {\n environment = window.__TURNKEY_SIGNER_ENVIRONMENT__;\n }\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\n// Decryption key -- held in memory only, never persisted to localStorage.\n// This is a P-256 private key in JWK format used to decrypt stored bundles.\nlet decryptionKey = null;\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Verifies the enclave signature on a v1.0.0 bundle and returns the parsed signed data.\n * @param {string} bundle - JSON-stringified bundle\n * @param {string} organizationId - Expected organization ID\n * @returns {Promise} - The parsed signed data {organizationId, encappedPublic, ciphertext}\n */\nasync function verifyAndParseBundleData(bundle, organizationId) {\n const bundleObj = JSON.parse(bundle);\n\n if (bundleObj.version !== \"v1.0.0\") {\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n const verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(`failed to verify enclave signature: ${bundle}`);\n }\n\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n\n return signedData;\n}\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n // Decrypt the ciphertext\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: embeddedKeyJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Encodes raw key bytes and loads them into the in-memory key store.\n * @param {string} address - Wallet address (case-sensitive)\n * @param {ArrayBuffer} keyBytes - Raw decrypted private key bytes\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} organizationId - Organization ID\n */\nasync function loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId) {\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair,\n },\n };\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Load decrypted key into memory\n await loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId);\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Set up sha512 for nobleEd25519 (required for signing)\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n\n // Extract the 32-byte private key from the 64-byte secretKey\n // Solana keypair.secretKey format: [32-byte private key][32-byte public key]\n const privateKey = keypair.secretKey.slice(0, 32);\n // Sign the message using nobleEd25519\n const signature = nobleEd25519.sign(messageBytes, privateKey);\n\n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n/**\n * Handler for STORE_ENCRYPTED_BUNDLE events.\n * Verifies the enclave signature on an encrypted bundle and stores\n * the encrypted payload in localStorage for later decryption.\n * If the decryption key is already in memory, also decrypts and loads\n * the key into memory immediately.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle JSON\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} address - Wallet address\n * @param {Function} HpkeDecrypt\n */\nasync function onStoreEncryptedBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n if (!address) {\n throw new Error(\"address is required for STORE_ENCRYPTED_BUNDLE\");\n }\n\n // Verify enclave signature and parse the signed data\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const resolvedKeyFormat = keyFormat || \"HEXADECIMAL\";\n\n // Store the encrypted fields in localStorage (just what's needed for decryption)\n TKHQ.setEncryptedBundle(address, {\n encappedPublic: signedData.encappedPublic,\n ciphertext: signedData.ciphertext,\n organizationId: organizationId,\n keyFormat: resolvedKeyFormat,\n });\n\n // If the decryption key is already in memory, decrypt and load immediately\n if (decryptionKey && HpkeDecrypt) {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n await loadKeyIntoMemory(\n address,\n keyBytes,\n resolvedKeyFormat,\n organizationId\n );\n }\n\n TKHQ.sendMessageUp(\"ENCRYPTED_BUNDLE_STORED\", true, requestId);\n}\n\n/**\n * Converts raw P-256 private key bytes (32-byte scalar) to a JWK.\n * Constructs a PKCS8 wrapper around the raw bytes, imports via WebCrypto\n * (which derives the public key), then exports as JWK.\n * @param {Uint8Array} rawPrivateKeyBytes - 32-byte P-256 private key scalar\n * @returns {Promise} - Full P-256 ECDH private key JWK\n */\nasync function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) {\n if (rawPrivateKeyBytes.length !== 32) {\n throw new Error(\n `invalid decryption key length: expected 32 bytes, got ${rawPrivateKeyBytes.length}`\n );\n }\n\n // PKCS8 DER prefix for a P-256 private key (without optional public key field)\n // SEQUENCE {\n // INTEGER 0 (version)\n // SEQUENCE { OID ecPublicKey, OID P-256 }\n // OCTET STRING { SEQUENCE { INTEGER 1, OCTET STRING(32) } }\n // }\n const pkcs8Prefix = new Uint8Array([\n 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48,\n 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03,\n 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20,\n ]);\n\n const pkcs8 = new Uint8Array(pkcs8Prefix.length + 32);\n pkcs8.set(pkcs8Prefix);\n pkcs8.set(rawPrivateKeyBytes, pkcs8Prefix.length);\n\n const cryptoKey = await crypto.subtle.importKey(\n \"pkcs8\",\n pkcs8,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"]\n );\n\n return await crypto.subtle.exportKey(\"jwk\", cryptoKey);\n}\n\n/**\n * Handler for INJECT_DECRYPTION_KEY_BUNDLE events.\n * Decrypts the P-256 private key using the iframe's embedded key,\n * then iterates all stored encrypted bundles, HPKE-decrypts each one\n * with the key, and loads them into inMemoryKeys.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle containing the private key\n * @param {Function} HpkeDecrypt\n */\nasync function onInjectDecryptionKeyBundle(\n requestId,\n organizationId,\n bundle,\n HpkeDecrypt\n) {\n // Decrypt the private key using the iframe's embedded key.\n // The decrypted payload is a raw 32-byte P-256 private key scalar.\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto)\n const keyJwk = await rawP256PrivateKeyToJwk(new Uint8Array(keyBytes));\n\n // Store in module-level variable (memory only)\n decryptionKey = keyJwk;\n\n // Iterate all stored encrypted bundles and decrypt each one\n const storedBundles = TKHQ.getEncryptedBundles();\n let decryptedCount = 0;\n\n if (storedBundles) {\n const addresses = Object.keys(storedBundles);\n\n for (const addr of addresses) {\n const bundleData = storedBundles[addr];\n\n try {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n bundleData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(\n bundleData.ciphertext\n );\n\n // HPKE-decrypt using the key\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n // Load the decrypted key into memory\n await loadKeyIntoMemory(\n addr,\n keyBytes,\n bundleData.keyFormat,\n bundleData.organizationId\n );\n\n decryptedCount++;\n } catch (e) {\n TKHQ.logMessage(\n `Failed to decrypt bundle for address ${addr}: ${e.toString()}`\n );\n }\n }\n }\n\n TKHQ.sendMessageUp(\"DECRYPTION_KEY_INJECTED\", decryptedCount, requestId);\n}\n\n/**\n * Handler for BURN_SESSION events.\n * Clears the decryption key and all in-memory wallet keys.\n * Encrypted bundles in localStorage are preserved for the next session.\n * @param {string} requestId\n */\nfunction onBurnSession(requestId) {\n decryptionKey = null;\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"SESSION_BURNED\", true, requestId);\n}\n\n/**\n * Handler for GET_STORED_WALLET_ADDRESSES events.\n * Returns a JSON array of all wallet addresses that have encrypted bundles in localStorage.\n * @param {string} requestId\n */\nfunction onGetStoredWalletAddresses(requestId) {\n const bundles = TKHQ.getEncryptedBundles();\n const addresses = bundles ? Object.keys(bundles) : [];\n TKHQ.sendMessageUp(\n \"STORED_WALLET_ADDRESSES\",\n JSON.stringify(addresses),\n requestId\n );\n}\n\n/**\n * Handler for CLEAR_STORED_BUNDLES events.\n * Removes encrypted bundles from localStorage AND the corresponding\n * in-memory keys. If address is provided, removes only that address.\n * If no address, removes ALL encrypted bundles and ALL in-memory keys.\n * @param {string} requestId\n * @param {string|undefined} address - Optional wallet address\n */\nfunction onClearStoredBundles(requestId, address) {\n if (address) {\n TKHQ.removeEncryptedBundle(address);\n delete inMemoryKeys[address];\n } else {\n TKHQ.clearAllEncryptedBundles();\n inMemoryKeys = {};\n }\n TKHQ.sendMessageUp(\"STORED_BUNDLES_CLEARED\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error(\n `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`\n ).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n undefined, // keyFormat - default to HEXADECIMAL\n undefined, // address - default to \"default\"\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"STORE_ENCRYPTED_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n await onStoreEncryptedBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_DECRYPTION_KEY_BUNDLE\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onInjectDecryptionKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"BURN_SESSION\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onBurnSession(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_STORED_WALLET_ADDRESSES\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onGetStoredWalletAddresses(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_STORED_BUNDLES\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n onClearStoredBundles(event.data[\"requestId\"], event.data[\"address\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n onStoreEncryptedBundle,\n onInjectDecryptionKeyBundle,\n onBurnSession,\n onGetStoredWalletAddresses,\n onClearStoredBundles,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"@shared/crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n","module.exports = crypto;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","\n__webpack_require__.sriHashes = {\"291\":\"*-*-*-CHUNK-SRI-HASH-r3NPGwA4ft5fHgGXhVIptCiDVf06qPa+sxzG6L+8GwPuhn89e/\",\"825\":\"*-*-*-CHUNK-SRI-HASH-mfog3UJdGPOmSk4QZbKxsxHPFZtt298WnZNc1aQ1MCgc6YirFj\"};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(560)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","TURNKEY_ENCRYPTED_BUNDLES","parentFrameMessageChannelPort","getSubtleCrypto","globalThis","crypto","subtle","window","global","isDoublyIframed","undefined","location","ancestorOrigins","parent","top","_loadQuorumKey","_callee","quorumPublic","_context","Error","importKey","namedCurve","_initEmbeddedKey","_callee3","_context3","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee4","p256key","_context4","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","getEncryptedBundles","data","localStorage","getItem","key","ttl","item","expiry","Date","getTime","setItem","itemStr","hasOwnProperty","removeItem","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","concat","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","p256JWKPrivateToPublic","_x6","_p256JWKPrivateToPublic","_callee6","jwkPrivate","jwkPrivateCopy","publicKey","_context6","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","push","k","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee9","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_t2","_context9","set","console","warn","sharedInitEmbeddedKey","SharedTKHQ","validateStyles","styles","element","validStyles","cssValidationRegex","padding","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref","_ref2","_arrayWithHoles","next","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","loadQuorumKey","_x","_verifyEnclaveSignature","_callee2","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","meta","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context2","prod","preprod","querySelector","__TURNKEY_SIGNER_ENVIRONMENT__","fromDerSignature","verify","hash","TKHQ","initEmbeddedKey","onResetEmbeddedKey","encodeKey","_x0","_x1","_x10","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","normalizePadding","byteArray","targetLength","paddingLength","fill","expectedZeroCount","zeroCount","verifyEnclaveSignature","_x2","_x3","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","style","getSettings","setSettings","parsePrivateKey","error","setEncryptedBundle","address","bundleData","bundles","removeEncryptedBundle","keys","clearAllEncryptedBundles","_slicedToArray","inMemoryKeys","decryptionKey","textEncoder","TextEncoder","textDecoder","TextDecoder","verifyAndParseBundleData","_verifyAndParseBundleData","_callee8","bundle","organizationId","bundleObj","_context8","version","dataSignature","decode","encappedPublic","ciphertext","decryptBundle","_x4","_x5","_decryptBundle","HpkeDecrypt","encappedKeyBuf","ciphertextBuf","embeddedKeyJwk","receiverPrivJwk","onGetPublicEmbeddedKey","_onGetPublicEmbeddedKey","_callee0","targetPubBuf","targetPubHex","_context0","loadKeyIntoMemory","_x7","_x8","_x9","_loadKeyIntoMemory","_callee1","keyBytes","keyAddress","cachedKeypair","_context1","subarray","Keypair","fromSecretKey","createSolanaKeypair","_defineProperty","format","keypair","onInjectKeyBundle","_x11","_x12","_x13","_x14","_onInjectKeyBundle","_callee10","_context10","onApplySettings","_x15","_x16","_onApplySettings","_callee11","_context11","onSignTransaction","_x17","_x18","_x19","_onSignTransaction","_callee12","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context12","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x20","_x21","_x22","_onSignMessage","_callee13","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context13","encode","secretKey","onClearEmbeddedPrivateKey","_x23","_x24","_onClearEmbeddedPrivateKey","_callee14","_context14","onStoreEncryptedBundle","_x25","_x26","_x27","_x28","_x29","_x30","_onStoreEncryptedBundle","_callee15","resolvedKeyFormat","_context15","rawP256PrivateKeyToJwk","_x31","_rawP256PrivateKeyToJwk","_callee16","rawPrivateKeyBytes","pkcs8Prefix","pkcs8","cryptoKey","_context16","onInjectDecryptionKeyBundle","_x32","_x33","_x34","_x35","_onInjectDecryptionKeyBundle","_callee17","keyJwk","storedBundles","decryptedCount","addresses","_i3","_addresses","addr","_keyBytes","_t0","_context17","onBurnSession","onGetStoredWalletAddresses","onClearStoredBundles","_x36","_createSolanaKeypair","_callee18","_context18","fromSeed","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x37","_getOrCreateKeypair","_callee19","_context19","initEventHandlers","messageEventListener","_messageEventListener","event","_t","_t3","_t4","_t5","_t6","_t7","_t8","_t9","_x43","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","preventDefault","_x38","_x39","_ref3","_x40","_ref4","_x41","injectWalletBtn","_ref5","_callee5","_context5","_x42","addDOMEventListeners","capture","signal","_ref6","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x44","ownKeys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","_HpkeDecrypt","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","styleSettings","module","exports","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","g","Function","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","crossOrigin","integrity","sriHashes","onScriptComplete","prev","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/index.test.js b/export-and-sign/index.test.js index 6e6bd00..6d6e4f6 100644 --- a/export-and-sign/index.test.js +++ b/export-and-sign/index.test.js @@ -1185,7 +1185,11 @@ describe("Encryption Escrow", () => { // Signing should fail (key not in memory) try { - await onSignTransaction(requestId, serializedTransaction, "wallet-addr-1"); + await onSignTransaction( + requestId, + serializedTransaction, + "wallet-addr-1" + ); } catch (e) { expect(e.toString()).toContain("key bytes not found"); } @@ -1219,9 +1223,7 @@ describe("Encryption Escrow", () => { callCount++; if (callCount === 1) { // First call: decrypting the escrow key bundle -> returns JWK bytes - return Promise.resolve( - mockEscrowKeyBytes - ); + return Promise.resolve(mockEscrowKeyBytes); } // Subsequent calls: decrypting wallet bundles -> returns key bytes return Promise.resolve(new Uint8Array(64).fill(9)); @@ -1253,9 +1255,7 @@ describe("Encryption Escrow", () => { }); it("handles empty localStorage gracefully", async () => { - const HpkeDecryptMock = jest.fn().mockResolvedValue( - mockEscrowKeyBytes - ); + const HpkeDecryptMock = jest.fn().mockResolvedValue(mockEscrowKeyBytes); await onInjectDecryptionKeyBundle( requestId, @@ -1299,9 +1299,7 @@ describe("Encryption Escrow", () => { callCount++; if (callCount === 1) { // First call: escrow key - return Promise.resolve( - mockEscrowKeyBytes - ); + return Promise.resolve(mockEscrowKeyBytes); } // Fail for the second wallet bundle (callCount 3 = wallet2-bad) if (callCount === 3) { @@ -1579,9 +1577,7 @@ describe("Encryption Escrow", () => { const HpkeDecryptMock = jest.fn().mockImplementation(() => { callCount++; if (callCount === 1) { - return Promise.resolve( - mockEscrowKeyBytes - ); + return Promise.resolve(mockEscrowKeyBytes); } return Promise.resolve(new Uint8Array(64).fill(9)); }); diff --git a/export-and-sign/src/event-handlers.js b/export-and-sign/src/event-handlers.js index a06e5da..9e37aa2 100644 --- a/export-and-sign/src/event-handlers.js +++ b/export-and-sign/src/event-handlers.js @@ -388,7 +388,12 @@ async function onStoreEncryptedBundle( receiverPrivJwk: decryptionKey, }); - await loadKeyIntoMemory(address, keyBytes, resolvedKeyFormat, organizationId); + await loadKeyIntoMemory( + address, + keyBytes, + resolvedKeyFormat, + organizationId + ); } TKHQ.sendMessageUp("ENCRYPTED_BUNDLE_STORED", true, requestId); @@ -453,16 +458,10 @@ async function onInjectDecryptionKeyBundle( ) { // Decrypt the private key using the iframe's embedded key. // The decrypted payload is a raw 32-byte P-256 private key scalar. - const keyBytes = await decryptBundle( - bundle, - organizationId, - HpkeDecrypt - ); + const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt); // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto) - const keyJwk = await rawP256PrivateKeyToJwk( - new Uint8Array(keyBytes) - ); + const keyJwk = await rawP256PrivateKeyToJwk(new Uint8Array(keyBytes)); // Store in module-level variable (memory only) decryptionKey = keyJwk; @@ -851,9 +850,7 @@ function initMessageEventListener(HpkeDecrypt) { } } if (event.data && event.data["type"] == "INJECT_DECRYPTION_KEY_BUNDLE") { - TKHQ.logMessage( - `⬇️ Received message ${event.data["type"]}` - ); + TKHQ.logMessage(`⬇️ Received message ${event.data["type"]}`); try { await onInjectDecryptionKeyBundle( event.data["requestId"], diff --git a/import/dist/551.bundle.27da59437a4e403e3c24.js.map b/import/dist/551.bundle.27da59437a4e403e3c24.js.map index 811b1db..dca01ff 100644 --- a/import/dist/551.bundle.27da59437a4e403e3c24.js.map +++ b/import/dist/551.bundle.27da59437a4e403e3c24.js.map @@ -1 +1 @@ -{"version":3,"file":"551.bundle.27da59437a4e403e3c24.js","mappings":";moFACA,IAAAA,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH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GAAAwD,EAAAvC,EAAAnB,EAAAI,EAAA6D,EAAAC,EAAA,OAAAhE,EAAA,UAAAgE,EAAAhE,GAAAwD,EAAAvC,EAAAnB,EAAAI,EAAA6D,EAAAC,EAAA,QAAAhE,EAAA,CAAA+D,OAAA,OA2HCD,MAAA,KAAAD,WA3HD,IAAA7D,CA2HC,C","sources":["webpack://import/../shared/turnkey-core.js","webpack://import/./src/turnkey-core.js","webpack://import/../shared/crypto-utils.js"],"sourcesContent":["import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n};\n","import * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n} = SharedTKHQ;\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n const settingsObj = JSON.parse(settings);\n\n const passphraseLabel = document.getElementById(\"passphrase-label\");\n const mnemonicLabel = document.getElementById(\"mnemonic-label\");\n const passphraseTextarea = document.getElementById(\"passphrase\");\n\n if (!passphraseLabel || !passphraseTextarea) {\n throw new Error(\"no passphrase HTML elements found to apply settings to.\");\n }\n const plaintextTextarea = document.getElementById(\"plaintext\");\n if (!plaintextTextarea) {\n throw new Error(\n \"no plaintext textarea HTML element found to apply settings to.\"\n );\n }\n\n // Apply enablePassphrase setting\n if (settingsObj.enablePassphrase === true) {\n passphraseLabel.style.display = \"inline-block\";\n passphraseTextarea.style.display = \"inline-block\";\n passphraseTextarea.style.border = \"solid 1px #ccc\";\n passphraseTextarea.style.borderRadius = \"4px\";\n\n mnemonicLabel.style.display = \"inline-block\";\n plaintextTextarea.style.border = \"solid 1px #ccc\";\n plaintextTextarea.style.borderRadius = \"4px\";\n\n validSettings[\"enablePassphrase\"] = true;\n } else {\n passphraseLabel.style.display = \"none\";\n passphraseTextarea.style.display = \"none\";\n mnemonicLabel.style.display = \"none\";\n\n plaintextTextarea.style.border = \"none\";\n validSettings[\"enablePassphrase\"] = false;\n }\n\n if (settingsObj.styles) {\n // Validate, sanitize, and apply the styles to the \"plaintext\" textarea.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n plaintextTextarea.style[key] = value;\n });\n\n if (validStyles.backgroundColor) {\n // Apply background color to document and body as well.\n document.documentElement.style.backgroundColor =\n validStyles.backgroundColor;\n document.body.style.backgroundColor = validStyles.backgroundColor;\n }\n\n if (validStyles.labelColor) {\n document.getElementById(\"mnemonic-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"styles\"] = validStyles;\n }\n\n if (settingsObj.passphraseStyles) {\n // Validate, sanitize, and apply the styles to the \"passphrase\" textarea.\n const validStyles = validateStyles(settingsObj.passphraseStyles);\n Object.entries(validStyles).forEach(([key, value]) => {\n passphraseTextarea.style[key] = value;\n });\n\n if (validStyles.labelColor) {\n document.getElementById(\"passphrase-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"passphraseStyles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n applySettings,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n"],"names":["e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_OverloadYield","k","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_TARGET_EMBEDDED_KEY","TURNKEY_SETTINGS","parentFrameMessageChannelPort","cryptoProviderOverride","getSubtleCrypto","subtle","globalThis","crypto","window","global","setCryptoProvider","cryptoProvider","loadQuorumKey","_x","_loadQuorumKey","_regeneratorRuntime","mark","_callee","quorumPublic","wrap","_context","prev","next","Error","importKey","namedCurve","abrupt","sent","stop","loadTargetKey","_x2","_loadTargetKey","_callee2","targetPublic","targetKey","_context2","exportKey","getTargetEmbeddedKey","jwtKey","localStorage","getItem","JSON","parse","setTargetEmbeddedKey","setItem","stringify","resetTargetEmbeddedKey","removeItem","setParentFrameMessageChannelPort","port","getSettings","settings","setSettings","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","normalizePadding","byteArray","targetLength","paddingLength","padding","fill","concat","expectedZeroCount","zeroCount","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","fromDerSignature","derSignature","derSignatureBuf","index","rLength","sLength","rPadded","sPadded","verifyEnclaveSignature","_x3","_x4","_x5","_verifyEnclaveSignature","_callee5","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context5","prod","preprod","__TURNKEY_SIGNER_ENVIRONMENT__","undefined","verify","hash","sendMessageUp","type","requestId","message","postMessage","parent","content","messageLog","document","getElementById","createElement","innerText","appendChild","logMessage","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","carry","push","j","currentByte","result","reverse","base58CheckDecode","_x7","_base58CheckDecode","_callee7","decoded","payload","checksum","hash1Buf","hash1","hash2Buf","hash2","computedChecksum","_context7","subarray","digest","decodeKey","_x8","_x9","_decodeKey","_callee8","privateKey","keyFormat","decodedKeyBytes","version","keyAndFlags","_payload","_version","_keyAndFlags","_bech32$decode","prefix","words","bytes","schemeFlag","privkey","_context8","t0","bech32","decode","fromWords","console","warn","validateStyles","styles","element","validStyles","cssValidationRegex","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref","_ref2","_arrayWithHoles","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","SharedTKHQ","applySettings","validSettings","settingsObj","passphraseLabel","mnemonicLabel","passphraseTextarea","plaintextTextarea","enablePassphrase","style","display","border","_slicedToArray","key","documentElement","body","passphraseStyles","_ref3","_ref4","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","_objectSpread","_defineProperty","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","TextEncoder","encode","HpkeEncrypt","_HpkeEncrypt","plaintextBuf","receiverPubJwk","kemContext","receiverPub","suite","senderCtx","receiverPubCryptoKey","receiverPubRaw","encappedKeyBuf","aad","ciphertextBuf","ciphertextHex","encappedKeyBufHex","encryptedBundle","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createSenderContext","recipientPublicKey","info","enc","seal","encappedPublic","ciphertext"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"551.bundle.27da59437a4e403e3c24.js","mappings":";moFACA,IAAAA,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IAAAE,EAAAC,EAAAG,EAAAI,EAAA,EAAAC,EAAAX,GAAA,GAAAY,GAAA,EAAAC,EAAA,CAAAF,EAAA,EAAAb,EAAA,EAAAgB,EAAApB,EAAAqB,EAAAC,EAAAN,EAAAM,EAAAC,KAAAvB,EAAA,GAAAsB,EAAA,SAAArB,EAAAC,GAAA,OAAAM,EAAAP,EAAAQ,EAAA,EAAAG,EAAAZ,EAAAmB,EAAAf,EAAAF,EAAAmB,CAAA,Y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,QACNoC,WAAY,UAEd,EACA,IACD,QATyB,OAApB4O,EAAoBlO,EAAAR,KAAAQ,EAAAb,KAAG,GAUAf,OAAOF,OAAO+B,UACzC,MACAiO,GACD,QAKmE,OAR9DC,EAAcnO,EAAAR,KAIdmD,EAAiB,IAAIrB,WAAW6M,GAEhCC,EAAiB,IAAI9M,WAAW2M,EAAUmB,KAE1Cf,GAAM5L,EAAAA,EAAAA,IAAyB2L,EAAgBzL,GAAe3C,EAAAd,KAAA,GAAAc,EAAAb,KAAA,GAI5C8O,EAAUoB,KAAKzB,EAAcS,GAAI,QAAvDC,EAAatO,EAAAR,KAAAQ,EAAAb,KAAG,GAAH,oBAAAa,EAAAd,KAAG,GAAHc,EAAAwI,GAAAxI,EAAA,UAEP,IAAIZ,MAAM,oCAAsCY,EAAAwI,GAAEzL,YAAW,QAQnE,OALIwR,GAAgB5M,EAAAA,EAAAA,IAAsB,IAAIL,WAAWgN,IACrDE,GAAoB7M,EAAAA,EAAAA,IAAsByM,GAC1CK,EAAkBnO,KAAKI,UAAU,CACrC4O,eAAgBd,EAChBe,WAAYhB,IACZvO,EAAAT,OAAA,SACKkP,GAAe,yBAAAzO,EAAAP,OAAA,EAAAI,EAAA,kBACvB8N,EA3HD,eAAAlU,EAAA,KAAAD,EAAAiE,UAAA,WAAAJ,QAAA,SAAA3D,EAAAI,GAAA,IAAAe,EAAAjB,EAAA8D,MAAAjE,EAAAD,GAAA,SAAAmE,EAAA/D,GAAAwD,EAAAvC,EAAAnB,EAAAI,EAAA6D,EAAAC,EAAA,OAAAhE,EAAA,UAAAgE,EAAAhE,GAAAwD,EAAAvC,EAAAnB,EAAAI,EAAA6D,EAAAC,EAAA,QAAAhE,EAAA,CAAA+D,OAAA,OA2HCD,MAAA,KAAAD,WA3HD,IAAA7D,CA2HC,C","sources":["webpack://import/../shared/turnkey-core.js","webpack://import/./src/turnkey-core.js","webpack://import/../shared/crypto-utils.js"],"sourcesContent":["import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n return data ? JSON.parse(data) : null;\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * @param {string} address - The wallet address to remove\n */\nfunction removeEncryptedBundle(address) {\n const bundles = getEncryptedBundles();\n if (bundles && bundles[address]) {\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n }\n}\n\n/**\n * Removes all encrypted bundles from localStorage.\n */\nfunction clearAllEncryptedBundles() {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n} = SharedTKHQ;\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n const settingsObj = JSON.parse(settings);\n\n const passphraseLabel = document.getElementById(\"passphrase-label\");\n const mnemonicLabel = document.getElementById(\"mnemonic-label\");\n const passphraseTextarea = document.getElementById(\"passphrase\");\n\n if (!passphraseLabel || !passphraseTextarea) {\n throw new Error(\"no passphrase HTML elements found to apply settings to.\");\n }\n const plaintextTextarea = document.getElementById(\"plaintext\");\n if (!plaintextTextarea) {\n throw new Error(\n \"no plaintext textarea HTML element found to apply settings to.\"\n );\n }\n\n // Apply enablePassphrase setting\n if (settingsObj.enablePassphrase === true) {\n passphraseLabel.style.display = \"inline-block\";\n passphraseTextarea.style.display = \"inline-block\";\n passphraseTextarea.style.border = \"solid 1px #ccc\";\n passphraseTextarea.style.borderRadius = \"4px\";\n\n mnemonicLabel.style.display = \"inline-block\";\n plaintextTextarea.style.border = \"solid 1px #ccc\";\n plaintextTextarea.style.borderRadius = \"4px\";\n\n validSettings[\"enablePassphrase\"] = true;\n } else {\n passphraseLabel.style.display = \"none\";\n passphraseTextarea.style.display = \"none\";\n mnemonicLabel.style.display = \"none\";\n\n plaintextTextarea.style.border = \"none\";\n validSettings[\"enablePassphrase\"] = false;\n }\n\n if (settingsObj.styles) {\n // Validate, sanitize, and apply the styles to the \"plaintext\" textarea.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n plaintextTextarea.style[key] = value;\n });\n\n if (validStyles.backgroundColor) {\n // Apply background color to document and body as well.\n document.documentElement.style.backgroundColor =\n validStyles.backgroundColor;\n document.body.style.backgroundColor = validStyles.backgroundColor;\n }\n\n if (validStyles.labelColor) {\n document.getElementById(\"mnemonic-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"styles\"] = validStyles;\n }\n\n if (settingsObj.passphraseStyles) {\n // Validate, sanitize, and apply the styles to the \"passphrase\" textarea.\n const validStyles = validateStyles(settingsObj.passphraseStyles);\n Object.entries(validStyles).forEach(([key, value]) => {\n passphraseTextarea.style[key] = value;\n });\n\n if (validStyles.labelColor) {\n document.getElementById(\"passphrase-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"passphraseStyles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n applySettings,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n"],"names":["e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_OverloadYield","k","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_TARGET_EMBEDDED_KEY","TURNKEY_SETTINGS","parentFrameMessageChannelPort","cryptoProviderOverride","getSubtleCrypto","subtle","globalThis","crypto","window","global","setCryptoProvider","cryptoProvider","loadQuorumKey","_x","_loadQuorumKey","_regeneratorRuntime","mark","_callee","quorumPublic","wrap","_context","prev","next","Error","importKey","namedCurve","abrupt","sent","stop","loadTargetKey","_x2","_loadTargetKey","_callee2","targetPublic","targetKey","_context2","exportKey","getTargetEmbeddedKey","jwtKey","localStorage","getItem","JSON","parse","setTargetEmbeddedKey","setItem","stringify","resetTargetEmbeddedKey","removeItem","setParentFrameMessageChannelPort","port","getSettings","settings","setSettings","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","normalizePadding","byteArray","targetLength","paddingLength","padding","fill","concat","expectedZeroCount","zeroCount","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","fromDerSignature","derSignature","derSignatureBuf","index","rLength","sLength","rPadded","sPadded","verifyEnclaveSignature","_x3","_x4","_x5","_verifyEnclaveSignature","_callee5","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context5","prod","preprod","__TURNKEY_SIGNER_ENVIRONMENT__","undefined","verify","hash","sendMessageUp","type","requestId","message","postMessage","parent","content","messageLog","document","getElementById","createElement","innerText","appendChild","logMessage","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","carry","push","j","currentByte","result","reverse","base58CheckDecode","_x7","_base58CheckDecode","_callee7","decoded","payload","checksum","hash1Buf","hash1","hash2Buf","hash2","computedChecksum","_context7","subarray","digest","decodeKey","_x8","_x9","_decodeKey","_callee8","privateKey","keyFormat","decodedKeyBytes","version","keyAndFlags","_payload","_version","_keyAndFlags","_bech32$decode","prefix","words","bytes","schemeFlag","privkey","_context8","t0","bech32","decode","fromWords","console","warn","validateStyles","styles","element","validStyles","cssValidationRegex","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref","_ref2","_arrayWithHoles","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","SharedTKHQ","applySettings","validSettings","settingsObj","passphraseLabel","mnemonicLabel","passphraseTextarea","plaintextTextarea","enablePassphrase","style","display","border","_slicedToArray","key","documentElement","body","passphraseStyles","_ref3","_ref4","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","_objectSpread","_defineProperty","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","TextEncoder","encode","HpkeEncrypt","_HpkeEncrypt","plaintextBuf","receiverPubJwk","kemContext","receiverPub","suite","senderCtx","receiverPubCryptoKey","receiverPubRaw","encappedKeyBuf","aad","ciphertextBuf","ciphertextHex","encappedKeyBufHex","encryptedBundle","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createSenderContext","recipientPublicKey","info","enc","seal","encappedPublic","ciphertext"],"sourceRoot":""} \ No newline at end of file From 51d986791be7cc64ea1ecb61a486e1bb745613a9 Mon Sep 17 00:00:00 2001 From: Ethan Konkolowicz Date: Wed, 11 Feb 2026 20:42:05 -0500 Subject: [PATCH 3/7] fixed sub-org specific bundles leaking to other sub-org sessions --- .../dist/bundle.3f29bf7d8e30fb1dd823.js | 3 + ...undle.3f29bf7d8e30fb1dd823.js.LICENSE.txt} | 0 .../dist/bundle.3f29bf7d8e30fb1dd823.js.map | 1 + .../dist/bundle.8ccdeed719db48416e34.js | 3 - .../dist/bundle.8ccdeed719db48416e34.js.map | 1 - export-and-sign/dist/index.html | 2 +- export-and-sign/index.test.js | 14 ++--- export-and-sign/src/event-handlers.js | 31 ++++++--- .../551.bundle.27da59437a4e403e3c24.js.map | 2 +- shared/turnkey-core.js | 63 ++++++++++++++----- 10 files changed, 85 insertions(+), 35 deletions(-) create mode 100644 export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js rename export-and-sign/dist/{bundle.8ccdeed719db48416e34.js.LICENSE.txt => bundle.3f29bf7d8e30fb1dd823.js.LICENSE.txt} (100%) create mode 100644 export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js.map delete mode 100644 export-and-sign/dist/bundle.8ccdeed719db48416e34.js delete mode 100644 export-and-sign/dist/bundle.8ccdeed719db48416e34.js.map diff --git a/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js b/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js new file mode 100644 index 0000000..8340d5c --- /dev/null +++ b/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js @@ -0,0 +1,3 @@ +/*! For license information please see bundle.3f29bf7d8e30fb1dd823.js.LICENSE.txt */ +(()=>{var e,t,r,n,a,o={560:(e,t,r)=>{"use strict";var n=r(598),a=r(443),o=r(566);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function c(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function u(e){for(var t=1;t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var l=[][n]?t(t([][n]())):(d(t={},n,function(){return this}),t),p=s.prototype=c.prototype=Object.create(l);function y(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,d(e,a,"GeneratorFunction")),e.prototype=Object.create(p),e}return u.prototype=s,d(p,"constructor",s),d(s,"constructor",u),u.displayName="GeneratorFunction",d(s,a,"GeneratorFunction"),d(p),d(p,a,"Generator"),d(p,n,function(){return this}),d(p,"toString",function(){return"[object Generator]"}),(f=function(){return{w:o,m:y}})()}function d(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}d=function(e,t,r,n){function o(t,r){d(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},d(e,t,r,n)}function l(e){return function(e){if(Array.isArray(e))return v(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||y(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,a,o,i,c=[],u=!0,s=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=o.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,a=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw a}}return c}}(e,t)||y(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(e,t){if(e){if("string"==typeof e)return v(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?v(e,t):void 0}}function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1:window.parent!==window.top}function k(){return(k=g(f().m(function e(t){var r;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=S()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,r.importKey("raw",t,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function P(){return(P=g(f().m(function e(){return f().w(function(e){for(;;)switch(e.n){case 0:if(!O()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,_();case 2:if(null!==e.v){e.n=4;break}return e.n=3,j();case 3:x(e.v);case 4:return e.a(2)}},e)}))).apply(this,arguments)}function j(){return I.apply(this,arguments)}function I(){return(I=g(f().m(function e(){var t,r;return f().w(function(e){for(;;)switch(e.n){case 0:if(t=S()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,t.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return r=e.v,e.n=3,t.exportKey("jwk",r.privateKey);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function _(){var e=R(m);return e?JSON.parse(e):null}function x(e){A(m,JSON.stringify(e),1728e5)}function T(){var e=window.localStorage.getItem(w);if(!e)return null;try{return JSON.parse(e)}catch(e){return window.localStorage.removeItem(w),null}}function A(e,t,r){var n={value:t,expiry:(new Date).getTime()+r};window.localStorage.setItem(e,JSON.stringify(n))}function R(e){var t=window.localStorage.getItem(e);if(!t)return null;var r=JSON.parse(t);return Object.prototype.hasOwnProperty.call(r,"expiry")&&Object.prototype.hasOwnProperty.call(r,"value")?(new Date).getTime()>r.expiry?(window.localStorage.removeItem(e),null):r.value:(window.localStorage.removeItem(e),null)}function D(e){if(!e||"string"!=typeof e)throw new Error("cannot create uint8array from invalid hex string");var t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0||!/^[0-9A-Fa-f]+$/.test(t))throw new Error("cannot create uint8array from invalid hex string");return new Uint8Array(t.match(/../g).map(function(e){return parseInt(e,16)}))}function N(e){return l(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function M(e,t){var r=Array.from(new Uint8Array(e)),n=Array.from(new Uint8Array(t));return new Uint8Array([].concat(r,n))}function U(e){var t=document.getElementById("message-log");if(t){var r=document.createElement("p");r.innerText=e,t.appendChild(r)}}function K(e){return C.apply(this,arguments)}function C(){return(C=g(f().m(function e(t){var r,n,a,o;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=S()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return delete(n=u({},t)).d,n.key_ops=["verify"],e.n=2,r.importKey("jwk",n,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return a=e.v,e.n=3,r.exportKey("raw",a);case 3:return o=e.v,e.a(2,new Uint8Array(o))}},e)}))).apply(this,arguments)}function B(e){for(var t="",r=[0],n=0;n0;)r.push(a%58),a=a/58|0}for(var i=0;i0;){var c=r[i];o=(c=void 0===c?o:58*c+o)>>8,r[i]=c%256,i++}}var u=n.concat(r.reverse());return new Uint8Array(u)}function G(){return(G=g(f().m(function e(t,r,n){var a,o;return f().w(function(e){for(;;)switch(e.n){case 0:o=r,e.n="SOLANA"===o?1:"HEXADECIMAL"===o?5:6;break;case 1:if(n){e.n=2;break}throw new Error("public key must be specified for SOLANA key format");case 2:if(32===t.length){e.n=3;break}throw new Error("invalid private key length. Expected 32 bytes. Got ".concat(t.length,"."));case 3:if(32===n.length){e.n=4;break}throw new Error("invalid public key length. Expected 32 bytes. Got ".concat(n.length,"."));case 4:return(a=new Uint8Array(64)).set(t,0),a.set(n,32),e.a(2,B(a));case 5:return e.a(2,"0x"+N(t));case 6:return console.warn("invalid key format: ".concat(r,". Defaulting to HEXADECIMAL.")),e.a(2,"0x"+N(t));case 7:return e.a(2)}},e)}))).apply(this,arguments)}function F(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",a=r.toStringTag||"@@toStringTag";function o(r,n,a,o){var u=n&&n.prototype instanceof c?n:c,s=Object.create(u.prototype);return H(s,"_invoke",function(r,n,a){var o,c,u,s=0,f=a||[],d=!1,l={p:0,n:0,v:e,a:p,f:p.bind(e,4),d:function(t,r){return o=t,c=0,u=e,l.n=r,i}};function p(r,n){for(c=r,u=n,t=0;!d&&s&&!a&&t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(H(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,H(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,H(d,"constructor",s),H(s,"constructor",u),u.displayName="GeneratorFunction",H(s,a,"GeneratorFunction"),H(d),H(d,a,"Generator"),H(d,n,function(){return this}),H(d,"toString",function(){return"[object Generator]"}),(F=function(){return{w:o,m:l}})()}function H(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}H=function(e,t,r,n){function o(t,r){H(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},H(e,t,r,n)}function Y(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r]*$',color:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",labelColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",backgroundColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",width:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",height:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",maxWidth:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",maxHeight:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",lineHeight:"^(\\d+(\\.\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$",boxShadow:"^(none|(\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)) ?(inset)?)$",textAlign:"^(left|right|center|justify|initial|inherit)$",overflowWrap:"^(normal|break-word|anywhere)$",wordWrap:"^(normal|break-word)$",resize:"^(none|both|horizontal|vertical|block|inline)$"};return Object.entries(e).forEach(function(e){var t=p(e,2),a=t[0],o=t[1],i=a.trim();if(0===i.length)throw new Error("css style property cannot be empty");var c=n[i];if(!c)throw new Error('invalid or unsupported css style property: "'.concat(i,'"'));var u=new RegExp(c),s=o.trim();if(0==s.length)throw new Error('css style for "'.concat(i,'" is empty'));if(!u.test(s))throw new Error('invalid css style value for property "'.concat(i,'"'));r[i]=s}),r},V=O,Q=function(e){return k.apply(this,arguments)},Z=T;function ee(){return(ee=J(F().m(function e(){return F().w(function(e){for(;;)switch(e.n){case 0:if(!V()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,q();case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function te(){return(te=J(F().m(function e(t,r,n){var a,i,c,u,s,f,d,l;return F().w(function(e){for(;;)switch(e.n){case 0:if(a={prod:"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569",preprod:"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212"},i=null,"undefined"!=typeof document&&(c=document.querySelector('meta[name="turnkey-signer-environment"]'))&&c.content&&"__TURNKEY_SIGNER_ENVIRONMENT__"!==c.content&&(i=c.content),i||"undefined"==typeof window||(i=window.__TURNKEY_SIGNER_ENVIRONMENT__),void 0!==(u=a[i])){e.n=1;break}throw new Error("Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined");case 1:if(t===u){e.n=2;break}throw new Error("enclave quorum public keys from client and bundle do not match. Client: ".concat(u,". Bundle: ").concat(t,"."));case 2:return s=new Uint8Array($(u)),e.n=3,Q(s);case 3:if(f=e.v){e.n=4;break}throw new Error("failed to load quorum key");case 4:return d=(0,o.g8)(r),l=$(n),e.n=5,crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},f,d,l);case 5:return e.a(2,e.v)}},e)}))).apply(this,arguments)}var re={initEmbeddedKey:function(){return ee.apply(this,arguments)},generateTargetKey:j,setItemWithExpiry:A,getItemWithExpiry:R,getEmbeddedKey:_,setEmbeddedKey:x,onResetEmbeddedKey:function(){window.localStorage.removeItem(m),window.localStorage.removeItem("TURNKEY_EMBEDDED_KEY_ORIGIN")},p256JWKPrivateToPublic:K,base58Encode:B,base58Decode:L,encodeKey:function(e,t,r){return G.apply(this,arguments)},sendMessageUp:function(e,t,r){var n={type:e,value:t};r&&(n.requestId=r),E?E.postMessage(n):window.parent!==window&&window.parent.postMessage({type:e,value:t},"*"),U("⬆️ Sent message ".concat(e,": ").concat(t))},logMessage:U,uint8arrayFromHexString:$,uint8arrayToHexString:N,setParentFrameMessageChannelPort:function(e){E=e},normalizePadding:function(e,t){var r=t-e.length;if(r>0){var n=new Uint8Array(r).fill(0);return new Uint8Array([].concat(l(n),l(e)))}if(r<0){for(var a=-1*r,o=0,i=0;i3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(se(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,se(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,se(d,"constructor",s),se(s,"constructor",u),u.displayName="GeneratorFunction",se(s,a,"GeneratorFunction"),se(d),se(d,a,"Generator"),se(d,n,function(){return this}),se(d,"toString",function(){return"[object Generator]"}),(ue=function(){return{w:o,m:l}})()}function se(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}se=function(e,t,r,n){function o(t,r){se(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},se(e,t,r,n)}function fe(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,a,o,i,c=[],u=!0,s=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=o.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,a=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw a}}return c}}(e,t)||function(e,t){if(e){if("string"==typeof e)return de(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?de(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function de(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r= v2.0.0 to pass "organizationId" for security purposes.');case 8:if(a.organizationId&&a.organizationId===r){e.n=9;break}throw new Error("organization id does not match expected value. Expected: ".concat(r,". Found: ").concat(a.organizationId,"."));case 9:if(a.encappedPublic){e.n=10;break}throw new Error('missing "encappedPublic" in bundle signed data');case 10:if(a.ciphertext){e.n=11;break}throw new Error('missing "ciphertext" in bundle signed data');case 11:return e.a(2,a)}},e)}))).apply(this,arguments)}function we(e,t,r){return Ee.apply(this,arguments)}function Ee(){return Ee=pe(ue().m(function e(t,r,n){var a,o,i,c;return ue().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,me(t,r);case 1:return a=e.v,o=re.uint8arrayFromHexString(a.encappedPublic),i=re.uint8arrayFromHexString(a.ciphertext),e.n=2,re.getEmbeddedKey();case 2:return c=e.v,e.n=3,n({ciphertextBuf:i,encappedKeyBuf:o,receiverPrivJwk:c});case 3:return e.a(2,e.v)}},e)})),Ee.apply(this,arguments)}function Se(e){return Oe.apply(this,arguments)}function Oe(){return(Oe=pe(ue().m(function e(t){var r,n,a;return ue().w(function(e){for(;;)switch(e.n){case 0:if(r=re.getEmbeddedKey()){e.n=1;break}return re.sendMessageUp("EMBEDDED_PUBLIC_KEY","",t),e.a(2);case 1:return e.n=2,re.p256JWKPrivateToPublic(r);case 2:n=e.v,a=re.uint8arrayToHexString(n),re.sendMessageUp("EMBEDDED_PUBLIC_KEY",a,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function ke(e,t,r,n){return Pe.apply(this,arguments)}function Pe(){return(Pe=pe(ue().m(function e(t,r,n,a){var o,i,c,u,s,f;return ue().w(function(e){for(;;)switch(e.n){case 0:if(i=new Uint8Array(r),"SOLANA"!==n){e.n=2;break}return c=re.uint8arrayToHexString(i.subarray(0,32)),u=re.getEd25519PublicKey(c),e.n=1,re.encodeKey(i,n,u);case 1:o=e.v,e.n=4;break;case 2:return e.n=3,re.encodeKey(i,n);case 3:o=e.v;case 4:if(s=t||"default","SOLANA"!==n){e.n=5;break}f=ne.AX.fromSecretKey(re.base58Decode(o)),e.n=7;break;case 5:if("HEXADECIMAL"!==n){e.n=7;break}return e.n=6,ze(Array.from(re.uint8arrayFromHexString(o)));case 6:f=e.v;case 7:ye=ie(ie({},ye),{},ce({},s,{organizationId:a,privateKey:o,format:n,expiry:(new Date).getTime()+864e5,keypair:f}));case 8:return e.a(2)}},e)}))).apply(this,arguments)}function je(e,t,r,n,a,o){return Ie.apply(this,arguments)}function Ie(){return Ie=pe(ue().m(function e(t,r,n,a,o,i){var c;return ue().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,we(n,r,i);case 1:return c=e.v,e.n=2,ke(o,c,a,r);case 2:re.sendMessageUp("BUNDLE_INJECTED",!0,t);case 3:return e.a(2)}},e)})),Ie.apply(this,arguments)}function _e(e,t){return xe.apply(this,arguments)}function xe(){return(xe=pe(ue().m(function e(t,r){var n;return ue().w(function(e){for(;;)switch(e.n){case 0:n=re.applySettings(t),re.setSettings(n),re.sendMessageUp("SETTINGS_APPLIED",!0,r);case 1:return e.a(2)}},e)}))).apply(this,arguments)}function Te(e,t,r){return Ae.apply(this,arguments)}function Ae(){return(Ae=pe(ue().m(function e(t,r,n){var a,o,i,c,u,s,f,d,l;return ue().w(function(e){for(;;)switch(e.n){case 0:if($e(o=ye[a=n||"default"],a)){e.n=1;break}return e.a(2);case 1:return e.n=2,We(o);case 2:if(i=e.v,c=JSON.parse(r),u=c.transaction,"SOLANA"!==c.type){e.n=3;break}f=re.uint8arrayFromHexString(u),(d=ne.Kt.deserialize(f)).sign([i]),s=d.serialize(),e.n=4;break;case 3:throw new Error("unsupported transaction type");case 4:l=re.uint8arrayToHexString(s),re.sendMessageUp("TRANSACTION_SIGNED",l,t);case 5:return e.a(2)}},e)}))).apply(this,arguments)}function Re(e,t,r){return De.apply(this,arguments)}function De(){return De=pe(ue().m(function e(t,r,o){var i,c,u,s,f,d,l,p,y,v;return ue().w(function(e){for(;;)switch(e.n){case 0:if($e(c=ye[i=o||"default"],i)){e.n=1;break}return e.a(2);case 1:return u=JSON.parse(r),s=u.message,f=u.type,d=be.encode(s),e.n=2,We(c);case 2:if(p=e.v,"SOLANA"!==f){e.n=3;break}n.jn.sha512Sync=function(){var e;return a.Zf((e=n.jn).concatBytes.apply(e,arguments))},y=p.secretKey.slice(0,32),v=n._S(d,y),l=re.uint8arrayToHexString(v),e.n=4;break;case 3:return re.sendMessageUp("ERROR","unsupported message type",t),e.a(2);case 4:re.sendMessageUp("MESSAGE_SIGNED",l,t);case 5:return e.a(2)}},e)})),De.apply(this,arguments)}function Ne(e,t){return Me.apply(this,arguments)}function Me(){return(Me=pe(ue().m(function e(t,r){return ue().w(function(e){for(;;)switch(e.n){case 0:if(r){e.n=1;break}return ye={},re.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t),e.a(2);case 1:if(ye[r]){e.n=2;break}return re.sendMessageUp("ERROR",new Error("key not found for address ".concat(r,". Note that address is case sensitive.")).toString(),t),e.a(2);case 2:delete ye[r],re.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function Ue(e,t,r,n,a,o){return Ke.apply(this,arguments)}function Ke(){return Ke=pe(ue().m(function e(t,r,n,a,o,i){var c,u,s,f,d;return ue().w(function(e){for(;;)switch(e.n){case 0:if(o){e.n=1;break}throw new Error("address is required for STORE_ENCRYPTED_BUNDLE");case 1:return e.n=2,me(n,r);case 2:if(c=e.v,u=a||"HEXADECIMAL",re.setEncryptedBundle(o,{encappedPublic:c.encappedPublic,ciphertext:c.ciphertext,organizationId:r,keyFormat:u}),!ve||!i){e.n=4;break}return s=re.uint8arrayFromHexString(c.encappedPublic),f=re.uint8arrayFromHexString(c.ciphertext),e.n=3,i({ciphertextBuf:f,encappedKeyBuf:s,receiverPrivJwk:ve});case 3:return d=e.v,e.n=4,ke(o,d,u,r);case 4:re.sendMessageUp("ENCRYPTED_BUNDLE_STORED",!0,t);case 5:return e.a(2)}},e)})),Ke.apply(this,arguments)}function Ce(e){return Be.apply(this,arguments)}function Be(){return(Be=pe(ue().m(function e(t){var r,n,a;return ue().w(function(e){for(;;)switch(e.n){case 0:if(32===t.length){e.n=1;break}throw new Error("invalid decryption key length: expected 32 bytes, got ".concat(t.length));case 1:return r=new Uint8Array([48,65,2,1,0,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,4,39,48,37,2,1,1,4,32]),(n=new Uint8Array(r.length+32)).set(r),n.set(t,r.length),e.n=2,crypto.subtle.importKey("pkcs8",n,{name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return a=e.v,e.n=3,crypto.subtle.exportKey("jwk",a);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function Le(e,t,r,n){return Ge.apply(this,arguments)}function Ge(){return Ge=pe(ue().m(function e(t,r,n,a){var o,i,c,u,s,f,d,l,p,y,v,b,g,m;return ue().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.n=1,we(n,r,a);case 1:return o=e.v,e.n=2,Ce(new Uint8Array(o));case 2:if(i=e.v,ve=i,c=re.getEncryptedBundles(),u=0,!c){e.n=10;break}s=Object.keys(c),f=0,d=s;case 3:if(!(f=e.expiry)throw function(){for(var e=(new Date).getTime(),t=[],r=0,n=Object.entries(ye);r=i.expiry&&t.push(o)}for(var c=0,u=t;c3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(tt(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,tt(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,tt(d,"constructor",s),tt(s,"constructor",u),u.displayName="GeneratorFunction",tt(s,a,"GeneratorFunction"),tt(d),tt(d,a,"Generator"),tt(d,n,function(){return this}),tt(d,"toString",function(){return"[object Generator]"}),(et=function(){return{w:o,m:l}})()}function tt(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}tt=function(e,t,r,n){function o(t,r){tt(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},tt(e,t,r,n)}function rt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function nt(e){for(var t=1;t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(ft(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,ft(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,ft(d,"constructor",s),ft(s,"constructor",u),u.displayName="GeneratorFunction",ft(s,a,"GeneratorFunction"),ft(d),ft(d,a,"Generator"),ft(d,n,function(){return this}),ft(d,"toString",function(){return"[object Generator]"}),(st=function(){return{w:o,m:l}})()}function ft(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}ft=function(e,t,r,n){function o(t,r){ft(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},ft(e,t,r,n)}function dt(e,t,r,n,a,o,i){try{var c=e[o](i),u=c.value}catch(e){return void r(e)}c.done?t(u):Promise.resolve(u).then(n,a)}function lt(e){return function(){var t=this,r=arguments;return new Promise(function(n,a){var o=e.apply(t,r);function i(e){dt(o,n,a,i,c,"next",e)}function c(e){dt(o,n,a,i,c,"throw",e)}i(void 0)})}}window.TKHQ=re,document.addEventListener("DOMContentLoaded",lt(st().m(function e(){var t,r,n,a;return st().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,re.initEmbeddedKey();case 1:return e.n=2,re.getEmbeddedKey();case 2:return t=e.v,e.n=3,re.p256JWKPrivateToPublic(t);case 3:r=e.v,n=re.uint8arrayToHexString(r),document.getElementById("embedded-key").value=n,Ve(ct),(a=re.getSettings())&&re.applySettings(a),re.sendMessageUp("PUBLIC_KEY_READY",n);case 4:return e.a(2)}},e)})))},790:()=>{},846:e=>{"use strict";e.exports=crypto}},i={};function c(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={id:e,loaded:!1,exports:{}};return o[e].call(r.exports,r,r.exports,c),r.loaded=!0,r.exports}c.m=o,e=[],c.O=(t,r,n,a)=>{if(!r){var o=1/0;for(f=0;f=a)&&Object.keys(c.O).every(e=>c.O[e](r[u]))?r.splice(u--,1):(i=!1,a0&&e[f-1][2]>a;f--)e[f]=e[f-1];e[f]=[r,n,a]},c.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return c.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,c.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var a=Object.create(null);c.r(a);var o={};t=t||[null,r({}),r([]),r(r)];for(var i=2&n&&e;("object"==typeof i||"function"==typeof i)&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach(t=>o[t]=()=>e[t]);return o.default=()=>e,c.d(a,o),a},c.d=(e,t)=>{for(var r in t)c.o(t,r)&&!c.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},c.f={},c.e=e=>Promise.all(Object.keys(c.f).reduce((t,r)=>(c.f[r](e,t),t),[])),c.u=e=>"bundle."+{291:"3eaea85f4001b9cc63c3",825:"aaba32bf7338e3d0f1cc"}[e]+".js",c.miniCssF=e=>{},c.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),c.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},a="export-and-sign:",c.l=(e,t,r,o)=>{if(n[e])n[e].push(t);else{var i,u;if(void 0!==r)for(var s=document.getElementsByTagName("script"),f=0;f{i.onerror=i.onload=null,clearTimeout(p);var a=n[e];if(delete n[e],i.parentNode&&i.parentNode.removeChild(i),a&&a.forEach(e=>e(r)),t)return t(r)},p=setTimeout(l.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=l.bind(null,i.onerror),i.onload=l.bind(null,i.onload),u&&document.head.appendChild(i)}},c.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),c.p="/",c.sriHashes={291:"sha384-G5pDFEAG9UZITbluyje/R/rWohZTUJf+Vu3ZIh0rsnLFLTw3SP/ca/XVNZVtv48f",825:"sha384-R9OIdd42i5GcdtZiHJuQgIUVvqyqJ0s7eaBnJHAfGllpi4YwbF7NSkjIRwOPUtsP"},(()=>{var e={792:0};c.f.j=(t,r)=>{var n=c.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[2]);else{var a=new Promise((r,a)=>n=e[t]=[r,a]);r.push(n[2]=a);var o=c.p+c.u(t),i=new Error;c.l(o,r=>{if(c.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var a=r&&("load"===r.type?"missing":r.type),o=r&&r.target&&r.target.src;i.message="Loading chunk "+t+" failed.\n("+a+": "+o+")",i.name="ChunkLoadError",i.type=a,i.request=o,n[1](i)}},"chunk-"+t,t)}},c.O.j=t=>0===e[t];var t=(t,r)=>{var n,a,[o,i,u]=r,s=0;if(o.some(t=>0!==e[t])){for(n in i)c.o(i,n)&&(c.m[n]=i[n]);if(u)var f=u(c)}for(t&&t(r);sc(560));u=c.O(u)})(); +//# sourceMappingURL=bundle.3f29bf7d8e30fb1dd823.js.map \ No newline at end of file diff --git a/export-and-sign/dist/bundle.8ccdeed719db48416e34.js.LICENSE.txt b/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js.LICENSE.txt similarity index 100% rename from export-and-sign/dist/bundle.8ccdeed719db48416e34.js.LICENSE.txt rename to export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js.LICENSE.txt diff --git a/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js.map b/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js.map new file mode 100644 index 0000000..06ec1cc --- /dev/null +++ b/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bundle.3f29bf7d8e30fb1dd823.js","mappings":";UAAIA,ECCAC,EADAC,ECAAC,EACAC,E,svCCAJ,IAAAC,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,E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xE,EAClC,CAEA,IADGsE,GAA4BA,EAA2B1f,GACrD7G,EAAIwiB,EAASxhB,OAAQhB,IACzB2jB,EAAUnB,EAASxiB,GAChBiiB,EAAoBniB,EAAEimB,EAAiBpC,IAAYoC,EAAgBpC,IACrEoC,EAAgBpC,GAAS,KAE1BoC,EAAgBpC,GAAW,EAE5B,OAAO1B,EAAoBM,EAAErY,IAG1Byc,EAAqBC,KAAkC,4BAAIA,KAAkC,6BAAK,GACtGD,EAAmBpZ,QAAQ+Y,EAAqBvlB,KAAK,KAAM,IAC3D4lB,EAAmB3jB,KAAOsjB,EAAqBvlB,KAAK,KAAM4lB,EAAmB3jB,KAAKjC,KAAK4lB,G,KClFvF,IAAIE,EAAsB5E,EAAoBM,OAAE3d,EAAW,CAAC,IAAK,IAAOqd,EAAoB,MAC5F4E,EAAsB5E,EAAoBM,EAAEsE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/../shared/turnkey-core.js","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/../shared/crypto-utils.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/external var \"crypto\"","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/global","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/compat","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t\tif (script.src.indexOf(window.location.origin + '/') !== 0) {\n\t\t\tscript.crossOrigin = \"anonymous\";\n\t\t}\n\t\tscript.integrity = __webpack_require__.sriHashes[chunkId];\n\t\tscript.crossOrigin = \"anonymous\";\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n if (!data) {\n return null;\n }\n try {\n return JSON.parse(data);\n } catch (e) {\n // If the stored data is corrupted or not valid JSON, remove it to self-heal.\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n return null;\n }\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * Only removes the bundle if it belongs to the specified organization.\n * @param {string} address - The wallet address to remove\n * @param {string} organizationId - Only remove if the bundle belongs to this org\n */\nfunction removeEncryptedBundle(address, organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles || !bundles[address]) return;\n\n // Only remove if the bundle belongs to the specified organization\n if (bundles[address].organizationId !== organizationId) return;\n\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n}\n\n/**\n * Removes all encrypted bundles belonging to the specified organization.\n * Bundles from other organizations are preserved.\n * @param {string} organizationId - Remove bundles belonging to this org\n */\nfunction clearAllEncryptedBundles(organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles) return;\n\n // Keep only bundles that do NOT belong to this organization\n const remaining = Object.fromEntries(\n Object.entries(bundles).filter(\n ([, bundle]) => bundle.organizationId !== organizationId\n )\n );\n\n if (Object.keys(remaining).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(remaining)\n );\n }\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\nimport { fromDerSignature } from \"@turnkey/crypto\";\nimport * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n initEmbeddedKey: sharedInitEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n additionalAssociatedData,\n getSettings,\n setSettings,\n parsePrivateKey,\n validateStyles,\n isDoublyIframed,\n loadQuorumKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n} = SharedTKHQ;\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n return await sharedInitEmbeddedKey();\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Read environment from meta tag (templated at deploy time), fall back to window variable (for testing)\n let environment = null;\n if (typeof document !== \"undefined\") {\n const meta = document.querySelector(\n 'meta[name=\"turnkey-signer-environment\"]'\n );\n if (\n meta &&\n meta.content &&\n meta.content !== \"__TURNKEY_SIGNER_ENVIRONMENT__\"\n ) {\n environment = meta.content;\n }\n }\n if (!environment && typeof window !== \"undefined\") {\n environment = window.__TURNKEY_SIGNER_ENVIRONMENT__;\n }\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\n// Decryption key -- held in memory only, never persisted to localStorage.\n// This is a P-256 private key in JWK format used to decrypt stored bundles.\nlet decryptionKey = null;\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Verifies the enclave signature on a v1.0.0 bundle and returns the parsed signed data.\n * @param {string} bundle - JSON-stringified bundle\n * @param {string} organizationId - Expected organization ID\n * @returns {Promise} - The parsed signed data {organizationId, encappedPublic, ciphertext}\n */\nasync function verifyAndParseBundleData(bundle, organizationId) {\n const bundleObj = JSON.parse(bundle);\n\n if (bundleObj.version !== \"v1.0.0\") {\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n const verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(`failed to verify enclave signature: ${bundle}`);\n }\n\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n\n return signedData;\n}\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n // Decrypt the ciphertext\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: embeddedKeyJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Encodes raw key bytes and loads them into the in-memory key store.\n * @param {string} address - Wallet address (case-sensitive)\n * @param {ArrayBuffer} keyBytes - Raw decrypted private key bytes\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} organizationId - Organization ID\n */\nasync function loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId) {\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair,\n },\n };\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Load decrypted key into memory\n await loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId);\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Set up sha512 for nobleEd25519 (required for signing)\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n\n // Extract the 32-byte private key from the 64-byte secretKey\n // Solana keypair.secretKey format: [32-byte private key][32-byte public key]\n const privateKey = keypair.secretKey.slice(0, 32);\n // Sign the message using nobleEd25519\n const signature = nobleEd25519.sign(messageBytes, privateKey);\n\n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n/**\n * Handler for STORE_ENCRYPTED_BUNDLE events.\n * Verifies the enclave signature on an encrypted bundle and stores\n * the encrypted payload in localStorage for later decryption.\n * If the decryption key is already in memory, also decrypts and loads\n * the key into memory immediately.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle JSON\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} address - Wallet address\n * @param {Function} HpkeDecrypt\n */\nasync function onStoreEncryptedBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n if (!address) {\n throw new Error(\"address is required for STORE_ENCRYPTED_BUNDLE\");\n }\n\n // Verify enclave signature and parse the signed data\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const resolvedKeyFormat = keyFormat || \"HEXADECIMAL\";\n\n // Store the encrypted fields in localStorage (just what's needed for decryption)\n TKHQ.setEncryptedBundle(address, {\n encappedPublic: signedData.encappedPublic,\n ciphertext: signedData.ciphertext,\n organizationId: organizationId,\n keyFormat: resolvedKeyFormat,\n });\n\n // If the decryption key is already in memory, decrypt and load immediately\n if (decryptionKey && HpkeDecrypt) {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n await loadKeyIntoMemory(\n address,\n keyBytes,\n resolvedKeyFormat,\n organizationId\n );\n }\n\n TKHQ.sendMessageUp(\"ENCRYPTED_BUNDLE_STORED\", true, requestId);\n}\n\n/**\n * Converts raw P-256 private key bytes (32-byte scalar) to a JWK.\n * Constructs a PKCS8 wrapper around the raw bytes, imports via WebCrypto\n * (which derives the public key), then exports as JWK.\n * @param {Uint8Array} rawPrivateKeyBytes - 32-byte P-256 private key scalar\n * @returns {Promise} - Full P-256 ECDH private key JWK\n */\nasync function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) {\n if (rawPrivateKeyBytes.length !== 32) {\n throw new Error(\n `invalid decryption key length: expected 32 bytes, got ${rawPrivateKeyBytes.length}`\n );\n }\n\n // PKCS8 DER prefix for a P-256 private key (without optional public key field)\n // SEQUENCE {\n // INTEGER 0 (version)\n // SEQUENCE { OID ecPublicKey, OID P-256 }\n // OCTET STRING { SEQUENCE { INTEGER 1, OCTET STRING(32) } }\n // }\n const pkcs8Prefix = new Uint8Array([\n 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48,\n 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03,\n 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20,\n ]);\n\n const pkcs8 = new Uint8Array(pkcs8Prefix.length + 32);\n pkcs8.set(pkcs8Prefix);\n pkcs8.set(rawPrivateKeyBytes, pkcs8Prefix.length);\n\n const cryptoKey = await crypto.subtle.importKey(\n \"pkcs8\",\n pkcs8,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"]\n );\n\n return await crypto.subtle.exportKey(\"jwk\", cryptoKey);\n}\n\n/**\n * Handler for INJECT_DECRYPTION_KEY_BUNDLE events.\n * Decrypts the P-256 private key using the iframe's embedded key,\n * then iterates all stored encrypted bundles, HPKE-decrypts each one\n * with the key, and loads them into inMemoryKeys.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle containing the private key\n * @param {Function} HpkeDecrypt\n */\nasync function onInjectDecryptionKeyBundle(\n requestId,\n organizationId,\n bundle,\n HpkeDecrypt\n) {\n // Decrypt the private key using the iframe's embedded key.\n // The decrypted payload is a raw 32-byte P-256 private key scalar.\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto)\n const keyJwk = await rawP256PrivateKeyToJwk(new Uint8Array(keyBytes));\n\n // Store in module-level variable (memory only)\n decryptionKey = keyJwk;\n\n // Iterate all stored encrypted bundles and decrypt each one\n const storedBundles = TKHQ.getEncryptedBundles();\n let decryptedCount = 0;\n\n if (storedBundles) {\n const addresses = Object.keys(storedBundles);\n\n for (const addr of addresses) {\n const bundleData = storedBundles[addr];\n\n try {\n const bundleOrgId = bundleData.organizationId;\n\n if (organizationId !== bundleOrgId) continue; // skip bundles that don't match the organization ID of the decryption key\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n bundleData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(\n bundleData.ciphertext\n );\n\n // HPKE-decrypt using the key\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n // Load the decrypted key into memory\n await loadKeyIntoMemory(\n addr,\n keyBytes,\n bundleData.keyFormat,\n bundleData.organizationId\n );\n\n decryptedCount++;\n } catch (e) {\n TKHQ.logMessage(\n `Failed to decrypt bundle for address ${addr}: ${e.toString()}`\n );\n }\n }\n }\n\n TKHQ.sendMessageUp(\"DECRYPTION_KEY_INJECTED\", decryptedCount, requestId);\n}\n\n/**\n * Handler for BURN_SESSION events.\n * Clears the decryption key and all in-memory wallet keys.\n * Encrypted bundles in localStorage are preserved for the next session.\n * @param {string} requestId\n */\nfunction onBurnSession(requestId) {\n decryptionKey = null;\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"SESSION_BURNED\", true, requestId);\n}\n\n/**\n * Handler for GET_STORED_WALLET_ADDRESSES events.\n * Returns a JSON array of all wallet addresses that have encrypted bundles in localStorage.\n * @param {string} requestId\n * @param {string} organizationId - Organization ID to filter addresses by (only return addresses with bundles matching the organization ID)\n */\nfunction onGetStoredWalletAddresses(requestId, organizationId) {\n const bundles = TKHQ.getEncryptedBundles();\n const addresses = bundles\n ? Object.entries(bundles)\n .filter(([, bundle]) => bundle.organizationId === organizationId)\n .map(([address]) => address)\n : [];\n TKHQ.sendMessageUp(\n \"STORED_WALLET_ADDRESSES\",\n JSON.stringify(addresses),\n requestId\n );\n}\n\n/**\n * Handler for CLEAR_STORED_BUNDLES events.\n * Removes encrypted bundles from localStorage AND the corresponding\n * in-memory keys. If address is provided, removes only that address.\n * If no address, removes ALL encrypted bundles and ALL in-memory keys.\n * @param {string} requestId\n * @param {string} organizationId - Organization ID to filter addresses by (only remove bundles matching the organization ID)\n * @param {string|undefined} address - Optional wallet address\n */\nfunction onClearStoredBundles(requestId, address, organizationId) {\n if (address) {\n TKHQ.removeEncryptedBundle(address, organizationId);\n delete inMemoryKeys[address];\n } else {\n TKHQ.clearAllEncryptedBundles(organizationId);\n inMemoryKeys = {};\n }\n TKHQ.sendMessageUp(\"STORED_BUNDLES_CLEARED\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error(\n `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`\n ).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n undefined, // keyFormat - default to HEXADECIMAL\n undefined, // address - default to \"default\"\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"STORE_ENCRYPTED_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n await onStoreEncryptedBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_DECRYPTION_KEY_BUNDLE\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onInjectDecryptionKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"BURN_SESSION\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onBurnSession(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_STORED_WALLET_ADDRESSES\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onGetStoredWalletAddresses(\n event.data[\"requestId\"],\n event.data[\"organizationId\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_STORED_BUNDLES\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n onClearStoredBundles(\n event.data[\"requestId\"],\n event.data[\"address\"],\n event.data[\"organizationId\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n onStoreEncryptedBundle,\n onInjectDecryptionKeyBundle,\n onBurnSession,\n onGetStoredWalletAddresses,\n onClearStoredBundles,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"@shared/crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n","module.exports = crypto;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","\n__webpack_require__.sriHashes = {\"291\":\"*-*-*-CHUNK-SRI-HASH-r3NPGwA4ft5fHgGXhVIptCiDVf06qPa+sxzG6L+8GwPuhn89e/\",\"825\":\"*-*-*-CHUNK-SRI-HASH-mfog3UJdGPOmSk4QZbKxsxHPFZtt298WnZNc1aQ1MCgc6YirFj\"};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(560)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","_slicedToArray","_arrayWithHoles","next","push","_iterableToArrayLimit","_nonIterableRest","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","TURNKEY_ENCRYPTED_BUNDLES","parentFrameMessageChannelPort","getSubtleCrypto","globalThis","crypto","subtle","window","global","isDoublyIframed","undefined","location","ancestorOrigins","parent","top","_loadQuorumKey","_callee","quorumPublic","_context","Error","importKey","namedCurve","_initEmbeddedKey","_callee3","_context3","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee4","p256key","_context4","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","getEncryptedBundles","data","localStorage","getItem","removeItem","key","ttl","item","expiry","Date","getTime","setItem","itemStr","hasOwnProperty","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","concat","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","p256JWKPrivateToPublic","_x6","_p256JWKPrivateToPublic","_callee6","jwkPrivate","jwkPrivateCopy","publicKey","_context6","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","k","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee9","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_t2","_context9","set","console","warn","sharedInitEmbeddedKey","SharedTKHQ","validateStyles","styles","element","validStyles","cssValidationRegex","padding","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref3","_ref4","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","loadQuorumKey","_x","_verifyEnclaveSignature","_callee2","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","meta","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context2","prod","preprod","querySelector","__TURNKEY_SIGNER_ENVIRONMENT__","fromDerSignature","verify","hash","TKHQ","initEmbeddedKey","onResetEmbeddedKey","encodeKey","_x0","_x1","_x10","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","normalizePadding","byteArray","targetLength","paddingLength","fill","expectedZeroCount","zeroCount","verifyEnclaveSignature","_x2","_x3","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","_ref","_ref2","style","getSettings","setSettings","parsePrivateKey","error","setEncryptedBundle","address","bundleData","bundles","removeEncryptedBundle","organizationId","keys","clearAllEncryptedBundles","remaining","fromEntries","filter","inMemoryKeys","decryptionKey","textEncoder","TextEncoder","textDecoder","TextDecoder","verifyAndParseBundleData","_verifyAndParseBundleData","_callee8","bundle","bundleObj","_context8","version","dataSignature","decode","encappedPublic","ciphertext","decryptBundle","_x4","_x5","_decryptBundle","HpkeDecrypt","encappedKeyBuf","ciphertextBuf","embeddedKeyJwk","receiverPrivJwk","onGetPublicEmbeddedKey","_onGetPublicEmbeddedKey","_callee0","targetPubBuf","targetPubHex","_context0","loadKeyIntoMemory","_x7","_x8","_x9","_loadKeyIntoMemory","_callee1","keyBytes","keyAddress","cachedKeypair","_context1","subarray","Keypair","fromSecretKey","createSolanaKeypair","_defineProperty","format","keypair","onInjectKeyBundle","_x11","_x12","_x13","_x14","_onInjectKeyBundle","_callee10","_context10","onApplySettings","_x15","_x16","_onApplySettings","_callee11","_context11","onSignTransaction","_x17","_x18","_x19","_onSignTransaction","_callee12","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context12","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x20","_x21","_x22","_onSignMessage","_callee13","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context13","encode","secretKey","onClearEmbeddedPrivateKey","_x23","_x24","_onClearEmbeddedPrivateKey","_callee14","_context14","onStoreEncryptedBundle","_x25","_x26","_x27","_x28","_x29","_x30","_onStoreEncryptedBundle","_callee15","resolvedKeyFormat","_context15","rawP256PrivateKeyToJwk","_x31","_rawP256PrivateKeyToJwk","_callee16","rawPrivateKeyBytes","pkcs8Prefix","pkcs8","cryptoKey","_context16","onInjectDecryptionKeyBundle","_x32","_x33","_x34","_x35","_onInjectDecryptionKeyBundle","_callee17","keyJwk","storedBundles","decryptedCount","addresses","_i3","_addresses","addr","bundleOrgId","_keyBytes","_t0","_context17","onBurnSession","onGetStoredWalletAddresses","onClearStoredBundles","_x36","_createSolanaKeypair","_callee18","_context18","fromSeed","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x37","_getOrCreateKeypair","_callee19","_context19","initEventHandlers","messageEventListener","_messageEventListener","event","_t","_t3","_t4","_t5","_t6","_t7","_t8","_t9","_x43","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","_ref5","preventDefault","_x38","_ref6","_x39","_ref7","_x40","_ref8","_x41","injectWalletBtn","_ref9","_callee5","_context5","_x42","addDOMEventListeners","capture","signal","_ref0","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x44","ownKeys","getOwnPropertySymbols","getOwnPropertyDescriptor","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","_HpkeDecrypt","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","styleSettings","module","exports","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","g","Function","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","crossOrigin","integrity","sriHashes","onScriptComplete","prev","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/dist/bundle.8ccdeed719db48416e34.js b/export-and-sign/dist/bundle.8ccdeed719db48416e34.js deleted file mode 100644 index 17101ab..0000000 --- a/export-and-sign/dist/bundle.8ccdeed719db48416e34.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! For license information please see bundle.8ccdeed719db48416e34.js.LICENSE.txt */ -(()=>{var e,t,r,n,a,o={560:(e,t,r)=>{"use strict";var n=r(598),a=r(443),o=r(566);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function c(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function u(e){for(var t=1;t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,d.n=y,c=0))}if(a||r>1)return i;throw l=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){o||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var d=[][n]?t(t([][n]())):(l(t={},n,function(){return this}),t),p=s.prototype=c.prototype=Object.create(d);function y(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,l(e,a,"GeneratorFunction")),e.prototype=Object.create(p),e}return u.prototype=s,l(p,"constructor",s),l(s,"constructor",u),u.displayName="GeneratorFunction",l(s,a,"GeneratorFunction"),l(p),l(p,a,"Generator"),l(p,n,function(){return this}),l(p,"toString",function(){return"[object Generator]"}),(f=function(){return{w:o,m:y}})()}function l(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}l=function(e,t,r,n){function o(t,r){l(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},l(e,t,r,n)}function d(e){return function(e){if(Array.isArray(e))return y(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||p(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e,t){if(e){if("string"==typeof e)return y(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?y(e,t):void 0}}function y(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1:window.parent!==window.top}function O(){return(O=b(f().m(function e(t){var r;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=E()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,r.importKey("raw",t,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function k(){return(k=b(f().m(function e(){return f().w(function(e){for(;;)switch(e.n){case 0:if(!S()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,_();case 2:if(null!==e.v){e.n=4;break}return e.n=3,P();case 3:I(e.v);case 4:return e.a(2)}},e)}))).apply(this,arguments)}function P(){return j.apply(this,arguments)}function j(){return(j=b(f().m(function e(){var t,r;return f().w(function(e){for(;;)switch(e.n){case 0:if(t=E()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,t.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return r=e.v,e.n=3,t.exportKey("jwk",r.privateKey);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function _(){var e=A(g);return e?JSON.parse(e):null}function I(e){T(g,JSON.stringify(e),1728e5)}function x(){var e=window.localStorage.getItem(h);return e?JSON.parse(e):null}function T(e,t,r){var n={value:t,expiry:(new Date).getTime()+r};window.localStorage.setItem(e,JSON.stringify(n))}function A(e){var t=window.localStorage.getItem(e);if(!t)return null;var r=JSON.parse(t);return Object.prototype.hasOwnProperty.call(r,"expiry")&&Object.prototype.hasOwnProperty.call(r,"value")?(new Date).getTime()>r.expiry?(window.localStorage.removeItem(e),null):r.value:(window.localStorage.removeItem(e),null)}function R(e){if(!e||"string"!=typeof e)throw new Error("cannot create uint8array from invalid hex string");var t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0||!/^[0-9A-Fa-f]+$/.test(t))throw new Error("cannot create uint8array from invalid hex string");return new Uint8Array(t.match(/../g).map(function(e){return parseInt(e,16)}))}function D(e){return d(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function N(e,t){var r=Array.from(new Uint8Array(e)),n=Array.from(new Uint8Array(t));return new Uint8Array([].concat(r,n))}function M(e){var t=document.getElementById("message-log");if(t){var r=document.createElement("p");r.innerText=e,t.appendChild(r)}}function U(e){return K.apply(this,arguments)}function K(){return(K=b(f().m(function e(t){var r,n,a,o;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=E()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return delete(n=u({},t)).d,n.key_ops=["verify"],e.n=2,r.importKey("jwk",n,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return a=e.v,e.n=3,r.exportKey("raw",a);case 3:return o=e.v,e.a(2,new Uint8Array(o))}},e)}))).apply(this,arguments)}function C(e){for(var t="",r=[0],n=0;n0;)r.push(a%58),a=a/58|0}for(var i=0;i0;){var c=r[i];o=(c=void 0===c?o:58*c+o)>>8,r[i]=c%256,i++}}var u=n.concat(r.reverse());return new Uint8Array(u)}function L(){return(L=b(f().m(function e(t,r,n){var a,o;return f().w(function(e){for(;;)switch(e.n){case 0:o=r,e.n="SOLANA"===o?1:"HEXADECIMAL"===o?5:6;break;case 1:if(n){e.n=2;break}throw new Error("public key must be specified for SOLANA key format");case 2:if(32===t.length){e.n=3;break}throw new Error("invalid private key length. Expected 32 bytes. Got ".concat(t.length,"."));case 3:if(32===n.length){e.n=4;break}throw new Error("invalid public key length. Expected 32 bytes. Got ".concat(n.length,"."));case 4:return(a=new Uint8Array(64)).set(t,0),a.set(n,32),e.a(2,C(a));case 5:return e.a(2,"0x"+D(t));case 6:return console.warn("invalid key format: ".concat(r,". Defaulting to HEXADECIMAL.")),e.a(2,"0x"+D(t));case 7:return e.a(2)}},e)}))).apply(this,arguments)}function G(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",a=r.toStringTag||"@@toStringTag";function o(r,n,a,o){var u=n&&n.prototype instanceof c?n:c,s=Object.create(u.prototype);return F(s,"_invoke",function(r,n,a){var o,c,u,s=0,f=a||[],l=!1,d={p:0,n:0,v:e,a:p,f:p.bind(e,4),d:function(t,r){return o=t,c=0,u=e,d.n=r,i}};function p(r,n){for(c=r,u=n,t=0;!l&&s&&!a&&t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,d.n=y,c=0))}if(a||r>1)return i;throw l=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){o||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(F(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,F(e,a,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,F(l,"constructor",s),F(s,"constructor",u),u.displayName="GeneratorFunction",F(s,a,"GeneratorFunction"),F(l),F(l,a,"Generator"),F(l,n,function(){return this}),F(l,"toString",function(){return"[object Generator]"}),(G=function(){return{w:o,m:d}})()}function F(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}F=function(e,t,r,n){function o(t,r){F(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},F(e,t,r,n)}function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r]*$',color:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",labelColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",backgroundColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",width:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",height:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",maxWidth:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",maxHeight:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",lineHeight:"^(\\d+(\\.\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$",boxShadow:"^(none|(\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)) ?(inset)?)$",textAlign:"^(left|right|center|justify|initial|inherit)$",overflowWrap:"^(normal|break-word|anywhere)$",wordWrap:"^(normal|break-word)$",resize:"^(none|both|horizontal|vertical|block|inline)$"};return Object.entries(e).forEach(function(e){var t,a,o=(a=2,function(e){if(Array.isArray(e))return e}(t=e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,a,o,i,c=[],u=!0,s=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=o.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,a=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw a}}return c}}(t,a)||p(t,a)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),i=o[0],c=o[1],u=i.trim();if(0===u.length)throw new Error("css style property cannot be empty");var s=n[u];if(!s)throw new Error('invalid or unsupported css style property: "'.concat(u,'"'));var f=new RegExp(s),l=c.trim();if(0==l.length)throw new Error('css style for "'.concat(u,'" is empty'));if(!f.test(l))throw new Error('invalid css style value for property "'.concat(u,'"'));r[u]=l}),r},X=S,V=function(e){return O.apply(this,arguments)},Q=x;function Z(){return(Z=J(G().m(function e(){return G().w(function(e){for(;;)switch(e.n){case 0:if(!X()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,q();case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function ee(){return(ee=J(G().m(function e(t,r,n){var a,i,c,u,s,f,l,d;return G().w(function(e){for(;;)switch(e.n){case 0:if(a={prod:"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569",preprod:"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212"},i=null,"undefined"!=typeof document&&(c=document.querySelector('meta[name="turnkey-signer-environment"]'))&&c.content&&"__TURNKEY_SIGNER_ENVIRONMENT__"!==c.content&&(i=c.content),i||"undefined"==typeof window||(i=window.__TURNKEY_SIGNER_ENVIRONMENT__),void 0!==(u=a[i])){e.n=1;break}throw new Error("Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined");case 1:if(t===u){e.n=2;break}throw new Error("enclave quorum public keys from client and bundle do not match. Client: ".concat(u,". Bundle: ").concat(t,"."));case 2:return s=new Uint8Array(z(u)),e.n=3,V(s);case 3:if(f=e.v){e.n=4;break}throw new Error("failed to load quorum key");case 4:return l=(0,o.g8)(r),d=z(n),e.n=5,crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},f,l,d);case 5:return e.a(2,e.v)}},e)}))).apply(this,arguments)}var te={initEmbeddedKey:function(){return Z.apply(this,arguments)},generateTargetKey:P,setItemWithExpiry:T,getItemWithExpiry:A,getEmbeddedKey:_,setEmbeddedKey:I,onResetEmbeddedKey:function(){window.localStorage.removeItem(g),window.localStorage.removeItem("TURNKEY_EMBEDDED_KEY_ORIGIN")},p256JWKPrivateToPublic:U,base58Encode:C,base58Decode:B,encodeKey:function(e,t,r){return L.apply(this,arguments)},sendMessageUp:function(e,t,r){var n={type:e,value:t};r&&(n.requestId=r),w?w.postMessage(n):window.parent!==window&&window.parent.postMessage({type:e,value:t},"*"),M("⬆️ Sent message ".concat(e,": ").concat(t))},logMessage:M,uint8arrayFromHexString:z,uint8arrayToHexString:D,setParentFrameMessageChannelPort:function(e){w=e},normalizePadding:function(e,t){var r=t-e.length;if(r>0){var n=new Uint8Array(r).fill(0);return new Uint8Array([].concat(d(n),d(e)))}if(r<0){for(var a=-1*r,o=0,i=0;i3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,d.n=y,c=0))}if(a||r>1)return i;throw l=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){o||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(ue(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,ue(e,a,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,ue(l,"constructor",s),ue(s,"constructor",u),u.displayName="GeneratorFunction",ue(s,a,"GeneratorFunction"),ue(l),ue(l,a,"Generator"),ue(l,n,function(){return this}),ue(l,"toString",function(){return"[object Generator]"}),(ce=function(){return{w:o,m:d}})()}function ue(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}ue=function(e,t,r,n){function o(t,r){ue(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},ue(e,t,r,n)}function se(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,a,o,i,c=[],u=!0,s=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=o.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,a=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw a}}return c}}(e,t)||function(e,t){if(e){if("string"==typeof e)return fe(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?fe(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function fe(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r= v2.0.0 to pass "organizationId" for security purposes.');case 8:if(a.organizationId&&a.organizationId===r){e.n=9;break}throw new Error("organization id does not match expected value. Expected: ".concat(r,". Found: ").concat(a.organizationId,"."));case 9:if(a.encappedPublic){e.n=10;break}throw new Error('missing "encappedPublic" in bundle signed data');case 10:if(a.ciphertext){e.n=11;break}throw new Error('missing "ciphertext" in bundle signed data');case 11:return e.a(2,a)}},e)}))).apply(this,arguments)}function he(e,t,r){return we.apply(this,arguments)}function we(){return we=de(ce().m(function e(t,r,n){var a,o,i,c;return ce().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,ge(t,r);case 1:return a=e.v,o=te.uint8arrayFromHexString(a.encappedPublic),i=te.uint8arrayFromHexString(a.ciphertext),e.n=2,te.getEmbeddedKey();case 2:return c=e.v,e.n=3,n({ciphertextBuf:i,encappedKeyBuf:o,receiverPrivJwk:c});case 3:return e.a(2,e.v)}},e)})),we.apply(this,arguments)}function Ee(e){return Se.apply(this,arguments)}function Se(){return(Se=de(ce().m(function e(t){var r,n,a;return ce().w(function(e){for(;;)switch(e.n){case 0:if(r=te.getEmbeddedKey()){e.n=1;break}return te.sendMessageUp("EMBEDDED_PUBLIC_KEY","",t),e.a(2);case 1:return e.n=2,te.p256JWKPrivateToPublic(r);case 2:n=e.v,a=te.uint8arrayToHexString(n),te.sendMessageUp("EMBEDDED_PUBLIC_KEY",a,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function Oe(e,t,r,n){return ke.apply(this,arguments)}function ke(){return(ke=de(ce().m(function e(t,r,n,a){var o,i,c,u,s,f;return ce().w(function(e){for(;;)switch(e.n){case 0:if(i=new Uint8Array(r),"SOLANA"!==n){e.n=2;break}return c=te.uint8arrayToHexString(i.subarray(0,32)),u=te.getEd25519PublicKey(c),e.n=1,te.encodeKey(i,n,u);case 1:o=e.v,e.n=4;break;case 2:return e.n=3,te.encodeKey(i,n);case 3:o=e.v;case 4:if(s=t||"default","SOLANA"!==n){e.n=5;break}f=re.AX.fromSecretKey(te.base58Decode(o)),e.n=7;break;case 5:if("HEXADECIMAL"!==n){e.n=7;break}return e.n=6,Ye(Array.from(te.uint8arrayFromHexString(o)));case 6:f=e.v;case 7:pe=oe(oe({},pe),{},ie({},s,{organizationId:a,privateKey:o,format:n,expiry:(new Date).getTime()+864e5,keypair:f}));case 8:return e.a(2)}},e)}))).apply(this,arguments)}function Pe(e,t,r,n,a,o){return je.apply(this,arguments)}function je(){return je=de(ce().m(function e(t,r,n,a,o,i){var c;return ce().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,he(n,r,i);case 1:return c=e.v,e.n=2,Oe(o,c,a,r);case 2:te.sendMessageUp("BUNDLE_INJECTED",!0,t);case 3:return e.a(2)}},e)})),je.apply(this,arguments)}function _e(e,t){return Ie.apply(this,arguments)}function Ie(){return(Ie=de(ce().m(function e(t,r){var n;return ce().w(function(e){for(;;)switch(e.n){case 0:n=te.applySettings(t),te.setSettings(n),te.sendMessageUp("SETTINGS_APPLIED",!0,r);case 1:return e.a(2)}},e)}))).apply(this,arguments)}function xe(e,t,r){return Te.apply(this,arguments)}function Te(){return(Te=de(ce().m(function e(t,r,n){var a,o,i,c,u,s,f,l,d;return ce().w(function(e){for(;;)switch(e.n){case 0:if(ze(o=pe[a=n||"default"],a)){e.n=1;break}return e.a(2);case 1:return e.n=2,$e(o);case 2:if(i=e.v,c=JSON.parse(r),u=c.transaction,"SOLANA"!==c.type){e.n=3;break}f=te.uint8arrayFromHexString(u),(l=re.Kt.deserialize(f)).sign([i]),s=l.serialize(),e.n=4;break;case 3:throw new Error("unsupported transaction type");case 4:d=te.uint8arrayToHexString(s),te.sendMessageUp("TRANSACTION_SIGNED",d,t);case 5:return e.a(2)}},e)}))).apply(this,arguments)}function Ae(e,t,r){return Re.apply(this,arguments)}function Re(){return Re=de(ce().m(function e(t,r,o){var i,c,u,s,f,l,d,p,y,v;return ce().w(function(e){for(;;)switch(e.n){case 0:if(ze(c=pe[i=o||"default"],i)){e.n=1;break}return e.a(2);case 1:return u=JSON.parse(r),s=u.message,f=u.type,l=ve.encode(s),e.n=2,$e(c);case 2:if(p=e.v,"SOLANA"!==f){e.n=3;break}n.jn.sha512Sync=function(){var e;return a.Zf((e=n.jn).concatBytes.apply(e,arguments))},y=p.secretKey.slice(0,32),v=n._S(l,y),d=te.uint8arrayToHexString(v),e.n=4;break;case 3:return te.sendMessageUp("ERROR","unsupported message type",t),e.a(2);case 4:te.sendMessageUp("MESSAGE_SIGNED",d,t);case 5:return e.a(2)}},e)})),Re.apply(this,arguments)}function De(e,t){return Ne.apply(this,arguments)}function Ne(){return(Ne=de(ce().m(function e(t,r){return ce().w(function(e){for(;;)switch(e.n){case 0:if(r){e.n=1;break}return pe={},te.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t),e.a(2);case 1:if(pe[r]){e.n=2;break}return te.sendMessageUp("ERROR",new Error("key not found for address ".concat(r,". Note that address is case sensitive.")).toString(),t),e.a(2);case 2:delete pe[r],te.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function Me(e,t,r,n,a,o){return Ue.apply(this,arguments)}function Ue(){return Ue=de(ce().m(function e(t,r,n,a,o,i){var c,u,s,f,l;return ce().w(function(e){for(;;)switch(e.n){case 0:if(o){e.n=1;break}throw new Error("address is required for STORE_ENCRYPTED_BUNDLE");case 1:return e.n=2,ge(n,r);case 2:if(c=e.v,u=a||"HEXADECIMAL",te.setEncryptedBundle(o,{encappedPublic:c.encappedPublic,ciphertext:c.ciphertext,organizationId:r,keyFormat:u}),!ye||!i){e.n=4;break}return s=te.uint8arrayFromHexString(c.encappedPublic),f=te.uint8arrayFromHexString(c.ciphertext),e.n=3,i({ciphertextBuf:f,encappedKeyBuf:s,receiverPrivJwk:ye});case 3:return l=e.v,e.n=4,Oe(o,l,u,r);case 4:te.sendMessageUp("ENCRYPTED_BUNDLE_STORED",!0,t);case 5:return e.a(2)}},e)})),Ue.apply(this,arguments)}function Ke(e){return Ce.apply(this,arguments)}function Ce(){return(Ce=de(ce().m(function e(t){var r,n,a;return ce().w(function(e){for(;;)switch(e.n){case 0:if(32===t.length){e.n=1;break}throw new Error("invalid decryption key length: expected 32 bytes, got ".concat(t.length));case 1:return r=new Uint8Array([48,65,2,1,0,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,4,39,48,37,2,1,1,4,32]),(n=new Uint8Array(r.length+32)).set(r),n.set(t,r.length),e.n=2,crypto.subtle.importKey("pkcs8",n,{name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return a=e.v,e.n=3,crypto.subtle.exportKey("jwk",a);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function Be(e,t,r,n){return Le.apply(this,arguments)}function Le(){return Le=de(ce().m(function e(t,r,n,a){var o,i,c,u,s,f,l,d,p,y,v,b,g;return ce().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.n=1,he(n,r,a);case 1:return o=e.v,e.n=2,Ke(new Uint8Array(o));case 2:if(i=e.v,ye=i,c=te.getEncryptedBundles(),u=0,!c){e.n=9;break}s=Object.keys(c),f=0,l=s;case 3:if(!(f=e.expiry)throw function(){for(var e=(new Date).getTime(),t=[],r=0,n=Object.entries(pe);r=i.expiry&&t.push(o)}for(var c=0,u=t;c3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,d.n=y,c=0))}if(a||r>1)return i;throw l=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){o||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(et(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,et(e,a,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,et(l,"constructor",s),et(s,"constructor",u),u.displayName="GeneratorFunction",et(s,a,"GeneratorFunction"),et(l),et(l,a,"Generator"),et(l,n,function(){return this}),et(l,"toString",function(){return"[object Generator]"}),(Ze=function(){return{w:o,m:d}})()}function et(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}et=function(e,t,r,n){function o(t,r){et(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},et(e,t,r,n)}function tt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function rt(e){for(var t=1;t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,d.n=y,c=0))}if(a||r>1)return i;throw l=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){o||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(st(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,st(e,a,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,st(l,"constructor",s),st(s,"constructor",u),u.displayName="GeneratorFunction",st(s,a,"GeneratorFunction"),st(l),st(l,a,"Generator"),st(l,n,function(){return this}),st(l,"toString",function(){return"[object Generator]"}),(ut=function(){return{w:o,m:d}})()}function st(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}st=function(e,t,r,n){function o(t,r){st(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},st(e,t,r,n)}function ft(e,t,r,n,a,o,i){try{var c=e[o](i),u=c.value}catch(e){return void r(e)}c.done?t(u):Promise.resolve(u).then(n,a)}function lt(e){return function(){var t=this,r=arguments;return new Promise(function(n,a){var o=e.apply(t,r);function i(e){ft(o,n,a,i,c,"next",e)}function c(e){ft(o,n,a,i,c,"throw",e)}i(void 0)})}}window.TKHQ=te,document.addEventListener("DOMContentLoaded",lt(ut().m(function e(){var t,r,n,a;return ut().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,te.initEmbeddedKey();case 1:return e.n=2,te.getEmbeddedKey();case 2:return t=e.v,e.n=3,te.p256JWKPrivateToPublic(t);case 3:r=e.v,n=te.uint8arrayToHexString(r),document.getElementById("embedded-key").value=n,Xe(it),(a=te.getSettings())&&te.applySettings(a),te.sendMessageUp("PUBLIC_KEY_READY",n);case 4:return e.a(2)}},e)})))},790:()=>{},846:e=>{"use strict";e.exports=crypto}},i={};function c(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={id:e,loaded:!1,exports:{}};return o[e].call(r.exports,r,r.exports,c),r.loaded=!0,r.exports}c.m=o,e=[],c.O=(t,r,n,a)=>{if(!r){var o=1/0;for(f=0;f=a)&&Object.keys(c.O).every(e=>c.O[e](r[u]))?r.splice(u--,1):(i=!1,a0&&e[f-1][2]>a;f--)e[f]=e[f-1];e[f]=[r,n,a]},c.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return c.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,c.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var a=Object.create(null);c.r(a);var o={};t=t||[null,r({}),r([]),r(r)];for(var i=2&n&&e;("object"==typeof i||"function"==typeof i)&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach(t=>o[t]=()=>e[t]);return o.default=()=>e,c.d(a,o),a},c.d=(e,t)=>{for(var r in t)c.o(t,r)&&!c.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},c.f={},c.e=e=>Promise.all(Object.keys(c.f).reduce((t,r)=>(c.f[r](e,t),t),[])),c.u=e=>"bundle."+{291:"3eaea85f4001b9cc63c3",825:"aaba32bf7338e3d0f1cc"}[e]+".js",c.miniCssF=e=>{},c.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),c.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},a="export-and-sign:",c.l=(e,t,r,o)=>{if(n[e])n[e].push(t);else{var i,u;if(void 0!==r)for(var s=document.getElementsByTagName("script"),f=0;f{i.onerror=i.onload=null,clearTimeout(p);var a=n[e];if(delete n[e],i.parentNode&&i.parentNode.removeChild(i),a&&a.forEach(e=>e(r)),t)return t(r)},p=setTimeout(d.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=d.bind(null,i.onerror),i.onload=d.bind(null,i.onload),u&&document.head.appendChild(i)}},c.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),c.p="/",c.sriHashes={291:"sha384-G5pDFEAG9UZITbluyje/R/rWohZTUJf+Vu3ZIh0rsnLFLTw3SP/ca/XVNZVtv48f",825:"sha384-R9OIdd42i5GcdtZiHJuQgIUVvqyqJ0s7eaBnJHAfGllpi4YwbF7NSkjIRwOPUtsP"},(()=>{var e={792:0};c.f.j=(t,r)=>{var n=c.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[2]);else{var a=new Promise((r,a)=>n=e[t]=[r,a]);r.push(n[2]=a);var o=c.p+c.u(t),i=new Error;c.l(o,r=>{if(c.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var a=r&&("load"===r.type?"missing":r.type),o=r&&r.target&&r.target.src;i.message="Loading chunk "+t+" failed.\n("+a+": "+o+")",i.name="ChunkLoadError",i.type=a,i.request=o,n[1](i)}},"chunk-"+t,t)}},c.O.j=t=>0===e[t];var t=(t,r)=>{var n,a,[o,i,u]=r,s=0;if(o.some(t=>0!==e[t])){for(n in i)c.o(i,n)&&(c.m[n]=i[n]);if(u)var f=u(c)}for(t&&t(r);sc(560));u=c.O(u)})(); -//# sourceMappingURL=bundle.8ccdeed719db48416e34.js.map \ No newline at end of file diff --git a/export-and-sign/dist/bundle.8ccdeed719db48416e34.js.map b/export-and-sign/dist/bundle.8ccdeed719db48416e34.js.map deleted file mode 100644 index 62355ac..0000000 --- a/export-and-sign/dist/bundle.8ccdeed719db48416e34.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bundle.8ccdeed719db48416e34.js","mappings":";UAAIA,ECCAC,EADAC,ECAAC,EACAC,E,svCCAJ,IAAAC,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IAAAE,EAAAC,EAAAG,EAAAI,EAAA,EAAAC,EAAAX,GAAA,GAAAY,GAAA,EAAAC,EAAA,CAAAF,EAAA,EAAAb,EAAA,EAAAgB,EAAApB,EAAAqB,EAAAC,EAAAN,EAAAM,EAAAC,KAAAvB,EAAA,GAAAsB,EAAA,SAAArB,EAAAC,GAAA,OAAAM,EAAAP,EAAAQ,EAAA,EAAAG,EAAAZ,EAAAmB,EAAAf,EAAAF,EAAAmB,CAAA,YAAAC,EAAApB,EAAAE,GAAA,IAAAK,EAAAP,EAAAU,EAAAR,EAAAH,EAAA,GAAAiB,GAAAF,IAAAV,GAAAL,EAAAgB,EAAAO,OAAAvB,IAAA,KAAAK,EAAAE,EA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AAO1B,EAAoBM,EAAEpY,IAG1Bwc,EAAqBC,KAAkC,4BAAIA,KAAkC,6BAAK,GACtGD,EAAmBlZ,QAAQ6Y,EAAqBhlB,KAAK,KAAM,IAC3DqlB,EAAmBpc,KAAO+b,EAAqBhlB,KAAK,KAAMqlB,EAAmBpc,KAAKjJ,KAAKqlB,G,KClFvF,IAAIE,EAAsB5E,EAAoBM,OAAE1d,EAAW,CAAC,IAAK,IAAOod,EAAoB,MAC5F4E,EAAsB5E,EAAoBM,EAAEsE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/../shared/turnkey-core.js","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/../shared/crypto-utils.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/external var \"crypto\"","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/global","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/compat","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t\tif (script.src.indexOf(window.location.origin + '/') !== 0) {\n\t\t\tscript.crossOrigin = \"anonymous\";\n\t\t}\n\t\tscript.integrity = __webpack_require__.sriHashes[chunkId];\n\t\tscript.crossOrigin = \"anonymous\";\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n return data ? JSON.parse(data) : null;\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * @param {string} address - The wallet address to remove\n */\nfunction removeEncryptedBundle(address) {\n const bundles = getEncryptedBundles();\n if (bundles && bundles[address]) {\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n }\n}\n\n/**\n * Removes all encrypted bundles from localStorage.\n */\nfunction clearAllEncryptedBundles() {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\nimport { fromDerSignature } from \"@turnkey/crypto\";\nimport * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n initEmbeddedKey: sharedInitEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n additionalAssociatedData,\n getSettings,\n setSettings,\n parsePrivateKey,\n validateStyles,\n isDoublyIframed,\n loadQuorumKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n} = SharedTKHQ;\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n return await sharedInitEmbeddedKey();\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Read environment from meta tag (templated at deploy time), fall back to window variable (for testing)\n let environment = null;\n if (typeof document !== \"undefined\") {\n const meta = document.querySelector(\n 'meta[name=\"turnkey-signer-environment\"]'\n );\n if (\n meta &&\n meta.content &&\n meta.content !== \"__TURNKEY_SIGNER_ENVIRONMENT__\"\n ) {\n environment = meta.content;\n }\n }\n if (!environment && typeof window !== \"undefined\") {\n environment = window.__TURNKEY_SIGNER_ENVIRONMENT__;\n }\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\n// Decryption key -- held in memory only, never persisted to localStorage.\n// This is a P-256 private key in JWK format used to decrypt stored bundles.\nlet decryptionKey = null;\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Verifies the enclave signature on a v1.0.0 bundle and returns the parsed signed data.\n * @param {string} bundle - JSON-stringified bundle\n * @param {string} organizationId - Expected organization ID\n * @returns {Promise} - The parsed signed data {organizationId, encappedPublic, ciphertext}\n */\nasync function verifyAndParseBundleData(bundle, organizationId) {\n const bundleObj = JSON.parse(bundle);\n\n if (bundleObj.version !== \"v1.0.0\") {\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n const verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(`failed to verify enclave signature: ${bundle}`);\n }\n\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n\n return signedData;\n}\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n // Decrypt the ciphertext\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: embeddedKeyJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Encodes raw key bytes and loads them into the in-memory key store.\n * @param {string} address - Wallet address (case-sensitive)\n * @param {ArrayBuffer} keyBytes - Raw decrypted private key bytes\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} organizationId - Organization ID\n */\nasync function loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId) {\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair,\n },\n };\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Load decrypted key into memory\n await loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId);\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Set up sha512 for nobleEd25519 (required for signing)\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n\n // Extract the 32-byte private key from the 64-byte secretKey\n // Solana keypair.secretKey format: [32-byte private key][32-byte public key]\n const privateKey = keypair.secretKey.slice(0, 32);\n // Sign the message using nobleEd25519\n const signature = nobleEd25519.sign(messageBytes, privateKey);\n\n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n/**\n * Handler for STORE_ENCRYPTED_BUNDLE events.\n * Verifies the enclave signature on an encrypted bundle and stores\n * the encrypted payload in localStorage for later decryption.\n * If the decryption key is already in memory, also decrypts and loads\n * the key into memory immediately.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle JSON\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} address - Wallet address\n * @param {Function} HpkeDecrypt\n */\nasync function onStoreEncryptedBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n if (!address) {\n throw new Error(\"address is required for STORE_ENCRYPTED_BUNDLE\");\n }\n\n // Verify enclave signature and parse the signed data\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const resolvedKeyFormat = keyFormat || \"HEXADECIMAL\";\n\n // Store the encrypted fields in localStorage (just what's needed for decryption)\n TKHQ.setEncryptedBundle(address, {\n encappedPublic: signedData.encappedPublic,\n ciphertext: signedData.ciphertext,\n organizationId: organizationId,\n keyFormat: resolvedKeyFormat,\n });\n\n // If the decryption key is already in memory, decrypt and load immediately\n if (decryptionKey && HpkeDecrypt) {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n await loadKeyIntoMemory(\n address,\n keyBytes,\n resolvedKeyFormat,\n organizationId\n );\n }\n\n TKHQ.sendMessageUp(\"ENCRYPTED_BUNDLE_STORED\", true, requestId);\n}\n\n/**\n * Converts raw P-256 private key bytes (32-byte scalar) to a JWK.\n * Constructs a PKCS8 wrapper around the raw bytes, imports via WebCrypto\n * (which derives the public key), then exports as JWK.\n * @param {Uint8Array} rawPrivateKeyBytes - 32-byte P-256 private key scalar\n * @returns {Promise} - Full P-256 ECDH private key JWK\n */\nasync function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) {\n if (rawPrivateKeyBytes.length !== 32) {\n throw new Error(\n `invalid decryption key length: expected 32 bytes, got ${rawPrivateKeyBytes.length}`\n );\n }\n\n // PKCS8 DER prefix for a P-256 private key (without optional public key field)\n // SEQUENCE {\n // INTEGER 0 (version)\n // SEQUENCE { OID ecPublicKey, OID P-256 }\n // OCTET STRING { SEQUENCE { INTEGER 1, OCTET STRING(32) } }\n // }\n const pkcs8Prefix = new Uint8Array([\n 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48,\n 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03,\n 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20,\n ]);\n\n const pkcs8 = new Uint8Array(pkcs8Prefix.length + 32);\n pkcs8.set(pkcs8Prefix);\n pkcs8.set(rawPrivateKeyBytes, pkcs8Prefix.length);\n\n const cryptoKey = await crypto.subtle.importKey(\n \"pkcs8\",\n pkcs8,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"]\n );\n\n return await crypto.subtle.exportKey(\"jwk\", cryptoKey);\n}\n\n/**\n * Handler for INJECT_DECRYPTION_KEY_BUNDLE events.\n * Decrypts the P-256 private key using the iframe's embedded key,\n * then iterates all stored encrypted bundles, HPKE-decrypts each one\n * with the key, and loads them into inMemoryKeys.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle containing the private key\n * @param {Function} HpkeDecrypt\n */\nasync function onInjectDecryptionKeyBundle(\n requestId,\n organizationId,\n bundle,\n HpkeDecrypt\n) {\n // Decrypt the private key using the iframe's embedded key.\n // The decrypted payload is a raw 32-byte P-256 private key scalar.\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto)\n const keyJwk = await rawP256PrivateKeyToJwk(new Uint8Array(keyBytes));\n\n // Store in module-level variable (memory only)\n decryptionKey = keyJwk;\n\n // Iterate all stored encrypted bundles and decrypt each one\n const storedBundles = TKHQ.getEncryptedBundles();\n let decryptedCount = 0;\n\n if (storedBundles) {\n const addresses = Object.keys(storedBundles);\n\n for (const addr of addresses) {\n const bundleData = storedBundles[addr];\n\n try {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n bundleData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(\n bundleData.ciphertext\n );\n\n // HPKE-decrypt using the key\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n // Load the decrypted key into memory\n await loadKeyIntoMemory(\n addr,\n keyBytes,\n bundleData.keyFormat,\n bundleData.organizationId\n );\n\n decryptedCount++;\n } catch (e) {\n TKHQ.logMessage(\n `Failed to decrypt bundle for address ${addr}: ${e.toString()}`\n );\n }\n }\n }\n\n TKHQ.sendMessageUp(\"DECRYPTION_KEY_INJECTED\", decryptedCount, requestId);\n}\n\n/**\n * Handler for BURN_SESSION events.\n * Clears the decryption key and all in-memory wallet keys.\n * Encrypted bundles in localStorage are preserved for the next session.\n * @param {string} requestId\n */\nfunction onBurnSession(requestId) {\n decryptionKey = null;\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"SESSION_BURNED\", true, requestId);\n}\n\n/**\n * Handler for GET_STORED_WALLET_ADDRESSES events.\n * Returns a JSON array of all wallet addresses that have encrypted bundles in localStorage.\n * @param {string} requestId\n */\nfunction onGetStoredWalletAddresses(requestId) {\n const bundles = TKHQ.getEncryptedBundles();\n const addresses = bundles ? Object.keys(bundles) : [];\n TKHQ.sendMessageUp(\n \"STORED_WALLET_ADDRESSES\",\n JSON.stringify(addresses),\n requestId\n );\n}\n\n/**\n * Handler for CLEAR_STORED_BUNDLES events.\n * Removes encrypted bundles from localStorage AND the corresponding\n * in-memory keys. If address is provided, removes only that address.\n * If no address, removes ALL encrypted bundles and ALL in-memory keys.\n * @param {string} requestId\n * @param {string|undefined} address - Optional wallet address\n */\nfunction onClearStoredBundles(requestId, address) {\n if (address) {\n TKHQ.removeEncryptedBundle(address);\n delete inMemoryKeys[address];\n } else {\n TKHQ.clearAllEncryptedBundles();\n inMemoryKeys = {};\n }\n TKHQ.sendMessageUp(\"STORED_BUNDLES_CLEARED\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error(\n `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`\n ).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n undefined, // keyFormat - default to HEXADECIMAL\n undefined, // address - default to \"default\"\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"STORE_ENCRYPTED_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n await onStoreEncryptedBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_DECRYPTION_KEY_BUNDLE\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onInjectDecryptionKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"BURN_SESSION\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onBurnSession(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_STORED_WALLET_ADDRESSES\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onGetStoredWalletAddresses(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_STORED_BUNDLES\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n onClearStoredBundles(event.data[\"requestId\"], event.data[\"address\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n onStoreEncryptedBundle,\n onInjectDecryptionKeyBundle,\n onBurnSession,\n onGetStoredWalletAddresses,\n onClearStoredBundles,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"@shared/crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n","module.exports = crypto;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","\n__webpack_require__.sriHashes = {\"291\":\"*-*-*-CHUNK-SRI-HASH-r3NPGwA4ft5fHgGXhVIptCiDVf06qPa+sxzG6L+8GwPuhn89e/\",\"825\":\"*-*-*-CHUNK-SRI-HASH-mfog3UJdGPOmSk4QZbKxsxHPFZtt298WnZNc1aQ1MCgc6YirFj\"};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(560)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","TURNKEY_ENCRYPTED_BUNDLES","parentFrameMessageChannelPort","getSubtleCrypto","globalThis","crypto","subtle","window","global","isDoublyIframed","undefined","location","ancestorOrigins","parent","top","_loadQuorumKey","_callee","quorumPublic","_context","Error","importKey","namedCurve","_initEmbeddedKey","_callee3","_context3","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee4","p256key","_context4","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","getEncryptedBundles","data","localStorage","getItem","key","ttl","item","expiry","Date","getTime","setItem","itemStr","hasOwnProperty","removeItem","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","concat","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","p256JWKPrivateToPublic","_x6","_p256JWKPrivateToPublic","_callee6","jwkPrivate","jwkPrivateCopy","publicKey","_context6","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","push","k","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee9","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_t2","_context9","set","console","warn","sharedInitEmbeddedKey","SharedTKHQ","validateStyles","styles","element","validStyles","cssValidationRegex","padding","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref","_ref2","_arrayWithHoles","next","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","loadQuorumKey","_x","_verifyEnclaveSignature","_callee2","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","meta","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context2","prod","preprod","querySelector","__TURNKEY_SIGNER_ENVIRONMENT__","fromDerSignature","verify","hash","TKHQ","initEmbeddedKey","onResetEmbeddedKey","encodeKey","_x0","_x1","_x10","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","normalizePadding","byteArray","targetLength","paddingLength","fill","expectedZeroCount","zeroCount","verifyEnclaveSignature","_x2","_x3","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","style","getSettings","setSettings","parsePrivateKey","error","setEncryptedBundle","address","bundleData","bundles","removeEncryptedBundle","keys","clearAllEncryptedBundles","_slicedToArray","inMemoryKeys","decryptionKey","textEncoder","TextEncoder","textDecoder","TextDecoder","verifyAndParseBundleData","_verifyAndParseBundleData","_callee8","bundle","organizationId","bundleObj","_context8","version","dataSignature","decode","encappedPublic","ciphertext","decryptBundle","_x4","_x5","_decryptBundle","HpkeDecrypt","encappedKeyBuf","ciphertextBuf","embeddedKeyJwk","receiverPrivJwk","onGetPublicEmbeddedKey","_onGetPublicEmbeddedKey","_callee0","targetPubBuf","targetPubHex","_context0","loadKeyIntoMemory","_x7","_x8","_x9","_loadKeyIntoMemory","_callee1","keyBytes","keyAddress","cachedKeypair","_context1","subarray","Keypair","fromSecretKey","createSolanaKeypair","_defineProperty","format","keypair","onInjectKeyBundle","_x11","_x12","_x13","_x14","_onInjectKeyBundle","_callee10","_context10","onApplySettings","_x15","_x16","_onApplySettings","_callee11","_context11","onSignTransaction","_x17","_x18","_x19","_onSignTransaction","_callee12","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context12","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x20","_x21","_x22","_onSignMessage","_callee13","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context13","encode","secretKey","onClearEmbeddedPrivateKey","_x23","_x24","_onClearEmbeddedPrivateKey","_callee14","_context14","onStoreEncryptedBundle","_x25","_x26","_x27","_x28","_x29","_x30","_onStoreEncryptedBundle","_callee15","resolvedKeyFormat","_context15","rawP256PrivateKeyToJwk","_x31","_rawP256PrivateKeyToJwk","_callee16","rawPrivateKeyBytes","pkcs8Prefix","pkcs8","cryptoKey","_context16","onInjectDecryptionKeyBundle","_x32","_x33","_x34","_x35","_onInjectDecryptionKeyBundle","_callee17","keyJwk","storedBundles","decryptedCount","addresses","_i3","_addresses","addr","_keyBytes","_t0","_context17","onBurnSession","onGetStoredWalletAddresses","onClearStoredBundles","_x36","_createSolanaKeypair","_callee18","_context18","fromSeed","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x37","_getOrCreateKeypair","_callee19","_context19","initEventHandlers","messageEventListener","_messageEventListener","event","_t","_t3","_t4","_t5","_t6","_t7","_t8","_t9","_x43","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","preventDefault","_x38","_x39","_ref3","_x40","_ref4","_x41","injectWalletBtn","_ref5","_callee5","_context5","_x42","addDOMEventListeners","capture","signal","_ref6","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x44","ownKeys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","_HpkeDecrypt","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","styleSettings","module","exports","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","g","Function","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","crossOrigin","integrity","sriHashes","onScriptComplete","prev","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/dist/index.html b/export-and-sign/dist/index.html index a10ff89..360cf0d 100644 --- a/export-and-sign/dist/index.html +++ b/export-and-sign/dist/index.html @@ -1 +1 @@ -Turnkey Export

Export Key Material

This public key will be sent along with a private key ID or wallet ID inside of a new EXPORT_PRIVATE_KEY or EXPORT_WALLET activity




Inject Key Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).





Inject Wallet Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).




Sign Transaction

Input a serialized transaction to sign.



Sign Message

Input a serialized message to sign.



Message log

Below we display a log of the messages sent / received. The forms above send messages, and the code communicates results by sending events via the postMessage API.

\ No newline at end of file +Turnkey Export

Export Key Material

This public key will be sent along with a private key ID or wallet ID inside of a new EXPORT_PRIVATE_KEY or EXPORT_WALLET activity




Inject Key Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).





Inject Wallet Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).




Sign Transaction

Input a serialized transaction to sign.



Sign Message

Input a serialized message to sign.



Message log

Below we display a log of the messages sent / received. The forms above send messages, and the code communicates results by sending events via the postMessage API.

\ No newline at end of file diff --git a/export-and-sign/index.test.js b/export-and-sign/index.test.js index 6d6e4f6..4424cf9 100644 --- a/export-and-sign/index.test.js +++ b/export-and-sign/index.test.js @@ -1018,7 +1018,7 @@ describe("Encryption Escrow", () => { keyFormat: "SOLANA", }); - TKHQ.removeEncryptedBundle("addr1"); + TKHQ.removeEncryptedBundle("addr1", "org1"); const bundles = TKHQ.getEncryptedBundles(); expect(bundles["addr1"]).toBeUndefined(); @@ -1033,7 +1033,7 @@ describe("Encryption Escrow", () => { keyFormat: "SOLANA", }); - TKHQ.removeEncryptedBundle("addr1"); + TKHQ.removeEncryptedBundle("addr1", "org1"); expect(TKHQ.getEncryptedBundles()).toBeNull(); }); @@ -1051,7 +1051,7 @@ describe("Encryption Escrow", () => { keyFormat: "SOLANA", }); - TKHQ.clearAllEncryptedBundles(); + TKHQ.clearAllEncryptedBundles("org1"); expect(TKHQ.getEncryptedBundles()).toBeNull(); }); }); @@ -1414,7 +1414,7 @@ describe("Encryption Escrow", () => { keyFormat: "SOLANA", }); - onGetStoredWalletAddresses(requestId); + onGetStoredWalletAddresses(requestId, "org1"); expect(sendMessageSpy).toHaveBeenCalledWith( "STORED_WALLET_ADDRESSES", @@ -1424,7 +1424,7 @@ describe("Encryption Escrow", () => { }); it("returns empty array when no bundles stored", () => { - onGetStoredWalletAddresses(requestId); + onGetStoredWalletAddresses(requestId, "org1"); expect(sendMessageSpy).toHaveBeenCalledWith( "STORED_WALLET_ADDRESSES", @@ -1471,7 +1471,7 @@ describe("Encryption Escrow", () => { ); // Clear addr1 - onClearStoredBundles(requestId, "addr1"); + onClearStoredBundles(requestId, "addr1", "org1"); expect(sendMessageSpy).toHaveBeenCalledWith( "STORED_BUNDLES_CLEARED", @@ -1528,7 +1528,7 @@ describe("Encryption Escrow", () => { ); // Clear all - onClearStoredBundles(requestId, undefined); + onClearStoredBundles(requestId, undefined, "org1"); expect(sendMessageSpy).toHaveBeenCalledWith( "STORED_BUNDLES_CLEARED", diff --git a/export-and-sign/src/event-handlers.js b/export-and-sign/src/event-handlers.js index 9e37aa2..d5231df 100644 --- a/export-and-sign/src/event-handlers.js +++ b/export-and-sign/src/event-handlers.js @@ -477,6 +477,10 @@ async function onInjectDecryptionKeyBundle( const bundleData = storedBundles[addr]; try { + const bundleOrgId = bundleData.organizationId; + + if (organizationId !== bundleOrgId) continue; // skip bundles that don't match the organization ID of the decryption key + const encappedKeyBuf = TKHQ.uint8arrayFromHexString( bundleData.encappedPublic ); @@ -527,10 +531,15 @@ function onBurnSession(requestId) { * Handler for GET_STORED_WALLET_ADDRESSES events. * Returns a JSON array of all wallet addresses that have encrypted bundles in localStorage. * @param {string} requestId + * @param {string} organizationId - Organization ID to filter addresses by (only return addresses with bundles matching the organization ID) */ -function onGetStoredWalletAddresses(requestId) { +function onGetStoredWalletAddresses(requestId, organizationId) { const bundles = TKHQ.getEncryptedBundles(); - const addresses = bundles ? Object.keys(bundles) : []; + const addresses = bundles + ? Object.entries(bundles) + .filter(([, bundle]) => bundle.organizationId === organizationId) + .map(([address]) => address) + : []; TKHQ.sendMessageUp( "STORED_WALLET_ADDRESSES", JSON.stringify(addresses), @@ -544,14 +553,15 @@ function onGetStoredWalletAddresses(requestId) { * in-memory keys. If address is provided, removes only that address. * If no address, removes ALL encrypted bundles and ALL in-memory keys. * @param {string} requestId + * @param {string} organizationId - Organization ID to filter addresses by (only remove bundles matching the organization ID) * @param {string|undefined} address - Optional wallet address */ -function onClearStoredBundles(requestId, address) { +function onClearStoredBundles(requestId, address, organizationId) { if (address) { - TKHQ.removeEncryptedBundle(address); + TKHQ.removeEncryptedBundle(address, organizationId); delete inMemoryKeys[address]; } else { - TKHQ.clearAllEncryptedBundles(); + TKHQ.clearAllEncryptedBundles(organizationId); inMemoryKeys = {}; } TKHQ.sendMessageUp("STORED_BUNDLES_CLEARED", true, requestId); @@ -873,7 +883,10 @@ function initMessageEventListener(HpkeDecrypt) { if (event.data && event.data["type"] == "GET_STORED_WALLET_ADDRESSES") { TKHQ.logMessage(`⬇️ Received message ${event.data["type"]}`); try { - onGetStoredWalletAddresses(event.data["requestId"]); + onGetStoredWalletAddresses( + event.data["requestId"], + event.data["organizationId"] + ); } catch (e) { TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); } @@ -883,7 +896,11 @@ function initMessageEventListener(HpkeDecrypt) { `⬇️ Received message ${event.data["type"]}: address=${event.data["address"]}` ); try { - onClearStoredBundles(event.data["requestId"], event.data["address"]); + onClearStoredBundles( + event.data["requestId"], + event.data["address"], + event.data["organizationId"] + ); } catch (e) { TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); } diff --git a/import/dist/551.bundle.27da59437a4e403e3c24.js.map b/import/dist/551.bundle.27da59437a4e403e3c24.js.map index dca01ff..5bfe133 100644 --- a/import/dist/551.bundle.27da59437a4e403e3c24.js.map +++ b/import/dist/551.bundle.27da59437a4e403e3c24.js.map @@ -1 +1 @@ -{"version":3,"file":"551.bundle.27da59437a4e403e3c24.js","mappings":";moFACA,IAAAA,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IA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6D,EAAAC,EAAA,OAAAhE,EAAA,UAAAgE,EAAAhE,GAAAwD,EAAAvC,EAAAnB,EAAAI,EAAA6D,EAAAC,EAAA,QAAAhE,EAAA,CAAA+D,OAAA,OA2HCD,MAAA,KAAAD,WA3HD,IAAA7D,CA2HC,C","sources":["webpack://import/../shared/turnkey-core.js","webpack://import/./src/turnkey-core.js","webpack://import/../shared/crypto-utils.js"],"sourcesContent":["import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n return data ? JSON.parse(data) : null;\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * @param {string} address - The wallet address to remove\n */\nfunction removeEncryptedBundle(address) {\n const bundles = getEncryptedBundles();\n if (bundles && bundles[address]) {\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n }\n}\n\n/**\n * Removes all encrypted bundles from localStorage.\n */\nfunction clearAllEncryptedBundles() {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n} = SharedTKHQ;\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n const settingsObj = JSON.parse(settings);\n\n const passphraseLabel = document.getElementById(\"passphrase-label\");\n const mnemonicLabel = document.getElementById(\"mnemonic-label\");\n const passphraseTextarea = document.getElementById(\"passphrase\");\n\n if (!passphraseLabel || !passphraseTextarea) {\n throw new Error(\"no passphrase HTML elements found to apply settings to.\");\n }\n const plaintextTextarea = document.getElementById(\"plaintext\");\n if (!plaintextTextarea) {\n throw new Error(\n \"no plaintext textarea HTML element found to apply settings to.\"\n );\n }\n\n // Apply enablePassphrase setting\n if (settingsObj.enablePassphrase === true) {\n passphraseLabel.style.display = \"inline-block\";\n passphraseTextarea.style.display = \"inline-block\";\n passphraseTextarea.style.border = \"solid 1px #ccc\";\n passphraseTextarea.style.borderRadius = \"4px\";\n\n mnemonicLabel.style.display = \"inline-block\";\n plaintextTextarea.style.border = \"solid 1px #ccc\";\n plaintextTextarea.style.borderRadius = \"4px\";\n\n validSettings[\"enablePassphrase\"] = true;\n } else {\n passphraseLabel.style.display = \"none\";\n passphraseTextarea.style.display = \"none\";\n mnemonicLabel.style.display = \"none\";\n\n plaintextTextarea.style.border = \"none\";\n validSettings[\"enablePassphrase\"] = false;\n }\n\n if (settingsObj.styles) {\n // Validate, sanitize, and apply the styles to the \"plaintext\" textarea.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n plaintextTextarea.style[key] = value;\n });\n\n if (validStyles.backgroundColor) {\n // Apply background color to document and body as well.\n document.documentElement.style.backgroundColor =\n validStyles.backgroundColor;\n document.body.style.backgroundColor = validStyles.backgroundColor;\n }\n\n if (validStyles.labelColor) {\n document.getElementById(\"mnemonic-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"styles\"] = validStyles;\n }\n\n if (settingsObj.passphraseStyles) {\n // Validate, sanitize, and apply the styles to the \"passphrase\" textarea.\n const validStyles = validateStyles(settingsObj.passphraseStyles);\n Object.entries(validStyles).forEach(([key, value]) => {\n passphraseTextarea.style[key] = value;\n });\n\n if (validStyles.labelColor) {\n document.getElementById(\"passphrase-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"passphraseStyles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n applySettings,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n"],"names":["e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_OverloadYield","k","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_TARGET_EMBEDDED_KEY","TURNKEY_SETTINGS","parentFrameMessageChannelPort","cryptoProviderOverride","getSubtleCrypto","subtle","globalThis","crypto","window","global","setCryptoProvider","cryptoProvider","loadQuorumKey","_x","_loadQuorumKey","_regeneratorRuntime","mark","_callee","quorumPublic","wrap","_context","prev","next","Error","importKey","namedCurve","abrupt","sent","stop","loadTargetKey","_x2","_loadTargetKey","_callee2","targetPublic","targetKey","_context2","exportKey","getTargetEmbeddedKey","jwtKey","localStorage","getItem","JSON","parse","setTargetEmbeddedKey","setItem","stringify","resetTargetEmbeddedKey","removeItem","setParentFrameMessageChannelPort","port","getSettings","settings","setSettings","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","normalizePadding","byteArray","targetLength","paddingLength","padding","fill","concat","expectedZeroCount","zeroCount","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","fromDerSignature","derSignature","derSignatureBuf","index","rLength","sLength","rPadded","sPadded","verifyEnclaveSignature","_x3","_x4","_x5","_verifyEnclaveSignature","_callee5","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context5","prod","preprod","__TURNKEY_SIGNER_ENVIRONMENT__","undefined","verify","hash","sendMessageUp","type","requestId","message","postMessage","parent","content","messageLog","document","getElementById","createElement","innerText","appendChild","logMessage","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","carry","push","j","currentByte","result","reverse","base58CheckDecode","_x7","_base58CheckDecode","_callee7","decoded","payload","checksum","hash1Buf","hash1","hash2Buf","hash2","computedChecksum","_context7","subarray","digest","decodeKey","_x8","_x9","_decodeKey","_callee8","privateKey","keyFormat","decodedKeyBytes","version","keyAndFlags","_payload","_version","_keyAndFlags","_bech32$decode","prefix","words","bytes","schemeFlag","privkey","_context8","t0","bech32","decode","fromWords","console","warn","validateStyles","styles","element","validStyles","cssValidationRegex","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref","_ref2","_arrayWithHoles","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","SharedTKHQ","applySettings","validSettings","settingsObj","passphraseLabel","mnemonicLabel","passphraseTextarea","plaintextTextarea","enablePassphrase","style","display","border","_slicedToArray","key","documentElement","body","passphraseStyles","_ref3","_ref4","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","_objectSpread","_defineProperty","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","TextEncoder","encode","HpkeEncrypt","_HpkeEncrypt","plaintextBuf","receiverPubJwk","kemContext","receiverPub","suite","senderCtx","receiverPubCryptoKey","receiverPubRaw","encappedKeyBuf","aad","ciphertextBuf","ciphertextHex","encappedKeyBufHex","encryptedBundle","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createSenderContext","recipientPublicKey","info","enc","seal","encappedPublic","ciphertext"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"551.bundle.27da59437a4e403e3c24.js","mappings":";moFACA,IAAAA,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IAAAE,EAAAC,EAAAG,EAAAI,EAAA,EAAAC,EAAAX,GAAA,GAAAY,GAAA,EAAAC,EAAA,CAAAF,EAAA,EAAAb,EAAA,EAAAgB,EAAApB,EAAAqB,EAAAC,EAAAN,EAAAM,EAAAC,KAAAvB,EAAA,GAAAsB,EAAA,SAAArB,EAAAC,GAAA,OAAAM,EAAAP,EAAAQ,EAAA,EAAAG,EAAAZ,EAAAmB,EAAAf,EAAAF,EAAAmB,CAAA,YAAAC,EAAApB,EAAAE,GAAA,IAAAK,EAAAP,EAAAU,EAAAR,EAAAH,EAAA,GAAAiB,GAAAF,IAAAV,GAAAL,EAAAgB,EAAAO,OAAAvB,IAAA,KAAAK,EAAAE,EAAAS,EAAAhB,GAAAqB,EAAAH,EAAAF,EAAAQ,EAAAjB,EAAA,GAAAN,EAAA,GAAAI,EAAAmB,IAAArB,KAAAQ,EAAAJ,GAAAC,EAAAD,EAAA,OAAAC,EAAA,MAAAD,EAAA,GAAAA,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AAb,KAAA,GAI5C8O,EAAUoB,KAAKzB,EAAcS,GAAI,QAAvDC,EAAatO,EAAAR,KAAAQ,EAAAb,KAAG,GAAH,oBAAAa,EAAAd,KAAG,GAAHc,EAAAwI,GAAAxI,EAAA,UAEP,IAAIZ,MAAM,oCAAsCY,EAAAwI,GAAEzL,YAAW,QAQnE,OALIwR,GAAgB5M,EAAAA,EAAAA,IAAsB,IAAIL,WAAWgN,IACrDE,GAAoB7M,EAAAA,EAAAA,IAAsByM,GAC1CK,EAAkBnO,KAAKI,UAAU,CACrC4O,eAAgBd,EAChBe,WAAYhB,IACZvO,EAAAT,OAAA,SACKkP,GAAe,yBAAAzO,EAAAP,OAAA,EAAAI,EAAA,kBACvB8N,EA3HD,eAAAlU,EAAA,KAAAD,EAAAiE,UAAA,WAAAJ,QAAA,SAAA3D,EAAAI,GAAA,IAAAe,EAAAjB,EAAA8D,MAAAjE,EAAAD,GAAA,SAAAmE,EAAA/D,GAAAwD,EAAAvC,EAAAnB,EAAAI,EAAA6D,EAAAC,EAAA,OAAAhE,EAAA,UAAAgE,EAAAhE,GAAAwD,EAAAvC,EAAAnB,EAAAI,EAAA6D,EAAAC,EAAA,QAAAhE,EAAA,CAAA+D,OAAA,OA2HCD,MAAA,KAAAD,WA3HD,IAAA7D,CA2HC,C","sources":["webpack://import/../shared/turnkey-core.js","webpack://import/./src/turnkey-core.js","webpack://import/../shared/crypto-utils.js"],"sourcesContent":["import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n return data ? JSON.parse(data) : null;\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * Only removes the bundle if it belongs to the specified organization.\n * @param {string} address - The wallet address to remove\n * @param {string} organizationId - Only remove if the bundle belongs to this org\n */\nfunction removeEncryptedBundle(address, organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles || !bundles[address]) return;\n\n // Only remove if the bundle belongs to the specified organization\n if (bundles[address].organizationId !== organizationId) return;\n\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n}\n\n/**\n * Removes all encrypted bundles belonging to the specified organization.\n * Bundles from other organizations are preserved.\n * @param {string} organizationId - Remove bundles belonging to this org\n */\nfunction clearAllEncryptedBundles(organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles) return;\n\n // Keep only bundles that do NOT belong to this organization\n const remaining = Object.fromEntries(\n Object.entries(bundles).filter(\n ([, bundle]) => bundle.organizationId !== organizationId\n )\n );\n\n if (Object.keys(remaining).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(remaining)\n );\n }\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n} = SharedTKHQ;\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n const settingsObj = JSON.parse(settings);\n\n const passphraseLabel = document.getElementById(\"passphrase-label\");\n const mnemonicLabel = document.getElementById(\"mnemonic-label\");\n const passphraseTextarea = document.getElementById(\"passphrase\");\n\n if (!passphraseLabel || !passphraseTextarea) {\n throw new Error(\"no passphrase HTML elements found to apply settings to.\");\n }\n const plaintextTextarea = document.getElementById(\"plaintext\");\n if (!plaintextTextarea) {\n throw new Error(\n \"no plaintext textarea HTML element found to apply settings to.\"\n );\n }\n\n // Apply enablePassphrase setting\n if (settingsObj.enablePassphrase === true) {\n passphraseLabel.style.display = \"inline-block\";\n passphraseTextarea.style.display = \"inline-block\";\n passphraseTextarea.style.border = \"solid 1px #ccc\";\n passphraseTextarea.style.borderRadius = \"4px\";\n\n mnemonicLabel.style.display = \"inline-block\";\n plaintextTextarea.style.border = \"solid 1px #ccc\";\n plaintextTextarea.style.borderRadius = \"4px\";\n\n validSettings[\"enablePassphrase\"] = true;\n } else {\n passphraseLabel.style.display = \"none\";\n passphraseTextarea.style.display = \"none\";\n mnemonicLabel.style.display = \"none\";\n\n plaintextTextarea.style.border = \"none\";\n validSettings[\"enablePassphrase\"] = false;\n }\n\n if (settingsObj.styles) {\n // Validate, sanitize, and apply the styles to the \"plaintext\" textarea.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n plaintextTextarea.style[key] = value;\n });\n\n if (validStyles.backgroundColor) {\n // Apply background color to document and body as well.\n document.documentElement.style.backgroundColor =\n validStyles.backgroundColor;\n document.body.style.backgroundColor = validStyles.backgroundColor;\n }\n\n if (validStyles.labelColor) {\n document.getElementById(\"mnemonic-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"styles\"] = validStyles;\n }\n\n if (settingsObj.passphraseStyles) {\n // Validate, sanitize, and apply the styles to the \"passphrase\" textarea.\n const validStyles = validateStyles(settingsObj.passphraseStyles);\n Object.entries(validStyles).forEach(([key, value]) => {\n passphraseTextarea.style[key] = value;\n });\n\n if (validStyles.labelColor) {\n document.getElementById(\"passphrase-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"passphraseStyles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n applySettings,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n"],"names":["e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_OverloadYield","k","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_TARGET_EMBEDDED_KEY","TURNKEY_SETTINGS","parentFrameMessageChannelPort","cryptoProviderOverride","getSubtleCrypto","subtle","globalThis","crypto","window","global","setCryptoProvider","cryptoProvider","loadQuorumKey","_x","_loadQuorumKey","_regeneratorRuntime","mark","_callee","quorumPublic","wrap","_context","prev","next","Error","importKey","namedCurve","abrupt","sent","stop","loadTargetKey","_x2","_loadTargetKey","_callee2","targetPublic","targetKey","_context2","exportKey","getTargetEmbeddedKey","jwtKey","localStorage","getItem","JSON","parse","setTargetEmbeddedKey","setItem","stringify","resetTargetEmbeddedKey","removeItem","setParentFrameMessageChannelPort","port","getSettings","settings","setSettings","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","normalizePadding","byteArray","targetLength","paddingLength","padding","fill","concat","expectedZeroCount","zeroCount","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","fromDerSignature","derSignature","derSignatureBuf","index","rLength","sLength","rPadded","sPadded","verifyEnclaveSignature","_x3","_x4","_x5","_verifyEnclaveSignature","_callee5","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context5","prod","preprod","__TURNKEY_SIGNER_ENVIRONMENT__","undefined","verify","hash","sendMessageUp","type","requestId","message","postMessage","parent","content","messageLog","document","getElementById","createElement","innerText","appendChild","logMessage","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","carry","push","j","currentByte","result","reverse","base58CheckDecode","_x7","_base58CheckDecode","_callee7","decoded","payload","checksum","hash1Buf","hash1","hash2Buf","hash2","computedChecksum","_context7","subarray","digest","decodeKey","_x8","_x9","_decodeKey","_callee8","privateKey","keyFormat","decodedKeyBytes","version","keyAndFlags","_payload","_version","_keyAndFlags","_bech32$decode","prefix","words","bytes","schemeFlag","privkey","_context8","t0","bech32","decode","fromWords","console","warn","validateStyles","styles","element","validStyles","cssValidationRegex","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref3","_ref4","_arrayWithHoles","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","SharedTKHQ","applySettings","validSettings","settingsObj","passphraseLabel","mnemonicLabel","passphraseTextarea","plaintextTextarea","enablePassphrase","style","display","border","_ref","_ref2","_slicedToArray","key","documentElement","body","passphraseStyles","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","_objectSpread","_defineProperty","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","TextEncoder","encode","HpkeEncrypt","_HpkeEncrypt","plaintextBuf","receiverPubJwk","kemContext","receiverPub","suite","senderCtx","receiverPubCryptoKey","receiverPubRaw","encappedKeyBuf","aad","ciphertextBuf","ciphertextHex","encappedKeyBufHex","encryptedBundle","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createSenderContext","recipientPublicKey","info","enc","seal","encappedPublic","ciphertext"],"sourceRoot":""} \ No newline at end of file diff --git a/shared/turnkey-core.js b/shared/turnkey-core.js index 8bde880..6c94460 100644 --- a/shared/turnkey-core.js +++ b/shared/turnkey-core.js @@ -223,7 +223,16 @@ function setSettings(settings) { */ function getEncryptedBundles() { const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES); - return data ? JSON.parse(data) : null; + if (!data) { + return null; + } + try { + return JSON.parse(data); + } catch (e) { + // If the stored data is corrupted or not valid JSON, remove it to self-heal. + window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES); + return null; + } } /** @@ -242,28 +251,52 @@ function setEncryptedBundle(address, bundleData) { /** * Removes a single encrypted bundle by address. + * Only removes the bundle if it belongs to the specified organization. * @param {string} address - The wallet address to remove + * @param {string} organizationId - Only remove if the bundle belongs to this org */ -function removeEncryptedBundle(address) { +function removeEncryptedBundle(address, organizationId) { const bundles = getEncryptedBundles(); - if (bundles && bundles[address]) { - delete bundles[address]; - if (Object.keys(bundles).length === 0) { - window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES); - } else { - window.localStorage.setItem( - TURNKEY_ENCRYPTED_BUNDLES, - JSON.stringify(bundles) - ); - } + if (!bundles || !bundles[address]) return; + + // Only remove if the bundle belongs to the specified organization + if (bundles[address].organizationId !== organizationId) return; + + delete bundles[address]; + if (Object.keys(bundles).length === 0) { + window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES); + } else { + window.localStorage.setItem( + TURNKEY_ENCRYPTED_BUNDLES, + JSON.stringify(bundles) + ); } } /** - * Removes all encrypted bundles from localStorage. + * Removes all encrypted bundles belonging to the specified organization. + * Bundles from other organizations are preserved. + * @param {string} organizationId - Remove bundles belonging to this org */ -function clearAllEncryptedBundles() { - window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES); +function clearAllEncryptedBundles(organizationId) { + const bundles = getEncryptedBundles(); + if (!bundles) return; + + // Keep only bundles that do NOT belong to this organization + const remaining = Object.fromEntries( + Object.entries(bundles).filter( + ([, bundle]) => bundle.organizationId !== organizationId + ) + ); + + if (Object.keys(remaining).length === 0) { + window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES); + } else { + window.localStorage.setItem( + TURNKEY_ENCRYPTED_BUNDLES, + JSON.stringify(remaining) + ); + } } /** From 905ecf5508655ba1b7b38e046b74e9ec7ac6d740 Mon Sep 17 00:00:00 2001 From: Ethan Konkolowicz Date: Wed, 11 Feb 2026 20:53:35 -0500 Subject: [PATCH 4/7] added org leakage test cases --- .../551.bundle.27da59437a4e403e3c24.js.map | 2 +- shared/turnkey-core.test.js | 82 +++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/import/dist/551.bundle.27da59437a4e403e3c24.js.map b/import/dist/551.bundle.27da59437a4e403e3c24.js.map index 5bfe133..6971264 100644 --- a/import/dist/551.bundle.27da59437a4e403e3c24.js.map +++ b/import/dist/551.bundle.27da59437a4e403e3c24.js.map @@ -1 +1 @@ -{"version":3,"file":"551.bundle.27da59437a4e403e3c24.js","mappings":";moFACA,IAAAA,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IAAAE,EAAAC,EAAAG,EAAAI,EAAA,EAAAC,EAAAX,GAAA,GAAAY,GAAA,EAAAC,EAAA,CAAAF,EAAA,EAAAb,EAAA,EAAAgB,EAAApB,EAAAqB,EAAAC,EAAAN,EAAAM,EAAAC,KAAAvB,EAAA,GAAAsB,EAAA,SAAArB,EAAAC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core.js","webpack://import/./src/turnkey-core.js","webpack://import/../shared/crypto-utils.js"],"sourcesContent":["import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n return data ? JSON.parse(data) : null;\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * Only removes the bundle if it belongs to the specified organization.\n * @param {string} address - The wallet address to remove\n * @param {string} organizationId - Only remove if the bundle belongs to this org\n */\nfunction removeEncryptedBundle(address, organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles || !bundles[address]) return;\n\n // Only remove if the bundle belongs to the specified organization\n if (bundles[address].organizationId !== organizationId) return;\n\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n}\n\n/**\n * Removes all encrypted bundles belonging to the specified organization.\n * Bundles from other organizations are preserved.\n * @param {string} organizationId - Remove bundles belonging to this org\n */\nfunction clearAllEncryptedBundles(organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles) return;\n\n // Keep only bundles that do NOT belong to this organization\n const remaining = Object.fromEntries(\n Object.entries(bundles).filter(\n ([, bundle]) => bundle.organizationId !== organizationId\n )\n );\n\n if (Object.keys(remaining).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(remaining)\n );\n }\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n} = SharedTKHQ;\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n const settingsObj = JSON.parse(settings);\n\n const passphraseLabel = document.getElementById(\"passphrase-label\");\n const mnemonicLabel = document.getElementById(\"mnemonic-label\");\n const passphraseTextarea = document.getElementById(\"passphrase\");\n\n if (!passphraseLabel || !passphraseTextarea) {\n throw new Error(\"no passphrase HTML elements found to apply settings to.\");\n }\n const plaintextTextarea = document.getElementById(\"plaintext\");\n if (!plaintextTextarea) {\n throw new Error(\n \"no plaintext textarea HTML element found to apply settings to.\"\n );\n }\n\n // Apply enablePassphrase setting\n if (settingsObj.enablePassphrase === true) {\n passphraseLabel.style.display = \"inline-block\";\n passphraseTextarea.style.display = \"inline-block\";\n passphraseTextarea.style.border = \"solid 1px #ccc\";\n passphraseTextarea.style.borderRadius = \"4px\";\n\n mnemonicLabel.style.display = \"inline-block\";\n plaintextTextarea.style.border = \"solid 1px #ccc\";\n plaintextTextarea.style.borderRadius = \"4px\";\n\n validSettings[\"enablePassphrase\"] = true;\n } else {\n passphraseLabel.style.display = \"none\";\n passphraseTextarea.style.display = \"none\";\n mnemonicLabel.style.display = \"none\";\n\n plaintextTextarea.style.border = \"none\";\n validSettings[\"enablePassphrase\"] = false;\n }\n\n if (settingsObj.styles) {\n // Validate, sanitize, and apply the styles to the \"plaintext\" textarea.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n plaintextTextarea.style[key] = value;\n });\n\n if (validStyles.backgroundColor) {\n // Apply background color to document and body as well.\n document.documentElement.style.backgroundColor =\n validStyles.backgroundColor;\n document.body.style.backgroundColor = validStyles.backgroundColor;\n }\n\n if (validStyles.labelColor) {\n document.getElementById(\"mnemonic-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"styles\"] = validStyles;\n }\n\n if (settingsObj.passphraseStyles) {\n // Validate, sanitize, and apply the styles to the \"passphrase\" textarea.\n const validStyles = validateStyles(settingsObj.passphraseStyles);\n Object.entries(validStyles).forEach(([key, value]) => {\n passphraseTextarea.style[key] = value;\n });\n\n if (validStyles.labelColor) {\n document.getElementById(\"passphrase-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"passphraseStyles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n applySettings,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n"],"names":["e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_OverloadYield","k","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_TARGET_EMBEDDED_KEY","TURNKEY_SETTINGS","parentFrameMessageChannelPort","cryptoProviderOverride","getSubtleCrypto","subtle","globalThis","crypto","window","global","setCryptoProvider","cryptoProvider","loadQuorumKey","_x","_loadQuorumKey","_regeneratorRuntime","mark","_callee","quorumPublic","wrap","_context","prev","next","Error","importKey","namedCurve","abrupt","sent","stop","loadTargetKey","_x2","_loadTargetKey","_callee2","targetPublic","targetKey","_context2","exportKey","getTargetEmbeddedKey","jwtKey","localStorage","getItem","JSON","parse","setTargetEmbeddedKey","setItem","stringify","resetTargetEmbeddedKey","removeItem","setParentFrameMessageChannelPort","port","getSettings","settings","setSettings","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","normalizePadding","byteArray","targetLength","paddingLength","padding","fill","concat","expectedZeroCount","zeroCount","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","fromDerSignature","derSignature","derSignatureBuf","index","rLength","sLength","rPadded","sPadded","verifyEnclaveSignature","_x3","_x4","_x5","_verifyEnclaveSignature","_callee5","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context5","prod","preprod","__TURNKEY_SIGNER_ENVIRONMENT__","undefined","verify","hash","sendMessageUp","type","requestId","message","postMessage","parent","content","messageLog","document","getElementById","createElement","innerText","appendChild","logMessage","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","carry","push","j","currentByte","result","reverse","base58CheckDecode","_x7","_base58CheckDecode","_callee7","decoded","payload","checksum","hash1Buf","hash1","hash2Buf","hash2","computedChecksum","_context7","subarray","digest","decodeKey","_x8","_x9","_decodeKey","_callee8","privateKey","keyFormat","decodedKeyBytes","version","keyAndFlags","_payload","_version","_keyAndFlags","_bech32$decode","prefix","words","bytes","schemeFlag","privkey","_context8","t0","bech32","decode","fromWords","console","warn","validateStyles","styles","element","validStyles","cssValidationRegex","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref3","_ref4","_arrayWithHoles","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","SharedTKHQ","applySettings","validSettings","settingsObj","passphraseLabel","mnemonicLabel","passphraseTextarea","plaintextTextarea","enablePassphrase","style","display","border","_ref","_ref2","_slicedToArray","key","documentElement","body","passphraseStyles","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","_objectSpread","_defineProperty","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","TextEncoder","encode","HpkeEncrypt","_HpkeEncrypt","plaintextBuf","receiverPubJwk","kemContext","receiverPub","suite","senderCtx","receiverPubCryptoKey","receiverPubRaw","encappedKeyBuf","aad","ciphertextBuf","ciphertextHex","encappedKeyBufHex","encryptedBundle","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createSenderContext","recipientPublicKey","info","enc","seal","encappedPublic","ciphertext"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"551.bundle.27da59437a4e403e3c24.js","mappings":";moFACA,IAAAA,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IAAAE,EAAAC,EAAAG,EAAAI,EAAA,EAAAC,EAAAX,GAAA,GAAAY,GAAA,EAAAC,EAAA,CAAAF,EAAA,EAAAb,EAAA,EAAAgB,EAAApB,EAAAqB,EAAAC,EAAAN,EAAAM,EAAAC,KAAAvB,EAAA,GAAAsB,EAAA,SAAArB,EAAAC,GAAA,OAAAM,EAAAP,EAAAQ,EAAA,EAAAG,EAAAZ,EAAAmB,EAAAf,EAAAF,EAAAmB,CAAA,YAAAC,EAAApB,EAAAE,GAAA,IAAAK,EAAAP,EAAAU,EAAAR,EAAAH,EAAA,GAAAiB,GAAAF,IAA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f,OAAOF,OAAO+B,UACzC,MACAiO,GACD,QAKmE,OAR9DC,EAAcnO,EAAAR,KAIdmD,EAAiB,IAAIrB,WAAW6M,GAEhCC,EAAiB,IAAI9M,WAAW2M,EAAUmB,KAE1Cf,GAAM5L,EAAAA,EAAAA,IAAyB2L,EAAgBzL,GAAe3C,EAAAd,KAAA,GAAAc,EAAAb,KAAA,GAI5C8O,EAAUoB,KAAKzB,EAAcS,GAAI,QAAvDC,EAAatO,EAAAR,KAAAQ,EAAAb,KAAG,GAAH,oBAAAa,EAAAd,KAAG,GAAHc,EAAAwI,GAAAxI,EAAA,UAEP,IAAIZ,MAAM,oCAAsCY,EAAAwI,GAAEzL,YAAW,QAQnE,OALIwR,GAAgB5M,EAAAA,EAAAA,IAAsB,IAAIL,WAAWgN,IACrDE,GAAoB7M,EAAAA,EAAAA,IAAsByM,GAC1CK,EAAkBnO,KAAKI,UAAU,CACrC4O,eAAgBd,EAChBe,WAAYhB,IACZvO,EAAAT,OAAA,SACKkP,GAAe,yBAAAzO,EAAAP,OAAA,EAAAI,EAAA,kBACvB8N,EA3HD,eAAAlU,EAAA,KAAAD,EAAAiE,UAAA,WAAAJ,QAAA,SAAA3D,EAAAI,GAAA,IAAAe,EAAAjB,EAAA8D,MAAAjE,EAAAD,GAAA,SAAAmE,EAAA/D,GAAAwD,EAAAvC,EAAAnB,EAAAI,EAAA6D,EAAAC,EAAA,OAAAhE,EAAA,UAAAgE,EAAAhE,GAAAwD,EAAAvC,EAAAnB,EAAAI,EAAA6D,EAAAC,EAAA,QAAAhE,EAAA,CAAA+D,OAAA,OA2HCD,MAAA,KAAAD,WA3HD,IAAA7D,CA2HC,C","sources":["webpack://import/../shared/turnkey-core.js","webpack://import/./src/turnkey-core.js","webpack://import/../shared/crypto-utils.js"],"sourcesContent":["import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n if (!data) {\n return null;\n }\n try {\n return JSON.parse(data);\n } catch (e) {\n // If the stored data is corrupted or not valid JSON, remove it to self-heal.\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n return null;\n }\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * Only removes the bundle if it belongs to the specified organization.\n * @param {string} address - The wallet address to remove\n * @param {string} organizationId - Only remove if the bundle belongs to this org\n */\nfunction removeEncryptedBundle(address, organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles || !bundles[address]) return;\n\n // Only remove if the bundle belongs to the specified organization\n if (bundles[address].organizationId !== organizationId) return;\n\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n}\n\n/**\n * Removes all encrypted bundles belonging to the specified organization.\n * Bundles from other organizations are preserved.\n * @param {string} organizationId - Remove bundles belonging to this org\n */\nfunction clearAllEncryptedBundles(organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles) return;\n\n // Keep only bundles that do NOT belong to this organization\n const remaining = Object.fromEntries(\n Object.entries(bundles).filter(\n ([, bundle]) => bundle.organizationId !== organizationId\n )\n );\n\n if (Object.keys(remaining).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(remaining)\n );\n }\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n} = SharedTKHQ;\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n const settingsObj = JSON.parse(settings);\n\n const passphraseLabel = document.getElementById(\"passphrase-label\");\n const mnemonicLabel = document.getElementById(\"mnemonic-label\");\n const passphraseTextarea = document.getElementById(\"passphrase\");\n\n if (!passphraseLabel || !passphraseTextarea) {\n throw new Error(\"no passphrase HTML elements found to apply settings to.\");\n }\n const plaintextTextarea = document.getElementById(\"plaintext\");\n if (!plaintextTextarea) {\n throw new Error(\n \"no plaintext textarea HTML element found to apply settings to.\"\n );\n }\n\n // Apply enablePassphrase setting\n if (settingsObj.enablePassphrase === true) {\n passphraseLabel.style.display = \"inline-block\";\n passphraseTextarea.style.display = \"inline-block\";\n passphraseTextarea.style.border = \"solid 1px #ccc\";\n passphraseTextarea.style.borderRadius = \"4px\";\n\n mnemonicLabel.style.display = \"inline-block\";\n plaintextTextarea.style.border = \"solid 1px #ccc\";\n plaintextTextarea.style.borderRadius = \"4px\";\n\n validSettings[\"enablePassphrase\"] = true;\n } else {\n passphraseLabel.style.display = \"none\";\n passphraseTextarea.style.display = \"none\";\n mnemonicLabel.style.display = \"none\";\n\n plaintextTextarea.style.border = \"none\";\n validSettings[\"enablePassphrase\"] = false;\n }\n\n if (settingsObj.styles) {\n // Validate, sanitize, and apply the styles to the \"plaintext\" textarea.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n plaintextTextarea.style[key] = value;\n });\n\n if (validStyles.backgroundColor) {\n // Apply background color to document and body as well.\n document.documentElement.style.backgroundColor =\n validStyles.backgroundColor;\n document.body.style.backgroundColor = validStyles.backgroundColor;\n }\n\n if (validStyles.labelColor) {\n document.getElementById(\"mnemonic-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"styles\"] = validStyles;\n }\n\n if (settingsObj.passphraseStyles) {\n // Validate, sanitize, and apply the styles to the \"passphrase\" textarea.\n const validStyles = validateStyles(settingsObj.passphraseStyles);\n Object.entries(validStyles).forEach(([key, value]) => {\n passphraseTextarea.style[key] = value;\n });\n\n if (validStyles.labelColor) {\n document.getElementById(\"passphrase-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"passphraseStyles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n applySettings,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n"],"names":["e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_OverloadYield","k","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_TARGET_EMBEDDED_KEY","TURNKEY_SETTINGS","parentFrameMessageChannelPort","cryptoProviderOverride","getSubtleCrypto","subtle","globalThis","crypto","window","global","setCryptoProvider","cryptoProvider","loadQuorumKey","_x","_loadQuorumKey","_regeneratorRuntime","mark","_callee","quorumPublic","wrap","_context","prev","next","Error","importKey","namedCurve","abrupt","sent","stop","loadTargetKey","_x2","_loadTargetKey","_callee2","targetPublic","targetKey","_context2","exportKey","getTargetEmbeddedKey","jwtKey","localStorage","getItem","JSON","parse","setTargetEmbeddedKey","setItem","stringify","resetTargetEmbeddedKey","removeItem","setParentFrameMessageChannelPort","port","getSettings","settings","setSettings","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","normalizePadding","byteArray","targetLength","paddingLength","padding","fill","concat","expectedZeroCount","zeroCount","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","fromDerSignature","derSignature","derSignatureBuf","index","rLength","sLength","rPadded","sPadded","verifyEnclaveSignature","_x3","_x4","_x5","_verifyEnclaveSignature","_callee5","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context5","prod","preprod","__TURNKEY_SIGNER_ENVIRONMENT__","undefined","verify","hash","sendMessageUp","type","requestId","message","postMessage","parent","content","messageLog","document","getElementById","createElement","innerText","appendChild","logMessage","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","carry","push","j","currentByte","result","reverse","base58CheckDecode","_x7","_base58CheckDecode","_callee7","decoded","payload","checksum","hash1Buf","hash1","hash2Buf","hash2","computedChecksum","_context7","subarray","digest","decodeKey","_x8","_x9","_decodeKey","_callee8","privateKey","keyFormat","decodedKeyBytes","version","keyAndFlags","_payload","_version","_keyAndFlags","_bech32$decode","prefix","words","bytes","schemeFlag","privkey","_context8","t0","bech32","decode","fromWords","console","warn","validateStyles","styles","element","validStyles","cssValidationRegex","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref3","_ref4","_arrayWithHoles","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","SharedTKHQ","applySettings","validSettings","settingsObj","passphraseLabel","mnemonicLabel","passphraseTextarea","plaintextTextarea","enablePassphrase","style","display","border","_ref","_ref2","_slicedToArray","key","documentElement","body","passphraseStyles","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","_objectSpread","_defineProperty","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","TextEncoder","encode","HpkeEncrypt","_HpkeEncrypt","plaintextBuf","receiverPubJwk","kemContext","receiverPub","suite","senderCtx","receiverPubCryptoKey","receiverPubRaw","encappedKeyBuf","aad","ciphertextBuf","ciphertextHex","encappedKeyBufHex","encryptedBundle","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createSenderContext","recipientPublicKey","info","enc","seal","encappedPublic","ciphertext"],"sourceRoot":""} \ No newline at end of file diff --git a/shared/turnkey-core.test.js b/shared/turnkey-core.test.js index 6ed8988..7c49d06 100644 --- a/shared/turnkey-core.test.js +++ b/shared/turnkey-core.test.js @@ -445,4 +445,86 @@ describe("Shared TKHQ Utilities", () => { expect(publicKey.length).toBe(65); // Uncompressed P-256 public key }); }); + + describe("Encrypted bundle org isolation", () => { + const orgA = "org-alpha"; + const orgB = "org-beta"; + + const bundleA1 = { + encappedPublic: "aa", + ciphertext: "bb", + organizationId: orgA, + keyFormat: "SOLANA", + }; + const bundleA2 = { + encappedPublic: "cc", + ciphertext: "dd", + organizationId: orgA, + keyFormat: "HEXADECIMAL", + }; + const bundleB1 = { + encappedPublic: "ee", + ciphertext: "ff", + organizationId: orgB, + keyFormat: "SOLANA", + }; + + beforeEach(() => { + SharedTKHQ.setEncryptedBundle("addrA1", bundleA1); + SharedTKHQ.setEncryptedBundle("addrA2", bundleA2); + SharedTKHQ.setEncryptedBundle("addrB1", bundleB1); + }); + + it("removeEncryptedBundle refuses to delete another org's bundle", () => { + // orgB tries to remove addrA1 (belongs to orgA) + SharedTKHQ.removeEncryptedBundle("addrA1", orgB); + + const bundles = SharedTKHQ.getEncryptedBundles(); + expect(bundles["addrA1"]).toEqual(bundleA1); // still present + expect(bundles["addrB1"]).toEqual(bundleB1); + }); + + it("removeEncryptedBundle succeeds when orgId matches", () => { + SharedTKHQ.removeEncryptedBundle("addrA1", orgA); + + const bundles = SharedTKHQ.getEncryptedBundles(); + expect(bundles["addrA1"]).toBeUndefined(); // gone + expect(bundles["addrA2"]).toEqual(bundleA2); // other orgA bundle untouched + expect(bundles["addrB1"]).toEqual(bundleB1); + }); + + it("clearAllEncryptedBundles only removes the target org's bundles", () => { + SharedTKHQ.clearAllEncryptedBundles(orgA); + + const bundles = SharedTKHQ.getEncryptedBundles(); + // orgA bundles are gone + expect(bundles["addrA1"]).toBeUndefined(); + expect(bundles["addrA2"]).toBeUndefined(); + // orgB bundle is still present + expect(bundles["addrB1"]).toEqual(bundleB1); + }); + + it("clearAllEncryptedBundles removes localStorage key when all remaining bundles are cleared", () => { + // Clear orgA first + SharedTKHQ.clearAllEncryptedBundles(orgA); + expect(SharedTKHQ.getEncryptedBundles()).not.toBeNull(); + + // Clear orgB — now nothing should remain + SharedTKHQ.clearAllEncryptedBundles(orgB); + expect(SharedTKHQ.getEncryptedBundles()).toBeNull(); + }); + + it("orgB cannot peek at orgA's bundle data via getEncryptedBundles", () => { + // getEncryptedBundles returns everything (it's a raw accessor), + // but the handler layer in event-handlers.js filters by orgId. + // At the storage layer, verify that removing orgB's data doesn't + // leak or corrupt orgA's entries. + SharedTKHQ.clearAllEncryptedBundles(orgB); + + const bundles = SharedTKHQ.getEncryptedBundles(); + expect(Object.keys(bundles)).toEqual(["addrA1", "addrA2"]); + expect(bundles["addrA1"]).toEqual(bundleA1); + expect(bundles["addrA2"]).toEqual(bundleA2); + }); + }); }); From e82ee2d0e19ed7854199907fa44f82d65863191a Mon Sep 17 00:00:00 2001 From: Ethan Konkolowicz Date: Thu, 12 Feb 2026 11:00:04 -0500 Subject: [PATCH 5/7] added more authoritative reference links for the pkcs8 prefixes --- .../dist/bundle.3f29bf7d8e30fb1dd823.js | 3 -- .../dist/bundle.3f29bf7d8e30fb1dd823.js.map | 1 - .../dist/bundle.801fe7bbee4484b5f44c.js | 3 ++ ...undle.801fe7bbee4484b5f44c.js.LICENSE.txt} | 0 .../dist/bundle.801fe7bbee4484b5f44c.js.map | 1 + export-and-sign/dist/index.html | 2 +- export-and-sign/src/event-handlers.js | 33 +++++++++++++++---- 7 files changed, 31 insertions(+), 12 deletions(-) delete mode 100644 export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js delete mode 100644 export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js.map create mode 100644 export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js rename export-and-sign/dist/{bundle.3f29bf7d8e30fb1dd823.js.LICENSE.txt => bundle.801fe7bbee4484b5f44c.js.LICENSE.txt} (100%) create mode 100644 export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.map diff --git a/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js b/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js deleted file mode 100644 index 8340d5c..0000000 --- a/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! For license information please see bundle.3f29bf7d8e30fb1dd823.js.LICENSE.txt */ -(()=>{var e,t,r,n,a,o={560:(e,t,r)=>{"use strict";var n=r(598),a=r(443),o=r(566);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function c(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function u(e){for(var t=1;t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var l=[][n]?t(t([][n]())):(d(t={},n,function(){return this}),t),p=s.prototype=c.prototype=Object.create(l);function y(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,d(e,a,"GeneratorFunction")),e.prototype=Object.create(p),e}return u.prototype=s,d(p,"constructor",s),d(s,"constructor",u),u.displayName="GeneratorFunction",d(s,a,"GeneratorFunction"),d(p),d(p,a,"Generator"),d(p,n,function(){return this}),d(p,"toString",function(){return"[object Generator]"}),(f=function(){return{w:o,m:y}})()}function d(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}d=function(e,t,r,n){function o(t,r){d(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},d(e,t,r,n)}function l(e){return function(e){if(Array.isArray(e))return v(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||y(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,a,o,i,c=[],u=!0,s=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=o.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,a=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw a}}return c}}(e,t)||y(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(e,t){if(e){if("string"==typeof e)return v(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?v(e,t):void 0}}function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1:window.parent!==window.top}function k(){return(k=g(f().m(function e(t){var r;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=S()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,r.importKey("raw",t,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function P(){return(P=g(f().m(function e(){return f().w(function(e){for(;;)switch(e.n){case 0:if(!O()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,_();case 2:if(null!==e.v){e.n=4;break}return e.n=3,j();case 3:x(e.v);case 4:return e.a(2)}},e)}))).apply(this,arguments)}function j(){return I.apply(this,arguments)}function I(){return(I=g(f().m(function e(){var t,r;return f().w(function(e){for(;;)switch(e.n){case 0:if(t=S()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,t.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return r=e.v,e.n=3,t.exportKey("jwk",r.privateKey);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function _(){var e=R(m);return e?JSON.parse(e):null}function x(e){A(m,JSON.stringify(e),1728e5)}function T(){var e=window.localStorage.getItem(w);if(!e)return null;try{return JSON.parse(e)}catch(e){return window.localStorage.removeItem(w),null}}function A(e,t,r){var n={value:t,expiry:(new Date).getTime()+r};window.localStorage.setItem(e,JSON.stringify(n))}function R(e){var t=window.localStorage.getItem(e);if(!t)return null;var r=JSON.parse(t);return Object.prototype.hasOwnProperty.call(r,"expiry")&&Object.prototype.hasOwnProperty.call(r,"value")?(new Date).getTime()>r.expiry?(window.localStorage.removeItem(e),null):r.value:(window.localStorage.removeItem(e),null)}function D(e){if(!e||"string"!=typeof e)throw new Error("cannot create uint8array from invalid hex string");var t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0||!/^[0-9A-Fa-f]+$/.test(t))throw new Error("cannot create uint8array from invalid hex string");return new Uint8Array(t.match(/../g).map(function(e){return parseInt(e,16)}))}function N(e){return l(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function M(e,t){var r=Array.from(new Uint8Array(e)),n=Array.from(new Uint8Array(t));return new Uint8Array([].concat(r,n))}function U(e){var t=document.getElementById("message-log");if(t){var r=document.createElement("p");r.innerText=e,t.appendChild(r)}}function K(e){return C.apply(this,arguments)}function C(){return(C=g(f().m(function e(t){var r,n,a,o;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=S()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return delete(n=u({},t)).d,n.key_ops=["verify"],e.n=2,r.importKey("jwk",n,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return a=e.v,e.n=3,r.exportKey("raw",a);case 3:return o=e.v,e.a(2,new Uint8Array(o))}},e)}))).apply(this,arguments)}function B(e){for(var t="",r=[0],n=0;n0;)r.push(a%58),a=a/58|0}for(var i=0;i0;){var c=r[i];o=(c=void 0===c?o:58*c+o)>>8,r[i]=c%256,i++}}var u=n.concat(r.reverse());return new Uint8Array(u)}function G(){return(G=g(f().m(function e(t,r,n){var a,o;return f().w(function(e){for(;;)switch(e.n){case 0:o=r,e.n="SOLANA"===o?1:"HEXADECIMAL"===o?5:6;break;case 1:if(n){e.n=2;break}throw new Error("public key must be specified for SOLANA key format");case 2:if(32===t.length){e.n=3;break}throw new Error("invalid private key length. Expected 32 bytes. Got ".concat(t.length,"."));case 3:if(32===n.length){e.n=4;break}throw new Error("invalid public key length. Expected 32 bytes. Got ".concat(n.length,"."));case 4:return(a=new Uint8Array(64)).set(t,0),a.set(n,32),e.a(2,B(a));case 5:return e.a(2,"0x"+N(t));case 6:return console.warn("invalid key format: ".concat(r,". Defaulting to HEXADECIMAL.")),e.a(2,"0x"+N(t));case 7:return e.a(2)}},e)}))).apply(this,arguments)}function F(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",a=r.toStringTag||"@@toStringTag";function o(r,n,a,o){var u=n&&n.prototype instanceof c?n:c,s=Object.create(u.prototype);return H(s,"_invoke",function(r,n,a){var o,c,u,s=0,f=a||[],d=!1,l={p:0,n:0,v:e,a:p,f:p.bind(e,4),d:function(t,r){return o=t,c=0,u=e,l.n=r,i}};function p(r,n){for(c=r,u=n,t=0;!d&&s&&!a&&t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(H(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,H(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,H(d,"constructor",s),H(s,"constructor",u),u.displayName="GeneratorFunction",H(s,a,"GeneratorFunction"),H(d),H(d,a,"Generator"),H(d,n,function(){return this}),H(d,"toString",function(){return"[object Generator]"}),(F=function(){return{w:o,m:l}})()}function H(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}H=function(e,t,r,n){function o(t,r){H(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},H(e,t,r,n)}function Y(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r]*$',color:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",labelColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",backgroundColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",width:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",height:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",maxWidth:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",maxHeight:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",lineHeight:"^(\\d+(\\.\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$",boxShadow:"^(none|(\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)) ?(inset)?)$",textAlign:"^(left|right|center|justify|initial|inherit)$",overflowWrap:"^(normal|break-word|anywhere)$",wordWrap:"^(normal|break-word)$",resize:"^(none|both|horizontal|vertical|block|inline)$"};return Object.entries(e).forEach(function(e){var t=p(e,2),a=t[0],o=t[1],i=a.trim();if(0===i.length)throw new Error("css style property cannot be empty");var c=n[i];if(!c)throw new Error('invalid or unsupported css style property: "'.concat(i,'"'));var u=new RegExp(c),s=o.trim();if(0==s.length)throw new Error('css style for "'.concat(i,'" is empty'));if(!u.test(s))throw new Error('invalid css style value for property "'.concat(i,'"'));r[i]=s}),r},V=O,Q=function(e){return k.apply(this,arguments)},Z=T;function ee(){return(ee=J(F().m(function e(){return F().w(function(e){for(;;)switch(e.n){case 0:if(!V()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,q();case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function te(){return(te=J(F().m(function e(t,r,n){var a,i,c,u,s,f,d,l;return F().w(function(e){for(;;)switch(e.n){case 0:if(a={prod:"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569",preprod:"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212"},i=null,"undefined"!=typeof document&&(c=document.querySelector('meta[name="turnkey-signer-environment"]'))&&c.content&&"__TURNKEY_SIGNER_ENVIRONMENT__"!==c.content&&(i=c.content),i||"undefined"==typeof window||(i=window.__TURNKEY_SIGNER_ENVIRONMENT__),void 0!==(u=a[i])){e.n=1;break}throw new Error("Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined");case 1:if(t===u){e.n=2;break}throw new Error("enclave quorum public keys from client and bundle do not match. Client: ".concat(u,". Bundle: ").concat(t,"."));case 2:return s=new Uint8Array($(u)),e.n=3,Q(s);case 3:if(f=e.v){e.n=4;break}throw new Error("failed to load quorum key");case 4:return d=(0,o.g8)(r),l=$(n),e.n=5,crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},f,d,l);case 5:return e.a(2,e.v)}},e)}))).apply(this,arguments)}var re={initEmbeddedKey:function(){return ee.apply(this,arguments)},generateTargetKey:j,setItemWithExpiry:A,getItemWithExpiry:R,getEmbeddedKey:_,setEmbeddedKey:x,onResetEmbeddedKey:function(){window.localStorage.removeItem(m),window.localStorage.removeItem("TURNKEY_EMBEDDED_KEY_ORIGIN")},p256JWKPrivateToPublic:K,base58Encode:B,base58Decode:L,encodeKey:function(e,t,r){return G.apply(this,arguments)},sendMessageUp:function(e,t,r){var n={type:e,value:t};r&&(n.requestId=r),E?E.postMessage(n):window.parent!==window&&window.parent.postMessage({type:e,value:t},"*"),U("⬆️ Sent message ".concat(e,": ").concat(t))},logMessage:U,uint8arrayFromHexString:$,uint8arrayToHexString:N,setParentFrameMessageChannelPort:function(e){E=e},normalizePadding:function(e,t){var r=t-e.length;if(r>0){var n=new Uint8Array(r).fill(0);return new Uint8Array([].concat(l(n),l(e)))}if(r<0){for(var a=-1*r,o=0,i=0;i3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(se(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,se(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,se(d,"constructor",s),se(s,"constructor",u),u.displayName="GeneratorFunction",se(s,a,"GeneratorFunction"),se(d),se(d,a,"Generator"),se(d,n,function(){return this}),se(d,"toString",function(){return"[object Generator]"}),(ue=function(){return{w:o,m:l}})()}function se(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}se=function(e,t,r,n){function o(t,r){se(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},se(e,t,r,n)}function fe(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,a,o,i,c=[],u=!0,s=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=o.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,a=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw a}}return c}}(e,t)||function(e,t){if(e){if("string"==typeof e)return de(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?de(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function de(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r= v2.0.0 to pass "organizationId" for security purposes.');case 8:if(a.organizationId&&a.organizationId===r){e.n=9;break}throw new Error("organization id does not match expected value. Expected: ".concat(r,". Found: ").concat(a.organizationId,"."));case 9:if(a.encappedPublic){e.n=10;break}throw new Error('missing "encappedPublic" in bundle signed data');case 10:if(a.ciphertext){e.n=11;break}throw new Error('missing "ciphertext" in bundle signed data');case 11:return e.a(2,a)}},e)}))).apply(this,arguments)}function we(e,t,r){return Ee.apply(this,arguments)}function Ee(){return Ee=pe(ue().m(function e(t,r,n){var a,o,i,c;return ue().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,me(t,r);case 1:return a=e.v,o=re.uint8arrayFromHexString(a.encappedPublic),i=re.uint8arrayFromHexString(a.ciphertext),e.n=2,re.getEmbeddedKey();case 2:return c=e.v,e.n=3,n({ciphertextBuf:i,encappedKeyBuf:o,receiverPrivJwk:c});case 3:return e.a(2,e.v)}},e)})),Ee.apply(this,arguments)}function Se(e){return Oe.apply(this,arguments)}function Oe(){return(Oe=pe(ue().m(function e(t){var r,n,a;return ue().w(function(e){for(;;)switch(e.n){case 0:if(r=re.getEmbeddedKey()){e.n=1;break}return re.sendMessageUp("EMBEDDED_PUBLIC_KEY","",t),e.a(2);case 1:return e.n=2,re.p256JWKPrivateToPublic(r);case 2:n=e.v,a=re.uint8arrayToHexString(n),re.sendMessageUp("EMBEDDED_PUBLIC_KEY",a,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function ke(e,t,r,n){return Pe.apply(this,arguments)}function Pe(){return(Pe=pe(ue().m(function e(t,r,n,a){var o,i,c,u,s,f;return ue().w(function(e){for(;;)switch(e.n){case 0:if(i=new Uint8Array(r),"SOLANA"!==n){e.n=2;break}return c=re.uint8arrayToHexString(i.subarray(0,32)),u=re.getEd25519PublicKey(c),e.n=1,re.encodeKey(i,n,u);case 1:o=e.v,e.n=4;break;case 2:return e.n=3,re.encodeKey(i,n);case 3:o=e.v;case 4:if(s=t||"default","SOLANA"!==n){e.n=5;break}f=ne.AX.fromSecretKey(re.base58Decode(o)),e.n=7;break;case 5:if("HEXADECIMAL"!==n){e.n=7;break}return e.n=6,ze(Array.from(re.uint8arrayFromHexString(o)));case 6:f=e.v;case 7:ye=ie(ie({},ye),{},ce({},s,{organizationId:a,privateKey:o,format:n,expiry:(new Date).getTime()+864e5,keypair:f}));case 8:return e.a(2)}},e)}))).apply(this,arguments)}function je(e,t,r,n,a,o){return Ie.apply(this,arguments)}function Ie(){return Ie=pe(ue().m(function e(t,r,n,a,o,i){var c;return ue().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,we(n,r,i);case 1:return c=e.v,e.n=2,ke(o,c,a,r);case 2:re.sendMessageUp("BUNDLE_INJECTED",!0,t);case 3:return e.a(2)}},e)})),Ie.apply(this,arguments)}function _e(e,t){return xe.apply(this,arguments)}function xe(){return(xe=pe(ue().m(function e(t,r){var n;return ue().w(function(e){for(;;)switch(e.n){case 0:n=re.applySettings(t),re.setSettings(n),re.sendMessageUp("SETTINGS_APPLIED",!0,r);case 1:return e.a(2)}},e)}))).apply(this,arguments)}function Te(e,t,r){return Ae.apply(this,arguments)}function Ae(){return(Ae=pe(ue().m(function e(t,r,n){var a,o,i,c,u,s,f,d,l;return ue().w(function(e){for(;;)switch(e.n){case 0:if($e(o=ye[a=n||"default"],a)){e.n=1;break}return e.a(2);case 1:return e.n=2,We(o);case 2:if(i=e.v,c=JSON.parse(r),u=c.transaction,"SOLANA"!==c.type){e.n=3;break}f=re.uint8arrayFromHexString(u),(d=ne.Kt.deserialize(f)).sign([i]),s=d.serialize(),e.n=4;break;case 3:throw new Error("unsupported transaction type");case 4:l=re.uint8arrayToHexString(s),re.sendMessageUp("TRANSACTION_SIGNED",l,t);case 5:return e.a(2)}},e)}))).apply(this,arguments)}function Re(e,t,r){return De.apply(this,arguments)}function De(){return De=pe(ue().m(function e(t,r,o){var i,c,u,s,f,d,l,p,y,v;return ue().w(function(e){for(;;)switch(e.n){case 0:if($e(c=ye[i=o||"default"],i)){e.n=1;break}return e.a(2);case 1:return u=JSON.parse(r),s=u.message,f=u.type,d=be.encode(s),e.n=2,We(c);case 2:if(p=e.v,"SOLANA"!==f){e.n=3;break}n.jn.sha512Sync=function(){var e;return a.Zf((e=n.jn).concatBytes.apply(e,arguments))},y=p.secretKey.slice(0,32),v=n._S(d,y),l=re.uint8arrayToHexString(v),e.n=4;break;case 3:return re.sendMessageUp("ERROR","unsupported message type",t),e.a(2);case 4:re.sendMessageUp("MESSAGE_SIGNED",l,t);case 5:return e.a(2)}},e)})),De.apply(this,arguments)}function Ne(e,t){return Me.apply(this,arguments)}function Me(){return(Me=pe(ue().m(function e(t,r){return ue().w(function(e){for(;;)switch(e.n){case 0:if(r){e.n=1;break}return ye={},re.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t),e.a(2);case 1:if(ye[r]){e.n=2;break}return re.sendMessageUp("ERROR",new Error("key not found for address ".concat(r,". Note that address is case sensitive.")).toString(),t),e.a(2);case 2:delete ye[r],re.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function Ue(e,t,r,n,a,o){return Ke.apply(this,arguments)}function Ke(){return Ke=pe(ue().m(function e(t,r,n,a,o,i){var c,u,s,f,d;return ue().w(function(e){for(;;)switch(e.n){case 0:if(o){e.n=1;break}throw new Error("address is required for STORE_ENCRYPTED_BUNDLE");case 1:return e.n=2,me(n,r);case 2:if(c=e.v,u=a||"HEXADECIMAL",re.setEncryptedBundle(o,{encappedPublic:c.encappedPublic,ciphertext:c.ciphertext,organizationId:r,keyFormat:u}),!ve||!i){e.n=4;break}return s=re.uint8arrayFromHexString(c.encappedPublic),f=re.uint8arrayFromHexString(c.ciphertext),e.n=3,i({ciphertextBuf:f,encappedKeyBuf:s,receiverPrivJwk:ve});case 3:return d=e.v,e.n=4,ke(o,d,u,r);case 4:re.sendMessageUp("ENCRYPTED_BUNDLE_STORED",!0,t);case 5:return e.a(2)}},e)})),Ke.apply(this,arguments)}function Ce(e){return Be.apply(this,arguments)}function Be(){return(Be=pe(ue().m(function e(t){var r,n,a;return ue().w(function(e){for(;;)switch(e.n){case 0:if(32===t.length){e.n=1;break}throw new Error("invalid decryption key length: expected 32 bytes, got ".concat(t.length));case 1:return r=new Uint8Array([48,65,2,1,0,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,4,39,48,37,2,1,1,4,32]),(n=new Uint8Array(r.length+32)).set(r),n.set(t,r.length),e.n=2,crypto.subtle.importKey("pkcs8",n,{name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return a=e.v,e.n=3,crypto.subtle.exportKey("jwk",a);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function Le(e,t,r,n){return Ge.apply(this,arguments)}function Ge(){return Ge=pe(ue().m(function e(t,r,n,a){var o,i,c,u,s,f,d,l,p,y,v,b,g,m;return ue().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.n=1,we(n,r,a);case 1:return o=e.v,e.n=2,Ce(new Uint8Array(o));case 2:if(i=e.v,ve=i,c=re.getEncryptedBundles(),u=0,!c){e.n=10;break}s=Object.keys(c),f=0,d=s;case 3:if(!(f=e.expiry)throw function(){for(var e=(new Date).getTime(),t=[],r=0,n=Object.entries(ye);r=i.expiry&&t.push(o)}for(var c=0,u=t;c3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(tt(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,tt(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,tt(d,"constructor",s),tt(s,"constructor",u),u.displayName="GeneratorFunction",tt(s,a,"GeneratorFunction"),tt(d),tt(d,a,"Generator"),tt(d,n,function(){return this}),tt(d,"toString",function(){return"[object Generator]"}),(et=function(){return{w:o,m:l}})()}function tt(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}tt=function(e,t,r,n){function o(t,r){tt(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},tt(e,t,r,n)}function rt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function nt(e){for(var t=1;t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(ft(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,ft(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,ft(d,"constructor",s),ft(s,"constructor",u),u.displayName="GeneratorFunction",ft(s,a,"GeneratorFunction"),ft(d),ft(d,a,"Generator"),ft(d,n,function(){return this}),ft(d,"toString",function(){return"[object Generator]"}),(st=function(){return{w:o,m:l}})()}function ft(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}ft=function(e,t,r,n){function o(t,r){ft(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},ft(e,t,r,n)}function dt(e,t,r,n,a,o,i){try{var c=e[o](i),u=c.value}catch(e){return void r(e)}c.done?t(u):Promise.resolve(u).then(n,a)}function lt(e){return function(){var t=this,r=arguments;return new Promise(function(n,a){var o=e.apply(t,r);function i(e){dt(o,n,a,i,c,"next",e)}function c(e){dt(o,n,a,i,c,"throw",e)}i(void 0)})}}window.TKHQ=re,document.addEventListener("DOMContentLoaded",lt(st().m(function e(){var t,r,n,a;return st().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,re.initEmbeddedKey();case 1:return e.n=2,re.getEmbeddedKey();case 2:return t=e.v,e.n=3,re.p256JWKPrivateToPublic(t);case 3:r=e.v,n=re.uint8arrayToHexString(r),document.getElementById("embedded-key").value=n,Ve(ct),(a=re.getSettings())&&re.applySettings(a),re.sendMessageUp("PUBLIC_KEY_READY",n);case 4:return e.a(2)}},e)})))},790:()=>{},846:e=>{"use strict";e.exports=crypto}},i={};function c(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={id:e,loaded:!1,exports:{}};return o[e].call(r.exports,r,r.exports,c),r.loaded=!0,r.exports}c.m=o,e=[],c.O=(t,r,n,a)=>{if(!r){var o=1/0;for(f=0;f=a)&&Object.keys(c.O).every(e=>c.O[e](r[u]))?r.splice(u--,1):(i=!1,a0&&e[f-1][2]>a;f--)e[f]=e[f-1];e[f]=[r,n,a]},c.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return c.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,c.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var a=Object.create(null);c.r(a);var o={};t=t||[null,r({}),r([]),r(r)];for(var i=2&n&&e;("object"==typeof i||"function"==typeof i)&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach(t=>o[t]=()=>e[t]);return o.default=()=>e,c.d(a,o),a},c.d=(e,t)=>{for(var r in t)c.o(t,r)&&!c.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},c.f={},c.e=e=>Promise.all(Object.keys(c.f).reduce((t,r)=>(c.f[r](e,t),t),[])),c.u=e=>"bundle."+{291:"3eaea85f4001b9cc63c3",825:"aaba32bf7338e3d0f1cc"}[e]+".js",c.miniCssF=e=>{},c.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),c.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},a="export-and-sign:",c.l=(e,t,r,o)=>{if(n[e])n[e].push(t);else{var i,u;if(void 0!==r)for(var s=document.getElementsByTagName("script"),f=0;f{i.onerror=i.onload=null,clearTimeout(p);var a=n[e];if(delete n[e],i.parentNode&&i.parentNode.removeChild(i),a&&a.forEach(e=>e(r)),t)return t(r)},p=setTimeout(l.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=l.bind(null,i.onerror),i.onload=l.bind(null,i.onload),u&&document.head.appendChild(i)}},c.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),c.p="/",c.sriHashes={291:"sha384-G5pDFEAG9UZITbluyje/R/rWohZTUJf+Vu3ZIh0rsnLFLTw3SP/ca/XVNZVtv48f",825:"sha384-R9OIdd42i5GcdtZiHJuQgIUVvqyqJ0s7eaBnJHAfGllpi4YwbF7NSkjIRwOPUtsP"},(()=>{var e={792:0};c.f.j=(t,r)=>{var n=c.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[2]);else{var a=new Promise((r,a)=>n=e[t]=[r,a]);r.push(n[2]=a);var o=c.p+c.u(t),i=new Error;c.l(o,r=>{if(c.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var a=r&&("load"===r.type?"missing":r.type),o=r&&r.target&&r.target.src;i.message="Loading chunk "+t+" failed.\n("+a+": "+o+")",i.name="ChunkLoadError",i.type=a,i.request=o,n[1](i)}},"chunk-"+t,t)}},c.O.j=t=>0===e[t];var t=(t,r)=>{var n,a,[o,i,u]=r,s=0;if(o.some(t=>0!==e[t])){for(n in i)c.o(i,n)&&(c.m[n]=i[n]);if(u)var f=u(c)}for(t&&t(r);sc(560));u=c.O(u)})(); -//# sourceMappingURL=bundle.3f29bf7d8e30fb1dd823.js.map \ No newline at end of file diff --git a/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js.map b/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js.map deleted file mode 100644 index 06ec1cc..0000000 --- a/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bundle.3f29bf7d8e30fb1dd823.js","mappings":";UAAIA,ECCAC,EADAC,ECAAC,EACAC,E,svCCAJ,IAAAC,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IAAAE,EAAAC,EAAAG,EAAAI,EAAA,EAAAC,EAAAX,GAAA,GAAAY,GAAA,EAAAC,EAAA,CAAAF,EAAA,EAAAb,EAAA,EAAAgB,EAAApB,EAAAqB,EAAAC,EAAAN,EAAAM,EAAAC,KAAAvB,EAAA,GAAAsB,EAAA,SAAArB,EAAAC,GAAA,OAAAM,EAAAP,EAAAQ,EAAA,EAAAG,EAAAZ,EAAAmB,EAAAf,EAAAF,EAAAmB,CAAA,YAAAC,EAAApB,EAAAE,G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AsB5E,EAAoBM,EAAEsE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/../shared/turnkey-core.js","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/../shared/crypto-utils.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/external var \"crypto\"","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/global","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/compat","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t\tif (script.src.indexOf(window.location.origin + '/') !== 0) {\n\t\t\tscript.crossOrigin = \"anonymous\";\n\t\t}\n\t\tscript.integrity = __webpack_require__.sriHashes[chunkId];\n\t\tscript.crossOrigin = \"anonymous\";\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n if (!data) {\n return null;\n }\n try {\n return JSON.parse(data);\n } catch (e) {\n // If the stored data is corrupted or not valid JSON, remove it to self-heal.\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n return null;\n }\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * Only removes the bundle if it belongs to the specified organization.\n * @param {string} address - The wallet address to remove\n * @param {string} organizationId - Only remove if the bundle belongs to this org\n */\nfunction removeEncryptedBundle(address, organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles || !bundles[address]) return;\n\n // Only remove if the bundle belongs to the specified organization\n if (bundles[address].organizationId !== organizationId) return;\n\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n}\n\n/**\n * Removes all encrypted bundles belonging to the specified organization.\n * Bundles from other organizations are preserved.\n * @param {string} organizationId - Remove bundles belonging to this org\n */\nfunction clearAllEncryptedBundles(organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles) return;\n\n // Keep only bundles that do NOT belong to this organization\n const remaining = Object.fromEntries(\n Object.entries(bundles).filter(\n ([, bundle]) => bundle.organizationId !== organizationId\n )\n );\n\n if (Object.keys(remaining).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(remaining)\n );\n }\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\nimport { fromDerSignature } from \"@turnkey/crypto\";\nimport * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n initEmbeddedKey: sharedInitEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n additionalAssociatedData,\n getSettings,\n setSettings,\n parsePrivateKey,\n validateStyles,\n isDoublyIframed,\n loadQuorumKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n} = SharedTKHQ;\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n return await sharedInitEmbeddedKey();\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Read environment from meta tag (templated at deploy time), fall back to window variable (for testing)\n let environment = null;\n if (typeof document !== \"undefined\") {\n const meta = document.querySelector(\n 'meta[name=\"turnkey-signer-environment\"]'\n );\n if (\n meta &&\n meta.content &&\n meta.content !== \"__TURNKEY_SIGNER_ENVIRONMENT__\"\n ) {\n environment = meta.content;\n }\n }\n if (!environment && typeof window !== \"undefined\") {\n environment = window.__TURNKEY_SIGNER_ENVIRONMENT__;\n }\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\n// Decryption key -- held in memory only, never persisted to localStorage.\n// This is a P-256 private key in JWK format used to decrypt stored bundles.\nlet decryptionKey = null;\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Verifies the enclave signature on a v1.0.0 bundle and returns the parsed signed data.\n * @param {string} bundle - JSON-stringified bundle\n * @param {string} organizationId - Expected organization ID\n * @returns {Promise} - The parsed signed data {organizationId, encappedPublic, ciphertext}\n */\nasync function verifyAndParseBundleData(bundle, organizationId) {\n const bundleObj = JSON.parse(bundle);\n\n if (bundleObj.version !== \"v1.0.0\") {\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n const verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(`failed to verify enclave signature: ${bundle}`);\n }\n\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n\n return signedData;\n}\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n // Decrypt the ciphertext\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: embeddedKeyJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Encodes raw key bytes and loads them into the in-memory key store.\n * @param {string} address - Wallet address (case-sensitive)\n * @param {ArrayBuffer} keyBytes - Raw decrypted private key bytes\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} organizationId - Organization ID\n */\nasync function loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId) {\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair,\n },\n };\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Load decrypted key into memory\n await loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId);\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Set up sha512 for nobleEd25519 (required for signing)\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n\n // Extract the 32-byte private key from the 64-byte secretKey\n // Solana keypair.secretKey format: [32-byte private key][32-byte public key]\n const privateKey = keypair.secretKey.slice(0, 32);\n // Sign the message using nobleEd25519\n const signature = nobleEd25519.sign(messageBytes, privateKey);\n\n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n/**\n * Handler for STORE_ENCRYPTED_BUNDLE events.\n * Verifies the enclave signature on an encrypted bundle and stores\n * the encrypted payload in localStorage for later decryption.\n * If the decryption key is already in memory, also decrypts and loads\n * the key into memory immediately.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle JSON\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} address - Wallet address\n * @param {Function} HpkeDecrypt\n */\nasync function onStoreEncryptedBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n if (!address) {\n throw new Error(\"address is required for STORE_ENCRYPTED_BUNDLE\");\n }\n\n // Verify enclave signature and parse the signed data\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const resolvedKeyFormat = keyFormat || \"HEXADECIMAL\";\n\n // Store the encrypted fields in localStorage (just what's needed for decryption)\n TKHQ.setEncryptedBundle(address, {\n encappedPublic: signedData.encappedPublic,\n ciphertext: signedData.ciphertext,\n organizationId: organizationId,\n keyFormat: resolvedKeyFormat,\n });\n\n // If the decryption key is already in memory, decrypt and load immediately\n if (decryptionKey && HpkeDecrypt) {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n await loadKeyIntoMemory(\n address,\n keyBytes,\n resolvedKeyFormat,\n organizationId\n );\n }\n\n TKHQ.sendMessageUp(\"ENCRYPTED_BUNDLE_STORED\", true, requestId);\n}\n\n/**\n * Converts raw P-256 private key bytes (32-byte scalar) to a JWK.\n * Constructs a PKCS8 wrapper around the raw bytes, imports via WebCrypto\n * (which derives the public key), then exports as JWK.\n * @param {Uint8Array} rawPrivateKeyBytes - 32-byte P-256 private key scalar\n * @returns {Promise} - Full P-256 ECDH private key JWK\n */\nasync function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) {\n if (rawPrivateKeyBytes.length !== 32) {\n throw new Error(\n `invalid decryption key length: expected 32 bytes, got ${rawPrivateKeyBytes.length}`\n );\n }\n\n // PKCS8 DER prefix for a P-256 private key (without optional public key field)\n // SEQUENCE {\n // INTEGER 0 (version)\n // SEQUENCE { OID ecPublicKey, OID P-256 }\n // OCTET STRING { SEQUENCE { INTEGER 1, OCTET STRING(32) } }\n // }\n const pkcs8Prefix = new Uint8Array([\n 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48,\n 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03,\n 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20,\n ]);\n\n const pkcs8 = new Uint8Array(pkcs8Prefix.length + 32);\n pkcs8.set(pkcs8Prefix);\n pkcs8.set(rawPrivateKeyBytes, pkcs8Prefix.length);\n\n const cryptoKey = await crypto.subtle.importKey(\n \"pkcs8\",\n pkcs8,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"]\n );\n\n return await crypto.subtle.exportKey(\"jwk\", cryptoKey);\n}\n\n/**\n * Handler for INJECT_DECRYPTION_KEY_BUNDLE events.\n * Decrypts the P-256 private key using the iframe's embedded key,\n * then iterates all stored encrypted bundles, HPKE-decrypts each one\n * with the key, and loads them into inMemoryKeys.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle containing the private key\n * @param {Function} HpkeDecrypt\n */\nasync function onInjectDecryptionKeyBundle(\n requestId,\n organizationId,\n bundle,\n HpkeDecrypt\n) {\n // Decrypt the private key using the iframe's embedded key.\n // The decrypted payload is a raw 32-byte P-256 private key scalar.\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto)\n const keyJwk = await rawP256PrivateKeyToJwk(new Uint8Array(keyBytes));\n\n // Store in module-level variable (memory only)\n decryptionKey = keyJwk;\n\n // Iterate all stored encrypted bundles and decrypt each one\n const storedBundles = TKHQ.getEncryptedBundles();\n let decryptedCount = 0;\n\n if (storedBundles) {\n const addresses = Object.keys(storedBundles);\n\n for (const addr of addresses) {\n const bundleData = storedBundles[addr];\n\n try {\n const bundleOrgId = bundleData.organizationId;\n\n if (organizationId !== bundleOrgId) continue; // skip bundles that don't match the organization ID of the decryption key\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n bundleData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(\n bundleData.ciphertext\n );\n\n // HPKE-decrypt using the key\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n // Load the decrypted key into memory\n await loadKeyIntoMemory(\n addr,\n keyBytes,\n bundleData.keyFormat,\n bundleData.organizationId\n );\n\n decryptedCount++;\n } catch (e) {\n TKHQ.logMessage(\n `Failed to decrypt bundle for address ${addr}: ${e.toString()}`\n );\n }\n }\n }\n\n TKHQ.sendMessageUp(\"DECRYPTION_KEY_INJECTED\", decryptedCount, requestId);\n}\n\n/**\n * Handler for BURN_SESSION events.\n * Clears the decryption key and all in-memory wallet keys.\n * Encrypted bundles in localStorage are preserved for the next session.\n * @param {string} requestId\n */\nfunction onBurnSession(requestId) {\n decryptionKey = null;\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"SESSION_BURNED\", true, requestId);\n}\n\n/**\n * Handler for GET_STORED_WALLET_ADDRESSES events.\n * Returns a JSON array of all wallet addresses that have encrypted bundles in localStorage.\n * @param {string} requestId\n * @param {string} organizationId - Organization ID to filter addresses by (only return addresses with bundles matching the organization ID)\n */\nfunction onGetStoredWalletAddresses(requestId, organizationId) {\n const bundles = TKHQ.getEncryptedBundles();\n const addresses = bundles\n ? Object.entries(bundles)\n .filter(([, bundle]) => bundle.organizationId === organizationId)\n .map(([address]) => address)\n : [];\n TKHQ.sendMessageUp(\n \"STORED_WALLET_ADDRESSES\",\n JSON.stringify(addresses),\n requestId\n );\n}\n\n/**\n * Handler for CLEAR_STORED_BUNDLES events.\n * Removes encrypted bundles from localStorage AND the corresponding\n * in-memory keys. If address is provided, removes only that address.\n * If no address, removes ALL encrypted bundles and ALL in-memory keys.\n * @param {string} requestId\n * @param {string} organizationId - Organization ID to filter addresses by (only remove bundles matching the organization ID)\n * @param {string|undefined} address - Optional wallet address\n */\nfunction onClearStoredBundles(requestId, address, organizationId) {\n if (address) {\n TKHQ.removeEncryptedBundle(address, organizationId);\n delete inMemoryKeys[address];\n } else {\n TKHQ.clearAllEncryptedBundles(organizationId);\n inMemoryKeys = {};\n }\n TKHQ.sendMessageUp(\"STORED_BUNDLES_CLEARED\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error(\n `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`\n ).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n undefined, // keyFormat - default to HEXADECIMAL\n undefined, // address - default to \"default\"\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"STORE_ENCRYPTED_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n await onStoreEncryptedBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_DECRYPTION_KEY_BUNDLE\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onInjectDecryptionKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"BURN_SESSION\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onBurnSession(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_STORED_WALLET_ADDRESSES\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onGetStoredWalletAddresses(\n event.data[\"requestId\"],\n event.data[\"organizationId\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_STORED_BUNDLES\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n onClearStoredBundles(\n event.data[\"requestId\"],\n event.data[\"address\"],\n event.data[\"organizationId\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n onStoreEncryptedBundle,\n onInjectDecryptionKeyBundle,\n onBurnSession,\n onGetStoredWalletAddresses,\n onClearStoredBundles,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"@shared/crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n","module.exports = crypto;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","\n__webpack_require__.sriHashes = {\"291\":\"*-*-*-CHUNK-SRI-HASH-r3NPGwA4ft5fHgGXhVIptCiDVf06qPa+sxzG6L+8GwPuhn89e/\",\"825\":\"*-*-*-CHUNK-SRI-HASH-mfog3UJdGPOmSk4QZbKxsxHPFZtt298WnZNc1aQ1MCgc6YirFj\"};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(560)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","_slicedToArray","_arrayWithHoles","next","push","_iterableToArrayLimit","_nonIterableRest","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","TURNKEY_ENCRYPTED_BUNDLES","parentFrameMessageChannelPort","getSubtleCrypto","globalThis","crypto","subtle","window","global","isDoublyIframed","undefined","location","ancestorOrigins","parent","top","_loadQuorumKey","_callee","quorumPublic","_context","Error","importKey","namedCurve","_initEmbeddedKey","_callee3","_context3","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee4","p256key","_context4","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","getEncryptedBundles","data","localStorage","getItem","removeItem","key","ttl","item","expiry","Date","getTime","setItem","itemStr","hasOwnProperty","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","concat","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","p256JWKPrivateToPublic","_x6","_p256JWKPrivateToPublic","_callee6","jwkPrivate","jwkPrivateCopy","publicKey","_context6","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","k","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee9","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_t2","_context9","set","console","warn","sharedInitEmbeddedKey","SharedTKHQ","validateStyles","styles","element","validStyles","cssValidationRegex","padding","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref3","_ref4","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","loadQuorumKey","_x","_verifyEnclaveSignature","_callee2","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","meta","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context2","prod","preprod","querySelector","__TURNKEY_SIGNER_ENVIRONMENT__","fromDerSignature","verify","hash","TKHQ","initEmbeddedKey","onResetEmbeddedKey","encodeKey","_x0","_x1","_x10","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","normalizePadding","byteArray","targetLength","paddingLength","fill","expectedZeroCount","zeroCount","verifyEnclaveSignature","_x2","_x3","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","_ref","_ref2","style","getSettings","setSettings","parsePrivateKey","error","setEncryptedBundle","address","bundleData","bundles","removeEncryptedBundle","organizationId","keys","clearAllEncryptedBundles","remaining","fromEntries","filter","inMemoryKeys","decryptionKey","textEncoder","TextEncoder","textDecoder","TextDecoder","verifyAndParseBundleData","_verifyAndParseBundleData","_callee8","bundle","bundleObj","_context8","version","dataSignature","decode","encappedPublic","ciphertext","decryptBundle","_x4","_x5","_decryptBundle","HpkeDecrypt","encappedKeyBuf","ciphertextBuf","embeddedKeyJwk","receiverPrivJwk","onGetPublicEmbeddedKey","_onGetPublicEmbeddedKey","_callee0","targetPubBuf","targetPubHex","_context0","loadKeyIntoMemory","_x7","_x8","_x9","_loadKeyIntoMemory","_callee1","keyBytes","keyAddress","cachedKeypair","_context1","subarray","Keypair","fromSecretKey","createSolanaKeypair","_defineProperty","format","keypair","onInjectKeyBundle","_x11","_x12","_x13","_x14","_onInjectKeyBundle","_callee10","_context10","onApplySettings","_x15","_x16","_onApplySettings","_callee11","_context11","onSignTransaction","_x17","_x18","_x19","_onSignTransaction","_callee12","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context12","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x20","_x21","_x22","_onSignMessage","_callee13","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context13","encode","secretKey","onClearEmbeddedPrivateKey","_x23","_x24","_onClearEmbeddedPrivateKey","_callee14","_context14","onStoreEncryptedBundle","_x25","_x26","_x27","_x28","_x29","_x30","_onStoreEncryptedBundle","_callee15","resolvedKeyFormat","_context15","rawP256PrivateKeyToJwk","_x31","_rawP256PrivateKeyToJwk","_callee16","rawPrivateKeyBytes","pkcs8Prefix","pkcs8","cryptoKey","_context16","onInjectDecryptionKeyBundle","_x32","_x33","_x34","_x35","_onInjectDecryptionKeyBundle","_callee17","keyJwk","storedBundles","decryptedCount","addresses","_i3","_addresses","addr","bundleOrgId","_keyBytes","_t0","_context17","onBurnSession","onGetStoredWalletAddresses","onClearStoredBundles","_x36","_createSolanaKeypair","_callee18","_context18","fromSeed","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x37","_getOrCreateKeypair","_callee19","_context19","initEventHandlers","messageEventListener","_messageEventListener","event","_t","_t3","_t4","_t5","_t6","_t7","_t8","_t9","_x43","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","_ref5","preventDefault","_x38","_ref6","_x39","_ref7","_x40","_ref8","_x41","injectWalletBtn","_ref9","_callee5","_context5","_x42","addDOMEventListeners","capture","signal","_ref0","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x44","ownKeys","getOwnPropertySymbols","getOwnPropertyDescriptor","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","_HpkeDecrypt","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","styleSettings","module","exports","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","g","Function","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","crossOrigin","integrity","sriHashes","onScriptComplete","prev","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js b/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js new file mode 100644 index 0000000..e076e52 --- /dev/null +++ b/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js @@ -0,0 +1,3 @@ +/*! For license information please see bundle.801fe7bbee4484b5f44c.js.LICENSE.txt */ +(()=>{var e,t,r,n,a,o={560:(e,t,r)=>{"use strict";var n=r(598),a=r(443),o=r(566);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function c(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function u(e){for(var t=1;t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var l=[][n]?t(t([][n]())):(d(t={},n,function(){return this}),t),p=s.prototype=c.prototype=Object.create(l);function y(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,d(e,a,"GeneratorFunction")),e.prototype=Object.create(p),e}return u.prototype=s,d(p,"constructor",s),d(s,"constructor",u),u.displayName="GeneratorFunction",d(s,a,"GeneratorFunction"),d(p),d(p,a,"Generator"),d(p,n,function(){return this}),d(p,"toString",function(){return"[object Generator]"}),(f=function(){return{w:o,m:y}})()}function d(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}d=function(e,t,r,n){function o(t,r){d(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},d(e,t,r,n)}function l(e){return function(e){if(Array.isArray(e))return v(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||y(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,a,o,i,c=[],u=!0,s=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=o.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,a=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw a}}return c}}(e,t)||y(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(e,t){if(e){if("string"==typeof e)return v(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?v(e,t):void 0}}function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1:window.parent!==window.top}function k(){return(k=g(f().m(function e(t){var r;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=S()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,r.importKey("raw",t,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function P(){return(P=g(f().m(function e(){return f().w(function(e){for(;;)switch(e.n){case 0:if(!O()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,_();case 2:if(null!==e.v){e.n=4;break}return e.n=3,j();case 3:x(e.v);case 4:return e.a(2)}},e)}))).apply(this,arguments)}function j(){return I.apply(this,arguments)}function I(){return(I=g(f().m(function e(){var t,r;return f().w(function(e){for(;;)switch(e.n){case 0:if(t=S()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,t.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return r=e.v,e.n=3,t.exportKey("jwk",r.privateKey);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function _(){var e=R(m);return e?JSON.parse(e):null}function x(e){A(m,JSON.stringify(e),1728e5)}function T(){var e=window.localStorage.getItem(w);if(!e)return null;try{return JSON.parse(e)}catch(e){return window.localStorage.removeItem(w),null}}function A(e,t,r){var n={value:t,expiry:(new Date).getTime()+r};window.localStorage.setItem(e,JSON.stringify(n))}function R(e){var t=window.localStorage.getItem(e);if(!t)return null;var r=JSON.parse(t);return Object.prototype.hasOwnProperty.call(r,"expiry")&&Object.prototype.hasOwnProperty.call(r,"value")?(new Date).getTime()>r.expiry?(window.localStorage.removeItem(e),null):r.value:(window.localStorage.removeItem(e),null)}function D(e){if(!e||"string"!=typeof e)throw new Error("cannot create uint8array from invalid hex string");var t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0||!/^[0-9A-Fa-f]+$/.test(t))throw new Error("cannot create uint8array from invalid hex string");return new Uint8Array(t.match(/../g).map(function(e){return parseInt(e,16)}))}function N(e){return l(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function M(e,t){var r=Array.from(new Uint8Array(e)),n=Array.from(new Uint8Array(t));return new Uint8Array([].concat(r,n))}function U(e){var t=document.getElementById("message-log");if(t){var r=document.createElement("p");r.innerText=e,t.appendChild(r)}}function K(e){return C.apply(this,arguments)}function C(){return(C=g(f().m(function e(t){var r,n,a,o;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=S()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return delete(n=u({},t)).d,n.key_ops=["verify"],e.n=2,r.importKey("jwk",n,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return a=e.v,e.n=3,r.exportKey("raw",a);case 3:return o=e.v,e.a(2,new Uint8Array(o))}},e)}))).apply(this,arguments)}function B(e){for(var t="",r=[0],n=0;n0;)r.push(a%58),a=a/58|0}for(var i=0;i0;){var c=r[i];o=(c=void 0===c?o:58*c+o)>>8,r[i]=c%256,i++}}var u=n.concat(r.reverse());return new Uint8Array(u)}function G(){return(G=g(f().m(function e(t,r,n){var a,o;return f().w(function(e){for(;;)switch(e.n){case 0:o=r,e.n="SOLANA"===o?1:"HEXADECIMAL"===o?5:6;break;case 1:if(n){e.n=2;break}throw new Error("public key must be specified for SOLANA key format");case 2:if(32===t.length){e.n=3;break}throw new Error("invalid private key length. Expected 32 bytes. Got ".concat(t.length,"."));case 3:if(32===n.length){e.n=4;break}throw new Error("invalid public key length. Expected 32 bytes. Got ".concat(n.length,"."));case 4:return(a=new Uint8Array(64)).set(t,0),a.set(n,32),e.a(2,B(a));case 5:return e.a(2,"0x"+N(t));case 6:return console.warn("invalid key format: ".concat(r,". Defaulting to HEXADECIMAL.")),e.a(2,"0x"+N(t));case 7:return e.a(2)}},e)}))).apply(this,arguments)}function F(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",a=r.toStringTag||"@@toStringTag";function o(r,n,a,o){var u=n&&n.prototype instanceof c?n:c,s=Object.create(u.prototype);return H(s,"_invoke",function(r,n,a){var o,c,u,s=0,f=a||[],d=!1,l={p:0,n:0,v:e,a:p,f:p.bind(e,4),d:function(t,r){return o=t,c=0,u=e,l.n=r,i}};function p(r,n){for(c=r,u=n,t=0;!d&&s&&!a&&t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(H(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,H(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,H(d,"constructor",s),H(s,"constructor",u),u.displayName="GeneratorFunction",H(s,a,"GeneratorFunction"),H(d),H(d,a,"Generator"),H(d,n,function(){return this}),H(d,"toString",function(){return"[object Generator]"}),(F=function(){return{w:o,m:l}})()}function H(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}H=function(e,t,r,n){function o(t,r){H(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},H(e,t,r,n)}function Y(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r]*$',color:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",labelColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",backgroundColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",width:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",height:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",maxWidth:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",maxHeight:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",lineHeight:"^(\\d+(\\.\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$",boxShadow:"^(none|(\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)) ?(inset)?)$",textAlign:"^(left|right|center|justify|initial|inherit)$",overflowWrap:"^(normal|break-word|anywhere)$",wordWrap:"^(normal|break-word)$",resize:"^(none|both|horizontal|vertical|block|inline)$"};return Object.entries(e).forEach(function(e){var t=p(e,2),a=t[0],o=t[1],i=a.trim();if(0===i.length)throw new Error("css style property cannot be empty");var c=n[i];if(!c)throw new Error('invalid or unsupported css style property: "'.concat(i,'"'));var u=new RegExp(c),s=o.trim();if(0==s.length)throw new Error('css style for "'.concat(i,'" is empty'));if(!u.test(s))throw new Error('invalid css style value for property "'.concat(i,'"'));r[i]=s}),r},V=O,Q=function(e){return k.apply(this,arguments)},Z=T;function ee(){return(ee=J(F().m(function e(){return F().w(function(e){for(;;)switch(e.n){case 0:if(!V()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,q();case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function te(){return(te=J(F().m(function e(t,r,n){var a,i,c,u,s,f,d,l;return F().w(function(e){for(;;)switch(e.n){case 0:if(a={prod:"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569",preprod:"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212"},i=null,"undefined"!=typeof document&&(c=document.querySelector('meta[name="turnkey-signer-environment"]'))&&c.content&&"__TURNKEY_SIGNER_ENVIRONMENT__"!==c.content&&(i=c.content),i||"undefined"==typeof window||(i=window.__TURNKEY_SIGNER_ENVIRONMENT__),void 0!==(u=a[i])){e.n=1;break}throw new Error("Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined");case 1:if(t===u){e.n=2;break}throw new Error("enclave quorum public keys from client and bundle do not match. Client: ".concat(u,". Bundle: ").concat(t,"."));case 2:return s=new Uint8Array($(u)),e.n=3,Q(s);case 3:if(f=e.v){e.n=4;break}throw new Error("failed to load quorum key");case 4:return d=(0,o.g8)(r),l=$(n),e.n=5,crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},f,d,l);case 5:return e.a(2,e.v)}},e)}))).apply(this,arguments)}var re={initEmbeddedKey:function(){return ee.apply(this,arguments)},generateTargetKey:j,setItemWithExpiry:A,getItemWithExpiry:R,getEmbeddedKey:_,setEmbeddedKey:x,onResetEmbeddedKey:function(){window.localStorage.removeItem(m),window.localStorage.removeItem("TURNKEY_EMBEDDED_KEY_ORIGIN")},p256JWKPrivateToPublic:K,base58Encode:B,base58Decode:L,encodeKey:function(e,t,r){return G.apply(this,arguments)},sendMessageUp:function(e,t,r){var n={type:e,value:t};r&&(n.requestId=r),E?E.postMessage(n):window.parent!==window&&window.parent.postMessage({type:e,value:t},"*"),U("⬆️ Sent message ".concat(e,": ").concat(t))},logMessage:U,uint8arrayFromHexString:$,uint8arrayToHexString:N,setParentFrameMessageChannelPort:function(e){E=e},normalizePadding:function(e,t){var r=t-e.length;if(r>0){var n=new Uint8Array(r).fill(0);return new Uint8Array([].concat(l(n),l(e)))}if(r<0){for(var a=-1*r,o=0,i=0;i3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(se(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,se(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,se(d,"constructor",s),se(s,"constructor",u),u.displayName="GeneratorFunction",se(s,a,"GeneratorFunction"),se(d),se(d,a,"Generator"),se(d,n,function(){return this}),se(d,"toString",function(){return"[object Generator]"}),(ue=function(){return{w:o,m:l}})()}function se(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}se=function(e,t,r,n){function o(t,r){se(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},se(e,t,r,n)}function fe(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,a,o,i,c=[],u=!0,s=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=o.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,a=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw a}}return c}}(e,t)||function(e,t){if(e){if("string"==typeof e)return de(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?de(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function de(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r= v2.0.0 to pass "organizationId" for security purposes.');case 8:if(a.organizationId&&a.organizationId===r){e.n=9;break}throw new Error("organization id does not match expected value. Expected: ".concat(r,". Found: ").concat(a.organizationId,"."));case 9:if(a.encappedPublic){e.n=10;break}throw new Error('missing "encappedPublic" in bundle signed data');case 10:if(a.ciphertext){e.n=11;break}throw new Error('missing "ciphertext" in bundle signed data');case 11:return e.a(2,a)}},e)}))).apply(this,arguments)}function we(e,t,r){return Ee.apply(this,arguments)}function Ee(){return Ee=pe(ue().m(function e(t,r,n){var a,o,i,c;return ue().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,me(t,r);case 1:return a=e.v,o=re.uint8arrayFromHexString(a.encappedPublic),i=re.uint8arrayFromHexString(a.ciphertext),e.n=2,re.getEmbeddedKey();case 2:return c=e.v,e.n=3,n({ciphertextBuf:i,encappedKeyBuf:o,receiverPrivJwk:c});case 3:return e.a(2,e.v)}},e)})),Ee.apply(this,arguments)}function Se(e){return Oe.apply(this,arguments)}function Oe(){return(Oe=pe(ue().m(function e(t){var r,n,a;return ue().w(function(e){for(;;)switch(e.n){case 0:if(r=re.getEmbeddedKey()){e.n=1;break}return re.sendMessageUp("EMBEDDED_PUBLIC_KEY","",t),e.a(2);case 1:return e.n=2,re.p256JWKPrivateToPublic(r);case 2:n=e.v,a=re.uint8arrayToHexString(n),re.sendMessageUp("EMBEDDED_PUBLIC_KEY",a,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function ke(e,t,r,n){return Pe.apply(this,arguments)}function Pe(){return(Pe=pe(ue().m(function e(t,r,n,a){var o,i,c,u,s,f;return ue().w(function(e){for(;;)switch(e.n){case 0:if(i=new Uint8Array(r),"SOLANA"!==n){e.n=2;break}return c=re.uint8arrayToHexString(i.subarray(0,32)),u=re.getEd25519PublicKey(c),e.n=1,re.encodeKey(i,n,u);case 1:o=e.v,e.n=4;break;case 2:return e.n=3,re.encodeKey(i,n);case 3:o=e.v;case 4:if(s=t||"default","SOLANA"!==n){e.n=5;break}f=ne.AX.fromSecretKey(re.base58Decode(o)),e.n=7;break;case 5:if("HEXADECIMAL"!==n){e.n=7;break}return e.n=6,ze(Array.from(re.uint8arrayFromHexString(o)));case 6:f=e.v;case 7:ye=ie(ie({},ye),{},ce({},s,{organizationId:a,privateKey:o,format:n,expiry:(new Date).getTime()+864e5,keypair:f}));case 8:return e.a(2)}},e)}))).apply(this,arguments)}function je(e,t,r,n,a,o){return Ie.apply(this,arguments)}function Ie(){return Ie=pe(ue().m(function e(t,r,n,a,o,i){var c;return ue().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,we(n,r,i);case 1:return c=e.v,e.n=2,ke(o,c,a,r);case 2:re.sendMessageUp("BUNDLE_INJECTED",!0,t);case 3:return e.a(2)}},e)})),Ie.apply(this,arguments)}function _e(e,t){return xe.apply(this,arguments)}function xe(){return(xe=pe(ue().m(function e(t,r){var n;return ue().w(function(e){for(;;)switch(e.n){case 0:n=re.applySettings(t),re.setSettings(n),re.sendMessageUp("SETTINGS_APPLIED",!0,r);case 1:return e.a(2)}},e)}))).apply(this,arguments)}function Te(e,t,r){return Ae.apply(this,arguments)}function Ae(){return(Ae=pe(ue().m(function e(t,r,n){var a,o,i,c,u,s,f,d,l;return ue().w(function(e){for(;;)switch(e.n){case 0:if($e(o=ye[a=n||"default"],a)){e.n=1;break}return e.a(2);case 1:return e.n=2,We(o);case 2:if(i=e.v,c=JSON.parse(r),u=c.transaction,"SOLANA"!==c.type){e.n=3;break}f=re.uint8arrayFromHexString(u),(d=ne.Kt.deserialize(f)).sign([i]),s=d.serialize(),e.n=4;break;case 3:throw new Error("unsupported transaction type");case 4:l=re.uint8arrayToHexString(s),re.sendMessageUp("TRANSACTION_SIGNED",l,t);case 5:return e.a(2)}},e)}))).apply(this,arguments)}function Re(e,t,r){return De.apply(this,arguments)}function De(){return De=pe(ue().m(function e(t,r,o){var i,c,u,s,f,d,l,p,y,v;return ue().w(function(e){for(;;)switch(e.n){case 0:if($e(c=ye[i=o||"default"],i)){e.n=1;break}return e.a(2);case 1:return u=JSON.parse(r),s=u.message,f=u.type,d=be.encode(s),e.n=2,We(c);case 2:if(p=e.v,"SOLANA"!==f){e.n=3;break}n.jn.sha512Sync=function(){var e;return a.Zf((e=n.jn).concatBytes.apply(e,arguments))},y=p.secretKey.slice(0,32),v=n._S(d,y),l=re.uint8arrayToHexString(v),e.n=4;break;case 3:return re.sendMessageUp("ERROR","unsupported message type",t),e.a(2);case 4:re.sendMessageUp("MESSAGE_SIGNED",l,t);case 5:return e.a(2)}},e)})),De.apply(this,arguments)}function Ne(e,t){return Me.apply(this,arguments)}function Me(){return(Me=pe(ue().m(function e(t,r){return ue().w(function(e){for(;;)switch(e.n){case 0:if(r){e.n=1;break}return ye={},re.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t),e.a(2);case 1:if(ye[r]){e.n=2;break}return re.sendMessageUp("ERROR",new Error("key not found for address ".concat(r,". Note that address is case sensitive.")).toString(),t),e.a(2);case 2:delete ye[r],re.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function Ue(e,t,r,n,a,o){return Ke.apply(this,arguments)}function Ke(){return Ke=pe(ue().m(function e(t,r,n,a,o,i){var c,u,s,f,d;return ue().w(function(e){for(;;)switch(e.n){case 0:if(o){e.n=1;break}throw new Error("address is required for STORE_ENCRYPTED_BUNDLE");case 1:return e.n=2,me(n,r);case 2:if(c=e.v,u=a||"HEXADECIMAL",re.setEncryptedBundle(o,{encappedPublic:c.encappedPublic,ciphertext:c.ciphertext,organizationId:r,keyFormat:u}),!ve||!i){e.n=4;break}return s=re.uint8arrayFromHexString(c.encappedPublic),f=re.uint8arrayFromHexString(c.ciphertext),e.n=3,i({ciphertextBuf:f,encappedKeyBuf:s,receiverPrivJwk:ve});case 3:return d=e.v,e.n=4,ke(o,d,u,r);case 4:re.sendMessageUp("ENCRYPTED_BUNDLE_STORED",!0,t);case 5:return e.a(2)}},e)})),Ke.apply(this,arguments)}function Ce(e){return Be.apply(this,arguments)}function Be(){return(Be=pe(ue().m(function e(t){var r,n,a;return ue().w(function(e){for(;;)switch(e.n){case 0:if(32===t.length){e.n=1;break}throw new Error("invalid decryption key length: expected 32 bytes, got ".concat(t.length));case 1:return r=new Uint8Array([48,65,2,1,0,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,4,39,48,37,2,1,1,4,32]),(n=new Uint8Array(r.length+32)).set(r),n.set(t,r.length),e.n=2,crypto.subtle.importKey("pkcs8",n,{name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return a=e.v,e.n=3,crypto.subtle.exportKey("jwk",a);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function Le(e,t,r,n){return Ge.apply(this,arguments)}function Ge(){return Ge=pe(ue().m(function e(t,r,n,a){var o,i,c,u,s,f,d,l,p,y,v,b,g,m;return ue().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.n=1,we(n,r,a);case 1:return o=e.v,e.n=2,Ce(new Uint8Array(o));case 2:if(i=e.v,ve=i,c=re.getEncryptedBundles(),u=0,!c){e.n=10;break}s=Object.keys(c),f=0,d=s;case 3:if(!(f=e.expiry)throw function(){for(var e=(new Date).getTime(),t=[],r=0,n=Object.entries(ye);r=i.expiry&&t.push(o)}for(var c=0,u=t;c3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(tt(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,tt(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,tt(d,"constructor",s),tt(s,"constructor",u),u.displayName="GeneratorFunction",tt(s,a,"GeneratorFunction"),tt(d),tt(d,a,"Generator"),tt(d,n,function(){return this}),tt(d,"toString",function(){return"[object Generator]"}),(et=function(){return{w:o,m:l}})()}function tt(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}tt=function(e,t,r,n){function o(t,r){tt(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},tt(e,t,r,n)}function rt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function nt(e){for(var t=1;t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(ft(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,ft(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,ft(d,"constructor",s),ft(s,"constructor",u),u.displayName="GeneratorFunction",ft(s,a,"GeneratorFunction"),ft(d),ft(d,a,"Generator"),ft(d,n,function(){return this}),ft(d,"toString",function(){return"[object Generator]"}),(st=function(){return{w:o,m:l}})()}function ft(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}ft=function(e,t,r,n){function o(t,r){ft(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},ft(e,t,r,n)}function dt(e,t,r,n,a,o,i){try{var c=e[o](i),u=c.value}catch(e){return void r(e)}c.done?t(u):Promise.resolve(u).then(n,a)}function lt(e){return function(){var t=this,r=arguments;return new Promise(function(n,a){var o=e.apply(t,r);function i(e){dt(o,n,a,i,c,"next",e)}function c(e){dt(o,n,a,i,c,"throw",e)}i(void 0)})}}window.TKHQ=re,document.addEventListener("DOMContentLoaded",lt(st().m(function e(){var t,r,n,a;return st().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,re.initEmbeddedKey();case 1:return e.n=2,re.getEmbeddedKey();case 2:return t=e.v,e.n=3,re.p256JWKPrivateToPublic(t);case 3:r=e.v,n=re.uint8arrayToHexString(r),document.getElementById("embedded-key").value=n,Ve(ct),(a=re.getSettings())&&re.applySettings(a),re.sendMessageUp("PUBLIC_KEY_READY",n);case 4:return e.a(2)}},e)})))},790:()=>{},846:e=>{"use strict";e.exports=crypto}},i={};function c(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={id:e,loaded:!1,exports:{}};return o[e].call(r.exports,r,r.exports,c),r.loaded=!0,r.exports}c.m=o,e=[],c.O=(t,r,n,a)=>{if(!r){var o=1/0;for(f=0;f=a)&&Object.keys(c.O).every(e=>c.O[e](r[u]))?r.splice(u--,1):(i=!1,a0&&e[f-1][2]>a;f--)e[f]=e[f-1];e[f]=[r,n,a]},c.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return c.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,c.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var a=Object.create(null);c.r(a);var o={};t=t||[null,r({}),r([]),r(r)];for(var i=2&n&&e;("object"==typeof i||"function"==typeof i)&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach(t=>o[t]=()=>e[t]);return o.default=()=>e,c.d(a,o),a},c.d=(e,t)=>{for(var r in t)c.o(t,r)&&!c.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},c.f={},c.e=e=>Promise.all(Object.keys(c.f).reduce((t,r)=>(c.f[r](e,t),t),[])),c.u=e=>"bundle."+{291:"3eaea85f4001b9cc63c3",825:"aaba32bf7338e3d0f1cc"}[e]+".js",c.miniCssF=e=>{},c.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),c.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},a="export-and-sign:",c.l=(e,t,r,o)=>{if(n[e])n[e].push(t);else{var i,u;if(void 0!==r)for(var s=document.getElementsByTagName("script"),f=0;f{i.onerror=i.onload=null,clearTimeout(p);var a=n[e];if(delete n[e],i.parentNode&&i.parentNode.removeChild(i),a&&a.forEach(e=>e(r)),t)return t(r)},p=setTimeout(l.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=l.bind(null,i.onerror),i.onload=l.bind(null,i.onload),u&&document.head.appendChild(i)}},c.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),c.p="/",c.sriHashes={291:"sha384-G5pDFEAG9UZITbluyje/R/rWohZTUJf+Vu3ZIh0rsnLFLTw3SP/ca/XVNZVtv48f",825:"sha384-R9OIdd42i5GcdtZiHJuQgIUVvqyqJ0s7eaBnJHAfGllpi4YwbF7NSkjIRwOPUtsP"},(()=>{var e={792:0};c.f.j=(t,r)=>{var n=c.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[2]);else{var a=new Promise((r,a)=>n=e[t]=[r,a]);r.push(n[2]=a);var o=c.p+c.u(t),i=new Error;c.l(o,r=>{if(c.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var a=r&&("load"===r.type?"missing":r.type),o=r&&r.target&&r.target.src;i.message="Loading chunk "+t+" failed.\n("+a+": "+o+")",i.name="ChunkLoadError",i.type=a,i.request=o,n[1](i)}},"chunk-"+t,t)}},c.O.j=t=>0===e[t];var t=(t,r)=>{var n,a,[o,i,u]=r,s=0;if(o.some(t=>0!==e[t])){for(n in i)c.o(i,n)&&(c.m[n]=i[n]);if(u)var f=u(c)}for(t&&t(r);sc(560));u=c.O(u)})(); +//# sourceMappingURL=bundle.801fe7bbee4484b5f44c.js.map \ No newline at end of file diff --git a/export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js.LICENSE.txt b/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.LICENSE.txt similarity index 100% rename from export-and-sign/dist/bundle.3f29bf7d8e30fb1dd823.js.LICENSE.txt rename to export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.LICENSE.txt diff --git a/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.map b/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.map new file mode 100644 index 0000000..7c14c13 --- /dev/null +++ b/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bundle.801fe7bbee4484b5f44c.js","mappings":";UAAIA,ECCAC,EADAC,ECAAC,EACAC,E,svCCAJ,IAAAC,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IAAAE,EAAAC,EAAAG,EAAAI,EAAA,EAAAC,EAAAX,GAAA,GAAAY,GAAA,EAAAC,EAAA,CAAAF,EAAA,EAAAb,EAAA,EAAAgB,EAAApB,EAAAqB,EAAAC,EAAAN,EAAAM,EAAAC,KAAAvB,EAAA,GAAAsB,EAAA,SAAArB,EAAAC,GAAA,OAAAM,EAAAP,EAAAQ,EAAA,EAAAG,EAAAZ,EAAAmB,EAAAf,EAAAF,EAAAmB,CAAA,YAAAC,EAAApB,EAAAE,GAAA,IAAAK,EAAAP,EAAAU,EAAAR,EAAAH,EAAA,GAAAiB,GAAAF,IAAAV,GAAAL,EAAAgB,EAAAO,OAAAvB,IAAA,KAAAK,EAAAE,EAAAS,EAAAhB,GAAAqB,EAAAH,EAAAF,EAAAQ,EAAAjB,EAAA,GAAAN,EAAA,GAAAI,EAAAmB,IAAArB,KAAAQ,EAAAJ,GAAAC,EAAAD,EAAA,OAAAC,EAAA,MAAAD,EAAA,GAAAA,EAAA,GAAAR,GAAAQ,EAAA,IAAAc,KAAAhB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W0R,EAASA,EAE/D,GAYH1B,EAAoBM,EAAElY,EAAKsZ,GAA0C,IAA7BoC,EAAgBpC,GAGxD,IAAI2C,EAAuB,CAACC,EAA4B1f,KACvD,IAGIqb,EAAUyB,GAHTnB,EAAUgE,EAAaC,GAAW5f,EAGhB7G,EAAI,EAC3B,GAAGwiB,EAASkE,KAAMtE,GAAgC,IAAxB2D,EAAgB3D,IAAa,CACtD,IAAIF,KAAYsE,EACZvE,EAAoBniB,EAAE0mB,EAAatE,KACrCD,EAAoBngB,EAAEogB,GAAYsE,EAAYtE,IAGhD,GAAGuE,EAAS,IAAIvc,EAASuc,EAAQxE,EAClC,CAEA,IADGsE,GAA4BA,EAA2B1f,GACrD7G,EAAIwiB,EAASxhB,OAAQhB,IACzB2jB,EAAUnB,EAASxiB,GAChBiiB,EAAoBniB,EAAEimB,EAAiBpC,IAAYoC,EAAgBpC,IACrEoC,EAAgBpC,GAAS,KAE1BoC,EAAgBpC,GAAW,EAE5B,OAAO1B,EAAoBM,EAAErY,IAG1Byc,EAAqBC,KAAkC,4BAAIA,KAAkC,6BAAK,GACtGD,EAAmBpZ,QAAQ+Y,EAAqBvlB,KAAK,KAAM,IAC3D4lB,EAAmB3jB,KAAOsjB,EAAqBvlB,KAAK,KAAM4lB,EAAmB3jB,KAAKjC,KAAK4lB,G,KClFvF,IAAIE,EAAsB5E,EAAoBM,OAAE3d,EAAW,CAAC,IAAK,IAAOqd,EAAoB,MAC5F4E,EAAsB5E,EAAoBM,EAAEsE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/../shared/turnkey-core.js","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/../shared/crypto-utils.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/external var \"crypto\"","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/global","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/compat","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t\tif (script.src.indexOf(window.location.origin + '/') !== 0) {\n\t\t\tscript.crossOrigin = \"anonymous\";\n\t\t}\n\t\tscript.integrity = __webpack_require__.sriHashes[chunkId];\n\t\tscript.crossOrigin = \"anonymous\";\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n if (!data) {\n return null;\n }\n try {\n return JSON.parse(data);\n } catch (e) {\n // If the stored data is corrupted or not valid JSON, remove it to self-heal.\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n return null;\n }\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * Only removes the bundle if it belongs to the specified organization.\n * @param {string} address - The wallet address to remove\n * @param {string} organizationId - Only remove if the bundle belongs to this org\n */\nfunction removeEncryptedBundle(address, organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles || !bundles[address]) return;\n\n // Only remove if the bundle belongs to the specified organization\n if (bundles[address].organizationId !== organizationId) return;\n\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n}\n\n/**\n * Removes all encrypted bundles belonging to the specified organization.\n * Bundles from other organizations are preserved.\n * @param {string} organizationId - Remove bundles belonging to this org\n */\nfunction clearAllEncryptedBundles(organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles) return;\n\n // Keep only bundles that do NOT belong to this organization\n const remaining = Object.fromEntries(\n Object.entries(bundles).filter(\n ([, bundle]) => bundle.organizationId !== organizationId\n )\n );\n\n if (Object.keys(remaining).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(remaining)\n );\n }\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\nimport { fromDerSignature } from \"@turnkey/crypto\";\nimport * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n initEmbeddedKey: sharedInitEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n additionalAssociatedData,\n getSettings,\n setSettings,\n parsePrivateKey,\n validateStyles,\n isDoublyIframed,\n loadQuorumKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n} = SharedTKHQ;\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n return await sharedInitEmbeddedKey();\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Read environment from meta tag (templated at deploy time), fall back to window variable (for testing)\n let environment = null;\n if (typeof document !== \"undefined\") {\n const meta = document.querySelector(\n 'meta[name=\"turnkey-signer-environment\"]'\n );\n if (\n meta &&\n meta.content &&\n meta.content !== \"__TURNKEY_SIGNER_ENVIRONMENT__\"\n ) {\n environment = meta.content;\n }\n }\n if (!environment && typeof window !== \"undefined\") {\n environment = window.__TURNKEY_SIGNER_ENVIRONMENT__;\n }\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\n// Decryption key -- held in memory only, never persisted to localStorage.\n// This is a P-256 private key in JWK format used to decrypt stored bundles.\nlet decryptionKey = null;\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Verifies the enclave signature on a v1.0.0 bundle and returns the parsed signed data.\n * @param {string} bundle - JSON-stringified bundle\n * @param {string} organizationId - Expected organization ID\n * @returns {Promise} - The parsed signed data {organizationId, encappedPublic, ciphertext}\n */\nasync function verifyAndParseBundleData(bundle, organizationId) {\n const bundleObj = JSON.parse(bundle);\n\n if (bundleObj.version !== \"v1.0.0\") {\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n const verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(\n `failed to verify enclave signature: ${bundleObj.dataSignature}`\n );\n }\n\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n\n return signedData;\n}\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n // Decrypt the ciphertext\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: embeddedKeyJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Encodes raw key bytes and loads them into the in-memory key store.\n * @param {string} address - Wallet address (case-sensitive)\n * @param {ArrayBuffer} keyBytes - Raw decrypted private key bytes\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} organizationId - Organization ID\n */\nasync function loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId) {\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair,\n },\n };\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Load decrypted key into memory\n await loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId);\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Set up sha512 for nobleEd25519 (required for signing)\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n\n // Extract the 32-byte private key from the 64-byte secretKey\n // Solana keypair.secretKey format: [32-byte private key][32-byte public key]\n const privateKey = keypair.secretKey.slice(0, 32);\n // Sign the message using nobleEd25519\n const signature = nobleEd25519.sign(messageBytes, privateKey);\n\n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n/**\n * Handler for STORE_ENCRYPTED_BUNDLE events.\n * Verifies the enclave signature on an encrypted bundle and stores\n * the encrypted payload in localStorage for later decryption.\n * If the decryption key is already in memory, also decrypts and loads\n * the key into memory immediately.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle JSON\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} address - Wallet address\n * @param {Function} HpkeDecrypt\n */\nasync function onStoreEncryptedBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n if (!address) {\n throw new Error(\"address is required for STORE_ENCRYPTED_BUNDLE\");\n }\n\n // Verify enclave signature and parse the signed data\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const resolvedKeyFormat = keyFormat || \"HEXADECIMAL\";\n\n // Store the encrypted fields in localStorage (just what's needed for decryption)\n TKHQ.setEncryptedBundle(address, {\n encappedPublic: signedData.encappedPublic,\n ciphertext: signedData.ciphertext,\n organizationId: organizationId,\n keyFormat: resolvedKeyFormat,\n });\n\n // If the decryption key is already in memory, decrypt and load immediately\n if (decryptionKey && HpkeDecrypt) {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n await loadKeyIntoMemory(\n address,\n keyBytes,\n resolvedKeyFormat,\n organizationId\n );\n }\n\n TKHQ.sendMessageUp(\"ENCRYPTED_BUNDLE_STORED\", true, requestId);\n}\n\n/**\n * Converts raw P-256 private key bytes (32-byte scalar) to a JWK.\n * Constructs a PKCS8 wrapper around the raw bytes, imports via WebCrypto\n * (which derives the public key), then exports as JWK.\n * @param {Uint8Array} rawPrivateKeyBytes - 32-byte P-256 private key scalar\n * @returns {Promise} - Full P-256 ECDH private key JWK\n */\nasync function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) {\n if (rawPrivateKeyBytes.length !== 32) {\n throw new Error(\n `invalid decryption key length: expected 32 bytes, got ${rawPrivateKeyBytes.length}`\n );\n }\n\n // Fixed PKCS#8 DER prefix for a P-256 private key (36 bytes).\n // This wraps a raw 32-byte scalar into the PrivateKeyInfo structure\n // that WebCrypto's importKey(\"pkcs8\", ...) expects.\n //\n // Structure (per RFC 5958 §2 / RFC 5208 §5):\n // SEQUENCE {\n // INTEGER 0 -- version (v1)\n // SEQUENCE { -- AlgorithmIdentifier (RFC 5480 §2.1.1)\n // OID 1.2.840.10045.2.1 -- id-ecPublicKey\n // OID 1.2.840.10045.3.1.7 -- secp256r1 (P-256)\n // }\n // OCTET STRING { -- privateKey (SEC 1 §C.4 / RFC 5915 §3)\n // SEQUENCE {\n // INTEGER 1 -- version\n // OCTET STRING (32 bytes) -- raw private key scalar\n // }\n // }\n // }\n //\n // References:\n // - RFC 5958 / RFC 5208: PKCS#8 PrivateKeyInfo\n // - RFC 5480 §2.1.1: ECC AlgorithmIdentifier (OIDs)\n // - RFC 5915 / SEC 1 v2 §C.4: ECPrivateKey encoding\n const pkcs8Prefix = new Uint8Array([\n 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48,\n 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03,\n 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20,\n ]);\n\n const pkcs8 = new Uint8Array(pkcs8Prefix.length + 32);\n pkcs8.set(pkcs8Prefix);\n pkcs8.set(rawPrivateKeyBytes, pkcs8Prefix.length);\n\n const cryptoKey = await crypto.subtle.importKey(\n \"pkcs8\",\n pkcs8,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"]\n );\n\n return await crypto.subtle.exportKey(\"jwk\", cryptoKey);\n}\n\n/**\n * Handler for INJECT_DECRYPTION_KEY_BUNDLE events.\n * Decrypts the P-256 private key using the iframe's embedded key,\n * then iterates all stored encrypted bundles, HPKE-decrypts each one\n * with the key, and loads them into inMemoryKeys.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle containing the private key\n * @param {Function} HpkeDecrypt\n */\nasync function onInjectDecryptionKeyBundle(\n requestId,\n organizationId,\n bundle,\n HpkeDecrypt\n) {\n // Decrypt the private key using the iframe's embedded key.\n // The decrypted payload is a raw 32-byte P-256 private key scalar.\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto)\n const keyJwk = await rawP256PrivateKeyToJwk(new Uint8Array(keyBytes));\n\n // Store in module-level variable (memory only)\n decryptionKey = keyJwk;\n\n // Iterate all stored encrypted bundles and decrypt each one\n const storedBundles = TKHQ.getEncryptedBundles();\n let decryptedCount = 0;\n\n if (storedBundles) {\n const addresses = Object.keys(storedBundles);\n\n for (const addr of addresses) {\n const bundleData = storedBundles[addr];\n\n try {\n const bundleOrgId = bundleData.organizationId;\n\n if (organizationId !== bundleOrgId) continue; // skip bundles that don't match the organization ID of the decryption key\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n bundleData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(\n bundleData.ciphertext\n );\n\n // HPKE-decrypt using the key\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n // Load the decrypted key into memory\n await loadKeyIntoMemory(\n addr,\n keyBytes,\n bundleData.keyFormat,\n bundleData.organizationId\n );\n\n decryptedCount++;\n } catch (e) {\n TKHQ.logMessage(\n `Failed to decrypt bundle for address ${addr}: ${e.toString()}`\n );\n }\n }\n }\n\n TKHQ.sendMessageUp(\"DECRYPTION_KEY_INJECTED\", decryptedCount, requestId);\n}\n\n/**\n * Handler for BURN_SESSION events.\n * Clears the decryption key and all in-memory wallet keys.\n * Encrypted bundles in localStorage are preserved for the next session.\n * @param {string} requestId\n */\nfunction onBurnSession(requestId) {\n decryptionKey = null;\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"SESSION_BURNED\", true, requestId);\n}\n\n/**\n * Handler for GET_STORED_WALLET_ADDRESSES events.\n * Returns a JSON array of all wallet addresses that have encrypted bundles in localStorage.\n * @param {string} requestId\n * @param {string} organizationId - Organization ID to filter addresses by (only return addresses with bundles matching the organization ID)\n */\nfunction onGetStoredWalletAddresses(requestId, organizationId) {\n const bundles = TKHQ.getEncryptedBundles();\n const addresses = bundles\n ? Object.entries(bundles)\n .filter(([, bundle]) => bundle.organizationId === organizationId)\n .map(([address]) => address)\n : [];\n TKHQ.sendMessageUp(\n \"STORED_WALLET_ADDRESSES\",\n JSON.stringify(addresses),\n requestId\n );\n}\n\n/**\n * Handler for CLEAR_STORED_BUNDLES events.\n * Removes encrypted bundles from localStorage AND the corresponding\n * in-memory keys. If address is provided, removes only that address.\n * If no address, removes ALL encrypted bundles and ALL in-memory keys.\n * @param {string} requestId\n * @param {string} organizationId - Organization ID to filter addresses by (only remove bundles matching the organization ID)\n * @param {string|undefined} address - Optional wallet address\n */\nfunction onClearStoredBundles(requestId, address, organizationId) {\n if (address) {\n TKHQ.removeEncryptedBundle(address, organizationId);\n delete inMemoryKeys[address];\n } else {\n TKHQ.clearAllEncryptedBundles(organizationId);\n inMemoryKeys = {};\n }\n TKHQ.sendMessageUp(\"STORED_BUNDLES_CLEARED\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error(\n `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`\n ).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n undefined, // keyFormat - default to HEXADECIMAL\n undefined, // address - default to \"default\"\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"STORE_ENCRYPTED_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n await onStoreEncryptedBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_DECRYPTION_KEY_BUNDLE\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onInjectDecryptionKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"BURN_SESSION\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onBurnSession(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_STORED_WALLET_ADDRESSES\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onGetStoredWalletAddresses(\n event.data[\"requestId\"],\n event.data[\"organizationId\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_STORED_BUNDLES\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n onClearStoredBundles(\n event.data[\"requestId\"],\n event.data[\"address\"],\n event.data[\"organizationId\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n onStoreEncryptedBundle,\n onInjectDecryptionKeyBundle,\n onBurnSession,\n onGetStoredWalletAddresses,\n onClearStoredBundles,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"@shared/crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n","module.exports = crypto;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","\n__webpack_require__.sriHashes = {\"291\":\"*-*-*-CHUNK-SRI-HASH-r3NPGwA4ft5fHgGXhVIptCiDVf06qPa+sxzG6L+8GwPuhn89e/\",\"825\":\"*-*-*-CHUNK-SRI-HASH-mfog3UJdGPOmSk4QZbKxsxHPFZtt298WnZNc1aQ1MCgc6YirFj\"};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(560)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","_slicedToArray","_arrayWithHoles","next","push","_iterableToArrayLimit","_nonIterableRest","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","TURNKEY_ENCRYPTED_BUNDLES","parentFrameMessageChannelPort","getSubtleCrypto","globalThis","crypto","subtle","window","global","isDoublyIframed","undefined","location","ancestorOrigins","parent","top","_loadQuorumKey","_callee","quorumPublic","_context","Error","importKey","namedCurve","_initEmbeddedKey","_callee3","_context3","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee4","p256key","_context4","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","getEncryptedBundles","data","localStorage","getItem","removeItem","key","ttl","item","expiry","Date","getTime","setItem","itemStr","hasOwnProperty","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","concat","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","p256JWKPrivateToPublic","_x6","_p256JWKPrivateToPublic","_callee6","jwkPrivate","jwkPrivateCopy","publicKey","_context6","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","k","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee9","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_t2","_context9","set","console","warn","sharedInitEmbeddedKey","SharedTKHQ","validateStyles","styles","element","validStyles","cssValidationRegex","padding","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref3","_ref4","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","loadQuorumKey","_x","_verifyEnclaveSignature","_callee2","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","meta","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context2","prod","preprod","querySelector","__TURNKEY_SIGNER_ENVIRONMENT__","fromDerSignature","verify","hash","TKHQ","initEmbeddedKey","onResetEmbeddedKey","encodeKey","_x0","_x1","_x10","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","normalizePadding","byteArray","targetLength","paddingLength","fill","expectedZeroCount","zeroCount","verifyEnclaveSignature","_x2","_x3","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","_ref","_ref2","style","getSettings","setSettings","parsePrivateKey","error","setEncryptedBundle","address","bundleData","bundles","removeEncryptedBundle","organizationId","keys","clearAllEncryptedBundles","remaining","fromEntries","filter","inMemoryKeys","decryptionKey","textEncoder","TextEncoder","textDecoder","TextDecoder","verifyAndParseBundleData","_verifyAndParseBundleData","_callee8","bundle","bundleObj","_context8","version","dataSignature","decode","encappedPublic","ciphertext","decryptBundle","_x4","_x5","_decryptBundle","HpkeDecrypt","encappedKeyBuf","ciphertextBuf","embeddedKeyJwk","receiverPrivJwk","onGetPublicEmbeddedKey","_onGetPublicEmbeddedKey","_callee0","targetPubBuf","targetPubHex","_context0","loadKeyIntoMemory","_x7","_x8","_x9","_loadKeyIntoMemory","_callee1","keyBytes","keyAddress","cachedKeypair","_context1","subarray","Keypair","fromSecretKey","createSolanaKeypair","_defineProperty","format","keypair","onInjectKeyBundle","_x11","_x12","_x13","_x14","_onInjectKeyBundle","_callee10","_context10","onApplySettings","_x15","_x16","_onApplySettings","_callee11","_context11","onSignTransaction","_x17","_x18","_x19","_onSignTransaction","_callee12","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context12","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x20","_x21","_x22","_onSignMessage","_callee13","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context13","encode","secretKey","onClearEmbeddedPrivateKey","_x23","_x24","_onClearEmbeddedPrivateKey","_callee14","_context14","onStoreEncryptedBundle","_x25","_x26","_x27","_x28","_x29","_x30","_onStoreEncryptedBundle","_callee15","resolvedKeyFormat","_context15","rawP256PrivateKeyToJwk","_x31","_rawP256PrivateKeyToJwk","_callee16","rawPrivateKeyBytes","pkcs8Prefix","pkcs8","cryptoKey","_context16","onInjectDecryptionKeyBundle","_x32","_x33","_x34","_x35","_onInjectDecryptionKeyBundle","_callee17","keyJwk","storedBundles","decryptedCount","addresses","_i3","_addresses","addr","bundleOrgId","_keyBytes","_t0","_context17","onBurnSession","onGetStoredWalletAddresses","onClearStoredBundles","_x36","_createSolanaKeypair","_callee18","_context18","fromSeed","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x37","_getOrCreateKeypair","_callee19","_context19","initEventHandlers","messageEventListener","_messageEventListener","event","_t","_t3","_t4","_t5","_t6","_t7","_t8","_t9","_x43","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","_ref5","preventDefault","_x38","_ref6","_x39","_ref7","_x40","_ref8","_x41","injectWalletBtn","_ref9","_callee5","_context5","_x42","addDOMEventListeners","capture","signal","_ref0","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x44","ownKeys","getOwnPropertySymbols","getOwnPropertyDescriptor","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","_HpkeDecrypt","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","styleSettings","module","exports","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","g","Function","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","crossOrigin","integrity","sriHashes","onScriptComplete","prev","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/dist/index.html b/export-and-sign/dist/index.html index 360cf0d..98098e1 100644 --- a/export-and-sign/dist/index.html +++ b/export-and-sign/dist/index.html @@ -1 +1 @@ -Turnkey Export

Export Key Material

This public key will be sent along with a private key ID or wallet ID inside of a new EXPORT_PRIVATE_KEY or EXPORT_WALLET activity




Inject Key Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).





Inject Wallet Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).




Sign Transaction

Input a serialized transaction to sign.



Sign Message

Input a serialized message to sign.



Message log

Below we display a log of the messages sent / received. The forms above send messages, and the code communicates results by sending events via the postMessage API.

\ No newline at end of file +Turnkey Export

Export Key Material

This public key will be sent along with a private key ID or wallet ID inside of a new EXPORT_PRIVATE_KEY or EXPORT_WALLET activity




Inject Key Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).





Inject Wallet Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).




Sign Transaction

Input a serialized transaction to sign.



Sign Message

Input a serialized message to sign.



Message log

Below we display a log of the messages sent / received. The forms above send messages, and the code communicates results by sending events via the postMessage API.

\ No newline at end of file diff --git a/export-and-sign/src/event-handlers.js b/export-and-sign/src/event-handlers.js index d5231df..45ee5f6 100644 --- a/export-and-sign/src/event-handlers.js +++ b/export-and-sign/src/event-handlers.js @@ -47,7 +47,9 @@ async function verifyAndParseBundleData(bundle, organizationId) { bundleObj.data ); if (!verified) { - throw new Error(`failed to verify enclave signature: ${bundle}`); + throw new Error( + `failed to verify enclave signature: ${bundleObj.dataSignature}` + ); } const signedData = JSON.parse( @@ -413,12 +415,29 @@ async function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) { ); } - // PKCS8 DER prefix for a P-256 private key (without optional public key field) - // SEQUENCE { - // INTEGER 0 (version) - // SEQUENCE { OID ecPublicKey, OID P-256 } - // OCTET STRING { SEQUENCE { INTEGER 1, OCTET STRING(32) } } - // } + // Fixed PKCS#8 DER prefix for a P-256 private key (36 bytes). + // This wraps a raw 32-byte scalar into the PrivateKeyInfo structure + // that WebCrypto's importKey("pkcs8", ...) expects. + // + // Structure (per RFC 5958 §2 / RFC 5208 §5): + // SEQUENCE { + // INTEGER 0 -- version (v1) + // SEQUENCE { -- AlgorithmIdentifier (RFC 5480 §2.1.1) + // OID 1.2.840.10045.2.1 -- id-ecPublicKey + // OID 1.2.840.10045.3.1.7 -- secp256r1 (P-256) + // } + // OCTET STRING { -- privateKey (SEC 1 §C.4 / RFC 5915 §3) + // SEQUENCE { + // INTEGER 1 -- version + // OCTET STRING (32 bytes) -- raw private key scalar + // } + // } + // } + // + // References: + // - RFC 5958 / RFC 5208: PKCS#8 PrivateKeyInfo + // - RFC 5480 §2.1.1: ECC AlgorithmIdentifier (OIDs) + // - RFC 5915 / SEC 1 v2 §C.4: ECPrivateKey encoding const pkcs8Prefix = new Uint8Array([ 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, From 29996bcca4762d6afe079d72f70b107b5cc2eaf8 Mon Sep 17 00:00:00 2001 From: Ethan Konkolowicz Date: Thu, 12 Feb 2026 13:29:58 -0500 Subject: [PATCH 6/7] resolved comments --- export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.map | 2 +- export-and-sign/src/event-handlers.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.map b/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.map index 7c14c13..b027639 100644 --- a/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.map +++ b/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.map @@ -1 +1 @@ -{"version":3,"file":"bundle.801fe7bbee4484b5f44c.js","mappings":";UAAIA,ECCAC,EADAC,ECAAC,EACAC,E,svCCAJ,IAAAC,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IAAAE,EAAAC,EAAAG,EAAAI,EAAA,EAAAC,EAAAX,GAAA,GAAAY,GAAA,EAAAC,EAAA,CAAAF,EAAA,EAAAb,EAAA,EAAAgB,EAAApB,EAAAqB,EAAAC,EAAAN,EAAAM,EAAAC,KAAAvB,EAAA,GAAAsB,EAAA,SAAArB,EAAAC,GAAA,OAAAM,EAAAP,EAAAQ,EAAA,EAAAG,EAAAZ,EAAAmB,EAAAf,EAAAF,EAAAmB,CAAA,YAAAC,EAAApB,EAAAE,GAAA,IAAAK,EAAAP,EAAAU,EAAAR,EAAAH,EAAA,GAAAiB,GAAAF,IAAAV,GAAAL,EAAAgB,EAAAO,OAAAvB,IAAA,KAAAK,EAAAE,EAAAS,EAAAhB,GAAAqB,EAAAH,EAAAF,EAAAQ,EAAAjB,EAAA,GAAAN,EAAA,GAAAI,EAAAmB,IAAArB,KAAAQ,EAAAJ,GAAAC,EAAAD,EAAA,OAAAC,EAAA,MAAAD,EAAA,GAAAA,EAAA,GAAAR,GA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,GAAG/T,EACvB,GAGuC,SAAW0R,EAASA,EAE/D,GAYH1B,EAAoBM,EAAElY,EAAKsZ,GAA0C,IAA7BoC,EAAgBpC,GAGxD,IAAI2C,EAAuB,CAACC,EAA4B1f,KACvD,IAGIqb,EAAUyB,GAHTnB,EAAUgE,EAAaC,GAAW5f,EAGhB7G,EAAI,EAC3B,GAAGwiB,EAASkE,KAAMtE,GAAgC,IAAxB2D,EAAgB3D,IAAa,CACtD,IAAIF,KAAYsE,EACZvE,EAAoBniB,EAAE0mB,EAAatE,KACrCD,EAAoBngB,EAAEogB,GAAYsE,EAAYtE,IAGhD,GAAGuE,EAAS,IAAIvc,EAASuc,EAAQxE,EAClC,CAEA,IADGsE,GAA4BA,EAA2B1f,GACrD7G,EAAIwiB,EAASxhB,OAAQhB,IACzB2jB,EAAUnB,EAASxiB,GAChBiiB,EAAoBniB,EAAEimB,EAAiBpC,IAAYoC,EAAgBpC,IACrEoC,EAAgBpC,GAAS,KAE1BoC,EAAgBpC,GAAW,EAE5B,OAAO1B,EAAoBM,EAAErY,IAG1Byc,EAAqBC,KAAkC,4BAAIA,KAAkC,6BAAK,GACtGD,EAAmBpZ,QAAQ+Y,EAAqBvlB,KAAK,KAAM,IAC3D4lB,EAAmB3jB,KAAOsjB,EAAqBvlB,KAAK,KAAM4lB,EAAmB3jB,KAAKjC,KAAK4lB,G,KClFvF,IAAIE,EAAsB5E,EAAoBM,OAAE3d,EAAW,CAAC,IAAK,IAAOqd,EAAoB,MAC5F4E,EAAsB5E,EAAoBM,EAAEsE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/../shared/turnkey-core.js","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/../shared/crypto-utils.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/external var \"crypto\"","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/global","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/compat","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t\tif (script.src.indexOf(window.location.origin + '/') !== 0) {\n\t\t\tscript.crossOrigin = \"anonymous\";\n\t\t}\n\t\tscript.integrity = __webpack_require__.sriHashes[chunkId];\n\t\tscript.crossOrigin = \"anonymous\";\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n if (!data) {\n return null;\n }\n try {\n return JSON.parse(data);\n } catch (e) {\n // If the stored data is corrupted or not valid JSON, remove it to self-heal.\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n return null;\n }\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * Only removes the bundle if it belongs to the specified organization.\n * @param {string} address - The wallet address to remove\n * @param {string} organizationId - Only remove if the bundle belongs to this org\n */\nfunction removeEncryptedBundle(address, organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles || !bundles[address]) return;\n\n // Only remove if the bundle belongs to the specified organization\n if (bundles[address].organizationId !== organizationId) return;\n\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n}\n\n/**\n * Removes all encrypted bundles belonging to the specified organization.\n * Bundles from other organizations are preserved.\n * @param {string} organizationId - Remove bundles belonging to this org\n */\nfunction clearAllEncryptedBundles(organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles) return;\n\n // Keep only bundles that do NOT belong to this organization\n const remaining = Object.fromEntries(\n Object.entries(bundles).filter(\n ([, bundle]) => bundle.organizationId !== organizationId\n )\n );\n\n if (Object.keys(remaining).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(remaining)\n );\n }\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\nimport { fromDerSignature } from \"@turnkey/crypto\";\nimport * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n initEmbeddedKey: sharedInitEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n additionalAssociatedData,\n getSettings,\n setSettings,\n parsePrivateKey,\n validateStyles,\n isDoublyIframed,\n loadQuorumKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n} = SharedTKHQ;\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n return await sharedInitEmbeddedKey();\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Read environment from meta tag (templated at deploy time), fall back to window variable (for testing)\n let environment = null;\n if (typeof document !== \"undefined\") {\n const meta = document.querySelector(\n 'meta[name=\"turnkey-signer-environment\"]'\n );\n if (\n meta &&\n meta.content &&\n meta.content !== \"__TURNKEY_SIGNER_ENVIRONMENT__\"\n ) {\n environment = meta.content;\n }\n }\n if (!environment && typeof window !== \"undefined\") {\n environment = window.__TURNKEY_SIGNER_ENVIRONMENT__;\n }\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\n// Decryption key -- held in memory only, never persisted to localStorage.\n// This is a P-256 private key in JWK format used to decrypt stored bundles.\nlet decryptionKey = null;\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Verifies the enclave signature on a v1.0.0 bundle and returns the parsed signed data.\n * @param {string} bundle - JSON-stringified bundle\n * @param {string} organizationId - Expected organization ID\n * @returns {Promise} - The parsed signed data {organizationId, encappedPublic, ciphertext}\n */\nasync function verifyAndParseBundleData(bundle, organizationId) {\n const bundleObj = JSON.parse(bundle);\n\n if (bundleObj.version !== \"v1.0.0\") {\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n const verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(\n `failed to verify enclave signature: ${bundleObj.dataSignature}`\n );\n }\n\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n\n return signedData;\n}\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n // Decrypt the ciphertext\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: embeddedKeyJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Encodes raw key bytes and loads them into the in-memory key store.\n * @param {string} address - Wallet address (case-sensitive)\n * @param {ArrayBuffer} keyBytes - Raw decrypted private key bytes\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} organizationId - Organization ID\n */\nasync function loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId) {\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair,\n },\n };\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Load decrypted key into memory\n await loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId);\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Set up sha512 for nobleEd25519 (required for signing)\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n\n // Extract the 32-byte private key from the 64-byte secretKey\n // Solana keypair.secretKey format: [32-byte private key][32-byte public key]\n const privateKey = keypair.secretKey.slice(0, 32);\n // Sign the message using nobleEd25519\n const signature = nobleEd25519.sign(messageBytes, privateKey);\n\n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n/**\n * Handler for STORE_ENCRYPTED_BUNDLE events.\n * Verifies the enclave signature on an encrypted bundle and stores\n * the encrypted payload in localStorage for later decryption.\n * If the decryption key is already in memory, also decrypts and loads\n * the key into memory immediately.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle JSON\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} address - Wallet address\n * @param {Function} HpkeDecrypt\n */\nasync function onStoreEncryptedBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n if (!address) {\n throw new Error(\"address is required for STORE_ENCRYPTED_BUNDLE\");\n }\n\n // Verify enclave signature and parse the signed data\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const resolvedKeyFormat = keyFormat || \"HEXADECIMAL\";\n\n // Store the encrypted fields in localStorage (just what's needed for decryption)\n TKHQ.setEncryptedBundle(address, {\n encappedPublic: signedData.encappedPublic,\n ciphertext: signedData.ciphertext,\n organizationId: organizationId,\n keyFormat: resolvedKeyFormat,\n });\n\n // If the decryption key is already in memory, decrypt and load immediately\n if (decryptionKey && HpkeDecrypt) {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n await loadKeyIntoMemory(\n address,\n keyBytes,\n resolvedKeyFormat,\n organizationId\n );\n }\n\n TKHQ.sendMessageUp(\"ENCRYPTED_BUNDLE_STORED\", true, requestId);\n}\n\n/**\n * Converts raw P-256 private key bytes (32-byte scalar) to a JWK.\n * Constructs a PKCS8 wrapper around the raw bytes, imports via WebCrypto\n * (which derives the public key), then exports as JWK.\n * @param {Uint8Array} rawPrivateKeyBytes - 32-byte P-256 private key scalar\n * @returns {Promise} - Full P-256 ECDH private key JWK\n */\nasync function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) {\n if (rawPrivateKeyBytes.length !== 32) {\n throw new Error(\n `invalid decryption key length: expected 32 bytes, got ${rawPrivateKeyBytes.length}`\n );\n }\n\n // Fixed PKCS#8 DER prefix for a P-256 private key (36 bytes).\n // This wraps a raw 32-byte scalar into the PrivateKeyInfo structure\n // that WebCrypto's importKey(\"pkcs8\", ...) expects.\n //\n // Structure (per RFC 5958 §2 / RFC 5208 §5):\n // SEQUENCE {\n // INTEGER 0 -- version (v1)\n // SEQUENCE { -- AlgorithmIdentifier (RFC 5480 §2.1.1)\n // OID 1.2.840.10045.2.1 -- id-ecPublicKey\n // OID 1.2.840.10045.3.1.7 -- secp256r1 (P-256)\n // }\n // OCTET STRING { -- privateKey (SEC 1 §C.4 / RFC 5915 §3)\n // SEQUENCE {\n // INTEGER 1 -- version\n // OCTET STRING (32 bytes) -- raw private key scalar\n // }\n // }\n // }\n //\n // References:\n // - RFC 5958 / RFC 5208: PKCS#8 PrivateKeyInfo\n // - RFC 5480 §2.1.1: ECC AlgorithmIdentifier (OIDs)\n // - RFC 5915 / SEC 1 v2 §C.4: ECPrivateKey encoding\n const pkcs8Prefix = new Uint8Array([\n 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48,\n 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03,\n 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20,\n ]);\n\n const pkcs8 = new Uint8Array(pkcs8Prefix.length + 32);\n pkcs8.set(pkcs8Prefix);\n pkcs8.set(rawPrivateKeyBytes, pkcs8Prefix.length);\n\n const cryptoKey = await crypto.subtle.importKey(\n \"pkcs8\",\n pkcs8,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"]\n );\n\n return await crypto.subtle.exportKey(\"jwk\", cryptoKey);\n}\n\n/**\n * Handler for INJECT_DECRYPTION_KEY_BUNDLE events.\n * Decrypts the P-256 private key using the iframe's embedded key,\n * then iterates all stored encrypted bundles, HPKE-decrypts each one\n * with the key, and loads them into inMemoryKeys.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle containing the private key\n * @param {Function} HpkeDecrypt\n */\nasync function onInjectDecryptionKeyBundle(\n requestId,\n organizationId,\n bundle,\n HpkeDecrypt\n) {\n // Decrypt the private key using the iframe's embedded key.\n // The decrypted payload is a raw 32-byte P-256 private key scalar.\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto)\n const keyJwk = await rawP256PrivateKeyToJwk(new Uint8Array(keyBytes));\n\n // Store in module-level variable (memory only)\n decryptionKey = keyJwk;\n\n // Iterate all stored encrypted bundles and decrypt each one\n const storedBundles = TKHQ.getEncryptedBundles();\n let decryptedCount = 0;\n\n if (storedBundles) {\n const addresses = Object.keys(storedBundles);\n\n for (const addr of addresses) {\n const bundleData = storedBundles[addr];\n\n try {\n const bundleOrgId = bundleData.organizationId;\n\n if (organizationId !== bundleOrgId) continue; // skip bundles that don't match the organization ID of the decryption key\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n bundleData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(\n bundleData.ciphertext\n );\n\n // HPKE-decrypt using the key\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n // Load the decrypted key into memory\n await loadKeyIntoMemory(\n addr,\n keyBytes,\n bundleData.keyFormat,\n bundleData.organizationId\n );\n\n decryptedCount++;\n } catch (e) {\n TKHQ.logMessage(\n `Failed to decrypt bundle for address ${addr}: ${e.toString()}`\n );\n }\n }\n }\n\n TKHQ.sendMessageUp(\"DECRYPTION_KEY_INJECTED\", decryptedCount, requestId);\n}\n\n/**\n * Handler for BURN_SESSION events.\n * Clears the decryption key and all in-memory wallet keys.\n * Encrypted bundles in localStorage are preserved for the next session.\n * @param {string} requestId\n */\nfunction onBurnSession(requestId) {\n decryptionKey = null;\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"SESSION_BURNED\", true, requestId);\n}\n\n/**\n * Handler for GET_STORED_WALLET_ADDRESSES events.\n * Returns a JSON array of all wallet addresses that have encrypted bundles in localStorage.\n * @param {string} requestId\n * @param {string} organizationId - Organization ID to filter addresses by (only return addresses with bundles matching the organization ID)\n */\nfunction onGetStoredWalletAddresses(requestId, organizationId) {\n const bundles = TKHQ.getEncryptedBundles();\n const addresses = bundles\n ? Object.entries(bundles)\n .filter(([, bundle]) => bundle.organizationId === organizationId)\n .map(([address]) => address)\n : [];\n TKHQ.sendMessageUp(\n \"STORED_WALLET_ADDRESSES\",\n JSON.stringify(addresses),\n requestId\n );\n}\n\n/**\n * Handler for CLEAR_STORED_BUNDLES events.\n * Removes encrypted bundles from localStorage AND the corresponding\n * in-memory keys. If address is provided, removes only that address.\n * If no address, removes ALL encrypted bundles and ALL in-memory keys.\n * @param {string} requestId\n * @param {string} organizationId - Organization ID to filter addresses by (only remove bundles matching the organization ID)\n * @param {string|undefined} address - Optional wallet address\n */\nfunction onClearStoredBundles(requestId, address, organizationId) {\n if (address) {\n TKHQ.removeEncryptedBundle(address, organizationId);\n delete inMemoryKeys[address];\n } else {\n TKHQ.clearAllEncryptedBundles(organizationId);\n inMemoryKeys = {};\n }\n TKHQ.sendMessageUp(\"STORED_BUNDLES_CLEARED\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error(\n `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`\n ).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n undefined, // keyFormat - default to HEXADECIMAL\n undefined, // address - default to \"default\"\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"STORE_ENCRYPTED_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n await onStoreEncryptedBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_DECRYPTION_KEY_BUNDLE\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onInjectDecryptionKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"BURN_SESSION\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onBurnSession(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_STORED_WALLET_ADDRESSES\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onGetStoredWalletAddresses(\n event.data[\"requestId\"],\n event.data[\"organizationId\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_STORED_BUNDLES\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n onClearStoredBundles(\n event.data[\"requestId\"],\n event.data[\"address\"],\n event.data[\"organizationId\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n onStoreEncryptedBundle,\n onInjectDecryptionKeyBundle,\n onBurnSession,\n onGetStoredWalletAddresses,\n onClearStoredBundles,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"@shared/crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n","module.exports = crypto;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","\n__webpack_require__.sriHashes = {\"291\":\"*-*-*-CHUNK-SRI-HASH-r3NPGwA4ft5fHgGXhVIptCiDVf06qPa+sxzG6L+8GwPuhn89e/\",\"825\":\"*-*-*-CHUNK-SRI-HASH-mfog3UJdGPOmSk4QZbKxsxHPFZtt298WnZNc1aQ1MCgc6YirFj\"};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(560)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","_slicedToArray","_arrayWithHoles","next","push","_iterableToArrayLimit","_nonIterableRest","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","TURNKEY_ENCRYPTED_BUNDLES","parentFrameMessageChannelPort","getSubtleCrypto","globalThis","crypto","subtle","window","global","isDoublyIframed","undefined","location","ancestorOrigins","parent","top","_loadQuorumKey","_callee","quorumPublic","_context","Error","importKey","namedCurve","_initEmbeddedKey","_callee3","_context3","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee4","p256key","_context4","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","getEncryptedBundles","data","localStorage","getItem","removeItem","key","ttl","item","expiry","Date","getTime","setItem","itemStr","hasOwnProperty","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","concat","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","p256JWKPrivateToPublic","_x6","_p256JWKPrivateToPublic","_callee6","jwkPrivate","jwkPrivateCopy","publicKey","_context6","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","k","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee9","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_t2","_context9","set","console","warn","sharedInitEmbeddedKey","SharedTKHQ","validateStyles","styles","element","validStyles","cssValidationRegex","padding","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref3","_ref4","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","loadQuorumKey","_x","_verifyEnclaveSignature","_callee2","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","meta","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context2","prod","preprod","querySelector","__TURNKEY_SIGNER_ENVIRONMENT__","fromDerSignature","verify","hash","TKHQ","initEmbeddedKey","onResetEmbeddedKey","encodeKey","_x0","_x1","_x10","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","normalizePadding","byteArray","targetLength","paddingLength","fill","expectedZeroCount","zeroCount","verifyEnclaveSignature","_x2","_x3","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","_ref","_ref2","style","getSettings","setSettings","parsePrivateKey","error","setEncryptedBundle","address","bundleData","bundles","removeEncryptedBundle","organizationId","keys","clearAllEncryptedBundles","remaining","fromEntries","filter","inMemoryKeys","decryptionKey","textEncoder","TextEncoder","textDecoder","TextDecoder","verifyAndParseBundleData","_verifyAndParseBundleData","_callee8","bundle","bundleObj","_context8","version","dataSignature","decode","encappedPublic","ciphertext","decryptBundle","_x4","_x5","_decryptBundle","HpkeDecrypt","encappedKeyBuf","ciphertextBuf","embeddedKeyJwk","receiverPrivJwk","onGetPublicEmbeddedKey","_onGetPublicEmbeddedKey","_callee0","targetPubBuf","targetPubHex","_context0","loadKeyIntoMemory","_x7","_x8","_x9","_loadKeyIntoMemory","_callee1","keyBytes","keyAddress","cachedKeypair","_context1","subarray","Keypair","fromSecretKey","createSolanaKeypair","_defineProperty","format","keypair","onInjectKeyBundle","_x11","_x12","_x13","_x14","_onInjectKeyBundle","_callee10","_context10","onApplySettings","_x15","_x16","_onApplySettings","_callee11","_context11","onSignTransaction","_x17","_x18","_x19","_onSignTransaction","_callee12","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context12","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x20","_x21","_x22","_onSignMessage","_callee13","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context13","encode","secretKey","onClearEmbeddedPrivateKey","_x23","_x24","_onClearEmbeddedPrivateKey","_callee14","_context14","onStoreEncryptedBundle","_x25","_x26","_x27","_x28","_x29","_x30","_onStoreEncryptedBundle","_callee15","resolvedKeyFormat","_context15","rawP256PrivateKeyToJwk","_x31","_rawP256PrivateKeyToJwk","_callee16","rawPrivateKeyBytes","pkcs8Prefix","pkcs8","cryptoKey","_context16","onInjectDecryptionKeyBundle","_x32","_x33","_x34","_x35","_onInjectDecryptionKeyBundle","_callee17","keyJwk","storedBundles","decryptedCount","addresses","_i3","_addresses","addr","bundleOrgId","_keyBytes","_t0","_context17","onBurnSession","onGetStoredWalletAddresses","onClearStoredBundles","_x36","_createSolanaKeypair","_callee18","_context18","fromSeed","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x37","_getOrCreateKeypair","_callee19","_context19","initEventHandlers","messageEventListener","_messageEventListener","event","_t","_t3","_t4","_t5","_t6","_t7","_t8","_t9","_x43","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","_ref5","preventDefault","_x38","_ref6","_x39","_ref7","_x40","_ref8","_x41","injectWalletBtn","_ref9","_callee5","_context5","_x42","addDOMEventListeners","capture","signal","_ref0","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x44","ownKeys","getOwnPropertySymbols","getOwnPropertyDescriptor","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","_HpkeDecrypt","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","styleSettings","module","exports","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","g","Function","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","crossOrigin","integrity","sriHashes","onScriptComplete","prev","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"bundle.801fe7bbee4484b5f44c.js","mappings":";UAAIA,ECCAC,EADAC,ECAAC,EACAC,E,svCCAJ,IAAAC,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IAAAE,EAAAC,EAAAG,EAAAI,EAAA,EAAAC,EAAAX,GAAA,GAAAY,GAAA,EAAAC,EAAA,CAAAF,EAAA,EAAAb,EAAA,EAAAgB,EAAApB,EAAAqB,EAAAC,EAAAN,EAAAM,EAAAC,KAAAvB,EAAA,GAAAsB,EAAA,SAAArB,EAAAC,GAAA,OAAAM,EAAAP,EAAAQ,EAAA,EAAAG,EAAAZ,EAAAmB,EAAAf,EAAAF,EAAAmB,CAAA,YAAAC,EAAApB,EAAAE,GAAA,IAAAK,EAAAP,EAAAU,EAAAR,EAAAH,EAAA,GAAAiB,GAAAF,IAAAV,GAAAL,EAAAgB,EAAAO,OAAAvB,IAAA,KAAAK,EAAAE,EAAAS,EAAAhB,GAAAqB,EAAAH,EAAAF,EAAAQ,EAAAjB,EAAA,GAAAN,EAAA,GAAAI,EAAAmB,IAAArB,KAAAQ,EAAAJ,GAAAC,EAAAD,EAAA,OAAAC,EAAA,MAAAD,EAAA,GAAAA,EAAA,GAAAR,GAAAQ,EAAA,IAAAc,KAAAhB,EAAAJ,EAAA,GAAAoB,EAAAd,EAAA,KAAAC,EAAA,EAAAU,EAAAC,EAAAhB,EAAAe,EAAAf,EAAA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AI2C,EAAuB,CAACC,EAA4Bzf,KACvD,IAGIob,EAAUyB,GAHTnB,EAAUgE,EAAaC,GAAW3f,EAGhB7G,EAAI,EAC3B,GAAGuiB,EAASkE,KAAMtE,GAAgC,IAAxB2D,EAAgB3D,IAAa,CACtD,IAAIF,KAAYsE,EACZvE,EAAoBliB,EAAEymB,EAAatE,KACrCD,EAAoBlgB,EAAEmgB,GAAYsE,EAAYtE,IAGhD,GAAGuE,EAAS,IAAItc,EAASsc,EAAQxE,EAClC,CAEA,IADGsE,GAA4BA,EAA2Bzf,GACrD7G,EAAIuiB,EAASvhB,OAAQhB,IACzB0jB,EAAUnB,EAASviB,GAChBgiB,EAAoBliB,EAAEgmB,EAAiBpC,IAAYoC,EAAgBpC,IACrEoC,EAAgBpC,GAAS,KAE1BoC,EAAgBpC,GAAW,EAE5B,OAAO1B,EAAoBM,EAAEpY,IAG1Bwc,EAAqBC,KAAkC,4BAAIA,KAAkC,6BAAK,GACtGD,EAAmBnZ,QAAQ8Y,EAAqBtlB,KAAK,KAAM,IAC3D2lB,EAAmB1jB,KAAOqjB,EAAqBtlB,KAAK,KAAM2lB,EAAmB1jB,KAAKjC,KAAK2lB,G,KClFvF,IAAIE,EAAsB5E,EAAoBM,OAAE1d,EAAW,CAAC,IAAK,IAAOod,EAAoB,MAC5F4E,EAAsB5E,EAAoBM,EAAEsE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/../shared/turnkey-core.js","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/../shared/crypto-utils.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/external var \"crypto\"","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/global","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/compat","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t\tif (script.src.indexOf(window.location.origin + '/') !== 0) {\n\t\t\tscript.crossOrigin = \"anonymous\";\n\t\t}\n\t\tscript.integrity = __webpack_require__.sriHashes[chunkId];\n\t\tscript.crossOrigin = \"anonymous\";\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n if (!data) {\n return null;\n }\n try {\n return JSON.parse(data);\n } catch (e) {\n // If the stored data is corrupted or not valid JSON, remove it to self-heal.\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n return null;\n }\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * Only removes the bundle if it belongs to the specified organization.\n * @param {string} address - The wallet address to remove\n * @param {string} organizationId - Only remove if the bundle belongs to this org\n */\nfunction removeEncryptedBundle(address, organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles || !bundles[address]) return;\n\n // Only remove if the bundle belongs to the specified organization\n if (bundles[address].organizationId !== organizationId) return;\n\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n}\n\n/**\n * Removes all encrypted bundles belonging to the specified organization.\n * Bundles from other organizations are preserved.\n * @param {string} organizationId - Remove bundles belonging to this org\n */\nfunction clearAllEncryptedBundles(organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles) return;\n\n // Keep only bundles that do NOT belong to this organization\n const remaining = Object.fromEntries(\n Object.entries(bundles).filter(\n ([, bundle]) => bundle.organizationId !== organizationId\n )\n );\n\n if (Object.keys(remaining).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(remaining)\n );\n }\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\nimport { fromDerSignature } from \"@turnkey/crypto\";\nimport * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n initEmbeddedKey: sharedInitEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n additionalAssociatedData,\n getSettings,\n setSettings,\n parsePrivateKey,\n validateStyles,\n isDoublyIframed,\n loadQuorumKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n} = SharedTKHQ;\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n return await sharedInitEmbeddedKey();\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Read environment from meta tag (templated at deploy time), fall back to window variable (for testing)\n let environment = null;\n if (typeof document !== \"undefined\") {\n const meta = document.querySelector(\n 'meta[name=\"turnkey-signer-environment\"]'\n );\n if (\n meta &&\n meta.content &&\n meta.content !== \"__TURNKEY_SIGNER_ENVIRONMENT__\"\n ) {\n environment = meta.content;\n }\n }\n if (!environment && typeof window !== \"undefined\") {\n environment = window.__TURNKEY_SIGNER_ENVIRONMENT__;\n }\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\n// Decryption key -- held in memory only, never persisted to localStorage.\n// This is a P-256 private key in JWK format used to decrypt stored bundles.\nlet decryptionKey = null;\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Verifies the enclave signature on a v1.0.0 bundle and returns the parsed signed data.\n * @param {string} bundle - JSON-stringified bundle\n * @param {string} organizationId - Expected organization ID\n * @returns {Promise} - The parsed signed data {organizationId, encappedPublic, ciphertext}\n */\nasync function verifyAndParseBundleData(bundle, organizationId) {\n const bundleObj = JSON.parse(bundle);\n\n if (bundleObj.version !== \"v1.0.0\") {\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n const verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(\n `failed to verify enclave signature: ${bundleObj.dataSignature}`\n );\n }\n\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n\n return signedData;\n}\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n // Decrypt the ciphertext\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: embeddedKeyJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Encodes raw key bytes and loads them into the in-memory key store.\n * @param {string} address - Wallet address (case-sensitive)\n * @param {ArrayBuffer} keyBytes - Raw decrypted private key bytes\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} organizationId - Organization ID\n */\nasync function loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId) {\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair,\n },\n };\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Load decrypted key into memory\n await loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId);\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Set up sha512 for nobleEd25519 (required for signing)\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n\n // Extract the 32-byte private key from the 64-byte secretKey\n // Solana keypair.secretKey format: [32-byte private key][32-byte public key]\n const privateKey = keypair.secretKey.slice(0, 32);\n // Sign the message using nobleEd25519\n const signature = nobleEd25519.sign(messageBytes, privateKey);\n\n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n/**\n * Handler for STORE_ENCRYPTED_BUNDLE events.\n * Verifies the enclave signature on an encrypted bundle and stores\n * the encrypted payload in localStorage for later decryption.\n * If the decryption key is already in memory, also decrypts and loads\n * the key into memory immediately.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle JSON\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} address - Wallet address\n * @param {Function} HpkeDecrypt\n */\nasync function onStoreEncryptedBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n if (!address) {\n throw new Error(\"address is required for STORE_ENCRYPTED_BUNDLE\");\n }\n\n // Verify enclave signature and parse the signed data\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const resolvedKeyFormat = keyFormat || \"HEXADECIMAL\";\n\n // Store the encrypted fields in localStorage (just what's needed for decryption)\n TKHQ.setEncryptedBundle(address, {\n encappedPublic: signedData.encappedPublic,\n ciphertext: signedData.ciphertext,\n organizationId: organizationId,\n keyFormat: resolvedKeyFormat,\n });\n\n // If the decryption key is already in memory, decrypt and load immediately\n if (decryptionKey && HpkeDecrypt) {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n await loadKeyIntoMemory(\n address,\n keyBytes,\n resolvedKeyFormat,\n organizationId\n );\n }\n\n TKHQ.sendMessageUp(\"ENCRYPTED_BUNDLE_STORED\", true, requestId);\n}\n\n/**\n * Converts raw P-256 private key bytes (32-byte scalar) to a JWK.\n * Constructs a PKCS8 wrapper around the raw bytes, imports via WebCrypto\n * (which derives the public key), then exports as JWK.\n * @param {Uint8Array} rawPrivateKeyBytes - 32-byte P-256 private key scalar\n * @returns {Promise} - Full P-256 ECDH private key JWK\n */\nasync function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) {\n if (rawPrivateKeyBytes.length !== 32) {\n throw new Error(\n `invalid decryption key length: expected 32 bytes, got ${rawPrivateKeyBytes.length}`\n );\n }\n\n // Fixed PKCS#8 DER prefix for a P-256 private key (36 bytes).\n // This wraps a raw 32-byte scalar into the PrivateKeyInfo structure\n // that WebCrypto's importKey(\"pkcs8\", ...) expects.\n //\n // Structure (per RFC 5958 §2 / RFC 5208 §5):\n // SEQUENCE {\n // INTEGER 0 -- version (v1)\n // SEQUENCE { -- AlgorithmIdentifier (RFC 5480 §2.1.1)\n // OID 1.2.840.10045.2.1 -- id-ecPublicKey\n // OID 1.2.840.10045.3.1.7 -- secp256r1 (P-256)\n // }\n // OCTET STRING { -- privateKey (SEC 1 §C.4 / RFC 5915 §3)\n // SEQUENCE {\n // INTEGER 1 -- version\n // OCTET STRING (32 bytes) -- raw private key scalar\n // }\n // }\n // }\n //\n // References:\n // - RFC 5958 / RFC 5208: PKCS#8 PrivateKeyInfo\n // - RFC 5480 §2.1.1: ECC AlgorithmIdentifier (OIDs)\n // - RFC 5915 / SEC 1 v2 §C.4: ECPrivateKey encoding\n const pkcs8Prefix = new Uint8Array([\n 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48,\n 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03,\n 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20,\n ]);\n\n const pkcs8 = new Uint8Array(pkcs8Prefix.length + 32);\n pkcs8.set(pkcs8Prefix);\n pkcs8.set(rawPrivateKeyBytes, pkcs8Prefix.length);\n\n const cryptoKey = await crypto.subtle.importKey(\n \"pkcs8\",\n pkcs8,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"]\n );\n\n return await crypto.subtle.exportKey(\"jwk\", cryptoKey);\n}\n\n/**\n * Handler for INJECT_DECRYPTION_KEY_BUNDLE events.\n * Decrypts the P-256 private key using the iframe's embedded key,\n * then iterates all stored encrypted bundles, HPKE-decrypts each one\n * with the key, and loads them into inMemoryKeys.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle containing the private key\n * @param {Function} HpkeDecrypt\n */\nasync function onInjectDecryptionKeyBundle(\n requestId,\n organizationId,\n bundle,\n HpkeDecrypt\n) {\n // Decrypt the private key using the iframe's embedded key.\n // The decrypted payload is a raw 32-byte P-256 private key scalar.\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto)\n const keyJwk = await rawP256PrivateKeyToJwk(new Uint8Array(keyBytes));\n\n // Store in module-level variable (memory only)\n decryptionKey = keyJwk;\n\n // Iterate all stored encrypted bundles and decrypt each one\n const storedBundles = TKHQ.getEncryptedBundles();\n let decryptedCount = 0;\n\n if (storedBundles) {\n const addresses = Object.keys(storedBundles);\n\n for (const addr of addresses) {\n const bundleData = storedBundles[addr];\n\n try {\n const bundleOrgId = bundleData.organizationId;\n\n if (organizationId !== bundleOrgId) continue; // skip bundles that don't match the organization ID of the decryption key\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n bundleData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(\n bundleData.ciphertext\n );\n\n // HPKE-decrypt using the key\n const bytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n // Load the decrypted key into memory\n await loadKeyIntoMemory(\n addr,\n bytes,\n bundleData.keyFormat,\n bundleData.organizationId\n );\n\n decryptedCount++;\n } catch (e) {\n TKHQ.logMessage(\n `Failed to decrypt bundle for address ${addr}: ${e.toString()}`\n );\n }\n }\n }\n\n TKHQ.sendMessageUp(\"DECRYPTION_KEY_INJECTED\", decryptedCount, requestId);\n}\n\n/**\n * Handler for BURN_SESSION events.\n * Clears the decryption key and all in-memory wallet keys.\n * Encrypted bundles in localStorage are preserved for the next session.\n * @param {string} requestId\n */\nfunction onBurnSession(requestId) {\n decryptionKey = null;\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"SESSION_BURNED\", true, requestId);\n}\n\n/**\n * Handler for GET_STORED_WALLET_ADDRESSES events.\n * Returns a JSON array of all wallet addresses that have encrypted bundles in localStorage.\n * @param {string} requestId\n * @param {string} organizationId - Organization ID to filter addresses by (only return addresses with bundles matching the organization ID)\n */\nfunction onGetStoredWalletAddresses(requestId, organizationId) {\n const bundles = TKHQ.getEncryptedBundles();\n const addresses = bundles\n ? Object.entries(bundles)\n .filter(([, bundle]) => bundle.organizationId === organizationId)\n .map(([address]) => address)\n : [];\n TKHQ.sendMessageUp(\n \"STORED_WALLET_ADDRESSES\",\n JSON.stringify(addresses),\n requestId\n );\n}\n\n/**\n * Handler for CLEAR_STORED_BUNDLES events.\n * Removes encrypted bundles from localStorage AND the corresponding\n * in-memory keys. If address is provided, removes only that address.\n * If no address, removes ALL encrypted bundles and ALL in-memory keys.\n * @param {string} requestId\n * @param {string} organizationId - Organization ID to filter addresses by (only remove bundles matching the organization ID)\n * @param {string|undefined} address - Optional wallet address\n */\nfunction onClearStoredBundles(requestId, address, organizationId) {\n if (address) {\n TKHQ.removeEncryptedBundle(address, organizationId);\n delete inMemoryKeys[address];\n } else {\n TKHQ.clearAllEncryptedBundles(organizationId);\n inMemoryKeys = {};\n }\n TKHQ.sendMessageUp(\"STORED_BUNDLES_CLEARED\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error(\n `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`\n ).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n undefined, // keyFormat - default to HEXADECIMAL\n undefined, // address - default to \"default\"\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"STORE_ENCRYPTED_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n await onStoreEncryptedBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_DECRYPTION_KEY_BUNDLE\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onInjectDecryptionKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"BURN_SESSION\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onBurnSession(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_STORED_WALLET_ADDRESSES\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onGetStoredWalletAddresses(\n event.data[\"requestId\"],\n event.data[\"organizationId\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_STORED_BUNDLES\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n onClearStoredBundles(\n event.data[\"requestId\"],\n event.data[\"address\"],\n event.data[\"organizationId\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n onStoreEncryptedBundle,\n onInjectDecryptionKeyBundle,\n onBurnSession,\n onGetStoredWalletAddresses,\n onClearStoredBundles,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"@shared/crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n","module.exports = crypto;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","\n__webpack_require__.sriHashes = {\"291\":\"*-*-*-CHUNK-SRI-HASH-r3NPGwA4ft5fHgGXhVIptCiDVf06qPa+sxzG6L+8GwPuhn89e/\",\"825\":\"*-*-*-CHUNK-SRI-HASH-mfog3UJdGPOmSk4QZbKxsxHPFZtt298WnZNc1aQ1MCgc6YirFj\"};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(560)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","_slicedToArray","_arrayWithHoles","next","push","_iterableToArrayLimit","_nonIterableRest","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","TURNKEY_ENCRYPTED_BUNDLES","parentFrameMessageChannelPort","getSubtleCrypto","globalThis","crypto","subtle","window","global","isDoublyIframed","undefined","location","ancestorOrigins","parent","top","_loadQuorumKey","_callee","quorumPublic","_context","Error","importKey","namedCurve","_initEmbeddedKey","_callee3","_context3","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee4","p256key","_context4","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","getEncryptedBundles","data","localStorage","getItem","removeItem","key","ttl","item","expiry","Date","getTime","setItem","itemStr","hasOwnProperty","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","concat","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","p256JWKPrivateToPublic","_x6","_p256JWKPrivateToPublic","_callee6","jwkPrivate","jwkPrivateCopy","publicKey","_context6","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","k","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee9","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_t2","_context9","set","console","warn","sharedInitEmbeddedKey","SharedTKHQ","validateStyles","styles","element","validStyles","cssValidationRegex","padding","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref3","_ref4","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","loadQuorumKey","_x","_verifyEnclaveSignature","_callee2","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","meta","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context2","prod","preprod","querySelector","__TURNKEY_SIGNER_ENVIRONMENT__","fromDerSignature","verify","hash","TKHQ","initEmbeddedKey","onResetEmbeddedKey","encodeKey","_x0","_x1","_x10","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","normalizePadding","byteArray","targetLength","paddingLength","fill","expectedZeroCount","zeroCount","verifyEnclaveSignature","_x2","_x3","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","_ref","_ref2","style","getSettings","setSettings","parsePrivateKey","error","setEncryptedBundle","address","bundleData","bundles","removeEncryptedBundle","organizationId","keys","clearAllEncryptedBundles","remaining","fromEntries","filter","inMemoryKeys","decryptionKey","textEncoder","TextEncoder","textDecoder","TextDecoder","verifyAndParseBundleData","_verifyAndParseBundleData","_callee8","bundle","bundleObj","_context8","version","dataSignature","decode","encappedPublic","ciphertext","decryptBundle","_x4","_x5","_decryptBundle","HpkeDecrypt","encappedKeyBuf","ciphertextBuf","embeddedKeyJwk","receiverPrivJwk","onGetPublicEmbeddedKey","_onGetPublicEmbeddedKey","_callee0","targetPubBuf","targetPubHex","_context0","loadKeyIntoMemory","_x7","_x8","_x9","_loadKeyIntoMemory","_callee1","keyBytes","keyAddress","cachedKeypair","_context1","subarray","Keypair","fromSecretKey","createSolanaKeypair","_defineProperty","format","keypair","onInjectKeyBundle","_x11","_x12","_x13","_x14","_onInjectKeyBundle","_callee10","_context10","onApplySettings","_x15","_x16","_onApplySettings","_callee11","_context11","onSignTransaction","_x17","_x18","_x19","_onSignTransaction","_callee12","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context12","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x20","_x21","_x22","_onSignMessage","_callee13","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context13","encode","secretKey","onClearEmbeddedPrivateKey","_x23","_x24","_onClearEmbeddedPrivateKey","_callee14","_context14","onStoreEncryptedBundle","_x25","_x26","_x27","_x28","_x29","_x30","_onStoreEncryptedBundle","_callee15","resolvedKeyFormat","_context15","rawP256PrivateKeyToJwk","_x31","_rawP256PrivateKeyToJwk","_callee16","rawPrivateKeyBytes","pkcs8Prefix","pkcs8","cryptoKey","_context16","onInjectDecryptionKeyBundle","_x32","_x33","_x34","_x35","_onInjectDecryptionKeyBundle","_callee17","keyJwk","storedBundles","decryptedCount","addresses","_i3","_addresses","addr","bundleOrgId","_t0","_context17","onBurnSession","onGetStoredWalletAddresses","onClearStoredBundles","_x36","_createSolanaKeypair","_callee18","_context18","fromSeed","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x37","_getOrCreateKeypair","_callee19","_context19","initEventHandlers","messageEventListener","_messageEventListener","event","_t","_t3","_t4","_t5","_t6","_t7","_t8","_t9","_x43","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","_ref5","preventDefault","_x38","_ref6","_x39","_ref7","_x40","_ref8","_x41","injectWalletBtn","_ref9","_callee5","_context5","_x42","addDOMEventListeners","capture","signal","_ref0","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x44","ownKeys","getOwnPropertySymbols","getOwnPropertyDescriptor","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","_HpkeDecrypt","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","styleSettings","module","exports","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","g","Function","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","crossOrigin","integrity","sriHashes","onScriptComplete","prev","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/src/event-handlers.js b/export-and-sign/src/event-handlers.js index 45ee5f6..7ab8a3f 100644 --- a/export-and-sign/src/event-handlers.js +++ b/export-and-sign/src/event-handlers.js @@ -508,7 +508,7 @@ async function onInjectDecryptionKeyBundle( ); // HPKE-decrypt using the key - const keyBytes = await HpkeDecrypt({ + const bytes = await HpkeDecrypt({ ciphertextBuf, encappedKeyBuf, receiverPrivJwk: decryptionKey, @@ -517,7 +517,7 @@ async function onInjectDecryptionKeyBundle( // Load the decrypted key into memory await loadKeyIntoMemory( addr, - keyBytes, + bytes, bundleData.keyFormat, bundleData.organizationId ); From 8081b07b32605c36dc25b0329ffca1294197e75b Mon Sep 17 00:00:00 2001 From: Ethan Konkolowicz Date: Thu, 19 Feb 2026 14:17:46 -0500 Subject: [PATCH 7/7] removed local storage caching mechanisms, kept only decryption key injection --- .../dist/bundle.801fe7bbee4484b5f44c.js | 3 - .../dist/bundle.801fe7bbee4484b5f44c.js.map | 1 - .../dist/bundle.dd09773f50e375d9ca7e.js | 3 + ...undle.dd09773f50e375d9ca7e.js.LICENSE.txt} | 0 .../dist/bundle.dd09773f50e375d9ca7e.js.map | 1 + export-and-sign/dist/index.html | 2 +- export-and-sign/index.test.js | 651 +++--------------- export-and-sign/src/event-handlers.js | 296 ++------ export-and-sign/src/turnkey-core.js | 8 - .../551.bundle.27da59437a4e403e3c24.js.map | 2 +- shared/turnkey-core.js | 89 --- shared/turnkey-core.test.js | 82 --- 12 files changed, 139 insertions(+), 999 deletions(-) delete mode 100644 export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js delete mode 100644 export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.map create mode 100644 export-and-sign/dist/bundle.dd09773f50e375d9ca7e.js rename export-and-sign/dist/{bundle.801fe7bbee4484b5f44c.js.LICENSE.txt => bundle.dd09773f50e375d9ca7e.js.LICENSE.txt} (100%) create mode 100644 export-and-sign/dist/bundle.dd09773f50e375d9ca7e.js.map diff --git a/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js b/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js deleted file mode 100644 index e076e52..0000000 --- a/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js +++ /dev/null @@ -1,3 +0,0 @@ -/*! For license information please see bundle.801fe7bbee4484b5f44c.js.LICENSE.txt */ -(()=>{var e,t,r,n,a,o={560:(e,t,r)=>{"use strict";var n=r(598),a=r(443),o=r(566);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function c(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function u(e){for(var t=1;t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var l=[][n]?t(t([][n]())):(d(t={},n,function(){return this}),t),p=s.prototype=c.prototype=Object.create(l);function y(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,d(e,a,"GeneratorFunction")),e.prototype=Object.create(p),e}return u.prototype=s,d(p,"constructor",s),d(s,"constructor",u),u.displayName="GeneratorFunction",d(s,a,"GeneratorFunction"),d(p),d(p,a,"Generator"),d(p,n,function(){return this}),d(p,"toString",function(){return"[object Generator]"}),(f=function(){return{w:o,m:y}})()}function d(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}d=function(e,t,r,n){function o(t,r){d(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},d(e,t,r,n)}function l(e){return function(e){if(Array.isArray(e))return v(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||y(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,a,o,i,c=[],u=!0,s=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=o.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,a=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw a}}return c}}(e,t)||y(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function y(e,t){if(e){if("string"==typeof e)return v(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?v(e,t):void 0}}function v(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1:window.parent!==window.top}function k(){return(k=g(f().m(function e(t){var r;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=S()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,r.importKey("raw",t,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function P(){return(P=g(f().m(function e(){return f().w(function(e){for(;;)switch(e.n){case 0:if(!O()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,_();case 2:if(null!==e.v){e.n=4;break}return e.n=3,j();case 3:x(e.v);case 4:return e.a(2)}},e)}))).apply(this,arguments)}function j(){return I.apply(this,arguments)}function I(){return(I=g(f().m(function e(){var t,r;return f().w(function(e){for(;;)switch(e.n){case 0:if(t=S()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,t.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return r=e.v,e.n=3,t.exportKey("jwk",r.privateKey);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function _(){var e=R(m);return e?JSON.parse(e):null}function x(e){A(m,JSON.stringify(e),1728e5)}function T(){var e=window.localStorage.getItem(w);if(!e)return null;try{return JSON.parse(e)}catch(e){return window.localStorage.removeItem(w),null}}function A(e,t,r){var n={value:t,expiry:(new Date).getTime()+r};window.localStorage.setItem(e,JSON.stringify(n))}function R(e){var t=window.localStorage.getItem(e);if(!t)return null;var r=JSON.parse(t);return Object.prototype.hasOwnProperty.call(r,"expiry")&&Object.prototype.hasOwnProperty.call(r,"value")?(new Date).getTime()>r.expiry?(window.localStorage.removeItem(e),null):r.value:(window.localStorage.removeItem(e),null)}function D(e){if(!e||"string"!=typeof e)throw new Error("cannot create uint8array from invalid hex string");var t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0||!/^[0-9A-Fa-f]+$/.test(t))throw new Error("cannot create uint8array from invalid hex string");return new Uint8Array(t.match(/../g).map(function(e){return parseInt(e,16)}))}function N(e){return l(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function M(e,t){var r=Array.from(new Uint8Array(e)),n=Array.from(new Uint8Array(t));return new Uint8Array([].concat(r,n))}function U(e){var t=document.getElementById("message-log");if(t){var r=document.createElement("p");r.innerText=e,t.appendChild(r)}}function K(e){return C.apply(this,arguments)}function C(){return(C=g(f().m(function e(t){var r,n,a,o;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=S()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return delete(n=u({},t)).d,n.key_ops=["verify"],e.n=2,r.importKey("jwk",n,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return a=e.v,e.n=3,r.exportKey("raw",a);case 3:return o=e.v,e.a(2,new Uint8Array(o))}},e)}))).apply(this,arguments)}function B(e){for(var t="",r=[0],n=0;n0;)r.push(a%58),a=a/58|0}for(var i=0;i0;){var c=r[i];o=(c=void 0===c?o:58*c+o)>>8,r[i]=c%256,i++}}var u=n.concat(r.reverse());return new Uint8Array(u)}function G(){return(G=g(f().m(function e(t,r,n){var a,o;return f().w(function(e){for(;;)switch(e.n){case 0:o=r,e.n="SOLANA"===o?1:"HEXADECIMAL"===o?5:6;break;case 1:if(n){e.n=2;break}throw new Error("public key must be specified for SOLANA key format");case 2:if(32===t.length){e.n=3;break}throw new Error("invalid private key length. Expected 32 bytes. Got ".concat(t.length,"."));case 3:if(32===n.length){e.n=4;break}throw new Error("invalid public key length. Expected 32 bytes. Got ".concat(n.length,"."));case 4:return(a=new Uint8Array(64)).set(t,0),a.set(n,32),e.a(2,B(a));case 5:return e.a(2,"0x"+N(t));case 6:return console.warn("invalid key format: ".concat(r,". Defaulting to HEXADECIMAL.")),e.a(2,"0x"+N(t));case 7:return e.a(2)}},e)}))).apply(this,arguments)}function F(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",a=r.toStringTag||"@@toStringTag";function o(r,n,a,o){var u=n&&n.prototype instanceof c?n:c,s=Object.create(u.prototype);return H(s,"_invoke",function(r,n,a){var o,c,u,s=0,f=a||[],d=!1,l={p:0,n:0,v:e,a:p,f:p.bind(e,4),d:function(t,r){return o=t,c=0,u=e,l.n=r,i}};function p(r,n){for(c=r,u=n,t=0;!d&&s&&!a&&t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(H(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,H(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,H(d,"constructor",s),H(s,"constructor",u),u.displayName="GeneratorFunction",H(s,a,"GeneratorFunction"),H(d),H(d,a,"Generator"),H(d,n,function(){return this}),H(d,"toString",function(){return"[object Generator]"}),(F=function(){return{w:o,m:l}})()}function H(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}H=function(e,t,r,n){function o(t,r){H(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},H(e,t,r,n)}function Y(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r]*$',color:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",labelColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",backgroundColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",width:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",height:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",maxWidth:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",maxHeight:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",lineHeight:"^(\\d+(\\.\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$",boxShadow:"^(none|(\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)) ?(inset)?)$",textAlign:"^(left|right|center|justify|initial|inherit)$",overflowWrap:"^(normal|break-word|anywhere)$",wordWrap:"^(normal|break-word)$",resize:"^(none|both|horizontal|vertical|block|inline)$"};return Object.entries(e).forEach(function(e){var t=p(e,2),a=t[0],o=t[1],i=a.trim();if(0===i.length)throw new Error("css style property cannot be empty");var c=n[i];if(!c)throw new Error('invalid or unsupported css style property: "'.concat(i,'"'));var u=new RegExp(c),s=o.trim();if(0==s.length)throw new Error('css style for "'.concat(i,'" is empty'));if(!u.test(s))throw new Error('invalid css style value for property "'.concat(i,'"'));r[i]=s}),r},V=O,Q=function(e){return k.apply(this,arguments)},Z=T;function ee(){return(ee=J(F().m(function e(){return F().w(function(e){for(;;)switch(e.n){case 0:if(!V()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,q();case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function te(){return(te=J(F().m(function e(t,r,n){var a,i,c,u,s,f,d,l;return F().w(function(e){for(;;)switch(e.n){case 0:if(a={prod:"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569",preprod:"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212"},i=null,"undefined"!=typeof document&&(c=document.querySelector('meta[name="turnkey-signer-environment"]'))&&c.content&&"__TURNKEY_SIGNER_ENVIRONMENT__"!==c.content&&(i=c.content),i||"undefined"==typeof window||(i=window.__TURNKEY_SIGNER_ENVIRONMENT__),void 0!==(u=a[i])){e.n=1;break}throw new Error("Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined");case 1:if(t===u){e.n=2;break}throw new Error("enclave quorum public keys from client and bundle do not match. Client: ".concat(u,". Bundle: ").concat(t,"."));case 2:return s=new Uint8Array($(u)),e.n=3,Q(s);case 3:if(f=e.v){e.n=4;break}throw new Error("failed to load quorum key");case 4:return d=(0,o.g8)(r),l=$(n),e.n=5,crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},f,d,l);case 5:return e.a(2,e.v)}},e)}))).apply(this,arguments)}var re={initEmbeddedKey:function(){return ee.apply(this,arguments)},generateTargetKey:j,setItemWithExpiry:A,getItemWithExpiry:R,getEmbeddedKey:_,setEmbeddedKey:x,onResetEmbeddedKey:function(){window.localStorage.removeItem(m),window.localStorage.removeItem("TURNKEY_EMBEDDED_KEY_ORIGIN")},p256JWKPrivateToPublic:K,base58Encode:B,base58Decode:L,encodeKey:function(e,t,r){return G.apply(this,arguments)},sendMessageUp:function(e,t,r){var n={type:e,value:t};r&&(n.requestId=r),E?E.postMessage(n):window.parent!==window&&window.parent.postMessage({type:e,value:t},"*"),U("⬆️ Sent message ".concat(e,": ").concat(t))},logMessage:U,uint8arrayFromHexString:$,uint8arrayToHexString:N,setParentFrameMessageChannelPort:function(e){E=e},normalizePadding:function(e,t){var r=t-e.length;if(r>0){var n=new Uint8Array(r).fill(0);return new Uint8Array([].concat(l(n),l(e)))}if(r<0){for(var a=-1*r,o=0,i=0;i3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(se(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,se(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,se(d,"constructor",s),se(s,"constructor",u),u.displayName="GeneratorFunction",se(s,a,"GeneratorFunction"),se(d),se(d,a,"Generator"),se(d,n,function(){return this}),se(d,"toString",function(){return"[object Generator]"}),(ue=function(){return{w:o,m:l}})()}function se(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}se=function(e,t,r,n){function o(t,r){se(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},se(e,t,r,n)}function fe(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,a,o,i,c=[],u=!0,s=!1;try{if(o=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=o.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,a=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw a}}return c}}(e,t)||function(e,t){if(e){if("string"==typeof e)return de(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?de(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function de(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r= v2.0.0 to pass "organizationId" for security purposes.');case 8:if(a.organizationId&&a.organizationId===r){e.n=9;break}throw new Error("organization id does not match expected value. Expected: ".concat(r,". Found: ").concat(a.organizationId,"."));case 9:if(a.encappedPublic){e.n=10;break}throw new Error('missing "encappedPublic" in bundle signed data');case 10:if(a.ciphertext){e.n=11;break}throw new Error('missing "ciphertext" in bundle signed data');case 11:return e.a(2,a)}},e)}))).apply(this,arguments)}function we(e,t,r){return Ee.apply(this,arguments)}function Ee(){return Ee=pe(ue().m(function e(t,r,n){var a,o,i,c;return ue().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,me(t,r);case 1:return a=e.v,o=re.uint8arrayFromHexString(a.encappedPublic),i=re.uint8arrayFromHexString(a.ciphertext),e.n=2,re.getEmbeddedKey();case 2:return c=e.v,e.n=3,n({ciphertextBuf:i,encappedKeyBuf:o,receiverPrivJwk:c});case 3:return e.a(2,e.v)}},e)})),Ee.apply(this,arguments)}function Se(e){return Oe.apply(this,arguments)}function Oe(){return(Oe=pe(ue().m(function e(t){var r,n,a;return ue().w(function(e){for(;;)switch(e.n){case 0:if(r=re.getEmbeddedKey()){e.n=1;break}return re.sendMessageUp("EMBEDDED_PUBLIC_KEY","",t),e.a(2);case 1:return e.n=2,re.p256JWKPrivateToPublic(r);case 2:n=e.v,a=re.uint8arrayToHexString(n),re.sendMessageUp("EMBEDDED_PUBLIC_KEY",a,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function ke(e,t,r,n){return Pe.apply(this,arguments)}function Pe(){return(Pe=pe(ue().m(function e(t,r,n,a){var o,i,c,u,s,f;return ue().w(function(e){for(;;)switch(e.n){case 0:if(i=new Uint8Array(r),"SOLANA"!==n){e.n=2;break}return c=re.uint8arrayToHexString(i.subarray(0,32)),u=re.getEd25519PublicKey(c),e.n=1,re.encodeKey(i,n,u);case 1:o=e.v,e.n=4;break;case 2:return e.n=3,re.encodeKey(i,n);case 3:o=e.v;case 4:if(s=t||"default","SOLANA"!==n){e.n=5;break}f=ne.AX.fromSecretKey(re.base58Decode(o)),e.n=7;break;case 5:if("HEXADECIMAL"!==n){e.n=7;break}return e.n=6,ze(Array.from(re.uint8arrayFromHexString(o)));case 6:f=e.v;case 7:ye=ie(ie({},ye),{},ce({},s,{organizationId:a,privateKey:o,format:n,expiry:(new Date).getTime()+864e5,keypair:f}));case 8:return e.a(2)}},e)}))).apply(this,arguments)}function je(e,t,r,n,a,o){return Ie.apply(this,arguments)}function Ie(){return Ie=pe(ue().m(function e(t,r,n,a,o,i){var c;return ue().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,we(n,r,i);case 1:return c=e.v,e.n=2,ke(o,c,a,r);case 2:re.sendMessageUp("BUNDLE_INJECTED",!0,t);case 3:return e.a(2)}},e)})),Ie.apply(this,arguments)}function _e(e,t){return xe.apply(this,arguments)}function xe(){return(xe=pe(ue().m(function e(t,r){var n;return ue().w(function(e){for(;;)switch(e.n){case 0:n=re.applySettings(t),re.setSettings(n),re.sendMessageUp("SETTINGS_APPLIED",!0,r);case 1:return e.a(2)}},e)}))).apply(this,arguments)}function Te(e,t,r){return Ae.apply(this,arguments)}function Ae(){return(Ae=pe(ue().m(function e(t,r,n){var a,o,i,c,u,s,f,d,l;return ue().w(function(e){for(;;)switch(e.n){case 0:if($e(o=ye[a=n||"default"],a)){e.n=1;break}return e.a(2);case 1:return e.n=2,We(o);case 2:if(i=e.v,c=JSON.parse(r),u=c.transaction,"SOLANA"!==c.type){e.n=3;break}f=re.uint8arrayFromHexString(u),(d=ne.Kt.deserialize(f)).sign([i]),s=d.serialize(),e.n=4;break;case 3:throw new Error("unsupported transaction type");case 4:l=re.uint8arrayToHexString(s),re.sendMessageUp("TRANSACTION_SIGNED",l,t);case 5:return e.a(2)}},e)}))).apply(this,arguments)}function Re(e,t,r){return De.apply(this,arguments)}function De(){return De=pe(ue().m(function e(t,r,o){var i,c,u,s,f,d,l,p,y,v;return ue().w(function(e){for(;;)switch(e.n){case 0:if($e(c=ye[i=o||"default"],i)){e.n=1;break}return e.a(2);case 1:return u=JSON.parse(r),s=u.message,f=u.type,d=be.encode(s),e.n=2,We(c);case 2:if(p=e.v,"SOLANA"!==f){e.n=3;break}n.jn.sha512Sync=function(){var e;return a.Zf((e=n.jn).concatBytes.apply(e,arguments))},y=p.secretKey.slice(0,32),v=n._S(d,y),l=re.uint8arrayToHexString(v),e.n=4;break;case 3:return re.sendMessageUp("ERROR","unsupported message type",t),e.a(2);case 4:re.sendMessageUp("MESSAGE_SIGNED",l,t);case 5:return e.a(2)}},e)})),De.apply(this,arguments)}function Ne(e,t){return Me.apply(this,arguments)}function Me(){return(Me=pe(ue().m(function e(t,r){return ue().w(function(e){for(;;)switch(e.n){case 0:if(r){e.n=1;break}return ye={},re.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t),e.a(2);case 1:if(ye[r]){e.n=2;break}return re.sendMessageUp("ERROR",new Error("key not found for address ".concat(r,". Note that address is case sensitive.")).toString(),t),e.a(2);case 2:delete ye[r],re.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function Ue(e,t,r,n,a,o){return Ke.apply(this,arguments)}function Ke(){return Ke=pe(ue().m(function e(t,r,n,a,o,i){var c,u,s,f,d;return ue().w(function(e){for(;;)switch(e.n){case 0:if(o){e.n=1;break}throw new Error("address is required for STORE_ENCRYPTED_BUNDLE");case 1:return e.n=2,me(n,r);case 2:if(c=e.v,u=a||"HEXADECIMAL",re.setEncryptedBundle(o,{encappedPublic:c.encappedPublic,ciphertext:c.ciphertext,organizationId:r,keyFormat:u}),!ve||!i){e.n=4;break}return s=re.uint8arrayFromHexString(c.encappedPublic),f=re.uint8arrayFromHexString(c.ciphertext),e.n=3,i({ciphertextBuf:f,encappedKeyBuf:s,receiverPrivJwk:ve});case 3:return d=e.v,e.n=4,ke(o,d,u,r);case 4:re.sendMessageUp("ENCRYPTED_BUNDLE_STORED",!0,t);case 5:return e.a(2)}},e)})),Ke.apply(this,arguments)}function Ce(e){return Be.apply(this,arguments)}function Be(){return(Be=pe(ue().m(function e(t){var r,n,a;return ue().w(function(e){for(;;)switch(e.n){case 0:if(32===t.length){e.n=1;break}throw new Error("invalid decryption key length: expected 32 bytes, got ".concat(t.length));case 1:return r=new Uint8Array([48,65,2,1,0,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,4,39,48,37,2,1,1,4,32]),(n=new Uint8Array(r.length+32)).set(r),n.set(t,r.length),e.n=2,crypto.subtle.importKey("pkcs8",n,{name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return a=e.v,e.n=3,crypto.subtle.exportKey("jwk",a);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function Le(e,t,r,n){return Ge.apply(this,arguments)}function Ge(){return Ge=pe(ue().m(function e(t,r,n,a){var o,i,c,u,s,f,d,l,p,y,v,b,g,m;return ue().w(function(e){for(;;)switch(e.p=e.n){case 0:return e.n=1,we(n,r,a);case 1:return o=e.v,e.n=2,Ce(new Uint8Array(o));case 2:if(i=e.v,ve=i,c=re.getEncryptedBundles(),u=0,!c){e.n=10;break}s=Object.keys(c),f=0,d=s;case 3:if(!(f=e.expiry)throw function(){for(var e=(new Date).getTime(),t=[],r=0,n=Object.entries(ye);r=i.expiry&&t.push(o)}for(var c=0,u=t;c3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(tt(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,tt(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,tt(d,"constructor",s),tt(s,"constructor",u),u.displayName="GeneratorFunction",tt(s,a,"GeneratorFunction"),tt(d),tt(d,a,"Generator"),tt(d,n,function(){return this}),tt(d,"toString",function(){return"[object Generator]"}),(et=function(){return{w:o,m:l}})()}function tt(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}tt=function(e,t,r,n){function o(t,r){tt(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},tt(e,t,r,n)}function rt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function nt(e){for(var t=1;t3?(a=y===n)&&(u=o[(c=o[4])?5:(c=3,3)],o[4]=o[5]=e):o[0]<=p&&((a=r<2&&pn||n>y)&&(o[4]=r,o[5]=n,l.n=y,c=0))}if(a||r>1)return i;throw d=!0,n}return function(a,f,y){if(s>1)throw TypeError("Generator is already running");for(d&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!d;){o||(c?c<3?(c>1&&(l.n=-1),p(c,u)):l.n=u:l.v=u);try{if(s=2,o){if(c||(a="next"),t=o[a]){if(!(t=t.call(o,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=o.return)&&t.call(o),c<2&&(u=TypeError("The iterator does not provide a '"+a+"' method"),c=1);o=e}else if((t=(d=l.n<0)?u:r.call(n,l))!==i)break}catch(t){o=e,c=1,u=t}finally{s=1}}return{value:t,done:d}}}(r,a,o),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(ft(t={},n,function(){return this}),t),d=s.prototype=c.prototype=Object.create(f);function l(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,ft(e,a,"GeneratorFunction")),e.prototype=Object.create(d),e}return u.prototype=s,ft(d,"constructor",s),ft(s,"constructor",u),u.displayName="GeneratorFunction",ft(s,a,"GeneratorFunction"),ft(d),ft(d,a,"Generator"),ft(d,n,function(){return this}),ft(d,"toString",function(){return"[object Generator]"}),(st=function(){return{w:o,m:l}})()}function ft(e,t,r,n){var a=Object.defineProperty;try{a({},"",{})}catch(e){a=0}ft=function(e,t,r,n){function o(t,r){ft(e,t,function(e){return this._invoke(t,r,e)})}t?a?a(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(o("next",0),o("throw",1),o("return",2))},ft(e,t,r,n)}function dt(e,t,r,n,a,o,i){try{var c=e[o](i),u=c.value}catch(e){return void r(e)}c.done?t(u):Promise.resolve(u).then(n,a)}function lt(e){return function(){var t=this,r=arguments;return new Promise(function(n,a){var o=e.apply(t,r);function i(e){dt(o,n,a,i,c,"next",e)}function c(e){dt(o,n,a,i,c,"throw",e)}i(void 0)})}}window.TKHQ=re,document.addEventListener("DOMContentLoaded",lt(st().m(function e(){var t,r,n,a;return st().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,re.initEmbeddedKey();case 1:return e.n=2,re.getEmbeddedKey();case 2:return t=e.v,e.n=3,re.p256JWKPrivateToPublic(t);case 3:r=e.v,n=re.uint8arrayToHexString(r),document.getElementById("embedded-key").value=n,Ve(ct),(a=re.getSettings())&&re.applySettings(a),re.sendMessageUp("PUBLIC_KEY_READY",n);case 4:return e.a(2)}},e)})))},790:()=>{},846:e=>{"use strict";e.exports=crypto}},i={};function c(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={id:e,loaded:!1,exports:{}};return o[e].call(r.exports,r,r.exports,c),r.loaded=!0,r.exports}c.m=o,e=[],c.O=(t,r,n,a)=>{if(!r){var o=1/0;for(f=0;f=a)&&Object.keys(c.O).every(e=>c.O[e](r[u]))?r.splice(u--,1):(i=!1,a0&&e[f-1][2]>a;f--)e[f]=e[f-1];e[f]=[r,n,a]},c.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return c.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,c.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var a=Object.create(null);c.r(a);var o={};t=t||[null,r({}),r([]),r(r)];for(var i=2&n&&e;("object"==typeof i||"function"==typeof i)&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach(t=>o[t]=()=>e[t]);return o.default=()=>e,c.d(a,o),a},c.d=(e,t)=>{for(var r in t)c.o(t,r)&&!c.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},c.f={},c.e=e=>Promise.all(Object.keys(c.f).reduce((t,r)=>(c.f[r](e,t),t),[])),c.u=e=>"bundle."+{291:"3eaea85f4001b9cc63c3",825:"aaba32bf7338e3d0f1cc"}[e]+".js",c.miniCssF=e=>{},c.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),c.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},a="export-and-sign:",c.l=(e,t,r,o)=>{if(n[e])n[e].push(t);else{var i,u;if(void 0!==r)for(var s=document.getElementsByTagName("script"),f=0;f{i.onerror=i.onload=null,clearTimeout(p);var a=n[e];if(delete n[e],i.parentNode&&i.parentNode.removeChild(i),a&&a.forEach(e=>e(r)),t)return t(r)},p=setTimeout(l.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=l.bind(null,i.onerror),i.onload=l.bind(null,i.onload),u&&document.head.appendChild(i)}},c.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),c.p="/",c.sriHashes={291:"sha384-G5pDFEAG9UZITbluyje/R/rWohZTUJf+Vu3ZIh0rsnLFLTw3SP/ca/XVNZVtv48f",825:"sha384-R9OIdd42i5GcdtZiHJuQgIUVvqyqJ0s7eaBnJHAfGllpi4YwbF7NSkjIRwOPUtsP"},(()=>{var e={792:0};c.f.j=(t,r)=>{var n=c.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[2]);else{var a=new Promise((r,a)=>n=e[t]=[r,a]);r.push(n[2]=a);var o=c.p+c.u(t),i=new Error;c.l(o,r=>{if(c.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var a=r&&("load"===r.type?"missing":r.type),o=r&&r.target&&r.target.src;i.message="Loading chunk "+t+" failed.\n("+a+": "+o+")",i.name="ChunkLoadError",i.type=a,i.request=o,n[1](i)}},"chunk-"+t,t)}},c.O.j=t=>0===e[t];var t=(t,r)=>{var n,a,[o,i,u]=r,s=0;if(o.some(t=>0!==e[t])){for(n in i)c.o(i,n)&&(c.m[n]=i[n]);if(u)var f=u(c)}for(t&&t(r);sc(560));u=c.O(u)})(); -//# sourceMappingURL=bundle.801fe7bbee4484b5f44c.js.map \ No newline at end of file diff --git a/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.map b/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.map deleted file mode 100644 index b027639..0000000 --- a/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,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ASkE,KAAMtE,GAAgC,IAAxB2D,EAAgB3D,IAAa,CACtD,IAAIF,KAAYsE,EACZvE,EAAoBliB,EAAEymB,EAAatE,KACrCD,EAAoBlgB,EAAEmgB,GAAYsE,EAAYtE,IAGhD,GAAGuE,EAAS,IAAItc,EAASsc,EAAQxE,EAClC,CAEA,IADGsE,GAA4BA,EAA2Bzf,GACrD7G,EAAIuiB,EAASvhB,OAAQhB,IACzB0jB,EAAUnB,EAASviB,GAChBgiB,EAAoBliB,EAAEgmB,EAAiBpC,IAAYoC,EAAgBpC,IACrEoC,EAAgBpC,GAAS,KAE1BoC,EAAgBpC,GAAW,EAE5B,OAAO1B,EAAoBM,EAAEpY,IAG1Bwc,EAAqBC,KAAkC,4BAAIA,KAAkC,6BAAK,GACtGD,EAAmBnZ,QAAQ8Y,EAAqBtlB,KAAK,KAAM,IAC3D2lB,EAAmB1jB,KAAOqjB,EAAqBtlB,KAAK,KAAM2lB,EAAmB1jB,KAAKjC,KAAK2lB,G,KClFvF,IAAIE,EAAsB5E,EAAoBM,OAAE1d,EAAW,CAAC,IAAK,IAAOod,EAAoB,MAC5F4E,EAAsB5E,EAAoBM,EAAEsE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/../shared/turnkey-core.js","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/../shared/crypto-utils.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/external var \"crypto\"","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/global","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/compat","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t\tif (script.src.indexOf(window.location.origin + '/') !== 0) {\n\t\t\tscript.crossOrigin = \"anonymous\";\n\t\t}\n\t\tscript.integrity = __webpack_require__.sriHashes[chunkId];\n\t\tscript.crossOrigin = \"anonymous\";\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n if (!data) {\n return null;\n }\n try {\n return JSON.parse(data);\n } catch (e) {\n // If the stored data is corrupted or not valid JSON, remove it to self-heal.\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n return null;\n }\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * Only removes the bundle if it belongs to the specified organization.\n * @param {string} address - The wallet address to remove\n * @param {string} organizationId - Only remove if the bundle belongs to this org\n */\nfunction removeEncryptedBundle(address, organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles || !bundles[address]) return;\n\n // Only remove if the bundle belongs to the specified organization\n if (bundles[address].organizationId !== organizationId) return;\n\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n}\n\n/**\n * Removes all encrypted bundles belonging to the specified organization.\n * Bundles from other organizations are preserved.\n * @param {string} organizationId - Remove bundles belonging to this org\n */\nfunction clearAllEncryptedBundles(organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles) return;\n\n // Keep only bundles that do NOT belong to this organization\n const remaining = Object.fromEntries(\n Object.entries(bundles).filter(\n ([, bundle]) => bundle.organizationId !== organizationId\n )\n );\n\n if (Object.keys(remaining).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(remaining)\n );\n }\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\nimport { fromDerSignature } from \"@turnkey/crypto\";\nimport * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n initEmbeddedKey: sharedInitEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n additionalAssociatedData,\n getSettings,\n setSettings,\n parsePrivateKey,\n validateStyles,\n isDoublyIframed,\n loadQuorumKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n} = SharedTKHQ;\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n return await sharedInitEmbeddedKey();\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Read environment from meta tag (templated at deploy time), fall back to window variable (for testing)\n let environment = null;\n if (typeof document !== \"undefined\") {\n const meta = document.querySelector(\n 'meta[name=\"turnkey-signer-environment\"]'\n );\n if (\n meta &&\n meta.content &&\n meta.content !== \"__TURNKEY_SIGNER_ENVIRONMENT__\"\n ) {\n environment = meta.content;\n }\n }\n if (!environment && typeof window !== \"undefined\") {\n environment = window.__TURNKEY_SIGNER_ENVIRONMENT__;\n }\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\n// Decryption key -- held in memory only, never persisted to localStorage.\n// This is a P-256 private key in JWK format used to decrypt stored bundles.\nlet decryptionKey = null;\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Verifies the enclave signature on a v1.0.0 bundle and returns the parsed signed data.\n * @param {string} bundle - JSON-stringified bundle\n * @param {string} organizationId - Expected organization ID\n * @returns {Promise} - The parsed signed data {organizationId, encappedPublic, ciphertext}\n */\nasync function verifyAndParseBundleData(bundle, organizationId) {\n const bundleObj = JSON.parse(bundle);\n\n if (bundleObj.version !== \"v1.0.0\") {\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n const verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(\n `failed to verify enclave signature: ${bundleObj.dataSignature}`\n );\n }\n\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n\n return signedData;\n}\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n // Decrypt the ciphertext\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: embeddedKeyJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Encodes raw key bytes and loads them into the in-memory key store.\n * @param {string} address - Wallet address (case-sensitive)\n * @param {ArrayBuffer} keyBytes - Raw decrypted private key bytes\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} organizationId - Organization ID\n */\nasync function loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId) {\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair,\n },\n };\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Load decrypted key into memory\n await loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId);\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Set up sha512 for nobleEd25519 (required for signing)\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n\n // Extract the 32-byte private key from the 64-byte secretKey\n // Solana keypair.secretKey format: [32-byte private key][32-byte public key]\n const privateKey = keypair.secretKey.slice(0, 32);\n // Sign the message using nobleEd25519\n const signature = nobleEd25519.sign(messageBytes, privateKey);\n\n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n/**\n * Handler for STORE_ENCRYPTED_BUNDLE events.\n * Verifies the enclave signature on an encrypted bundle and stores\n * the encrypted payload in localStorage for later decryption.\n * If the decryption key is already in memory, also decrypts and loads\n * the key into memory immediately.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle JSON\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} address - Wallet address\n * @param {Function} HpkeDecrypt\n */\nasync function onStoreEncryptedBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n if (!address) {\n throw new Error(\"address is required for STORE_ENCRYPTED_BUNDLE\");\n }\n\n // Verify enclave signature and parse the signed data\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const resolvedKeyFormat = keyFormat || \"HEXADECIMAL\";\n\n // Store the encrypted fields in localStorage (just what's needed for decryption)\n TKHQ.setEncryptedBundle(address, {\n encappedPublic: signedData.encappedPublic,\n ciphertext: signedData.ciphertext,\n organizationId: organizationId,\n keyFormat: resolvedKeyFormat,\n });\n\n // If the decryption key is already in memory, decrypt and load immediately\n if (decryptionKey && HpkeDecrypt) {\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n const keyBytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n await loadKeyIntoMemory(\n address,\n keyBytes,\n resolvedKeyFormat,\n organizationId\n );\n }\n\n TKHQ.sendMessageUp(\"ENCRYPTED_BUNDLE_STORED\", true, requestId);\n}\n\n/**\n * Converts raw P-256 private key bytes (32-byte scalar) to a JWK.\n * Constructs a PKCS8 wrapper around the raw bytes, imports via WebCrypto\n * (which derives the public key), then exports as JWK.\n * @param {Uint8Array} rawPrivateKeyBytes - 32-byte P-256 private key scalar\n * @returns {Promise} - Full P-256 ECDH private key JWK\n */\nasync function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) {\n if (rawPrivateKeyBytes.length !== 32) {\n throw new Error(\n `invalid decryption key length: expected 32 bytes, got ${rawPrivateKeyBytes.length}`\n );\n }\n\n // Fixed PKCS#8 DER prefix for a P-256 private key (36 bytes).\n // This wraps a raw 32-byte scalar into the PrivateKeyInfo structure\n // that WebCrypto's importKey(\"pkcs8\", ...) expects.\n //\n // Structure (per RFC 5958 §2 / RFC 5208 §5):\n // SEQUENCE {\n // INTEGER 0 -- version (v1)\n // SEQUENCE { -- AlgorithmIdentifier (RFC 5480 §2.1.1)\n // OID 1.2.840.10045.2.1 -- id-ecPublicKey\n // OID 1.2.840.10045.3.1.7 -- secp256r1 (P-256)\n // }\n // OCTET STRING { -- privateKey (SEC 1 §C.4 / RFC 5915 §3)\n // SEQUENCE {\n // INTEGER 1 -- version\n // OCTET STRING (32 bytes) -- raw private key scalar\n // }\n // }\n // }\n //\n // References:\n // - RFC 5958 / RFC 5208: PKCS#8 PrivateKeyInfo\n // - RFC 5480 §2.1.1: ECC AlgorithmIdentifier (OIDs)\n // - RFC 5915 / SEC 1 v2 §C.4: ECPrivateKey encoding\n const pkcs8Prefix = new Uint8Array([\n 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48,\n 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03,\n 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20,\n ]);\n\n const pkcs8 = new Uint8Array(pkcs8Prefix.length + 32);\n pkcs8.set(pkcs8Prefix);\n pkcs8.set(rawPrivateKeyBytes, pkcs8Prefix.length);\n\n const cryptoKey = await crypto.subtle.importKey(\n \"pkcs8\",\n pkcs8,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"]\n );\n\n return await crypto.subtle.exportKey(\"jwk\", cryptoKey);\n}\n\n/**\n * Handler for INJECT_DECRYPTION_KEY_BUNDLE events.\n * Decrypts the P-256 private key using the iframe's embedded key,\n * then iterates all stored encrypted bundles, HPKE-decrypts each one\n * with the key, and loads them into inMemoryKeys.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle containing the private key\n * @param {Function} HpkeDecrypt\n */\nasync function onInjectDecryptionKeyBundle(\n requestId,\n organizationId,\n bundle,\n HpkeDecrypt\n) {\n // Decrypt the private key using the iframe's embedded key.\n // The decrypted payload is a raw 32-byte P-256 private key scalar.\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto)\n const keyJwk = await rawP256PrivateKeyToJwk(new Uint8Array(keyBytes));\n\n // Store in module-level variable (memory only)\n decryptionKey = keyJwk;\n\n // Iterate all stored encrypted bundles and decrypt each one\n const storedBundles = TKHQ.getEncryptedBundles();\n let decryptedCount = 0;\n\n if (storedBundles) {\n const addresses = Object.keys(storedBundles);\n\n for (const addr of addresses) {\n const bundleData = storedBundles[addr];\n\n try {\n const bundleOrgId = bundleData.organizationId;\n\n if (organizationId !== bundleOrgId) continue; // skip bundles that don't match the organization ID of the decryption key\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n bundleData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(\n bundleData.ciphertext\n );\n\n // HPKE-decrypt using the key\n const bytes = await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk: decryptionKey,\n });\n\n // Load the decrypted key into memory\n await loadKeyIntoMemory(\n addr,\n bytes,\n bundleData.keyFormat,\n bundleData.organizationId\n );\n\n decryptedCount++;\n } catch (e) {\n TKHQ.logMessage(\n `Failed to decrypt bundle for address ${addr}: ${e.toString()}`\n );\n }\n }\n }\n\n TKHQ.sendMessageUp(\"DECRYPTION_KEY_INJECTED\", decryptedCount, requestId);\n}\n\n/**\n * Handler for BURN_SESSION events.\n * Clears the decryption key and all in-memory wallet keys.\n * Encrypted bundles in localStorage are preserved for the next session.\n * @param {string} requestId\n */\nfunction onBurnSession(requestId) {\n decryptionKey = null;\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"SESSION_BURNED\", true, requestId);\n}\n\n/**\n * Handler for GET_STORED_WALLET_ADDRESSES events.\n * Returns a JSON array of all wallet addresses that have encrypted bundles in localStorage.\n * @param {string} requestId\n * @param {string} organizationId - Organization ID to filter addresses by (only return addresses with bundles matching the organization ID)\n */\nfunction onGetStoredWalletAddresses(requestId, organizationId) {\n const bundles = TKHQ.getEncryptedBundles();\n const addresses = bundles\n ? Object.entries(bundles)\n .filter(([, bundle]) => bundle.organizationId === organizationId)\n .map(([address]) => address)\n : [];\n TKHQ.sendMessageUp(\n \"STORED_WALLET_ADDRESSES\",\n JSON.stringify(addresses),\n requestId\n );\n}\n\n/**\n * Handler for CLEAR_STORED_BUNDLES events.\n * Removes encrypted bundles from localStorage AND the corresponding\n * in-memory keys. If address is provided, removes only that address.\n * If no address, removes ALL encrypted bundles and ALL in-memory keys.\n * @param {string} requestId\n * @param {string} organizationId - Organization ID to filter addresses by (only remove bundles matching the organization ID)\n * @param {string|undefined} address - Optional wallet address\n */\nfunction onClearStoredBundles(requestId, address, organizationId) {\n if (address) {\n TKHQ.removeEncryptedBundle(address, organizationId);\n delete inMemoryKeys[address];\n } else {\n TKHQ.clearAllEncryptedBundles(organizationId);\n inMemoryKeys = {};\n }\n TKHQ.sendMessageUp(\"STORED_BUNDLES_CLEARED\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error(\n `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`\n ).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n undefined, // keyFormat - default to HEXADECIMAL\n undefined, // address - default to \"default\"\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"STORE_ENCRYPTED_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n await onStoreEncryptedBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_DECRYPTION_KEY_BUNDLE\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onInjectDecryptionKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"BURN_SESSION\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onBurnSession(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_STORED_WALLET_ADDRESSES\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onGetStoredWalletAddresses(\n event.data[\"requestId\"],\n event.data[\"organizationId\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_STORED_BUNDLES\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: address=${event.data[\"address\"]}`\n );\n try {\n onClearStoredBundles(\n event.data[\"requestId\"],\n event.data[\"address\"],\n event.data[\"organizationId\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n onStoreEncryptedBundle,\n onInjectDecryptionKeyBundle,\n onBurnSession,\n onGetStoredWalletAddresses,\n onClearStoredBundles,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"@shared/crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n","module.exports = crypto;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","\n__webpack_require__.sriHashes = {\"291\":\"*-*-*-CHUNK-SRI-HASH-r3NPGwA4ft5fHgGXhVIptCiDVf06qPa+sxzG6L+8GwPuhn89e/\",\"825\":\"*-*-*-CHUNK-SRI-HASH-mfog3UJdGPOmSk4QZbKxsxHPFZtt298WnZNc1aQ1MCgc6YirFj\"};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(560)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","_slicedToArray","_arrayWithHoles","next","push","_iterableToArrayLimit","_nonIterableRest","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","TURNKEY_ENCRYPTED_BUNDLES","parentFrameMessageChannelPort","getSubtleCrypto","globalThis","crypto","subtle","window","global","isDoublyIframed","undefined","location","ancestorOrigins","parent","top","_loadQuorumKey","_callee","quorumPublic","_context","Error","importKey","namedCurve","_initEmbeddedKey","_callee3","_context3","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee4","p256key","_context4","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","getEncryptedBundles","data","localStorage","getItem","removeItem","key","ttl","item","expiry","Date","getTime","setItem","itemStr","hasOwnProperty","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","concat","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","p256JWKPrivateToPublic","_x6","_p256JWKPrivateToPublic","_callee6","jwkPrivate","jwkPrivateCopy","publicKey","_context6","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","k","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee9","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_t2","_context9","set","console","warn","sharedInitEmbeddedKey","SharedTKHQ","validateStyles","styles","element","validStyles","cssValidationRegex","padding","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref3","_ref4","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","loadQuorumKey","_x","_verifyEnclaveSignature","_callee2","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","meta","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context2","prod","preprod","querySelector","__TURNKEY_SIGNER_ENVIRONMENT__","fromDerSignature","verify","hash","TKHQ","initEmbeddedKey","onResetEmbeddedKey","encodeKey","_x0","_x1","_x10","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","normalizePadding","byteArray","targetLength","paddingLength","fill","expectedZeroCount","zeroCount","verifyEnclaveSignature","_x2","_x3","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","_ref","_ref2","style","getSettings","setSettings","parsePrivateKey","error","setEncryptedBundle","address","bundleData","bundles","removeEncryptedBundle","organizationId","keys","clearAllEncryptedBundles","remaining","fromEntries","filter","inMemoryKeys","decryptionKey","textEncoder","TextEncoder","textDecoder","TextDecoder","verifyAndParseBundleData","_verifyAndParseBundleData","_callee8","bundle","bundleObj","_context8","version","dataSignature","decode","encappedPublic","ciphertext","decryptBundle","_x4","_x5","_decryptBundle","HpkeDecrypt","encappedKeyBuf","ciphertextBuf","embeddedKeyJwk","receiverPrivJwk","onGetPublicEmbeddedKey","_onGetPublicEmbeddedKey","_callee0","targetPubBuf","targetPubHex","_context0","loadKeyIntoMemory","_x7","_x8","_x9","_loadKeyIntoMemory","_callee1","keyBytes","keyAddress","cachedKeypair","_context1","subarray","Keypair","fromSecretKey","createSolanaKeypair","_defineProperty","format","keypair","onInjectKeyBundle","_x11","_x12","_x13","_x14","_onInjectKeyBundle","_callee10","_context10","onApplySettings","_x15","_x16","_onApplySettings","_callee11","_context11","onSignTransaction","_x17","_x18","_x19","_onSignTransaction","_callee12","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context12","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x20","_x21","_x22","_onSignMessage","_callee13","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context13","encode","secretKey","onClearEmbeddedPrivateKey","_x23","_x24","_onClearEmbeddedPrivateKey","_callee14","_context14","onStoreEncryptedBundle","_x25","_x26","_x27","_x28","_x29","_x30","_onStoreEncryptedBundle","_callee15","resolvedKeyFormat","_context15","rawP256PrivateKeyToJwk","_x31","_rawP256PrivateKeyToJwk","_callee16","rawPrivateKeyBytes","pkcs8Prefix","pkcs8","cryptoKey","_context16","onInjectDecryptionKeyBundle","_x32","_x33","_x34","_x35","_onInjectDecryptionKeyBundle","_callee17","keyJwk","storedBundles","decryptedCount","addresses","_i3","_addresses","addr","bundleOrgId","_t0","_context17","onBurnSession","onGetStoredWalletAddresses","onClearStoredBundles","_x36","_createSolanaKeypair","_callee18","_context18","fromSeed","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x37","_getOrCreateKeypair","_callee19","_context19","initEventHandlers","messageEventListener","_messageEventListener","event","_t","_t3","_t4","_t5","_t6","_t7","_t8","_t9","_x43","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","_ref5","preventDefault","_x38","_ref6","_x39","_ref7","_x40","_ref8","_x41","injectWalletBtn","_ref9","_callee5","_context5","_x42","addDOMEventListeners","capture","signal","_ref0","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x44","ownKeys","getOwnPropertySymbols","getOwnPropertyDescriptor","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","_HpkeDecrypt","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","styleSettings","module","exports","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","g","Function","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","crossOrigin","integrity","sriHashes","onScriptComplete","prev","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/dist/bundle.dd09773f50e375d9ca7e.js b/export-and-sign/dist/bundle.dd09773f50e375d9ca7e.js new file mode 100644 index 0000000..c86ea77 --- /dev/null +++ b/export-and-sign/dist/bundle.dd09773f50e375d9ca7e.js @@ -0,0 +1,3 @@ +/*! For license information please see bundle.dd09773f50e375d9ca7e.js.LICENSE.txt */ +(()=>{var e,t,r,n,o,a={560:(e,t,r)=>{"use strict";var n=r(598),o=r(443),a=r(566);function i(e){return i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},i(e)}function c(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function u(e){for(var t=1;t3?(o=y===n)&&(u=a[(c=a[4])?5:(c=3,3)],a[4]=a[5]=e):a[0]<=p&&((o=r<2&&pn||n>y)&&(a[4]=r,a[5]=n,d.n=y,c=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){a||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,a){if(c||(o="next"),t=a[o]){if(!(t=t.call(a,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=a.return)&&t.call(a),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);a=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){a=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var d=[][n]?t(t([][n]())):(l(t={},n,function(){return this}),t),p=s.prototype=c.prototype=Object.create(d);function y(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,l(e,o,"GeneratorFunction")),e.prototype=Object.create(p),e}return u.prototype=s,l(p,"constructor",s),l(s,"constructor",u),u.displayName="GeneratorFunction",l(s,o,"GeneratorFunction"),l(p),l(p,o,"Generator"),l(p,n,function(){return this}),l(p,"toString",function(){return"[object Generator]"}),(f=function(){return{w:a,m:y}})()}function l(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}l=function(e,t,r,n){function a(t,r){l(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},l(e,t,r,n)}function d(e){return function(e){if(Array.isArray(e))return y(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||p(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(e,t){if(e){if("string"==typeof e)return y(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?y(e,t):void 0}}function y(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r1:window.parent!==window.top}function S(){return(S=b(f().m(function e(t){var r;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=w()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,r.importKey("raw",t,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function O(){return(O=b(f().m(function e(){return f().w(function(e){for(;;)switch(e.n){case 0:if(!E()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,P();case 2:if(null!==e.v){e.n=4;break}return e.n=3,k();case 3:_(e.v);case 4:return e.a(2)}},e)}))).apply(this,arguments)}function k(){return j.apply(this,arguments)}function j(){return(j=b(f().m(function e(){var t,r;return f().w(function(e){for(;;)switch(e.n){case 0:if(t=w()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return e.n=2,t.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return r=e.v,e.n=3,t.exportKey("jwk",r.privateKey);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function P(){var e=T(m);return e?JSON.parse(e):null}function _(e){x(m,JSON.stringify(e),1728e5)}function x(e,t,r){var n={value:t,expiry:(new Date).getTime()+r};window.localStorage.setItem(e,JSON.stringify(n))}function T(e){var t=window.localStorage.getItem(e);if(!t)return null;var r=JSON.parse(t);return Object.prototype.hasOwnProperty.call(r,"expiry")&&Object.prototype.hasOwnProperty.call(r,"value")?(new Date).getTime()>r.expiry?(window.localStorage.removeItem(e),null):r.value:(window.localStorage.removeItem(e),null)}function I(e){if(!e||"string"!=typeof e)throw new Error("cannot create uint8array from invalid hex string");var t=e.startsWith("0x")||e.startsWith("0X")?e.slice(2):e;if(t.length%2!=0||!/^[0-9A-Fa-f]+$/.test(t))throw new Error("cannot create uint8array from invalid hex string");return new Uint8Array(t.match(/../g).map(function(e){return parseInt(e,16)}))}function A(e){return d(e).map(function(e){return e.toString(16).padStart(2,"0")}).join("")}function D(e,t){var r=Array.from(new Uint8Array(e)),n=Array.from(new Uint8Array(t));return new Uint8Array([].concat(r,n))}function R(e){var t=document.getElementById("message-log");if(t){var r=document.createElement("p");r.innerText=e,t.appendChild(r)}}function N(e){return M.apply(this,arguments)}function M(){return(M=b(f().m(function e(t){var r,n,o,a;return f().w(function(e){for(;;)switch(e.n){case 0:if(r=w()){e.n=1;break}throw new Error("WebCrypto subtle API is unavailable");case 1:return delete(n=u({},t)).d,n.key_ops=["verify"],e.n=2,r.importKey("jwk",n,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]);case 2:return o=e.v,e.n=3,r.exportKey("raw",o);case 3:return a=e.v,e.a(2,new Uint8Array(a))}},e)}))).apply(this,arguments)}function K(e){for(var t="",r=[0],n=0;n0;)r.push(o%58),o=o/58|0}for(var i=0;i0;){var c=r[i];a=(c=void 0===c?a:58*c+a)>>8,r[i]=c%256,i++}}var u=n.concat(r.reverse());return new Uint8Array(u)}function C(){return(C=b(f().m(function e(t,r,n){var o,a;return f().w(function(e){for(;;)switch(e.n){case 0:a=r,e.n="SOLANA"===a?1:"HEXADECIMAL"===a?5:6;break;case 1:if(n){e.n=2;break}throw new Error("public key must be specified for SOLANA key format");case 2:if(32===t.length){e.n=3;break}throw new Error("invalid private key length. Expected 32 bytes. Got ".concat(t.length,"."));case 3:if(32===n.length){e.n=4;break}throw new Error("invalid public key length. Expected 32 bytes. Got ".concat(n.length,"."));case 4:return(o=new Uint8Array(64)).set(t,0),o.set(n,32),e.a(2,K(o));case 5:return e.a(2,"0x"+A(t));case 6:return console.warn("invalid key format: ".concat(r,". Defaulting to HEXADECIMAL.")),e.a(2,"0x"+A(t));case 7:return e.a(2)}},e)}))).apply(this,arguments)}function G(){var e,t,r="function"==typeof Symbol?Symbol:{},n=r.iterator||"@@iterator",o=r.toStringTag||"@@toStringTag";function a(r,n,o,a){var u=n&&n.prototype instanceof c?n:c,s=Object.create(u.prototype);return B(s,"_invoke",function(r,n,o){var a,c,u,s=0,f=o||[],l=!1,d={p:0,n:0,v:e,a:p,f:p.bind(e,4),d:function(t,r){return a=t,c=0,u=e,d.n=r,i}};function p(r,n){for(c=r,u=n,t=0;!l&&s&&!o&&t3?(o=y===n)&&(u=a[(c=a[4])?5:(c=3,3)],a[4]=a[5]=e):a[0]<=p&&((o=r<2&&pn||n>y)&&(a[4]=r,a[5]=n,d.n=y,c=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){a||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,a){if(c||(o="next"),t=a[o]){if(!(t=t.call(a,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=a.return)&&t.call(a),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);a=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){a=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(B(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,B(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,B(l,"constructor",s),B(s,"constructor",u),u.displayName="GeneratorFunction",B(s,o,"GeneratorFunction"),B(l),B(l,o,"Generator"),B(l,n,function(){return this}),B(l,"toString",function(){return"[object Generator]"}),(G=function(){return{w:a,m:d}})()}function B(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}B=function(e,t,r,n){function a(t,r){B(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},B(e,t,r,n)}function L(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r]*$',color:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",labelColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",backgroundColor:"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)|hsla?\\(\\d{1,3}, \\d{1,3}%, \\d{1,3}%(, \\d?(\\.\\d{1,2})?)?\\))$",width:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",height:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$",maxWidth:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",maxHeight:"^(\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$",lineHeight:"^(\\d+(\\.\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$",boxShadow:"^(none|(\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\(\\d{1,3}, \\d{1,3}, \\d{1,3}(, \\d?(\\.\\d{1,2})?)?\\)) ?(inset)?)$",textAlign:"^(left|right|center|justify|initial|inherit)$",overflowWrap:"^(normal|break-word|anywhere)$",wordWrap:"^(normal|break-word)$",resize:"^(none|both|horizontal|vertical|block|inline)$"};return Object.entries(e).forEach(function(e){var t,o,a=(o=2,function(e){if(Array.isArray(e))return e}(t=e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,a,i,c=[],u=!0,s=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=a.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,o=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw o}}return c}}(t,o)||p(t,o)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),i=a[0],c=a[1],u=i.trim();if(0===u.length)throw new Error("css style property cannot be empty");var s=n[u];if(!s)throw new Error('invalid or unsupported css style property: "'.concat(u,'"'));var f=new RegExp(s),l=c.trim();if(0==l.length)throw new Error('css style for "'.concat(u,'" is empty'));if(!f.test(l))throw new Error('invalid css style value for property "'.concat(u,'"'));r[u]=l}),r},$=E,W=function(e){return S.apply(this,arguments)};function X(){return(X=H(G().m(function e(){return G().w(function(e){for(;;)switch(e.n){case 0:if(!$()){e.n=1;break}throw new Error("Doubly iframed");case 1:return e.n=2,Y();case 2:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function V(){return(V=H(G().m(function e(t,r,n){var o,i,c,u,s,f,l,d;return G().w(function(e){for(;;)switch(e.n){case 0:if(o={prod:"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569",preprod:"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212"},i=null,"undefined"!=typeof document&&(c=document.querySelector('meta[name="turnkey-signer-environment"]'))&&c.content&&"__TURNKEY_SIGNER_ENVIRONMENT__"!==c.content&&(i=c.content),i||"undefined"==typeof window||(i=window.__TURNKEY_SIGNER_ENVIRONMENT__),void 0!==(u=o[i])){e.n=1;break}throw new Error("Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined");case 1:if(t===u){e.n=2;break}throw new Error("enclave quorum public keys from client and bundle do not match. Client: ".concat(u,". Bundle: ").concat(t,"."));case 2:return s=new Uint8Array(J(u)),e.n=3,W(s);case 3:if(f=e.v){e.n=4;break}throw new Error("failed to load quorum key");case 4:return l=(0,a.g8)(r),d=J(n),e.n=5,crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},f,l,d);case 5:return e.a(2,e.v)}},e)}))).apply(this,arguments)}var Q={initEmbeddedKey:function(){return X.apply(this,arguments)},generateTargetKey:k,setItemWithExpiry:x,getItemWithExpiry:T,getEmbeddedKey:P,setEmbeddedKey:_,onResetEmbeddedKey:function(){window.localStorage.removeItem(m),window.localStorage.removeItem("TURNKEY_EMBEDDED_KEY_ORIGIN")},p256JWKPrivateToPublic:N,base58Encode:K,base58Decode:U,encodeKey:function(e,t,r){return C.apply(this,arguments)},sendMessageUp:function(e,t,r){var n={type:e,value:t};r&&(n.requestId=r),h?h.postMessage(n):window.parent!==window&&window.parent.postMessage({type:e,value:t},"*"),R("⬆️ Sent message ".concat(e,": ").concat(t))},logMessage:R,uint8arrayFromHexString:J,uint8arrayToHexString:A,setParentFrameMessageChannelPort:function(e){h=e},normalizePadding:function(e,t){var r=t-e.length;if(r>0){var n=new Uint8Array(r).fill(0);return new Uint8Array([].concat(d(n),d(e)))}if(r<0){for(var o=-1*r,a=0,i=0;i3?(o=y===n)&&(u=a[(c=a[4])?5:(c=3,3)],a[4]=a[5]=e):a[0]<=p&&((o=r<2&&pn||n>y)&&(a[4]=r,a[5]=n,d.n=y,c=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){a||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,a){if(c||(o="next"),t=a[o]){if(!(t=t.call(a,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=a.return)&&t.call(a),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);a=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){a=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(ae(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,ae(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,ae(l,"constructor",s),ae(s,"constructor",u),u.displayName="GeneratorFunction",ae(s,o,"GeneratorFunction"),ae(l),ae(l,o,"Generator"),ae(l,n,function(){return this}),ae(l,"toString",function(){return"[object Generator]"}),(oe=function(){return{w:a,m:d}})()}function ae(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}ae=function(e,t,r,n){function a(t,r){ae(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},ae(e,t,r,n)}function ie(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,o,a,i,c=[],u=!0,s=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;u=!1}else for(;!(u=(n=a.call(r)).done)&&(c.push(n.value),c.length!==t);u=!0);}catch(e){s=!0,o=e}finally{try{if(!u&&null!=r.return&&(i=r.return(),Object(i)!==i))return}finally{if(s)throw o}}return c}}(e,t)||function(e,t){if(e){if("string"==typeof e)return ce(e,t);var r={}.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?ce(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function ce(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);r= v2.0.0 to pass "organizationId" for security purposes.');case 8:if(o.organizationId&&o.organizationId===r){e.n=9;break}throw new Error("organization id does not match expected value. Expected: ".concat(r,". Found: ").concat(o.organizationId,"."));case 9:if(o.encappedPublic){e.n=10;break}throw new Error('missing "encappedPublic" in bundle signed data');case 10:if(o.ciphertext){e.n=11;break}throw new Error('missing "ciphertext" in bundle signed data');case 11:return e.a(2,o)}},e)}))).apply(this,arguments)}function be(e,t,r){return me.apply(this,arguments)}function me(){return me=se(oe().m(function e(t,r,n){var o,a,i,c,u;return oe().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,ye(t,r);case 1:if(o=e.v,a=Q.uint8arrayFromHexString(o.encappedPublic),i=Q.uint8arrayFromHexString(o.ciphertext),u=le){e.n=3;break}return e.n=2,Q.getEmbeddedKey();case 2:u=e.v;case 3:return c=u,e.n=4,n({ciphertextBuf:i,encappedKeyBuf:a,receiverPrivJwk:c});case 4:return e.a(2,e.v)}},e)})),me.apply(this,arguments)}function ge(e){return he.apply(this,arguments)}function he(){return(he=se(oe().m(function e(t){var r,n,o;return oe().w(function(e){for(;;)switch(e.n){case 0:if(r=Q.getEmbeddedKey()){e.n=1;break}return Q.sendMessageUp("EMBEDDED_PUBLIC_KEY","",t),e.a(2);case 1:return e.n=2,Q.p256JWKPrivateToPublic(r);case 2:n=e.v,o=Q.uint8arrayToHexString(n),Q.sendMessageUp("EMBEDDED_PUBLIC_KEY",o,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function we(e,t,r,n){return Ee.apply(this,arguments)}function Ee(){return(Ee=se(oe().m(function e(t,r,n,o){var a,i,c,u,s,f;return oe().w(function(e){for(;;)switch(e.n){case 0:if(i=new Uint8Array(r),"SOLANA"!==n){e.n=2;break}return c=Q.uint8arrayToHexString(i.subarray(0,32)),u=Q.getEd25519PublicKey(c),e.n=1,Q.encodeKey(i,n,u);case 1:a=e.v,e.n=4;break;case 2:return e.n=3,Q.encodeKey(i,n);case 3:a=e.v;case 4:if(s=t||"default","SOLANA"!==n){e.n=5;break}f=Z.AX.fromSecretKey(Q.base58Decode(a)),e.n=7;break;case 5:if("HEXADECIMAL"!==n){e.n=7;break}return e.n=6,Me(Array.from(Q.uint8arrayFromHexString(a)));case 6:f=e.v;case 7:fe=re(re({},fe),{},ne({},s,{organizationId:o,privateKey:a,format:n,expiry:(new Date).getTime()+864e5,keypair:f}));case 8:return e.a(2)}},e)}))).apply(this,arguments)}function Se(e,t,r,n,o,a){return Oe.apply(this,arguments)}function Oe(){return Oe=se(oe().m(function e(t,r,n,o,a,i){var c;return oe().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,be(n,r,i);case 1:return c=e.v,e.n=2,we(a,c,o,r);case 2:Q.sendMessageUp("BUNDLE_INJECTED",!0,t);case 3:return e.a(2)}},e)})),Oe.apply(this,arguments)}function ke(e,t){return je.apply(this,arguments)}function je(){return(je=se(oe().m(function e(t,r){var n;return oe().w(function(e){for(;;)switch(e.n){case 0:n=Q.applySettings(t),Q.setSettings(n),Q.sendMessageUp("SETTINGS_APPLIED",!0,r);case 1:return e.a(2)}},e)}))).apply(this,arguments)}function Pe(e,t,r){return _e.apply(this,arguments)}function _e(){return(_e=se(oe().m(function e(t,r,n){var o,a,i,c,u,s,f,l,d;return oe().w(function(e){for(;;)switch(e.n){case 0:if(Be(a=fe[o=n||"default"],o)){e.n=1;break}return e.a(2);case 1:return e.n=2,Le(a);case 2:if(i=e.v,c=JSON.parse(r),u=c.transaction,"SOLANA"!==c.type){e.n=3;break}f=Q.uint8arrayFromHexString(u),(l=Z.Kt.deserialize(f)).sign([i]),s=l.serialize(),e.n=4;break;case 3:throw new Error("unsupported transaction type");case 4:d=Q.uint8arrayToHexString(s),Q.sendMessageUp("TRANSACTION_SIGNED",d,t);case 5:return e.a(2)}},e)}))).apply(this,arguments)}function xe(e,t,r){return Te.apply(this,arguments)}function Te(){return Te=se(oe().m(function e(t,r,a){var i,c,u,s,f,l,d,p,y,v;return oe().w(function(e){for(;;)switch(e.n){case 0:if(Be(c=fe[i=a||"default"],i)){e.n=1;break}return e.a(2);case 1:return u=JSON.parse(r),s=u.message,f=u.type,l=de.encode(s),e.n=2,Le(c);case 2:if(p=e.v,"SOLANA"!==f){e.n=3;break}n.jn.sha512Sync=function(){var e;return o.Zf((e=n.jn).concatBytes.apply(e,arguments))},y=p.secretKey.slice(0,32),v=n._S(l,y),d=Q.uint8arrayToHexString(v),e.n=4;break;case 3:return Q.sendMessageUp("ERROR","unsupported message type",t),e.a(2);case 4:Q.sendMessageUp("MESSAGE_SIGNED",d,t);case 5:return e.a(2)}},e)})),Te.apply(this,arguments)}function Ie(e,t){return Ae.apply(this,arguments)}function Ae(){return(Ae=se(oe().m(function e(t,r){return oe().w(function(e){for(;;)switch(e.n){case 0:if(r){e.n=1;break}return fe={},Q.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t),e.a(2);case 1:if(fe[r]){e.n=2;break}return Q.sendMessageUp("ERROR",new Error("key not found for address ".concat(r,". Note that address is case sensitive.")).toString(),t),e.a(2);case 2:delete fe[r],Q.sendMessageUp("EMBEDDED_PRIVATE_KEY_CLEARED",!0,t);case 3:return e.a(2)}},e)}))).apply(this,arguments)}function De(e,t,r,n){return Re.apply(this,arguments)}function Re(){return Re=se(oe().m(function e(t,r,n,o){var a,i;return oe().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,be(n,r,o);case 1:return a=e.v,e.n=2,Ue(new Uint8Array(a));case 2:i=e.v,le=i,Q.sendMessageUp("DECRYPTION_KEY_INJECTED",!0,t);case 3:return e.a(2)}},e)})),Re.apply(this,arguments)}function Ne(e){le=null,Q.sendMessageUp("RESET_TO_DEFAULT_EMBEDDED_KEY",!0,e)}function Me(e){return Ke.apply(this,arguments)}function Ke(){return(Ke=se(oe().m(function e(t){var r,n;return oe().w(function(e){for(;;)switch(e.n){case 0:if(32!==(r=Q.parsePrivateKey(t)).length){e.n=1;break}n=Z.AX.fromSeed(r),e.n=3;break;case 1:if(64!==r.length){e.n=2;break}n=Z.AX.fromSecretKey(r),e.n=3;break;case 2:throw new Error("Invalid private key length: ".concat(r.length,". Expected 32 or 64 bytes."));case 3:return e.a(2,n)}},e)}))).apply(this,arguments)}function Ue(e){return Ce.apply(this,arguments)}function Ce(){return(Ce=se(oe().m(function e(t){var r,n,o;return oe().w(function(e){for(;;)switch(e.n){case 0:if(32===t.length){e.n=1;break}throw new Error("invalid decryption key length: expected 32 bytes, got ".concat(t.length));case 1:return r=new Uint8Array([48,65,2,1,0,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,4,39,48,37,2,1,1,4,32]),(n=new Uint8Array(r.length+32)).set(r),n.set(t,r.length),e.n=2,crypto.subtle.importKey("pkcs8",n,{name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]);case 2:return o=e.v,e.n=3,crypto.subtle.exportKey("jwk",o);case 3:return e.a(2,e.v)}},e)}))).apply(this,arguments)}function Ge(e){fe[e]&&delete fe[e]}function Be(e,t){if(!e)throw new Error("key bytes not found. Please re-inject export bundle for address ".concat(t," into iframe. Note that address is case sensitive.")).toString();if((new Date).getTime()>=e.expiry)throw function(){for(var e=(new Date).getTime(),t=[],r=0,n=Object.entries(fe);r=i.expiry&&t.push(a)}for(var c=0,u=t;c3?(o=y===n)&&(u=a[(c=a[4])?5:(c=3,3)],a[4]=a[5]=e):a[0]<=p&&((o=r<2&&pn||n>y)&&(a[4]=r,a[5]=n,d.n=y,c=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){a||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,a){if(c||(o="next"),t=a[o]){if(!(t=t.call(a,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=a.return)&&t.call(a),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);a=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){a=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(ze(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,ze(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,ze(l,"constructor",s),ze(s,"constructor",u),u.displayName="GeneratorFunction",ze(s,o,"GeneratorFunction"),ze(l),ze(l,o,"Generator"),ze(l,n,function(){return this}),ze(l,"toString",function(){return"[object Generator]"}),(qe=function(){return{w:a,m:d}})()}function ze(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}ze=function(e,t,r,n){function a(t,r){ze(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},ze(e,t,r,n)}function $e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function We(e){for(var t=1;t3?(o=y===n)&&(u=a[(c=a[4])?5:(c=3,3)],a[4]=a[5]=e):a[0]<=p&&((o=r<2&&pn||n>y)&&(a[4]=r,a[5]=n,d.n=y,c=0))}if(o||r>1)return i;throw l=!0,n}return function(o,f,y){if(s>1)throw TypeError("Generator is already running");for(l&&1===f&&p(f,y),c=f,u=y;(t=c<2?e:u)||!l;){a||(c?c<3?(c>1&&(d.n=-1),p(c,u)):d.n=u:d.v=u);try{if(s=2,a){if(c||(o="next"),t=a[o]){if(!(t=t.call(a,u)))throw TypeError("iterator result is not an object");if(!t.done)return t;u=t.value,c<2&&(c=0)}else 1===c&&(t=a.return)&&t.call(a),c<2&&(u=TypeError("The iterator does not provide a '"+o+"' method"),c=1);a=e}else if((t=(l=d.n<0)?u:r.call(n,d))!==i)break}catch(t){a=e,c=1,u=t}finally{s=1}}return{value:t,done:l}}}(r,o,a),!0),s}var i={};function c(){}function u(){}function s(){}t=Object.getPrototypeOf;var f=[][n]?t(t([][n]())):(rt(t={},n,function(){return this}),t),l=s.prototype=c.prototype=Object.create(f);function d(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,s):(e.__proto__=s,rt(e,o,"GeneratorFunction")),e.prototype=Object.create(l),e}return u.prototype=s,rt(l,"constructor",s),rt(s,"constructor",u),u.displayName="GeneratorFunction",rt(s,o,"GeneratorFunction"),rt(l),rt(l,o,"Generator"),rt(l,n,function(){return this}),rt(l,"toString",function(){return"[object Generator]"}),(tt=function(){return{w:a,m:d}})()}function rt(e,t,r,n){var o=Object.defineProperty;try{o({},"",{})}catch(e){o=0}rt=function(e,t,r,n){function a(t,r){rt(e,t,function(e){return this._invoke(t,r,e)})}t?o?o(e,t,{value:r,enumerable:!n,configurable:!n,writable:!n}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},rt(e,t,r,n)}function nt(e,t,r,n,o,a,i){try{var c=e[a](i),u=c.value}catch(e){return void r(e)}c.done?t(u):Promise.resolve(u).then(n,o)}function ot(e){return function(){var t=this,r=arguments;return new Promise(function(n,o){var a=e.apply(t,r);function i(e){nt(a,n,o,i,c,"next",e)}function c(e){nt(a,n,o,i,c,"throw",e)}i(void 0)})}}window.TKHQ=Q,document.addEventListener("DOMContentLoaded",ot(tt().m(function e(){var t,r,n,o;return tt().w(function(e){for(;;)switch(e.n){case 0:return e.n=1,Q.initEmbeddedKey();case 1:return e.n=2,Q.getEmbeddedKey();case 2:return t=e.v,e.n=3,Q.p256JWKPrivateToPublic(t);case 3:r=e.v,n=Q.uint8arrayToHexString(r),document.getElementById("embedded-key").value=n,He(Ze),(o=Q.getSettings())&&Q.applySettings(o),Q.sendMessageUp("PUBLIC_KEY_READY",n);case 4:return e.a(2)}},e)})))},790:()=>{},846:e=>{"use strict";e.exports=crypto}},i={};function c(e){var t=i[e];if(void 0!==t)return t.exports;var r=i[e]={id:e,loaded:!1,exports:{}};return a[e].call(r.exports,r,r.exports,c),r.loaded=!0,r.exports}c.m=a,e=[],c.O=(t,r,n,o)=>{if(!r){var a=1/0;for(f=0;f=o)&&Object.keys(c.O).every(e=>c.O[e](r[u]))?r.splice(u--,1):(i=!1,o0&&e[f-1][2]>o;f--)e[f]=e[f-1];e[f]=[r,n,o]},c.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return c.d(t,{a:t}),t},r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,c.t=function(e,n){if(1&n&&(e=this(e)),8&n)return e;if("object"==typeof e&&e){if(4&n&&e.__esModule)return e;if(16&n&&"function"==typeof e.then)return e}var o=Object.create(null);c.r(o);var a={};t=t||[null,r({}),r([]),r(r)];for(var i=2&n&&e;("object"==typeof i||"function"==typeof i)&&!~t.indexOf(i);i=r(i))Object.getOwnPropertyNames(i).forEach(t=>a[t]=()=>e[t]);return a.default=()=>e,c.d(o,a),o},c.d=(e,t)=>{for(var r in t)c.o(t,r)&&!c.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},c.f={},c.e=e=>Promise.all(Object.keys(c.f).reduce((t,r)=>(c.f[r](e,t),t),[])),c.u=e=>"bundle."+{291:"3eaea85f4001b9cc63c3",825:"aaba32bf7338e3d0f1cc"}[e]+".js",c.miniCssF=e=>{},c.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),c.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n={},o="export-and-sign:",c.l=(e,t,r,a)=>{if(n[e])n[e].push(t);else{var i,u;if(void 0!==r)for(var s=document.getElementsByTagName("script"),f=0;f{i.onerror=i.onload=null,clearTimeout(p);var o=n[e];if(delete n[e],i.parentNode&&i.parentNode.removeChild(i),o&&o.forEach(e=>e(r)),t)return t(r)},p=setTimeout(d.bind(null,void 0,{type:"timeout",target:i}),12e4);i.onerror=d.bind(null,i.onerror),i.onload=d.bind(null,i.onload),u&&document.head.appendChild(i)}},c.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),c.p="/",c.sriHashes={291:"sha384-G5pDFEAG9UZITbluyje/R/rWohZTUJf+Vu3ZIh0rsnLFLTw3SP/ca/XVNZVtv48f",825:"sha384-R9OIdd42i5GcdtZiHJuQgIUVvqyqJ0s7eaBnJHAfGllpi4YwbF7NSkjIRwOPUtsP"},(()=>{var e={792:0};c.f.j=(t,r)=>{var n=c.o(e,t)?e[t]:void 0;if(0!==n)if(n)r.push(n[2]);else{var o=new Promise((r,o)=>n=e[t]=[r,o]);r.push(n[2]=o);var a=c.p+c.u(t),i=new Error;c.l(a,r=>{if(c.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var o=r&&("load"===r.type?"missing":r.type),a=r&&r.target&&r.target.src;i.message="Loading chunk "+t+" failed.\n("+o+": "+a+")",i.name="ChunkLoadError",i.type=o,i.request=a,n[1](i)}},"chunk-"+t,t)}},c.O.j=t=>0===e[t];var t=(t,r)=>{var n,o,[a,i,u]=r,s=0;if(a.some(t=>0!==e[t])){for(n in i)c.o(i,n)&&(c.m[n]=i[n]);if(u)var f=u(c)}for(t&&t(r);sc(560));u=c.O(u)})(); +//# sourceMappingURL=bundle.dd09773f50e375d9ca7e.js.map \ No newline at end of file diff --git a/export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.LICENSE.txt b/export-and-sign/dist/bundle.dd09773f50e375d9ca7e.js.LICENSE.txt similarity index 100% rename from export-and-sign/dist/bundle.801fe7bbee4484b5f44c.js.LICENSE.txt rename to export-and-sign/dist/bundle.dd09773f50e375d9ca7e.js.LICENSE.txt diff --git a/export-and-sign/dist/bundle.dd09773f50e375d9ca7e.js.map b/export-and-sign/dist/bundle.dd09773f50e375d9ca7e.js.map new file mode 100644 index 0000000..efe35ed --- /dev/null +++ b/export-and-sign/dist/bundle.dd09773f50e375d9ca7e.js.map @@ -0,0 +1 @@ +{"version":3,"file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AU,cAAgBwC,EAAY,KAAOC,EAAU,IAC1FtS,EAAM3O,KAAO,iBACb2O,EAAM/B,KAAOoU,EACbrS,EAAMuS,QAAUD,EAChBJ,EAAmB,GAAGlS,EACvB,GAGuC,SAAW6P,EAASA,EAE/D,GAYH1B,EAAoBM,EAAExW,EAAK4X,GAA0C,IAA7BoC,EAAgBpC,GAGxD,IAAI2C,EAAuB,CAACC,EAA4BzR,KACvD,IAGIoN,EAAUyB,GAHTnB,EAAUgE,EAAaC,GAAW3R,EAGhB3S,EAAI,EAC3B,GAAGqgB,EAASkE,KAAMtE,GAAgC,IAAxB2D,EAAgB3D,IAAa,CACtD,IAAIF,KAAYsE,EACZvE,EAAoBhgB,EAAEukB,EAAatE,KACrCD,EAAoBhe,EAAEie,GAAYsE,EAAYtE,IAGhD,GAAGuE,EAAS,IAAI7a,EAAS6a,EAAQxE,EAClC,CAEA,IADGsE,GAA4BA,EAA2BzR,GACrD3S,EAAIqgB,EAASrf,OAAQhB,IACzBwhB,EAAUnB,EAASrgB,GAChB8f,EAAoBhgB,EAAE8jB,EAAiBpC,IAAYoC,EAAgBpC,IACrEoC,EAAgBpC,GAAS,KAE1BoC,EAAgBpC,GAAW,EAE5B,OAAO1B,EAAoBM,EAAE3W,IAG1B+a,EAAqBC,KAAkC,4BAAIA,KAAkC,6BAAK,GACtGD,EAAmBzX,QAAQoX,EAAqBpjB,KAAK,KAAM,IAC3DyjB,EAAmB3a,KAAOsa,EAAqBpjB,KAAK,KAAMyjB,EAAmB3a,KAAK9I,KAAKyjB,G,KClFvF,IAAIE,EAAsB5E,EAAoBM,OAAE/b,EAAW,CAAC,IAAK,IAAOyb,EAAoB,MAC5F4E,EAAsB5E,EAAoBM,EAAEsE,E","sources":["webpack://export-and-sign/webpack/runtime/chunk loaded","webpack://export-and-sign/webpack/runtime/create fake namespace object","webpack://export-and-sign/webpack/runtime/load script","webpack://export-and-sign/../shared/turnkey-core.js","webpack://export-and-sign/./src/turnkey-core.js","webpack://export-and-sign/./src/event-handlers.js","webpack://export-and-sign/../shared/crypto-utils.js","webpack://export-and-sign/./src/index.js","webpack://export-and-sign/external var \"crypto\"","webpack://export-and-sign/webpack/bootstrap","webpack://export-and-sign/webpack/runtime/compat get default export","webpack://export-and-sign/webpack/runtime/define property getters","webpack://export-and-sign/webpack/runtime/ensure chunk","webpack://export-and-sign/webpack/runtime/get javascript chunk filename","webpack://export-and-sign/webpack/runtime/get mini-css chunk filename","webpack://export-and-sign/webpack/runtime/global","webpack://export-and-sign/webpack/runtime/hasOwnProperty shorthand","webpack://export-and-sign/webpack/runtime/make namespace object","webpack://export-and-sign/webpack/runtime/node module decorator","webpack://export-and-sign/webpack/runtime/publicPath","webpack://export-and-sign/webpack/runtime/compat","webpack://export-and-sign/webpack/runtime/jsonp chunk loading","webpack://export-and-sign/webpack/startup"],"sourcesContent":["var deferred = [];\n__webpack_require__.O = (result, chunkIds, fn, priority) => {\n\tif(chunkIds) {\n\t\tpriority = priority || 0;\n\t\tfor(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];\n\t\tdeferred[i] = [chunkIds, fn, priority];\n\t\treturn;\n\t}\n\tvar notFulfilled = Infinity;\n\tfor (var i = 0; i < deferred.length; i++) {\n\t\tvar [chunkIds, fn, priority] = deferred[i];\n\t\tvar fulfilled = true;\n\t\tfor (var j = 0; j < chunkIds.length; j++) {\n\t\t\tif ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {\n\t\t\t\tchunkIds.splice(j--, 1);\n\t\t\t} else {\n\t\t\t\tfulfilled = false;\n\t\t\t\tif(priority < notFulfilled) notFulfilled = priority;\n\t\t\t}\n\t\t}\n\t\tif(fulfilled) {\n\t\t\tdeferred.splice(i--, 1)\n\t\t\tvar r = fn();\n\t\t\tif (r !== undefined) result = r;\n\t\t}\n\t}\n\treturn result;\n};","var getProto = Object.getPrototypeOf ? (obj) => (Object.getPrototypeOf(obj)) : (obj) => (obj.__proto__);\nvar leafPrototypes;\n// create a fake namespace object\n// mode & 1: value is a module id, require it\n// mode & 2: merge all properties of value into the ns\n// mode & 4: return value when already ns object\n// mode & 16: return value when it's Promise-like\n// mode & 8|1: behave like require\n__webpack_require__.t = function(value, mode) {\n\tif(mode & 1) value = this(value);\n\tif(mode & 8) return value;\n\tif(typeof value === 'object' && value) {\n\t\tif((mode & 4) && value.__esModule) return value;\n\t\tif((mode & 16) && typeof value.then === 'function') return value;\n\t}\n\tvar ns = Object.create(null);\n\t__webpack_require__.r(ns);\n\tvar def = {};\n\tleafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];\n\tfor(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {\n\t\tObject.getOwnPropertyNames(current).forEach((key) => (def[key] = () => (value[key])));\n\t}\n\tdef['default'] = () => (value);\n\t__webpack_require__.d(ns, def);\n\treturn ns;\n};","var inProgress = {};\nvar dataWebpackPrefix = \"export-and-sign:\";\n// loadScript function to load a script via script tag\n__webpack_require__.l = (url, done, key, chunkId) => {\n\tif(inProgress[url]) { inProgress[url].push(done); return; }\n\tvar script, needAttach;\n\tif(key !== undefined) {\n\t\tvar scripts = document.getElementsByTagName(\"script\");\n\t\tfor(var i = 0; i < scripts.length; i++) {\n\t\t\tvar s = scripts[i];\n\t\t\tif(s.getAttribute(\"src\") == url || s.getAttribute(\"data-webpack\") == dataWebpackPrefix + key) { script = s; break; }\n\t\t}\n\t}\n\tif(!script) {\n\t\tneedAttach = true;\n\t\tscript = document.createElement('script');\n\n\t\tscript.charset = 'utf-8';\n\t\tif (__webpack_require__.nc) {\n\t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n\t\t}\n\t\tscript.setAttribute(\"data-webpack\", dataWebpackPrefix + key);\n\n\t\tscript.src = url;\n\t\tif (script.src.indexOf(window.location.origin + '/') !== 0) {\n\t\t\tscript.crossOrigin = \"anonymous\";\n\t\t}\n\t\tscript.integrity = __webpack_require__.sriHashes[chunkId];\n\t\tscript.crossOrigin = \"anonymous\";\n\t}\n\tinProgress[url] = [done];\n\tvar onScriptComplete = (prev, event) => {\n\t\t// avoid mem leaks in IE.\n\t\tscript.onerror = script.onload = null;\n\t\tclearTimeout(timeout);\n\t\tvar doneFns = inProgress[url];\n\t\tdelete inProgress[url];\n\t\tscript.parentNode && script.parentNode.removeChild(script);\n\t\tdoneFns && doneFns.forEach((fn) => (fn(event)));\n\t\tif(prev) return prev(event);\n\t}\n\tvar timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), 120000);\n\tscript.onerror = onScriptComplete.bind(null, script.onerror);\n\tscript.onload = onScriptComplete.bind(null, script.onload);\n\tneedAttach && document.head.appendChild(script);\n};","import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n};\n","import * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\nimport { fromDerSignature } from \"@turnkey/crypto\";\nimport * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n initEmbeddedKey: sharedInitEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n additionalAssociatedData,\n getSettings,\n setSettings,\n parsePrivateKey,\n validateStyles,\n isDoublyIframed,\n loadQuorumKey,\n} = SharedTKHQ;\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n return await sharedInitEmbeddedKey();\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Read environment from meta tag (templated at deploy time), fall back to window variable (for testing)\n let environment = null;\n if (typeof document !== \"undefined\") {\n const meta = document.querySelector(\n 'meta[name=\"turnkey-signer-environment\"]'\n );\n if (\n meta &&\n meta.content &&\n meta.content !== \"__TURNKEY_SIGNER_ENVIRONMENT__\"\n ) {\n environment = meta.content;\n }\n }\n if (!environment && typeof window !== \"undefined\") {\n environment = window.__TURNKEY_SIGNER_ENVIRONMENT__;\n }\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n return await crypto.subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Returns the public key bytes for a hex-encoded Ed25519 private key.\n * @param {string} privateKeyHex\n */\nfunction getEd25519PublicKey(privateKeyHex) {\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n return nobleEd25519.getPublicKey(privateKeyHex);\n}\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n if (!settings) {\n return JSON.stringify(validSettings);\n }\n const settingsObj = JSON.parse(settings);\n if (settingsObj.styles) {\n // Valid styles will be applied the \"key-div\" div HTML element.\n const keyDivTextarea = document.getElementById(\"key-div\");\n if (!keyDivTextarea) {\n throw new Error(\"no key-div HTML element found to apply settings to.\");\n }\n\n // Validate, sanitize, and apply the styles to the \"key-div\" div element.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n keyDivTextarea.style[key] = value;\n });\n\n validSettings[\"styles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport const TKHQ = {\n initEmbeddedKey,\n generateTargetKey,\n setItemWithExpiry,\n getItemWithExpiry,\n getEmbeddedKey,\n setEmbeddedKey,\n onResetEmbeddedKey,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n encodeKey,\n sendMessageUp,\n logMessage,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n getEd25519PublicKey,\n applySettings,\n validateStyles,\n getSettings,\n setSettings,\n parsePrivateKey,\n};\n","import { TKHQ } from \"./turnkey-core.js\";\nimport { Keypair, VersionedTransaction } from \"@solana/web3.js\";\nimport * as nobleEd25519 from \"@noble/ed25519\";\nimport * as nobleHashes from \"@noble/hashes/sha512\";\n\n// Persist keys in memory via mapping of { address --> pk }\nlet inMemoryKeys = {};\n\n// Injected decryption key -- held in memory only, never persisted.\n// When set, decryptBundle uses this P-256 JWK instead of the iframe's embedded key.\nlet decryptionKey = null;\n\nexport const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds\n\n// Instantiate these once (for perf)\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n/**\n * Verifies the enclave signature on a v1.0.0 bundle and returns the parsed signed data.\n * @param {string} bundle - JSON-stringified bundle\n * @param {string} organizationId - Expected organization ID\n * @returns {Promise} - The parsed signed data {organizationId, encappedPublic, ciphertext}\n */\nasync function verifyAndParseBundleData(bundle, organizationId) {\n const bundleObj = JSON.parse(bundle);\n\n if (bundleObj.version !== \"v1.0.0\") {\n throw new Error(`unsupported version: ${bundleObj.version}`);\n }\n if (!bundleObj.data) {\n throw new Error('missing \"data\" in bundle');\n }\n if (!bundleObj.dataSignature) {\n throw new Error('missing \"dataSignature\" in bundle');\n }\n if (!bundleObj.enclaveQuorumPublic) {\n throw new Error('missing \"enclaveQuorumPublic\" in bundle');\n }\n\n if (!TKHQ.verifyEnclaveSignature) {\n throw new Error(\"method not loaded\");\n }\n const verified = await TKHQ.verifyEnclaveSignature(\n bundleObj.enclaveQuorumPublic,\n bundleObj.dataSignature,\n bundleObj.data\n );\n if (!verified) {\n throw new Error(\n `failed to verify enclave signature: ${bundleObj.dataSignature}`\n );\n }\n\n const signedData = JSON.parse(\n textDecoder.decode(TKHQ.uint8arrayFromHexString(bundleObj.data))\n );\n\n if (!organizationId) {\n throw new Error(\n `organization id is required. Please ensure you are using @turnkey/iframe-stamper >= v2.0.0 to pass \"organizationId\" for security purposes.`\n );\n } else if (\n !signedData.organizationId ||\n signedData.organizationId !== organizationId\n ) {\n throw new Error(\n `organization id does not match expected value. Expected: ${organizationId}. Found: ${signedData.organizationId}.`\n );\n }\n\n if (!signedData.encappedPublic) {\n throw new Error('missing \"encappedPublic\" in bundle signed data');\n }\n if (!signedData.ciphertext) {\n throw new Error('missing \"ciphertext\" in bundle signed data');\n }\n\n return signedData;\n}\n\n/**\n * Parse and decrypt the export bundle.\n * The `bundle` param is a JSON string of the encapsulated public\n * key, encapsulated public key signature, and the ciphertext.\n * @param {string} bundle\n * @param {string} organizationId\n * @param {Function} HpkeDecrypt\n */\nasync function decryptBundle(bundle, organizationId, HpkeDecrypt) {\n const signedData = await verifyAndParseBundleData(bundle, organizationId);\n\n const encappedKeyBuf = TKHQ.uint8arrayFromHexString(\n signedData.encappedPublic\n );\n const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext);\n\n // Use the injected decryption key if available, otherwise fall back to the embedded key\n const receiverPrivJwk = decryptionKey || (await TKHQ.getEmbeddedKey());\n return await HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n });\n}\n\n/**\n * Function triggered when GET_EMBEDDED_PUBLIC_KEY event is received.\n * @param {string} requestId\n */\nasync function onGetPublicEmbeddedKey(requestId) {\n const embeddedKeyJwk = TKHQ.getEmbeddedKey();\n\n if (!embeddedKeyJwk) {\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", \"\", requestId); // no key == empty string\n\n return;\n }\n\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n\n // Send up EMBEDDED_PUBLIC_KEY message\n TKHQ.sendMessageUp(\"EMBEDDED_PUBLIC_KEY\", targetPubHex, requestId);\n}\n\n/**\n * Encodes raw key bytes and loads them into the in-memory key store.\n * @param {string} address - Wallet address (case-sensitive)\n * @param {ArrayBuffer} keyBytes - Raw decrypted private key bytes\n * @param {string} keyFormat - \"SOLANA\" | \"HEXADECIMAL\"\n * @param {string} organizationId - Organization ID\n */\nasync function loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId) {\n let key;\n const privateKeyBytes = new Uint8Array(keyBytes);\n\n if (keyFormat === \"SOLANA\") {\n const privateKeyHex = TKHQ.uint8arrayToHexString(\n privateKeyBytes.subarray(0, 32)\n );\n const publicKeyBytes = TKHQ.getEd25519PublicKey(privateKeyHex);\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat, publicKeyBytes);\n } else {\n key = await TKHQ.encodeKey(privateKeyBytes, keyFormat);\n }\n\n const keyAddress = address || \"default\";\n\n // Cache keypair for improved signing perf\n let cachedKeypair;\n if (keyFormat === \"SOLANA\") {\n cachedKeypair = Keypair.fromSecretKey(TKHQ.base58Decode(key));\n } else if (keyFormat === \"HEXADECIMAL\") {\n cachedKeypair = await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key))\n );\n }\n\n inMemoryKeys = {\n ...inMemoryKeys,\n [keyAddress]: {\n organizationId,\n privateKey: key,\n format: keyFormat,\n expiry: new Date().getTime() + DEFAULT_TTL_MILLISECONDS,\n keypair: cachedKeypair,\n },\n };\n}\n\n/**\n * Function triggered when INJECT_KEY_EXPORT_BUNDLE event is received.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle\n * @param {string} keyFormat\n * @param {string} address\n * @param {Function} HpkeDecrypt // TODO: import this directly (instead of passing around)\n */\nasync function onInjectKeyBundle(\n requestId,\n organizationId,\n bundle,\n keyFormat,\n address,\n HpkeDecrypt\n) {\n // Decrypt the export bundle\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Load decrypted key into memory\n await loadKeyIntoMemory(address, keyBytes, keyFormat, organizationId);\n\n // Send up BUNDLE_INJECTED message\n TKHQ.sendMessageUp(\"BUNDLE_INJECTED\", true, requestId);\n}\n\n/**\n * Function triggered when APPLY_SETTINGS event is received.\n * For now, the only settings that can be applied are for \"styles\".\n * Persist them in local storage so they can be applied on every\n * page load.\n * @param {string} settings: JSON-stringified settings\n * @param {string} requestId\n */\nasync function onApplySettings(settings, requestId) {\n // Apply settings\n const validSettings = TKHQ.applySettings(settings);\n\n // Persist in local storage\n TKHQ.setSettings(validSettings);\n\n // Send up SETTINGS_APPLIED message\n TKHQ.sendMessageUp(\"SETTINGS_APPLIED\", true, requestId);\n}\n\n/**\n * Function triggered when SIGN_TRANSACTION event is received.\n * @param {string} requestId\n * @param {string} transaction (serialized)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignTransaction(requestId, serializedTransaction, address) {\n // If no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and is valid/non-expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n const transactionWrapper = JSON.parse(serializedTransaction);\n const transactionToSign = transactionWrapper.transaction;\n const transactionType = transactionWrapper.type;\n\n let signedTransaction;\n\n if (transactionType === \"SOLANA\") {\n // Fetch the transaction and sign\n const transactionBytes = TKHQ.uint8arrayFromHexString(transactionToSign);\n const transaction = VersionedTransaction.deserialize(transactionBytes);\n transaction.sign([keypair]);\n\n signedTransaction = transaction.serialize();\n } else {\n throw new Error(\"unsupported transaction type\");\n }\n\n const signedTransactionHex = TKHQ.uint8arrayToHexString(signedTransaction);\n\n TKHQ.sendMessageUp(\"TRANSACTION_SIGNED\", signedTransactionHex, requestId);\n}\n\n/**\n * Function triggered when SIGN_MESSAGE event is received.\n * @param {string} requestId\n * @param {string} message (serialized, JSON-stringified)\n * @param {string} address (case-sensitive --> enforce this, optional for backwards compatibility)\n */\nasync function onSignMessage(requestId, serializedMessage, address) {\n // Backwards compatibility: if no address provided, use \"default\"\n const keyAddress = address || \"default\";\n const key = inMemoryKeys[keyAddress];\n\n // Validate key exists and has not expired\n if (!validateKey(key, keyAddress, requestId)) {\n return;\n }\n\n const messageWrapper = JSON.parse(serializedMessage);\n const messageToSign = messageWrapper.message;\n const messageType = messageWrapper.type;\n const messageBytes = textEncoder.encode(messageToSign);\n\n let signatureHex;\n\n // Get or create keypair (uses cached keypair if available)\n const keypair = await getOrCreateKeypair(key);\n\n if (messageType === \"SOLANA\") {\n // Set up sha512 for nobleEd25519 (required for signing)\n nobleEd25519.etc.sha512Sync = (...m) =>\n nobleHashes.sha512(nobleEd25519.etc.concatBytes(...m));\n\n // Extract the 32-byte private key from the 64-byte secretKey\n // Solana keypair.secretKey format: [32-byte private key][32-byte public key]\n const privateKey = keypair.secretKey.slice(0, 32);\n // Sign the message using nobleEd25519\n const signature = nobleEd25519.sign(messageBytes, privateKey);\n\n // Note: Signature verification is skipped for performance. The signature will always be valid if signing succeeds with a valid keypair.\n // Clients can verify the signature returned.\n\n signatureHex = TKHQ.uint8arrayToHexString(signature);\n } else {\n TKHQ.sendMessageUp(\"ERROR\", \"unsupported message type\", requestId);\n\n return;\n }\n\n TKHQ.sendMessageUp(\"MESSAGE_SIGNED\", signatureHex, requestId);\n}\n\n/**\n * Function triggered when CLEAR_EMBEDDED_PRIVATE_KEY event is received.\n * @param {string} requestId\n * @param {string} address - Optional: The address of the key to clear (case-sensitive). If not provided, clears all keys.\n */\nasync function onClearEmbeddedPrivateKey(requestId, address) {\n // If no address is provided, clear all keys\n if (!address) {\n inMemoryKeys = {};\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n\n return;\n }\n\n // Check if key exists for the specific address\n if (!inMemoryKeys[address]) {\n TKHQ.sendMessageUp(\n \"ERROR\",\n new Error(\n `key not found for address ${address}. Note that address is case sensitive.`\n ).toString(),\n requestId\n );\n\n return;\n }\n\n // Clear the specific key from memory\n delete inMemoryKeys[address];\n\n TKHQ.sendMessageUp(\"EMBEDDED_PRIVATE_KEY_CLEARED\", true, requestId);\n}\n\n/**\n * Handler for REPLACE_EMBEDDED_KEY events.\n * Decrypts a P-256 private key bundle using the iframe's embedded key and\n * replaces the embedded key with it for subsequent bundle decryptions.\n * @param {string} requestId\n * @param {string} organizationId\n * @param {string} bundle - v1.0.0 bundle containing the P-256 private key\n * @param {Function} HpkeDecrypt\n */\nasync function onReplaceEmbeddedKey(\n requestId,\n organizationId,\n bundle,\n HpkeDecrypt\n) {\n // Decrypt the private key using the iframe's embedded key.\n // The decrypted payload is a raw 32-byte P-256 private key scalar.\n const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt);\n\n // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto)\n const keyJwk = await rawP256PrivateKeyToJwk(new Uint8Array(keyBytes));\n\n // Store in module-level variable (memory only)\n decryptionKey = keyJwk;\n\n TKHQ.sendMessageUp(\"DECRYPTION_KEY_INJECTED\", true, requestId);\n}\n\n/**\n * Handler for RESET_TO_DEFAULT_EMBEDDED_KEY events.\n * Clears the embedded decryption key from memory, replacing it with the iframe's default embedded key.\n * @param {string} requestId\n */\nfunction onResetToDefaultEmbeddedKey(requestId) {\n decryptionKey = null;\n TKHQ.sendMessageUp(\"RESET_TO_DEFAULT_EMBEDDED_KEY\", true, requestId);\n}\n\n// Utility functions\nasync function createSolanaKeypair(privateKey) {\n const privateKeyBytes = TKHQ.parsePrivateKey(privateKey);\n\n let keypair;\n if (privateKeyBytes.length === 32) {\n // 32-byte private key (seed)\n keypair = Keypair.fromSeed(privateKeyBytes);\n } else if (privateKeyBytes.length === 64) {\n // 64-byte secret key (private + public)\n keypair = Keypair.fromSecretKey(privateKeyBytes);\n } else {\n throw new Error(\n `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.`\n );\n }\n\n return keypair;\n}\n\n/**\n * Converts raw P-256 private key bytes (32-byte scalar) to a JWK.\n * Constructs a PKCS8 wrapper around the raw bytes, imports via WebCrypto\n * (which derives the public key), then exports as JWK.\n * @param {Uint8Array} rawPrivateKeyBytes - 32-byte P-256 private key scalar\n * @returns {Promise} - Full P-256 ECDH private key JWK\n */\nasync function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) {\n if (rawPrivateKeyBytes.length !== 32) {\n throw new Error(\n `invalid decryption key length: expected 32 bytes, got ${rawPrivateKeyBytes.length}`\n );\n }\n\n // Fixed PKCS#8 DER prefix for a P-256 private key (36 bytes).\n // This wraps a raw 32-byte scalar into the PrivateKeyInfo structure\n // that WebCrypto's importKey(\"pkcs8\", ...) expects.\n //\n // Structure (per RFC 5958 §2 / RFC 5208 §5):\n // SEQUENCE {\n // INTEGER 0 -- version (v1)\n // SEQUENCE { -- AlgorithmIdentifier (RFC 5480 §2.1.1)\n // OID 1.2.840.10045.2.1 -- id-ecPublicKey\n // OID 1.2.840.10045.3.1.7 -- secp256r1 (P-256)\n // }\n // OCTET STRING { -- privateKey (SEC 1 §C.4 / RFC 5915 §3)\n // SEQUENCE {\n // INTEGER 1 -- version\n // OCTET STRING (32 bytes) -- raw private key scalar\n // }\n // }\n // }\n //\n // References:\n // - RFC 5958 / RFC 5208: PKCS#8 PrivateKeyInfo\n // - RFC 5480 §2.1.1: ECC AlgorithmIdentifier (OIDs)\n // - RFC 5915 / SEC 1 v2 §C.4: ECPrivateKey encoding\n const pkcs8Prefix = new Uint8Array([\n 0x30, 0x41, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48,\n 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03,\n 0x01, 0x07, 0x04, 0x27, 0x30, 0x25, 0x02, 0x01, 0x01, 0x04, 0x20,\n ]);\n\n const pkcs8 = new Uint8Array(pkcs8Prefix.length + 32);\n pkcs8.set(pkcs8Prefix);\n pkcs8.set(rawPrivateKeyBytes, pkcs8Prefix.length);\n\n const cryptoKey = await crypto.subtle.importKey(\n \"pkcs8\",\n pkcs8,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n true,\n [\"deriveBits\"]\n );\n\n return await crypto.subtle.exportKey(\"jwk\", cryptoKey);\n}\n\n/**\n * Generates the error message for missing or expired keys.\n * @param {string} keyAddress - The address of the key\n * @returns {string} - The error message string\n */\nexport function getKeyNotFoundErrorMessage(keyAddress) {\n return `key bytes have expired. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`;\n}\n\n/**\n * Clears an expired key from memory. This is an internal helper function\n * that clears the key without sending messages to the parent frame.\n * @param {string} keyAddress - The address of the key to clear\n */\nfunction clearExpiredKey(keyAddress) {\n if (inMemoryKeys[keyAddress]) {\n delete inMemoryKeys[keyAddress];\n }\n}\n\n/**\n * Clears all expired keys from memory.\n * This function iterates through all keys and removes any that have expired.\n */\nfunction clearAllExpiredKeys() {\n const now = new Date().getTime();\n const addressesToRemove = [];\n\n for (const [address, key] of Object.entries(inMemoryKeys)) {\n if (key.expiry && now >= key.expiry) {\n addressesToRemove.push(address);\n }\n }\n\n for (const address of addressesToRemove) {\n clearExpiredKey(address);\n }\n}\n\n/**\n * Validates that a key exists and has not expired.\n * Clears the key from memory if it has expired.\n * Throws error if validation fails (and caller will send message up back to parent).\n * @param {Object} key - The key object from inMemoryKeys\n * @param {string} keyAddress - The address of the key\n * @returns {boolean} - True if key is valid, false otherwise\n */\nfunction validateKey(key, keyAddress) {\n if (!key) {\n throw new Error(\n `key bytes not found. Please re-inject export bundle for address ${keyAddress} into iframe. Note that address is case sensitive.`\n ).toString();\n }\n\n const now = new Date().getTime();\n if (now >= key.expiry) {\n // Clear all expired keys before processing the signing request\n clearAllExpiredKeys();\n throw new Error(getKeyNotFoundErrorMessage(keyAddress)).toString();\n }\n\n return true;\n}\n\n/**\n * Gets or creates a Solana keypair from a key object.\n * Uses cached keypair if available, otherwise creates a new one.\n * @param {Object} key - The key object containing format and privateKey\n * @returns {Promise} - The Solana keypair\n */\nasync function getOrCreateKeypair(key) {\n if (key.keypair) {\n return key.keypair;\n }\n\n if (key.format === \"SOLANA\") {\n return Keypair.fromSecretKey(TKHQ.base58Decode(key.privateKey));\n } else {\n return await createSolanaKeypair(\n Array.from(TKHQ.uint8arrayFromHexString(key.privateKey))\n );\n }\n}\n\n/**\n * DOM Event handlers to power the export flow in standalone mode\n * Instead of receiving events from the parent page, forms trigger them.\n * This is useful for debugging as well.\n */\nfunction addDOMEventListeners() {\n // only support injected keys, not wallets\n document.getElementById(\"inject-key\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_KEY_EXPORT_BUNDLE\",\n value: document.getElementById(\"key-export-bundle\").value,\n keyFormat: document.getElementById(\"key-export-format\").value,\n organizationId: document.getElementById(\"key-organization-id\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-transaction\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_TRANSACTION\",\n value: document.getElementById(\"transaction-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"sign-message\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"SIGN_MESSAGE\",\n value: document.getElementById(\"message-to-sign\").value,\n });\n },\n false\n );\n document.getElementById(\"reset\").addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({ type: \"RESET_EMBEDDED_KEY\" });\n },\n false\n );\n\n // Add wallet injection support\n const injectWalletBtn = document.getElementById(\"inject-wallet\");\n if (injectWalletBtn) {\n injectWalletBtn.addEventListener(\n \"click\",\n async (e) => {\n e.preventDefault();\n window.postMessage({\n type: \"INJECT_WALLET_EXPORT_BUNDLE\",\n value: document.getElementById(\"wallet-export-bundle\").value,\n organizationId: document.getElementById(\"wallet-organization-id\")\n .value,\n });\n },\n false\n );\n }\n}\n\n/**\n * Message Event Handlers to process messages from the parent frame\n */\nfunction initMessageEventListener(HpkeDecrypt) {\n return async function messageEventListener(event) {\n if (event.data && event.data[\"type\"] == \"INJECT_KEY_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"keyFormat\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"], // bundle\n event.data[\"keyFormat\"],\n event.data[\"address\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"INJECT_WALLET_EXPORT_BUNDLE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}, ${event.data[\"organizationId\"]}`\n );\n try {\n await onInjectKeyBundle(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n undefined, // keyFormat - default to HEXADECIMAL\n undefined, // address - default to \"default\"\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"APPLY_SETTINGS\") {\n try {\n await onApplySettings(event.data[\"value\"], event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n TKHQ.onResetEmbeddedKey();\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString());\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_TRANSACTION\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignTransaction(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"SIGN_MESSAGE\") {\n TKHQ.logMessage(\n `⬇️ Received message ${event.data[\"type\"]}: ${event.data[\"value\"]}`\n );\n try {\n await onSignMessage(\n event.data[\"requestId\"],\n event.data[\"value\"],\n event.data[\"address\"] // signing address (case sensitive)\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"CLEAR_EMBEDDED_PRIVATE_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onClearEmbeddedPrivateKey(\n event.data[\"requestId\"],\n event.data[\"address\"]\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"GET_EMBEDDED_PUBLIC_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onGetPublicEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"REPLACE_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n await onReplaceEmbeddedKey(\n event.data[\"requestId\"],\n event.data[\"organizationId\"],\n event.data[\"value\"],\n HpkeDecrypt\n );\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n if (event.data && event.data[\"type\"] == \"RESET_TO_DEFAULT_EMBEDDED_KEY\") {\n TKHQ.logMessage(`⬇️ Received message ${event.data[\"type\"]}`);\n try {\n onResetToDefaultEmbeddedKey(event.data[\"requestId\"]);\n } catch (e) {\n TKHQ.sendMessageUp(\"ERROR\", e.toString(), event.data[\"requestId\"]);\n }\n }\n };\n}\n\n/**\n * Set up event handlers for both DOM and message events\n * @param {Function} HpkeDecrypt\n */\nexport function initEventHandlers(HpkeDecrypt) {\n const messageEventListener = initMessageEventListener(HpkeDecrypt);\n\n // controllers to remove event listeners\n const messageListenerController = new AbortController();\n const turnkeyInitController = new AbortController();\n\n // Add DOM event listeners for standalone mode\n addDOMEventListeners();\n\n // Add window message listener for iframe mode\n window.addEventListener(\"message\", messageEventListener, {\n capture: false,\n signal: messageListenerController.signal,\n });\n\n // Handle MessageChannel initialization for iframe communication\n window.addEventListener(\n \"message\",\n async function (event) {\n /**\n * @turnkey/iframe-stamper >= v2.1.0 is using a MessageChannel to communicate with the parent frame.\n * The parent frame sends a TURNKEY_INIT_MESSAGE_CHANNEL event with the MessagePort.\n * If we receive this event, we want to remove the message event listener that was added in the DOMContentLoaded event to avoid processing messages twice.\n * We persist the MessagePort so we can use it to communicate with the parent window in subsequent calls to TKHQ.sendMessageUp\n */\n if (\n event.data &&\n event.data[\"type\"] == \"TURNKEY_INIT_MESSAGE_CHANNEL\" &&\n event.ports?.[0]\n ) {\n // remove the message event listener that was added in the DOMContentLoaded event\n messageListenerController.abort();\n\n const iframeMessagePort = event.ports[0];\n iframeMessagePort.onmessage = messageEventListener;\n\n TKHQ.setParentFrameMessageChannelPort(iframeMessagePort);\n\n await TKHQ.initEmbeddedKey(event.origin);\n var embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n var targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n var targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n\n // remove the listener for TURNKEY_INIT_MESSAGE_CHANNEL after it's been processed\n turnkeyInitController.abort();\n }\n },\n { signal: turnkeyInitController.signal }\n );\n\n return { messageEventListener };\n}\n/**\n * Expose internal handlers for targeted testing.\n */\nexport {\n onInjectKeyBundle,\n onSignTransaction,\n onSignMessage,\n onClearEmbeddedPrivateKey,\n onReplaceEmbeddedKey,\n onResetToDefaultEmbeddedKey,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n","// This file is the main entrypoint of the webpack-bundled application\n\n// Import relevant modules\nimport { TKHQ } from \"./turnkey-core.js\";\nimport { initEventHandlers } from \"./event-handlers.js\";\nimport { HpkeDecrypt } from \"@shared/crypto-utils.js\";\nimport \"./styles.css\";\n\n// Surface TKHQ for external access\nwindow.TKHQ = TKHQ;\n\n// Init app\ndocument.addEventListener(\"DOMContentLoaded\", async function () {\n await TKHQ.initEmbeddedKey();\n const embeddedKeyJwk = await TKHQ.getEmbeddedKey();\n const targetPubBuf = await TKHQ.p256JWKPrivateToPublic(embeddedKeyJwk);\n const targetPubHex = TKHQ.uint8arrayToHexString(targetPubBuf);\n document.getElementById(\"embedded-key\").value = targetPubHex;\n\n initEventHandlers(HpkeDecrypt);\n\n // If styles are saved in local storage, sanitize and apply them\n const styleSettings = TKHQ.getSettings();\n if (styleSettings) {\n TKHQ.applySettings(styleSettings);\n }\n\n TKHQ.sendMessageUp(\"PUBLIC_KEY_READY\", targetPubHex);\n});\n","module.exports = crypto;","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\tid: moduleId,\n\t\tloaded: false,\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Flag the module as loaded\n\tmodule.loaded = true;\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n// expose the modules object (__webpack_modules__)\n__webpack_require__.m = __webpack_modules__;\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.f = {};\n// This file contains only the entry chunk.\n// The chunk loading function for additional chunks\n__webpack_require__.e = (chunkId) => {\n\treturn Promise.all(Object.keys(__webpack_require__.f).reduce((promises, key) => {\n\t\t__webpack_require__.f[key](chunkId, promises);\n\t\treturn promises;\n\t}, []));\n};","// This function allow to reference async chunks\n__webpack_require__.u = (chunkId) => {\n\t// return url for filenames based on template\n\treturn \"bundle.\" + {\"291\":\"3eaea85f4001b9cc63c3\",\"825\":\"aaba32bf7338e3d0f1cc\"}[chunkId] + \".js\";\n};","// This function allow to reference async chunks\n__webpack_require__.miniCssF = (chunkId) => {\n\t// return url for filenames based on template\n\treturn undefined;\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","__webpack_require__.nmd = (module) => {\n\tmodule.paths = [];\n\tif (!module.children) module.children = [];\n\treturn module;\n};","__webpack_require__.p = \"/\";","\n__webpack_require__.sriHashes = {\"291\":\"*-*-*-CHUNK-SRI-HASH-r3NPGwA4ft5fHgGXhVIptCiDVf06qPa+sxzG6L+8GwPuhn89e/\",\"825\":\"*-*-*-CHUNK-SRI-HASH-mfog3UJdGPOmSk4QZbKxsxHPFZtt298WnZNc1aQ1MCgc6YirFj\"};","// no baseURI\n\n// object to store loaded and loading chunks\n// undefined = chunk not loaded, null = chunk preloaded/prefetched\n// [resolve, reject, Promise] = chunk loading, 0 = chunk loaded\nvar installedChunks = {\n\t792: 0\n};\n\n__webpack_require__.f.j = (chunkId, promises) => {\n\t\t// JSONP chunk loading for javascript\n\t\tvar installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;\n\t\tif(installedChunkData !== 0) { // 0 means \"already installed\".\n\n\t\t\t// a Promise means \"currently loading\".\n\t\t\tif(installedChunkData) {\n\t\t\t\tpromises.push(installedChunkData[2]);\n\t\t\t} else {\n\t\t\t\tif(true) { // all chunks have JS\n\t\t\t\t\t// setup Promise in chunk cache\n\t\t\t\t\tvar promise = new Promise((resolve, reject) => (installedChunkData = installedChunks[chunkId] = [resolve, reject]));\n\t\t\t\t\tpromises.push(installedChunkData[2] = promise);\n\n\t\t\t\t\t// start chunk loading\n\t\t\t\t\tvar url = __webpack_require__.p + __webpack_require__.u(chunkId);\n\t\t\t\t\t// create error before stack unwound to get useful stacktrace later\n\t\t\t\t\tvar error = new Error();\n\t\t\t\t\tvar loadingEnded = (event) => {\n\t\t\t\t\t\tif(__webpack_require__.o(installedChunks, chunkId)) {\n\t\t\t\t\t\t\tinstalledChunkData = installedChunks[chunkId];\n\t\t\t\t\t\t\tif(installedChunkData !== 0) installedChunks[chunkId] = undefined;\n\t\t\t\t\t\t\tif(installedChunkData) {\n\t\t\t\t\t\t\t\tvar errorType = event && (event.type === 'load' ? 'missing' : event.type);\n\t\t\t\t\t\t\t\tvar realSrc = event && event.target && event.target.src;\n\t\t\t\t\t\t\t\terror.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';\n\t\t\t\t\t\t\t\terror.name = 'ChunkLoadError';\n\t\t\t\t\t\t\t\terror.type = errorType;\n\t\t\t\t\t\t\t\terror.request = realSrc;\n\t\t\t\t\t\t\t\tinstalledChunkData[1](error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\t__webpack_require__.l(url, loadingEnded, \"chunk-\" + chunkId, chunkId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n};\n\n// no prefetching\n\n// no preloaded\n\n// no HMR\n\n// no HMR manifest\n\n__webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);\n\n// install a JSONP callback for chunk loading\nvar webpackJsonpCallback = (parentChunkLoadingFunction, data) => {\n\tvar [chunkIds, moreModules, runtime] = data;\n\t// add \"moreModules\" to the modules object,\n\t// then flag all \"chunkIds\" as loaded and fire callback\n\tvar moduleId, chunkId, i = 0;\n\tif(chunkIds.some((id) => (installedChunks[id] !== 0))) {\n\t\tfor(moduleId in moreModules) {\n\t\t\tif(__webpack_require__.o(moreModules, moduleId)) {\n\t\t\t\t__webpack_require__.m[moduleId] = moreModules[moduleId];\n\t\t\t}\n\t\t}\n\t\tif(runtime) var result = runtime(__webpack_require__);\n\t}\n\tif(parentChunkLoadingFunction) parentChunkLoadingFunction(data);\n\tfor(;i < chunkIds.length; i++) {\n\t\tchunkId = chunkIds[i];\n\t\tif(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {\n\t\t\tinstalledChunks[chunkId][0]();\n\t\t}\n\t\tinstalledChunks[chunkId] = 0;\n\t}\n\treturn __webpack_require__.O(result);\n}\n\nvar chunkLoadingGlobal = self[\"webpackChunkexport_and_sign\"] = self[\"webpackChunkexport_and_sign\"] || [];\nchunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));\nchunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));","// startup\n// Load entry module and return exports\n// This entry module depends on other loaded chunks and execution need to be delayed\nvar __webpack_exports__ = __webpack_require__.O(undefined, [96], () => (__webpack_require__(560)))\n__webpack_exports__ = __webpack_require__.O(__webpack_exports__);\n"],"names":["deferred","leafPrototypes","getProto","inProgress","dataWebpackPrefix","e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_EMBEDDED_KEY","TURNKEY_SETTINGS","parentFrameMessageChannelPort","getSubtleCrypto","globalThis","crypto","subtle","window","global","isDoublyIframed","undefined","location","ancestorOrigins","parent","top","_loadQuorumKey","_callee","quorumPublic","_context","Error","importKey","namedCurve","_initEmbeddedKey","_callee3","_context3","getEmbeddedKey","generateTargetKey","setEmbeddedKey","_generateTargetKey","_callee4","p256key","_context4","generateKey","exportKey","privateKey","jwtKey","getItemWithExpiry","JSON","parse","targetKey","setItemWithExpiry","stringify","key","ttl","item","expiry","Date","getTime","localStorage","setItem","itemStr","getItem","hasOwnProperty","removeItem","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","concat","logMessage","content","messageLog","document","getElementById","message","createElement","innerText","appendChild","p256JWKPrivateToPublic","_x6","_p256JWKPrivateToPublic","_callee6","jwkPrivate","jwkPrivateCopy","publicKey","_context6","_objectSpread","key_ops","base58Encode","bytes","result","digits","carry","j","push","k","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","currentByte","reverse","_encodeKey","_callee9","privateKeyBytes","keyFormat","publicKeyBytes","concatenatedBytes","_t2","_context9","set","console","warn","sharedInitEmbeddedKey","SharedTKHQ","validateStyles","styles","element","validStyles","cssValidationRegex","padding","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref","_ref2","_arrayWithHoles","next","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","loadQuorumKey","_x","_verifyEnclaveSignature","_callee2","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","meta","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context2","prod","preprod","querySelector","__TURNKEY_SIGNER_ENVIRONMENT__","fromDerSignature","verify","hash","TKHQ","initEmbeddedKey","onResetEmbeddedKey","encodeKey","_x0","_x1","_x10","sendMessageUp","type","requestId","postMessage","setParentFrameMessageChannelPort","port","normalizePadding","byteArray","targetLength","paddingLength","fill","expectedZeroCount","zeroCount","verifyEnclaveSignature","_x2","_x3","getEd25519PublicKey","privateKeyHex","nobleEd25519","sha512Sync","_nobleEd25519$etc","nobleHashes","concatBytes","applySettings","settings","validSettings","settingsObj","keyDivTextarea","style","getSettings","setSettings","parsePrivateKey","error","_slicedToArray","inMemoryKeys","decryptionKey","textEncoder","TextEncoder","textDecoder","TextDecoder","verifyAndParseBundleData","_verifyAndParseBundleData","_callee8","bundle","organizationId","bundleObj","_context8","version","data","dataSignature","decode","encappedPublic","ciphertext","decryptBundle","_x4","_x5","_decryptBundle","HpkeDecrypt","encappedKeyBuf","ciphertextBuf","receiverPrivJwk","_t9","onGetPublicEmbeddedKey","_onGetPublicEmbeddedKey","_callee0","embeddedKeyJwk","targetPubBuf","targetPubHex","_context0","loadKeyIntoMemory","_x7","_x8","_x9","_loadKeyIntoMemory","_callee1","address","keyBytes","keyAddress","cachedKeypair","_context1","subarray","Keypair","fromSecretKey","createSolanaKeypair","_defineProperty","format","keypair","onInjectKeyBundle","_x11","_x12","_x13","_x14","_onInjectKeyBundle","_callee10","_context10","onApplySettings","_x15","_x16","_onApplySettings","_callee11","_context11","onSignTransaction","_x17","_x18","_x19","_onSignTransaction","_callee12","serializedTransaction","transactionWrapper","transactionToSign","signedTransaction","transactionBytes","transaction","signedTransactionHex","_context12","validateKey","getOrCreateKeypair","VersionedTransaction","deserialize","sign","serialize","onSignMessage","_x20","_x21","_x22","_onSignMessage","_callee13","serializedMessage","messageWrapper","messageToSign","messageType","messageBytes","signatureHex","signature","_context13","encode","secretKey","onClearEmbeddedPrivateKey","_x23","_x24","_onClearEmbeddedPrivateKey","_callee14","_context14","onReplaceEmbeddedKey","_x25","_x26","_x27","_x28","_onReplaceEmbeddedKey","_callee15","keyJwk","_context15","rawP256PrivateKeyToJwk","onResetToDefaultEmbeddedKey","_x29","_createSolanaKeypair","_callee16","_context16","fromSeed","_x30","_rawP256PrivateKeyToJwk","_callee17","rawPrivateKeyBytes","pkcs8Prefix","pkcs8","cryptoKey","_context17","clearExpiredKey","now","addressesToRemove","_i","_Object$entries","_Object$entries$_i","_i2","_addressesToRemove","clearAllExpiredKeys","getKeyNotFoundErrorMessage","_x31","_getOrCreateKeypair","_callee18","_context18","initEventHandlers","messageEventListener","_messageEventListener","event","_t","_t3","_t4","_t5","_t6","_t7","_t8","_x37","initMessageEventListener","messageListenerController","AbortController","turnkeyInitController","addEventListener","preventDefault","_x32","_x33","_ref3","_x34","_ref4","_x35","injectWalletBtn","_ref5","_callee5","_context5","_x36","addDOMEventListeners","capture","signal","_ref6","_callee7","_event$ports","iframeMessagePort","_context7","ports","abort","onmessage","origin","_x38","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","_HpkeDecrypt","kemContext","receiverPriv","suite","recipientCtx","aad","res","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createRecipientContext","recipientKey","enc","info","open","styleSettings","module","exports","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","id","loaded","__webpack_modules__","O","chunkIds","fn","priority","notFulfilled","Infinity","fulfilled","every","splice","getter","__esModule","obj","mode","this","ns","def","current","getOwnPropertyNames","definition","get","chunkId","all","reduce","promises","miniCssF","g","Function","prop","url","script","needAttach","scripts","getElementsByTagName","getAttribute","charset","nc","setAttribute","src","crossOrigin","integrity","sriHashes","onScriptComplete","prev","onerror","onload","clearTimeout","timeout","doneFns","parentNode","removeChild","setTimeout","target","head","nmd","paths","children","installedChunks","installedChunkData","promise","reject","errorType","realSrc","request","webpackJsonpCallback","parentChunkLoadingFunction","moreModules","runtime","some","chunkLoadingGlobal","self","__webpack_exports__"],"sourceRoot":""} \ No newline at end of file diff --git a/export-and-sign/dist/index.html b/export-and-sign/dist/index.html index 98098e1..a4804ab 100644 --- a/export-and-sign/dist/index.html +++ b/export-and-sign/dist/index.html @@ -1 +1 @@ -Turnkey Export

Export Key Material

This public key will be sent along with a private key ID or wallet ID inside of a new EXPORT_PRIVATE_KEY or EXPORT_WALLET activity




Inject Key Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).





Inject Wallet Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).




Sign Transaction

Input a serialized transaction to sign.



Sign Message

Input a serialized message to sign.



Message log

Below we display a log of the messages sent / received. The forms above send messages, and the code communicates results by sending events via the postMessage API.

\ No newline at end of file +Turnkey Export

Export Key Material

This public key will be sent along with a private key ID or wallet ID inside of a new EXPORT_PRIVATE_KEY or EXPORT_WALLET activity




Inject Key Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).





Inject Wallet Export Bundle

The export bundle comes from the parent page and is composed of a public key and an encrypted payload. The payload is encrypted to this document's embedded key (stored in local storage and displayed above). The scheme relies on HPKE (RFC 9180).




Sign Transaction

Input a serialized transaction to sign.



Sign Message

Input a serialized message to sign.



Message log

Below we display a log of the messages sent / received. The forms above send messages, and the code communicates results by sending events via the postMessage API.

\ No newline at end of file diff --git a/export-and-sign/index.test.js b/export-and-sign/index.test.js index 4424cf9..d51484f 100644 --- a/export-and-sign/index.test.js +++ b/export-and-sign/index.test.js @@ -8,11 +8,8 @@ import { onInjectKeyBundle, onSignTransaction, getKeyNotFoundErrorMessage, - onStoreEncryptedBundle, - onInjectDecryptionKeyBundle, - onBurnSession, - onGetStoredWalletAddresses, - onClearStoredBundles, + onReplaceEmbeddedKey, + onResetToDefaultEmbeddedKey, } from "./src/event-handlers.js"; jest.mock("@solana/web3.js", () => { @@ -858,7 +855,7 @@ describe("Event Handler Expiration Flow", () => { }); }); -describe("Encryption Escrow", () => { +describe("Decryption Key Override", () => { const requestId = "test-request-id"; const serializedTransaction = JSON.stringify({ type: "SOLANA", @@ -869,9 +866,9 @@ describe("Encryption Escrow", () => { let TKHQ; let sendMessageSpy; - // Mock raw 32-byte P-256 private key (escrow decryption key) + // Mock raw 32-byte P-256 private key (decryption key) // This is what Turnkey exports after HPKE decryption - raw key bytes, not a JWK. - const mockEscrowKeyBytes = new Uint8Array(32).fill(42); + const mockDecryptionKeyBytes = new Uint8Array(32).fill(42); function buildBundle(organizationId = "org-test") { const signedData = { @@ -947,8 +944,8 @@ describe("Encryption Escrow", () => { }); afterEach(() => { - // Reset module-level state (decryptionKey + inMemoryKeys) - onBurnSession("cleanup"); + // Reset module-level decryptionKey + onResetToDefaultEmbeddedKey("cleanup"); jest.useRealTimers(); jest.restoreAllMocks(); delete global.window; @@ -957,689 +954,207 @@ describe("Encryption Escrow", () => { delete global.crypto; }); - describe("Encrypted Bundle Storage (TKHQ helpers)", () => { - it("returns null when no bundles stored", () => { - expect(TKHQ.getEncryptedBundles()).toBeNull(); - }); - - it("stores and retrieves an encrypted bundle", () => { - TKHQ.setEncryptedBundle("addr1", { - encappedPublic: "aa", - ciphertext: "bb", - organizationId: "org1", - keyFormat: "SOLANA", - }); - - const bundles = TKHQ.getEncryptedBundles(); - expect(bundles).not.toBeNull(); - expect(bundles["addr1"]).toEqual({ - encappedPublic: "aa", - ciphertext: "bb", - organizationId: "org1", - keyFormat: "SOLANA", - }); - }); - - it("stores multiple bundles and retrieves all", () => { - TKHQ.setEncryptedBundle("addr1", { - encappedPublic: "aa", - ciphertext: "bb", - organizationId: "org1", - keyFormat: "SOLANA", - }); - TKHQ.setEncryptedBundle("addr2", { - encappedPublic: "cc", - ciphertext: "dd", - organizationId: "org1", - keyFormat: "HEXADECIMAL", - }); - TKHQ.setEncryptedBundle("addr3", { - encappedPublic: "ee", - ciphertext: "ff", - organizationId: "org1", - keyFormat: "SOLANA", - }); - - const bundles = TKHQ.getEncryptedBundles(); - expect(Object.keys(bundles)).toHaveLength(3); - }); - - it("removes a single bundle by address", () => { - TKHQ.setEncryptedBundle("addr1", { - encappedPublic: "aa", - ciphertext: "bb", - organizationId: "org1", - keyFormat: "SOLANA", - }); - TKHQ.setEncryptedBundle("addr2", { - encappedPublic: "cc", - ciphertext: "dd", - organizationId: "org1", - keyFormat: "SOLANA", - }); - - TKHQ.removeEncryptedBundle("addr1", "org1"); - - const bundles = TKHQ.getEncryptedBundles(); - expect(bundles["addr1"]).toBeUndefined(); - expect(bundles["addr2"]).toBeDefined(); - }); - - it("clears localStorage key when last bundle removed", () => { - TKHQ.setEncryptedBundle("addr1", { - encappedPublic: "aa", - ciphertext: "bb", - organizationId: "org1", - keyFormat: "SOLANA", - }); - - TKHQ.removeEncryptedBundle("addr1", "org1"); - expect(TKHQ.getEncryptedBundles()).toBeNull(); - }); - - it("clears all bundles", () => { - TKHQ.setEncryptedBundle("addr1", { - encappedPublic: "aa", - ciphertext: "bb", - organizationId: "org1", - keyFormat: "SOLANA", - }); - TKHQ.setEncryptedBundle("addr2", { - encappedPublic: "cc", - ciphertext: "dd", - organizationId: "org1", - keyFormat: "SOLANA", - }); - - TKHQ.clearAllEncryptedBundles("org1"); - expect(TKHQ.getEncryptedBundles()).toBeNull(); - }); - }); + describe("REPLACE_EMBEDDED_KEY handler", () => { + it("decrypts and stores the decryption key", async () => { + const HpkeDecryptMock = jest + .fn() + .mockResolvedValue(mockDecryptionKeyBytes); - describe("STORE_ENCRYPTED_BUNDLE handler", () => { - it("verifies enclave signature and stores bundle", async () => { - await onStoreEncryptedBundle( + await onReplaceEmbeddedKey( requestId, "org-test", buildBundle(), - "SOLANA", - "wallet-addr-1" + HpkeDecryptMock ); + expect(HpkeDecryptMock).toHaveBeenCalledTimes(1); expect(sendMessageSpy).toHaveBeenCalledWith( - "ENCRYPTED_BUNDLE_STORED", + "DECRYPTION_KEY_INJECTED", true, requestId ); - - const bundles = TKHQ.getEncryptedBundles(); - expect(bundles["wallet-addr-1"]).toBeDefined(); - expect(bundles["wallet-addr-1"].encappedPublic).toBe("aa"); - expect(bundles["wallet-addr-1"].ciphertext).toBe("bb"); - expect(bundles["wallet-addr-1"].organizationId).toBe("org-test"); - expect(bundles["wallet-addr-1"].keyFormat).toBe("SOLANA"); }); - it("rejects bundle with invalid enclave signature", async () => { - jest.spyOn(TKHQ, "verifyEnclaveSignature").mockResolvedValue(false); - - await expect( - onStoreEncryptedBundle( - requestId, - "org-test", - buildBundle(), - "SOLANA", - "wallet-addr-1" - ) - ).rejects.toThrow("failed to verify enclave signature"); - }); + it("rejects invalid decryption key length", async () => { + const HpkeDecryptMock = jest + .fn() + .mockResolvedValue(new Uint8Array(16).fill(1)); - it("requires address parameter", async () => { await expect( - onStoreEncryptedBundle( + onReplaceEmbeddedKey( requestId, "org-test", buildBundle(), - "SOLANA", - undefined + HpkeDecryptMock ) - ).rejects.toThrow("address is required for STORE_ENCRYPTED_BUNDLE"); - }); - - it("defaults keyFormat to HEXADECIMAL when not provided", async () => { - await onStoreEncryptedBundle( - requestId, - "org-test", - buildBundle(), - undefined, - "wallet-addr-1" - ); - - const bundles = TKHQ.getEncryptedBundles(); - expect(bundles["wallet-addr-1"].keyFormat).toBe("HEXADECIMAL"); + ).rejects.toThrow("invalid decryption key length"); }); - it("auto-decrypts and loads key into memory when decryption key is available", async () => { - // First inject a decryption key so it's in memory + it("uses injected key for subsequent bundle decryptions", async () => { + // 1. Replace embedded key with decryption key let callCount = 0; const HpkeDecryptMock = jest.fn().mockImplementation(() => { callCount++; if (callCount === 1) { - // Escrow key decryption - return Promise.resolve(mockEscrowKeyBytes); + // First call: decrypting the decryption key bundle itself (uses embedded key) + return Promise.resolve(mockDecryptionKeyBytes); } - // Wallet bundle decryption + // Subsequent calls: decrypting wallet bundles (should use the injected key) return Promise.resolve(new Uint8Array(64).fill(9)); }); - await onInjectDecryptionKeyBundle( + await onReplaceEmbeddedKey( requestId, "org-test", buildBundle(), HpkeDecryptMock ); - // Now store a new bundle mid-session with HpkeDecrypt - await onStoreEncryptedBundle( + // 2. Inject a wallet bundle normally — decryptBundle should use the injected key + await onInjectKeyBundle( requestId, "org-test", buildBundle(), "SOLANA", - "new-wallet", + "wallet1", HpkeDecryptMock ); - expect(sendMessageSpy).toHaveBeenCalledWith( - "ENCRYPTED_BUNDLE_STORED", - true, - requestId - ); + // Verify the second HpkeDecrypt call used the injected key (not the embedded key) + const secondCall = HpkeDecryptMock.mock.calls[1][0]; + expect(secondCall.receiverPrivJwk).not.toEqual({ foo: "bar" }); // not the embedded key + expect(secondCall.receiverPrivJwk.kty).toBe("EC"); + expect(secondCall.receiverPrivJwk.crv).toBe("P-256"); - // Key should be immediately signable (no need for another INJECT_DECRYPTION_KEY_BUNDLE) - await onSignTransaction(requestId, serializedTransaction, "new-wallet"); + // 3. Verify key is usable by signing + await onSignTransaction(requestId, serializedTransaction, "wallet1"); expect(sendMessageSpy).toHaveBeenCalledWith( "TRANSACTION_SIGNED", expect.any(String), requestId ); }); - - it("stores without decrypting when no decryption key in memory", async () => { - const HpkeDecryptMock = jest.fn(); - - await onStoreEncryptedBundle( - requestId, - "org-test", - buildBundle(), - "SOLANA", - "wallet-addr-1", - HpkeDecryptMock - ); - - // Bundle stored in localStorage - const bundles = TKHQ.getEncryptedBundles(); - expect(bundles["wallet-addr-1"]).toBeDefined(); - - // HpkeDecrypt should NOT have been called (no decryption key) - expect(HpkeDecryptMock).not.toHaveBeenCalled(); - - // Signing should fail (key not in memory) - try { - await onSignTransaction( - requestId, - serializedTransaction, - "wallet-addr-1" - ); - } catch (e) { - expect(e.toString()).toContain("key bytes not found"); - } - }); }); - describe("INJECT_DECRYPTION_KEY_BUNDLE handler", () => { - it("decrypts escrow key and loads all stored bundles into memory", async () => { - // Pre-store 3 encrypted bundles - TKHQ.setEncryptedBundle("wallet1", { - encappedPublic: "aa", - ciphertext: "bb", - organizationId: "org-test", - keyFormat: "SOLANA", - }); - TKHQ.setEncryptedBundle("wallet2", { - encappedPublic: "cc", - ciphertext: "dd", - organizationId: "org-test", - keyFormat: "SOLANA", - }); - TKHQ.setEncryptedBundle("wallet3", { - encappedPublic: "ee", - ciphertext: "ff", - organizationId: "org-test", - keyFormat: "SOLANA", - }); - - let callCount = 0; - const HpkeDecryptMock = jest.fn().mockImplementation(() => { - callCount++; - if (callCount === 1) { - // First call: decrypting the escrow key bundle -> returns JWK bytes - return Promise.resolve(mockEscrowKeyBytes); - } - // Subsequent calls: decrypting wallet bundles -> returns key bytes - return Promise.resolve(new Uint8Array(64).fill(9)); - }); + describe("RESET_TO_DEFAULT_EMBEDDED_KEY handler", () => { + it("clears the injected decryption key", async () => { + // 1. Replace embedded key + const HpkeDecryptMock = jest + .fn() + .mockResolvedValue(mockDecryptionKeyBytes); - await onInjectDecryptionKeyBundle( + await onReplaceEmbeddedKey( requestId, "org-test", buildBundle(), HpkeDecryptMock ); - // 1 call for escrow key + 3 calls for wallet bundles - expect(HpkeDecryptMock).toHaveBeenCalledTimes(4); - - expect(sendMessageSpy).toHaveBeenCalledWith( - "DECRYPTION_KEY_INJECTED", - 3, - requestId - ); + // 2. Reset to default + onResetToDefaultEmbeddedKey(requestId); - // Verify keys are usable by signing - await onSignTransaction(requestId, serializedTransaction, "wallet1"); expect(sendMessageSpy).toHaveBeenCalledWith( - "TRANSACTION_SIGNED", - expect.any(String), + "RESET_TO_DEFAULT_EMBEDDED_KEY", + true, requestId ); - }); - - it("handles empty localStorage gracefully", async () => { - const HpkeDecryptMock = jest.fn().mockResolvedValue(mockEscrowKeyBytes); - await onInjectDecryptionKeyBundle( + // 3. Next bundle decryption should use the embedded key again + HpkeDecryptMock.mockResolvedValue(new Uint8Array(64).fill(9)); + await onInjectKeyBundle( requestId, "org-test", buildBundle(), + "SOLANA", + "wallet1", HpkeDecryptMock ); - // Only 1 call for the escrow key, no wallet bundles - expect(HpkeDecryptMock).toHaveBeenCalledTimes(1); - - expect(sendMessageSpy).toHaveBeenCalledWith( - "DECRYPTION_KEY_INJECTED", - 0, - requestId - ); + const lastCall = + HpkeDecryptMock.mock.calls[HpkeDecryptMock.mock.calls.length - 1][0]; + expect(lastCall.receiverPrivJwk).toEqual({ foo: "bar" }); // back to the embedded key }); + }); - it("continues past individual bundle failures", async () => { - TKHQ.setEncryptedBundle("wallet1", { - encappedPublic: "aa", - ciphertext: "bb", - organizationId: "org-test", - keyFormat: "SOLANA", - }); - TKHQ.setEncryptedBundle("wallet2-bad", { - encappedPublic: "cc", - ciphertext: "dd", - organizationId: "org-test", - keyFormat: "SOLANA", - }); - TKHQ.setEncryptedBundle("wallet3", { - encappedPublic: "ee", - ciphertext: "ff", - organizationId: "org-test", - keyFormat: "SOLANA", - }); - + describe("Full Lifecycle", () => { + it("replace key -> inject bundles -> sign -> reset -> inject uses embedded key", async () => { + // 1. Replace embedded key with decryption key let callCount = 0; const HpkeDecryptMock = jest.fn().mockImplementation(() => { callCount++; if (callCount === 1) { - // First call: escrow key - return Promise.resolve(mockEscrowKeyBytes); - } - // Fail for the second wallet bundle (callCount 3 = wallet2-bad) - if (callCount === 3) { - return Promise.reject(new Error("decryption failed for bad bundle")); + return Promise.resolve(mockDecryptionKeyBytes); } return Promise.resolve(new Uint8Array(64).fill(9)); }); - await onInjectDecryptionKeyBundle( + await onReplaceEmbeddedKey( requestId, "org-test", buildBundle(), HpkeDecryptMock ); - // Should report 2 successful decryptions (wallet1 + wallet3) expect(sendMessageSpy).toHaveBeenCalledWith( "DECRYPTION_KEY_INJECTED", - 2, + true, requestId ); - }); - - it("rejects invalid escrow key length", async () => { - // Return 16 bytes instead of 32 - invalid P-256 key length - const HpkeDecryptMock = jest - .fn() - .mockResolvedValue(new Uint8Array(16).fill(1)); - - await expect( - onInjectDecryptionKeyBundle( - requestId, - "org-test", - buildBundle(), - HpkeDecryptMock - ) - ).rejects.toThrow("invalid decryption key length"); - }); - }); - - describe("BURN_SESSION handler", () => { - it("clears in-memory keys but preserves localStorage bundles", async () => { - // Store a bundle in localStorage - TKHQ.setEncryptedBundle("wallet1", { - encappedPublic: "aa", - ciphertext: "bb", - organizationId: "org-test", - keyFormat: "SOLANA", - }); - // Inject a key into memory via normal flow - const HpkeDecryptMock = jest - .fn() - .mockResolvedValue(new Uint8Array(64).fill(9)); + // 2. Inject wallet bundles normally (decrypted with injected key) await onInjectKeyBundle( requestId, "org-test", buildBundle(), "SOLANA", - "wallet1", + "wallet-a", HpkeDecryptMock ); - - // Verify key is usable - await onSignTransaction(requestId, serializedTransaction, "wallet1"); - expect(sendMessageSpy).toHaveBeenCalledWith( - "TRANSACTION_SIGNED", - expect.any(String), - requestId - ); - - // Burn session - onBurnSession(requestId); - expect(sendMessageSpy).toHaveBeenCalledWith( - "SESSION_BURNED", - true, - requestId - ); - - // Signing should fail after burn - try { - await onSignTransaction(requestId, serializedTransaction, "wallet1"); - } catch (e) { - expect(e.toString()).toContain("key bytes not found"); - } - - // Encrypted bundles should still be in localStorage - const bundles = TKHQ.getEncryptedBundles(); - expect(bundles).not.toBeNull(); - expect(bundles["wallet1"]).toBeDefined(); - }); - }); - - describe("GET_STORED_WALLET_ADDRESSES handler", () => { - it("returns stored addresses as JSON array", () => { - TKHQ.setEncryptedBundle("addr1", { - encappedPublic: "aa", - ciphertext: "bb", - organizationId: "org1", - keyFormat: "SOLANA", - }); - TKHQ.setEncryptedBundle("addr2", { - encappedPublic: "cc", - ciphertext: "dd", - organizationId: "org1", - keyFormat: "SOLANA", - }); - TKHQ.setEncryptedBundle("addr3", { - encappedPublic: "ee", - ciphertext: "ff", - organizationId: "org1", - keyFormat: "SOLANA", - }); - - onGetStoredWalletAddresses(requestId, "org1"); - - expect(sendMessageSpy).toHaveBeenCalledWith( - "STORED_WALLET_ADDRESSES", - JSON.stringify(["addr1", "addr2", "addr3"]), - requestId - ); - }); - - it("returns empty array when no bundles stored", () => { - onGetStoredWalletAddresses(requestId, "org1"); - - expect(sendMessageSpy).toHaveBeenCalledWith( - "STORED_WALLET_ADDRESSES", - JSON.stringify([]), - requestId - ); - }); - }); - - describe("CLEAR_STORED_BUNDLES handler", () => { - it("clears a single address from localStorage and memory", async () => { - TKHQ.setEncryptedBundle("addr1", { - encappedPublic: "aa", - ciphertext: "bb", - organizationId: "org1", - keyFormat: "SOLANA", - }); - TKHQ.setEncryptedBundle("addr2", { - encappedPublic: "cc", - ciphertext: "dd", - organizationId: "org1", - keyFormat: "SOLANA", - }); - - // Load addr1 into memory via normal key injection - const HpkeDecryptMock = jest - .fn() - .mockResolvedValue(new Uint8Array(64).fill(9)); await onInjectKeyBundle( - requestId, - "org1", - buildBundle("org1"), - "SOLANA", - "addr1", - HpkeDecryptMock - ); - - // Verify addr1 is signable - await onSignTransaction(requestId, serializedTransaction, "addr1"); - expect(sendMessageSpy).toHaveBeenCalledWith( - "TRANSACTION_SIGNED", - expect.any(String), - requestId - ); - - // Clear addr1 - onClearStoredBundles(requestId, "addr1", "org1"); - - expect(sendMessageSpy).toHaveBeenCalledWith( - "STORED_BUNDLES_CLEARED", - true, - requestId - ); - - // localStorage: addr1 gone, addr2 still present - const bundles = TKHQ.getEncryptedBundles(); - expect(bundles["addr1"]).toBeUndefined(); - expect(bundles["addr2"]).toBeDefined(); - - // Memory: signing with addr1 should fail - try { - await onSignTransaction(requestId, serializedTransaction, "addr1"); - } catch (e) { - expect(e.toString()).toContain("key bytes not found"); - } - }); - - it("clears all bundles and all in-memory keys when no address provided", async () => { - TKHQ.setEncryptedBundle("addr1", { - encappedPublic: "aa", - ciphertext: "bb", - organizationId: "org1", - keyFormat: "SOLANA", - }); - TKHQ.setEncryptedBundle("addr2", { - encappedPublic: "cc", - ciphertext: "dd", - organizationId: "org1", - keyFormat: "SOLANA", - }); - - // Load both into memory - const HpkeDecryptMock = jest - .fn() - .mockResolvedValue(new Uint8Array(64).fill(9)); - await onInjectKeyBundle( - requestId, - "org1", - buildBundle("org1"), - "SOLANA", - "addr1", - HpkeDecryptMock - ); - await onInjectKeyBundle( - requestId, - "org1", - buildBundle("org1"), - "SOLANA", - "addr2", - HpkeDecryptMock - ); - - // Clear all - onClearStoredBundles(requestId, undefined, "org1"); - - expect(sendMessageSpy).toHaveBeenCalledWith( - "STORED_BUNDLES_CLEARED", - true, - requestId - ); - expect(TKHQ.getEncryptedBundles()).toBeNull(); - - // Memory: signing with either address should fail - try { - await onSignTransaction(requestId, serializedTransaction, "addr1"); - } catch (e) { - expect(e.toString()).toContain("key bytes not found"); - } - try { - await onSignTransaction(requestId, serializedTransaction, "addr2"); - } catch (e) { - expect(e.toString()).toContain("key bytes not found"); - } - }); - }); - - describe("Full Escrow Lifecycle", () => { - it("store -> decrypt -> sign -> burn -> re-decrypt -> sign", async () => { - // 1. Store 2 encrypted bundles - await onStoreEncryptedBundle( requestId, "org-test", buildBundle(), "SOLANA", - "wallet-a" - ); - await onStoreEncryptedBundle( - requestId, - "org-test", - buildBundle(), - "SOLANA", - "wallet-b" - ); - - expect(TKHQ.getEncryptedBundles()).not.toBeNull(); - expect(Object.keys(TKHQ.getEncryptedBundles())).toHaveLength(2); - - // 2. Inject decryption key -> decrypt all bundles - let callCount = 0; - const HpkeDecryptMock = jest.fn().mockImplementation(() => { - callCount++; - if (callCount === 1) { - return Promise.resolve(mockEscrowKeyBytes); - } - return Promise.resolve(new Uint8Array(64).fill(9)); - }); - - await onInjectDecryptionKeyBundle( - requestId, - "org-test", - buildBundle(), + "wallet-b", HpkeDecryptMock ); + // 3. Sign transactions + await onSignTransaction(requestId, serializedTransaction, "wallet-a"); expect(sendMessageSpy).toHaveBeenCalledWith( - "DECRYPTION_KEY_INJECTED", - 2, + "TRANSACTION_SIGNED", + expect.any(String), requestId ); - // 3. Sign a transaction - await onSignTransaction(requestId, serializedTransaction, "wallet-a"); + await onSignTransaction(requestId, serializedTransaction, "wallet-b"); expect(sendMessageSpy).toHaveBeenCalledWith( "TRANSACTION_SIGNED", expect.any(String), requestId ); - // 4. Burn session - onBurnSession(requestId); + // 4. Reset to default embedded key + onResetToDefaultEmbeddedKey(requestId); expect(sendMessageSpy).toHaveBeenCalledWith( - "SESSION_BURNED", + "RESET_TO_DEFAULT_EMBEDDED_KEY", true, requestId ); - // Signing should fail after burn - try { - await onSignTransaction(requestId, serializedTransaction, "wallet-a"); - } catch (e) { - expect(e.toString()).toContain("key bytes not found"); - } - - // 5. Re-inject decryption key (bundles survived the burn) - callCount = 0; - await onInjectDecryptionKeyBundle( + // 5. Next inject uses embedded key (not the injected one) + await onInjectKeyBundle( requestId, "org-test", buildBundle(), + "SOLANA", + "wallet-c", HpkeDecryptMock ); - expect(sendMessageSpy).toHaveBeenCalledWith( - "DECRYPTION_KEY_INJECTED", - 2, - requestId - ); - - // 6. Sign again - should work - await onSignTransaction(requestId, serializedTransaction, "wallet-b"); - expect(sendMessageSpy).toHaveBeenCalledWith( - "TRANSACTION_SIGNED", - expect.any(String), - requestId - ); + const lastCall = + HpkeDecryptMock.mock.calls[HpkeDecryptMock.mock.calls.length - 1][0]; + expect(lastCall.receiverPrivJwk).toEqual({ foo: "bar" }); // embedded key }); }); }); diff --git a/export-and-sign/src/event-handlers.js b/export-and-sign/src/event-handlers.js index 7ab8a3f..ce4bb59 100644 --- a/export-and-sign/src/event-handlers.js +++ b/export-and-sign/src/event-handlers.js @@ -6,8 +6,8 @@ import * as nobleHashes from "@noble/hashes/sha512"; // Persist keys in memory via mapping of { address --> pk } let inMemoryKeys = {}; -// Decryption key -- held in memory only, never persisted to localStorage. -// This is a P-256 private key in JWK format used to decrypt stored bundles. +// Injected decryption key -- held in memory only, never persisted. +// When set, decryptBundle uses this P-256 JWK instead of the iframe's embedded key. let decryptionKey = null; export const DEFAULT_TTL_MILLISECONDS = 1000 * 24 * 60 * 60; // 24 hours or 86,400,000 milliseconds @@ -95,12 +95,12 @@ async function decryptBundle(bundle, organizationId, HpkeDecrypt) { ); const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext); - // Decrypt the ciphertext - const embeddedKeyJwk = await TKHQ.getEmbeddedKey(); + // Use the injected decryption key if available, otherwise fall back to the embedded key + const receiverPrivJwk = decryptionKey || (await TKHQ.getEmbeddedKey()); return await HpkeDecrypt({ ciphertextBuf, encappedKeyBuf, - receiverPrivJwk: embeddedKeyJwk, + receiverPrivJwk, }); } @@ -340,65 +340,61 @@ async function onClearEmbeddedPrivateKey(requestId, address) { } /** - * Handler for STORE_ENCRYPTED_BUNDLE events. - * Verifies the enclave signature on an encrypted bundle and stores - * the encrypted payload in localStorage for later decryption. - * If the decryption key is already in memory, also decrypts and loads - * the key into memory immediately. + * Handler for REPLACE_EMBEDDED_KEY events. + * Decrypts a P-256 private key bundle using the iframe's embedded key and + * replaces the embedded key with it for subsequent bundle decryptions. * @param {string} requestId * @param {string} organizationId - * @param {string} bundle - v1.0.0 bundle JSON - * @param {string} keyFormat - "SOLANA" | "HEXADECIMAL" - * @param {string} address - Wallet address + * @param {string} bundle - v1.0.0 bundle containing the P-256 private key * @param {Function} HpkeDecrypt */ -async function onStoreEncryptedBundle( +async function onReplaceEmbeddedKey( requestId, organizationId, bundle, - keyFormat, - address, HpkeDecrypt ) { - if (!address) { - throw new Error("address is required for STORE_ENCRYPTED_BUNDLE"); - } + // Decrypt the private key using the iframe's embedded key. + // The decrypted payload is a raw 32-byte P-256 private key scalar. + const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt); - // Verify enclave signature and parse the signed data - const signedData = await verifyAndParseBundleData(bundle, organizationId); + // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto) + const keyJwk = await rawP256PrivateKeyToJwk(new Uint8Array(keyBytes)); - const resolvedKeyFormat = keyFormat || "HEXADECIMAL"; + // Store in module-level variable (memory only) + decryptionKey = keyJwk; - // Store the encrypted fields in localStorage (just what's needed for decryption) - TKHQ.setEncryptedBundle(address, { - encappedPublic: signedData.encappedPublic, - ciphertext: signedData.ciphertext, - organizationId: organizationId, - keyFormat: resolvedKeyFormat, - }); + TKHQ.sendMessageUp("DECRYPTION_KEY_INJECTED", true, requestId); +} - // If the decryption key is already in memory, decrypt and load immediately - if (decryptionKey && HpkeDecrypt) { - const encappedKeyBuf = TKHQ.uint8arrayFromHexString( - signedData.encappedPublic - ); - const ciphertextBuf = TKHQ.uint8arrayFromHexString(signedData.ciphertext); - - const keyBytes = await HpkeDecrypt({ - ciphertextBuf, - encappedKeyBuf, - receiverPrivJwk: decryptionKey, - }); - - await loadKeyIntoMemory( - address, - keyBytes, - resolvedKeyFormat, - organizationId +/** + * Handler for RESET_TO_DEFAULT_EMBEDDED_KEY events. + * Clears the embedded decryption key from memory, replacing it with the iframe's default embedded key. + * @param {string} requestId + */ +function onResetToDefaultEmbeddedKey(requestId) { + decryptionKey = null; + TKHQ.sendMessageUp("RESET_TO_DEFAULT_EMBEDDED_KEY", true, requestId); +} + +// Utility functions +async function createSolanaKeypair(privateKey) { + const privateKeyBytes = TKHQ.parsePrivateKey(privateKey); + + let keypair; + if (privateKeyBytes.length === 32) { + // 32-byte private key (seed) + keypair = Keypair.fromSeed(privateKeyBytes); + } else if (privateKeyBytes.length === 64) { + // 64-byte secret key (private + public) + keypair = Keypair.fromSecretKey(privateKeyBytes); + } else { + throw new Error( + `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.` ); } - TKHQ.sendMessageUp("ENCRYPTED_BUNDLE_STORED", true, requestId); + return keypair; } /** @@ -459,153 +455,6 @@ async function rawP256PrivateKeyToJwk(rawPrivateKeyBytes) { return await crypto.subtle.exportKey("jwk", cryptoKey); } -/** - * Handler for INJECT_DECRYPTION_KEY_BUNDLE events. - * Decrypts the P-256 private key using the iframe's embedded key, - * then iterates all stored encrypted bundles, HPKE-decrypts each one - * with the key, and loads them into inMemoryKeys. - * @param {string} requestId - * @param {string} organizationId - * @param {string} bundle - v1.0.0 bundle containing the private key - * @param {Function} HpkeDecrypt - */ -async function onInjectDecryptionKeyBundle( - requestId, - organizationId, - bundle, - HpkeDecrypt -) { - // Decrypt the private key using the iframe's embedded key. - // The decrypted payload is a raw 32-byte P-256 private key scalar. - const keyBytes = await decryptBundle(bundle, organizationId, HpkeDecrypt); - - // Convert raw P-256 bytes to a full JWK (derives public key via WebCrypto) - const keyJwk = await rawP256PrivateKeyToJwk(new Uint8Array(keyBytes)); - - // Store in module-level variable (memory only) - decryptionKey = keyJwk; - - // Iterate all stored encrypted bundles and decrypt each one - const storedBundles = TKHQ.getEncryptedBundles(); - let decryptedCount = 0; - - if (storedBundles) { - const addresses = Object.keys(storedBundles); - - for (const addr of addresses) { - const bundleData = storedBundles[addr]; - - try { - const bundleOrgId = bundleData.organizationId; - - if (organizationId !== bundleOrgId) continue; // skip bundles that don't match the organization ID of the decryption key - - const encappedKeyBuf = TKHQ.uint8arrayFromHexString( - bundleData.encappedPublic - ); - const ciphertextBuf = TKHQ.uint8arrayFromHexString( - bundleData.ciphertext - ); - - // HPKE-decrypt using the key - const bytes = await HpkeDecrypt({ - ciphertextBuf, - encappedKeyBuf, - receiverPrivJwk: decryptionKey, - }); - - // Load the decrypted key into memory - await loadKeyIntoMemory( - addr, - bytes, - bundleData.keyFormat, - bundleData.organizationId - ); - - decryptedCount++; - } catch (e) { - TKHQ.logMessage( - `Failed to decrypt bundle for address ${addr}: ${e.toString()}` - ); - } - } - } - - TKHQ.sendMessageUp("DECRYPTION_KEY_INJECTED", decryptedCount, requestId); -} - -/** - * Handler for BURN_SESSION events. - * Clears the decryption key and all in-memory wallet keys. - * Encrypted bundles in localStorage are preserved for the next session. - * @param {string} requestId - */ -function onBurnSession(requestId) { - decryptionKey = null; - inMemoryKeys = {}; - TKHQ.sendMessageUp("SESSION_BURNED", true, requestId); -} - -/** - * Handler for GET_STORED_WALLET_ADDRESSES events. - * Returns a JSON array of all wallet addresses that have encrypted bundles in localStorage. - * @param {string} requestId - * @param {string} organizationId - Organization ID to filter addresses by (only return addresses with bundles matching the organization ID) - */ -function onGetStoredWalletAddresses(requestId, organizationId) { - const bundles = TKHQ.getEncryptedBundles(); - const addresses = bundles - ? Object.entries(bundles) - .filter(([, bundle]) => bundle.organizationId === organizationId) - .map(([address]) => address) - : []; - TKHQ.sendMessageUp( - "STORED_WALLET_ADDRESSES", - JSON.stringify(addresses), - requestId - ); -} - -/** - * Handler for CLEAR_STORED_BUNDLES events. - * Removes encrypted bundles from localStorage AND the corresponding - * in-memory keys. If address is provided, removes only that address. - * If no address, removes ALL encrypted bundles and ALL in-memory keys. - * @param {string} requestId - * @param {string} organizationId - Organization ID to filter addresses by (only remove bundles matching the organization ID) - * @param {string|undefined} address - Optional wallet address - */ -function onClearStoredBundles(requestId, address, organizationId) { - if (address) { - TKHQ.removeEncryptedBundle(address, organizationId); - delete inMemoryKeys[address]; - } else { - TKHQ.clearAllEncryptedBundles(organizationId); - inMemoryKeys = {}; - } - TKHQ.sendMessageUp("STORED_BUNDLES_CLEARED", true, requestId); -} - -// Utility functions -async function createSolanaKeypair(privateKey) { - const privateKeyBytes = TKHQ.parsePrivateKey(privateKey); - - let keypair; - if (privateKeyBytes.length === 32) { - // 32-byte private key (seed) - keypair = Keypair.fromSeed(privateKeyBytes); - } else if (privateKeyBytes.length === 64) { - // 64-byte secret key (private + public) - keypair = Keypair.fromSecretKey(privateKeyBytes); - } else { - throw new Error( - `Invalid private key length: ${privateKeyBytes.length}. Expected 32 or 64 bytes.` - ); - } - - return keypair; -} - /** * Generates the error message for missing or expired keys. * @param {string} keyAddress - The address of the key @@ -861,27 +710,10 @@ function initMessageEventListener(HpkeDecrypt) { TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); } } - if (event.data && event.data["type"] == "STORE_ENCRYPTED_BUNDLE") { - TKHQ.logMessage( - `⬇️ Received message ${event.data["type"]}: address=${event.data["address"]}` - ); - try { - await onStoreEncryptedBundle( - event.data["requestId"], - event.data["organizationId"], - event.data["value"], - event.data["keyFormat"], - event.data["address"], - HpkeDecrypt - ); - } catch (e) { - TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); - } - } - if (event.data && event.data["type"] == "INJECT_DECRYPTION_KEY_BUNDLE") { + if (event.data && event.data["type"] == "REPLACE_EMBEDDED_KEY") { TKHQ.logMessage(`⬇️ Received message ${event.data["type"]}`); try { - await onInjectDecryptionKeyBundle( + await onReplaceEmbeddedKey( event.data["requestId"], event.data["organizationId"], event.data["value"], @@ -891,35 +723,10 @@ function initMessageEventListener(HpkeDecrypt) { TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); } } - if (event.data && event.data["type"] == "BURN_SESSION") { + if (event.data && event.data["type"] == "RESET_TO_DEFAULT_EMBEDDED_KEY") { TKHQ.logMessage(`⬇️ Received message ${event.data["type"]}`); try { - onBurnSession(event.data["requestId"]); - } catch (e) { - TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); - } - } - if (event.data && event.data["type"] == "GET_STORED_WALLET_ADDRESSES") { - TKHQ.logMessage(`⬇️ Received message ${event.data["type"]}`); - try { - onGetStoredWalletAddresses( - event.data["requestId"], - event.data["organizationId"] - ); - } catch (e) { - TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); - } - } - if (event.data && event.data["type"] == "CLEAR_STORED_BUNDLES") { - TKHQ.logMessage( - `⬇️ Received message ${event.data["type"]}: address=${event.data["address"]}` - ); - try { - onClearStoredBundles( - event.data["requestId"], - event.data["address"], - event.data["organizationId"] - ); + onResetToDefaultEmbeddedKey(event.data["requestId"]); } catch (e) { TKHQ.sendMessageUp("ERROR", e.toString(), event.data["requestId"]); } @@ -995,9 +802,6 @@ export { onSignTransaction, onSignMessage, onClearEmbeddedPrivateKey, - onStoreEncryptedBundle, - onInjectDecryptionKeyBundle, - onBurnSession, - onGetStoredWalletAddresses, - onClearStoredBundles, + onReplaceEmbeddedKey, + onResetToDefaultEmbeddedKey, }; diff --git a/export-and-sign/src/turnkey-core.js b/export-and-sign/src/turnkey-core.js index 6b90f04..8c79de7 100644 --- a/export-and-sign/src/turnkey-core.js +++ b/export-and-sign/src/turnkey-core.js @@ -28,10 +28,6 @@ const { validateStyles, isDoublyIframed, loadQuorumKey, - getEncryptedBundles, - setEncryptedBundle, - removeEncryptedBundle, - clearAllEncryptedBundles, } = SharedTKHQ; /** @@ -181,8 +177,4 @@ export const TKHQ = { getSettings, setSettings, parsePrivateKey, - getEncryptedBundles, - setEncryptedBundle, - removeEncryptedBundle, - clearAllEncryptedBundles, }; diff --git a/import/dist/551.bundle.27da59437a4e403e3c24.js.map b/import/dist/551.bundle.27da59437a4e403e3c24.js.map index 6971264..811b1db 100644 --- a/import/dist/551.bundle.27da59437a4e403e3c24.js.map +++ b/import/dist/551.bundle.27da59437a4e403e3c24.js.map @@ -1 +1 @@ -{"version":3,"file":"551.bundle.27da59437a4e403e3c24.js","mappings":";moFACA,IAAAA,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IAAAE,EAAAC,EAAAG,EAAAI,EAAA,EAAAC,EAAAX,GAAA,GAAAY,GAAA,EAAAC,EAAA,CAAAF,EAAA,EAAAb,EAAA,EAAAgB,EAAApB,EAAAqB,EAAAC,EAAAN,EAAAM,EAAAC,KAAAvB,EAAA,GAAAsB,EAAA,SAAArB,EAAAC,GAAA,OAAAM,EAAAP,EAAAQ,EAAA,EAAAG,EAAAZ,EAAAmB,EAAAf,EAAAF,EAAAmB,CAAA,YAAAC,EAAApB,EAAAE,GAAA,IAAAK,EAAAP,EAAAU,EAAAR,EAAAH,EAAA,GAAAiB,GAAAF,IAAAV,GAAAL,EAAAgB,EAAAO,OAAAvB,IAAA,KAAAK,EAAAE,EAAAS,EAAAhB,GAAAqB,EAAAH,EAAAF,EAAAQ,EAAAjB,EAAA,GAAAN,EAAA,GAAAI,E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B,KAE1Cf,GAAM5L,EAAAA,EAAAA,IAAyB2L,EAAgBzL,GAAe3C,EAAAd,KAAA,GAAAc,EAAAb,KAAA,GAI5C8O,EAAUoB,KAAKzB,EAAcS,GAAI,QAAvDC,EAAatO,EAAAR,KAAAQ,EAAAb,KAAG,GAAH,oBAAAa,EAAAd,KAAG,GAAHc,EAAAwI,GAAAxI,EAAA,UAEP,IAAIZ,MAAM,oCAAsCY,EAAAwI,GAAEzL,YAAW,QAQnE,OALIwR,GAAgB5M,EAAAA,EAAAA,IAAsB,IAAIL,WAAWgN,IACrDE,GAAoB7M,EAAAA,EAAAA,IAAsByM,GAC1CK,EAAkBnO,KAAKI,UAAU,CACrC4O,eAAgBd,EAChBe,WAAYhB,IACZvO,EAAAT,OAAA,SACKkP,GAAe,yBAAAzO,EAAAP,OAAA,EAAAI,EAAA,kBACvB8N,EA3HD,eAAAlU,EAAA,KAAAD,EAAAiE,UAAA,WAAAJ,QAAA,SAAA3D,EAAAI,GAAA,IAAAe,EAAAjB,EAAA8D,MAAAjE,EAAAD,GAAA,SAAAmE,EAAA/D,GAAAwD,EAAAvC,EAAAnB,EAAAI,EAAA6D,EAAAC,EAAA,OAAAhE,EAAA,UAAAgE,EAAAhE,GAAAwD,EAAAvC,EAAAnB,EAAAI,EAAA6D,EAAAC,EAAA,QAAAhE,EAAA,CAAA+D,OAAA,OA2HCD,MAAA,KAAAD,WA3HD,IAAA7D,CA2HC,C","sources":["webpack://import/../shared/turnkey-core.js","webpack://import/./src/turnkey-core.js","webpack://import/../shared/crypto-utils.js"],"sourcesContent":["import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\nconst TURNKEY_ENCRYPTED_BUNDLES = \"TURNKEY_ENCRYPTED_BUNDLES\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Gets all encrypted bundles from localStorage.\n * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat}\n * or null if no bundles are stored.\n * @returns {Object|null}\n */\nfunction getEncryptedBundles() {\n const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES);\n if (!data) {\n return null;\n }\n try {\n return JSON.parse(data);\n } catch (e) {\n // If the stored data is corrupted or not valid JSON, remove it to self-heal.\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n return null;\n }\n}\n\n/**\n * Stores or updates an encrypted bundle for a given address.\n * @param {string} address - The wallet address\n * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat}\n */\nfunction setEncryptedBundle(address, bundleData) {\n const bundles = getEncryptedBundles() || {};\n bundles[address] = bundleData;\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n}\n\n/**\n * Removes a single encrypted bundle by address.\n * Only removes the bundle if it belongs to the specified organization.\n * @param {string} address - The wallet address to remove\n * @param {string} organizationId - Only remove if the bundle belongs to this org\n */\nfunction removeEncryptedBundle(address, organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles || !bundles[address]) return;\n\n // Only remove if the bundle belongs to the specified organization\n if (bundles[address].organizationId !== organizationId) return;\n\n delete bundles[address];\n if (Object.keys(bundles).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(bundles)\n );\n }\n}\n\n/**\n * Removes all encrypted bundles belonging to the specified organization.\n * Bundles from other organizations are preserved.\n * @param {string} organizationId - Remove bundles belonging to this org\n */\nfunction clearAllEncryptedBundles(organizationId) {\n const bundles = getEncryptedBundles();\n if (!bundles) return;\n\n // Keep only bundles that do NOT belong to this organization\n const remaining = Object.fromEntries(\n Object.entries(bundles).filter(\n ([, bundle]) => bundle.organizationId !== organizationId\n )\n );\n\n if (Object.keys(remaining).length === 0) {\n window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES);\n } else {\n window.localStorage.setItem(\n TURNKEY_ENCRYPTED_BUNDLES,\n JSON.stringify(remaining)\n );\n }\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n getEncryptedBundles,\n setEncryptedBundle,\n removeEncryptedBundle,\n clearAllEncryptedBundles,\n};\n","import * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n} = SharedTKHQ;\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n const settingsObj = JSON.parse(settings);\n\n const passphraseLabel = document.getElementById(\"passphrase-label\");\n const mnemonicLabel = document.getElementById(\"mnemonic-label\");\n const passphraseTextarea = document.getElementById(\"passphrase\");\n\n if (!passphraseLabel || !passphraseTextarea) {\n throw new Error(\"no passphrase HTML elements found to apply settings to.\");\n }\n const plaintextTextarea = document.getElementById(\"plaintext\");\n if (!plaintextTextarea) {\n throw new Error(\n \"no plaintext textarea HTML element found to apply settings to.\"\n );\n }\n\n // Apply enablePassphrase setting\n if (settingsObj.enablePassphrase === true) {\n passphraseLabel.style.display = \"inline-block\";\n passphraseTextarea.style.display = \"inline-block\";\n passphraseTextarea.style.border = \"solid 1px #ccc\";\n passphraseTextarea.style.borderRadius = \"4px\";\n\n mnemonicLabel.style.display = \"inline-block\";\n plaintextTextarea.style.border = \"solid 1px #ccc\";\n plaintextTextarea.style.borderRadius = \"4px\";\n\n validSettings[\"enablePassphrase\"] = true;\n } else {\n passphraseLabel.style.display = \"none\";\n passphraseTextarea.style.display = \"none\";\n mnemonicLabel.style.display = \"none\";\n\n plaintextTextarea.style.border = \"none\";\n validSettings[\"enablePassphrase\"] = false;\n }\n\n if (settingsObj.styles) {\n // Validate, sanitize, and apply the styles to the \"plaintext\" textarea.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n plaintextTextarea.style[key] = value;\n });\n\n if (validStyles.backgroundColor) {\n // Apply background color to document and body as well.\n document.documentElement.style.backgroundColor =\n validStyles.backgroundColor;\n document.body.style.backgroundColor = validStyles.backgroundColor;\n }\n\n if (validStyles.labelColor) {\n document.getElementById(\"mnemonic-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"styles\"] = validStyles;\n }\n\n if (settingsObj.passphraseStyles) {\n // Validate, sanitize, and apply the styles to the \"passphrase\" textarea.\n const validStyles = validateStyles(settingsObj.passphraseStyles);\n Object.entries(validStyles).forEach(([key, value]) => {\n passphraseTextarea.style[key] = value;\n });\n\n if (validStyles.labelColor) {\n document.getElementById(\"passphrase-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"passphraseStyles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n applySettings,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n"],"names":["e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_OverloadYield","k","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_TARGET_EMBEDDED_KEY","TURNKEY_SETTINGS","parentFrameMessageChannelPort","cryptoProviderOverride","getSubtleCrypto","subtle","globalThis","crypto","window","global","setCryptoProvider","cryptoProvider","loadQuorumKey","_x","_loadQuorumKey","_regeneratorRuntime","mark","_callee","quorumPublic","wrap","_context","prev","next","Error","importKey","namedCurve","abrupt","sent","stop","loadTargetKey","_x2","_loadTargetKey","_callee2","targetPublic","targetKey","_context2","exportKey","getTargetEmbeddedKey","jwtKey","localStorage","getItem","JSON","parse","setTargetEmbeddedKey","setItem","stringify","resetTargetEmbeddedKey","removeItem","setParentFrameMessageChannelPort","port","getSettings","settings","setSettings","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","normalizePadding","byteArray","targetLength","paddingLength","padding","fill","concat","expectedZeroCount","zeroCount","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","fromDerSignature","derSignature","derSignatureBuf","index","rLength","sLength","rPadded","sPadded","verifyEnclaveSignature","_x3","_x4","_x5","_verifyEnclaveSignature","_callee5","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context5","prod","preprod","__TURNKEY_SIGNER_ENVIRONMENT__","undefined","verify","hash","sendMessageUp","type","requestId","message","postMessage","parent","content","messageLog","document","getElementById","createElement","innerText","appendChild","logMessage","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","carry","push","j","currentByte","result","reverse","base58CheckDecode","_x7","_base58CheckDecode","_callee7","decoded","payload","checksum","hash1Buf","hash1","hash2Buf","hash2","computedChecksum","_context7","subarray","digest","decodeKey","_x8","_x9","_decodeKey","_callee8","privateKey","keyFormat","decodedKeyBytes","version","keyAndFlags","_payload","_version","_keyAndFlags","_bech32$decode","prefix","words","bytes","schemeFlag","privkey","_context8","t0","bech32","decode","fromWords","console","warn","validateStyles","styles","element","validStyles","cssValidationRegex","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref3","_ref4","_arrayWithHoles","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","SharedTKHQ","applySettings","validSettings","settingsObj","passphraseLabel","mnemonicLabel","passphraseTextarea","plaintextTextarea","enablePassphrase","style","display","border","_ref","_ref2","_slicedToArray","key","documentElement","body","passphraseStyles","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","_objectSpread","_defineProperty","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","TextEncoder","encode","HpkeEncrypt","_HpkeEncrypt","plaintextBuf","receiverPubJwk","kemContext","receiverPub","suite","senderCtx","receiverPubCryptoKey","receiverPubRaw","encappedKeyBuf","aad","ciphertextBuf","ciphertextHex","encappedKeyBufHex","encryptedBundle","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createSenderContext","recipientPublicKey","info","enc","seal","encappedPublic","ciphertext"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"551.bundle.27da59437a4e403e3c24.js","mappings":";moFACA,IAAAA,EAAAC,EAAAC,EAAA,mBAAAC,OAAAA,OAAA,GAAAC,EAAAF,EAAAG,UAAA,aAAAC,EAAAJ,EAAAK,aAAA,yBAAAC,EAAAN,EAAAE,EAAAE,EAAAE,GAAA,IAAAC,EAAAL,GAAAA,EAAAM,qBAAAC,EAAAP,EAAAO,EAAAC,EAAAC,OAAAC,OAAAL,EAAAC,WAAA,OAAAK,EAAAH,EAAA,mBAAAV,EAAAE,EAAAE,GAAA,IAAAE,EAAAC,EAAAG,EAAAI,EAAA,EAAAC,EAAAX,GAAA,GAAAY,GAAA,EAAAC,EAAA,CAAAF,EAAA,EAAAb,EAAA,EAAAgB,EAAApB,EAAAqB,EAAAC,EAAAN,EAAAM,EAAAC,KAAAvB,EAAA,GAAAsB,EAAA,SAAArB,EAAAC,GAAA,OAAAM,EAAAP,EAAAQ,EAAA,EAAAG,EAAAZ,EAAAmB,EAAAf,EAAAF,EAAAmB,CAAA,YAAAC,EAAApB,EAAAE,GAAA,IAAAK,EAAAP,EAAAU,EAAAR,EAAAH,EAAA,GAAAiB,GAAAF,IAAAV,GAAAL,EAAAgB,EAAAO,OAAAvB,IAAA,KAAAK,EAAAE,EAAAS,EAAAhB,GAAAqB,EAAAH,EAAAF,EAAAQ,EAAAjB,EAAA,GAAAN,EAAA,GAAAI,EAAAmB,IAAArB,KAAAQ,EAAAJ,GAAAC,EAAAD,EAAA,OAAAC,E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,EAAAd,KAAA,GAAAc,EAAAb,KAAA,GAI5C8O,EAAUoB,KAAKzB,EAAcS,GAAI,QAAvDC,EAAatO,EAAAR,KAAAQ,EAAAb,KAAG,GAAH,oBAAAa,EAAAd,KAAG,GAAHc,EAAAwI,GAAAxI,EAAA,UAEP,IAAIZ,MAAM,oCAAsCY,EAAAwI,GAAEzL,YAAW,QAQnE,OALIwR,GAAgB5M,EAAAA,EAAAA,IAAsB,IAAIL,WAAWgN,IACrDE,GAAoB7M,EAAAA,EAAAA,IAAsByM,GAC1CK,EAAkBnO,KAAKI,UAAU,CACrC4O,eAAgBd,EAChBe,WAAYhB,IACZvO,EAAAT,OAAA,SACKkP,GAAe,yBAAAzO,EAAAP,OAAA,EAAAI,EAAA,kBACvB8N,EA3HD,eAAAlU,EAAA,KAAAD,EAAAiE,UAAA,WAAAJ,QAAA,SAAA3D,EAAAI,GAAA,IAAAe,EAAAjB,EAAA8D,MAAAjE,EAAAD,GAAA,SAAAmE,EAAA/D,GAAAwD,EAAAvC,EAAAnB,EAAAI,EAAA6D,EAAAC,EAAA,OAAAhE,EAAA,UAAAgE,EAAAhE,GAAAwD,EAAAvC,EAAAnB,EAAAI,EAAA6D,EAAAC,EAAA,QAAAhE,EAAA,CAAA+D,OAAA,OA2HCD,MAAA,KAAAD,WA3HD,IAAA7D,CA2HC,C","sources":["webpack://import/../shared/turnkey-core.js","webpack://import/./src/turnkey-core.js","webpack://import/../shared/crypto-utils.js"],"sourcesContent":["import { bech32 } from \"bech32\";\n\n/**\n * Turnkey Core Module - Shared\n * Contains all the core cryptographic and utility functions shared across frames\n */\n\n/** constants for LocalStorage */\nconst TURNKEY_EMBEDDED_KEY = \"TURNKEY_EMBEDDED_KEY\";\nconst TURNKEY_TARGET_EMBEDDED_KEY = \"TURNKEY_TARGET_EMBEDDED_KEY\";\nconst TURNKEY_SETTINGS = \"TURNKEY_SETTINGS\";\n/** 48 hours in milliseconds */\nconst TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48;\nconst TURNKEY_EMBEDDED_KEY_ORIGIN = \"TURNKEY_EMBEDDED_KEY_ORIGIN\";\n\nlet parentFrameMessageChannelPort = null;\nvar cryptoProviderOverride = null;\n\n/*\n * Returns a reference to the WebCrypto subtle interface regardless of the host environment.\n */\nfunction getSubtleCrypto() {\n if (cryptoProviderOverride && cryptoProviderOverride.subtle) {\n return cryptoProviderOverride.subtle;\n }\n if (\n typeof globalThis !== \"undefined\" &&\n globalThis.crypto &&\n globalThis.crypto.subtle\n ) {\n return globalThis.crypto.subtle;\n }\n if (typeof window !== \"undefined\" && window.crypto && window.crypto.subtle) {\n return window.crypto.subtle;\n }\n if (typeof global !== \"undefined\" && global.crypto && global.crypto.subtle) {\n return global.crypto.subtle;\n }\n if (typeof crypto !== \"undefined\" && crypto.subtle) {\n return crypto.subtle;\n }\n\n return null;\n}\n\n/*\n * Allows tests to explicitly set the crypto provider (e.g. crypto.webcrypto) when the runtime\n * environment does not expose one on the global/window objects.\n */\nfunction setCryptoProvider(cryptoProvider) {\n cryptoProviderOverride = cryptoProvider || null;\n}\n\n/* Security functions */\n\nfunction isDoublyIframed() {\n if (window.location.ancestorOrigins !== undefined) {\n // Does not exist in IE and firefox.\n // See https://developer.mozilla.org/en-US/docs/Web/API/Location/ancestorOrigins for how this works\n return window.location.ancestorOrigins.length > 1;\n } else {\n return window.parent !== window.top;\n }\n}\n\n/*\n * Loads the quorum public key as a CryptoKey.\n */\nasync function loadQuorumKey(quorumPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.importKey(\n \"raw\",\n quorumPublic,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n [\"verify\"]\n );\n}\n\n/*\n * Load a key to encrypt to as a CryptoKey and return it as a JSON Web Key.\n */\nasync function loadTargetKey(targetPublic) {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const targetKey = await subtle.importKey(\n \"raw\",\n targetPublic,\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n\n return await subtle.exportKey(\"jwk\", targetKey);\n}\n\n/**\n * Creates a new public/private key pair and persists it in localStorage\n */\nasync function initEmbeddedKey() {\n if (isDoublyIframed()) {\n throw new Error(\"Doubly iframed\");\n }\n const retrievedKey = await getEmbeddedKey();\n if (retrievedKey === null) {\n const targetKey = await generateTargetKey();\n setEmbeddedKey(targetKey);\n }\n // Nothing to do, key is correctly initialized!\n}\n\n/*\n * Generate a key to encrypt to and export it as a JSON Web Key.\n */\nasync function generateTargetKey() {\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n const p256key = await subtle.generateKey(\n {\n name: \"ECDH\",\n namedCurve: \"P-256\",\n },\n true,\n [\"deriveBits\"]\n );\n\n return await subtle.exportKey(\"jwk\", p256key.privateKey);\n}\n\n/**\n * Gets the current embedded private key JWK. Returns `null` if not found.\n */\nfunction getEmbeddedKey() {\n const jwtKey = getItemWithExpiry(TURNKEY_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the embedded private key JWK with the default expiration time.\n * @param {JsonWebKey} targetKey\n */\nfunction setEmbeddedKey(targetKey) {\n setItemWithExpiry(\n TURNKEY_EMBEDDED_KEY,\n JSON.stringify(targetKey),\n TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS\n );\n}\n\n/**\n * Gets the current target embedded private key JWK. Returns `null` if not found.\n */\nfunction getTargetEmbeddedKey() {\n const jwtKey = window.localStorage.getItem(TURNKEY_TARGET_EMBEDDED_KEY);\n return jwtKey ? JSON.parse(jwtKey) : null;\n}\n\n/**\n * Sets the target embedded public key JWK.\n * @param {JsonWebKey} targetKey\n */\nfunction setTargetEmbeddedKey(targetKey) {\n window.localStorage.setItem(\n TURNKEY_TARGET_EMBEDDED_KEY,\n JSON.stringify(targetKey)\n );\n}\n\n/**\n * Resets the current embedded private key JWK.\n */\nfunction onResetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY);\n window.localStorage.removeItem(TURNKEY_EMBEDDED_KEY_ORIGIN);\n}\n\n/**\n * Resets the current target embedded private key JWK.\n */\nfunction resetTargetEmbeddedKey() {\n window.localStorage.removeItem(TURNKEY_TARGET_EMBEDDED_KEY);\n}\n\nfunction setParentFrameMessageChannelPort(port) {\n parentFrameMessageChannelPort = port;\n}\n\n/**\n * Gets the current settings.\n */\nfunction getSettings() {\n const settings = window.localStorage.getItem(TURNKEY_SETTINGS);\n return settings ? JSON.parse(settings) : null;\n}\n\n/**\n * Sets the settings object.\n * @param {Object} settings\n */\nfunction setSettings(settings) {\n window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings));\n}\n\n/**\n * Set an item in localStorage with an expiration time\n * @param {string} key\n * @param {string} value\n * @param {number} ttl expiration time in milliseconds\n */\nfunction setItemWithExpiry(key, value, ttl) {\n const now = new Date();\n const item = {\n value: value,\n expiry: now.getTime() + ttl,\n };\n window.localStorage.setItem(key, JSON.stringify(item));\n}\n\n/**\n * Get an item from localStorage. Returns `null` and\n * removes the item from localStorage if expired or\n * expiry time is missing.\n * @param {string} key\n */\nfunction getItemWithExpiry(key) {\n const itemStr = window.localStorage.getItem(key);\n if (!itemStr) {\n return null;\n }\n const item = JSON.parse(itemStr);\n if (\n !Object.prototype.hasOwnProperty.call(item, \"expiry\") ||\n !Object.prototype.hasOwnProperty.call(item, \"value\")\n ) {\n window.localStorage.removeItem(key);\n return null;\n }\n const now = new Date();\n if (now.getTime() > item.expiry) {\n window.localStorage.removeItem(key);\n return null;\n }\n return item.value;\n}\n\n/**\n * Takes a hex string (e.g. \"e4567ab\" or \"0xe4567ab\") and returns an array buffer (Uint8Array)\n * @param {string} hexString - Hex string with or without \"0x\" prefix\n * @returns {Uint8Array}\n */\nfunction uint8arrayFromHexString(hexString) {\n if (!hexString || typeof hexString !== \"string\") {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n\n // Remove 0x prefix if present\n const hexWithoutPrefix =\n hexString.startsWith(\"0x\") || hexString.startsWith(\"0X\")\n ? hexString.slice(2)\n : hexString;\n\n var hexRegex = /^[0-9A-Fa-f]+$/;\n if (hexWithoutPrefix.length % 2 != 0 || !hexRegex.test(hexWithoutPrefix)) {\n throw new Error(\"cannot create uint8array from invalid hex string\");\n }\n return new Uint8Array(\n hexWithoutPrefix.match(/../g).map((h) => parseInt(h, 16))\n );\n}\n\n/**\n * Takes a Uint8Array and returns a hex string\n * @param {Uint8Array} buffer\n * @return {string}\n */\nfunction uint8arrayToHexString(buffer) {\n return [...buffer].map((x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * Function to normalize padding of byte array with 0's to a target length\n */\nfunction normalizePadding(byteArray, targetLength) {\n const paddingLength = targetLength - byteArray.length;\n\n // Add leading 0's to array\n if (paddingLength > 0) {\n const padding = new Uint8Array(paddingLength).fill(0);\n return new Uint8Array([...padding, ...byteArray]);\n }\n\n // Remove leading 0's from array\n if (paddingLength < 0) {\n const expectedZeroCount = paddingLength * -1;\n let zeroCount = 0;\n for (let i = 0; i < expectedZeroCount && i < byteArray.length; i++) {\n if (byteArray[i] === 0) {\n zeroCount++;\n }\n }\n // Check if the number of zeros found equals the number of zeroes expected\n if (zeroCount !== expectedZeroCount) {\n throw new Error(\n `invalid number of starting zeroes. Expected number of zeroes: ${expectedZeroCount}. Found: ${zeroCount}.`\n );\n }\n return byteArray.slice(expectedZeroCount, expectedZeroCount + targetLength);\n }\n return byteArray;\n}\n\n/**\n * Additional Associated Data (AAD) in the format dictated by the enclave_encrypt crate.\n */\nfunction additionalAssociatedData(senderPubBuf, receiverPubBuf) {\n const s = Array.from(new Uint8Array(senderPubBuf));\n const r = Array.from(new Uint8Array(receiverPubBuf));\n return new Uint8Array([...s, ...r]);\n}\n\n/**\n * Converts an ASN.1 DER-encoded ECDSA signature to the raw format that WebCrypto uses.\n */\nfunction fromDerSignature(derSignature) {\n const derSignatureBuf = uint8arrayFromHexString(derSignature);\n\n // Check and skip the sequence tag (0x30)\n let index = 2;\n\n // Parse 'r' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for r\"\n );\n }\n index++; // Move past the INTEGER tag\n const rLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const r = derSignatureBuf.slice(index, index + rLength);\n index += rLength; // Move to the start of s\n\n // Parse 's' and check for integer tag (0x02)\n if (derSignatureBuf[index] !== 0x02) {\n throw new Error(\n \"failed to convert DER-encoded signature: invalid tag for s\"\n );\n }\n index++; // Move past the INTEGER tag\n const sLength = derSignatureBuf[index];\n index++; // Move past the length byte\n const s = derSignatureBuf.slice(index, index + sLength);\n\n // Normalize 'r' and 's' to 32 bytes each\n const rPadded = normalizePadding(r, 32);\n const sPadded = normalizePadding(s, 32);\n\n // Concatenate and return the raw signature\n return new Uint8Array([...rPadded, ...sPadded]);\n}\n\n/**\n * Function to verify enclave signature on import bundle received from the server.\n * @param {string} enclaveQuorumPublic uncompressed public key for the quorum key which produced the signature\n * @param {string} publicSignature signature bytes encoded as a hexadecimal string\n * @param {string} signedData signed bytes encoded as a hexadecimal string. This could be public key bytes directly, or JSON-encoded bytes\n */\nasync function verifyEnclaveSignature(\n enclaveQuorumPublic,\n publicSignature,\n signedData\n) {\n /** Turnkey Signer enclave's public keys */\n const TURNKEY_SIGNERS_ENCLAVES = {\n prod: \"04cf288fe433cc4e1aa0ce1632feac4ea26bf2f5a09dcfe5a42c398e06898710330f0572882f4dbdf0f5304b8fc8703acd69adca9a4bbf7f5d00d20a5e364b2569\",\n preprod:\n \"04f3422b8afbe425d6ece77b8d2469954715a2ff273ab7ac89f1ed70e0a9325eaa1698b4351fd1b23734e65c0b6a86b62dd49d70b37c94606aac402cbd84353212\",\n };\n\n // Use window.__TURNKEY_SIGNER_ENVIRONMENT__ if available (for testing), otherwise use the webpack replacement\n const environment =\n (typeof window !== \"undefined\" && window.__TURNKEY_SIGNER_ENVIRONMENT__) ||\n \"__TURNKEY_SIGNER_ENVIRONMENT__\";\n const TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY =\n TURNKEY_SIGNERS_ENCLAVES[environment];\n\n if (TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY === undefined) {\n throw new Error(\n `Configuration error: TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY is undefined`\n );\n }\n\n // todo(olivia): throw error if enclave quorum public is null once server changes are deployed\n if (enclaveQuorumPublic) {\n if (enclaveQuorumPublic !== TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY) {\n throw new Error(\n `enclave quorum public keys from client and bundle do not match. Client: ${TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY}. Bundle: ${enclaveQuorumPublic}.`\n );\n }\n }\n\n const encryptionQuorumPublicBuf = new Uint8Array(\n uint8arrayFromHexString(TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY)\n );\n const quorumKey = await loadQuorumKey(encryptionQuorumPublicBuf);\n if (!quorumKey) {\n throw new Error(\"failed to load quorum key\");\n }\n\n // The ECDSA signature is ASN.1 DER encoded but WebCrypto uses raw format\n const publicSignatureBuf = fromDerSignature(publicSignature);\n const signedDataBuf = uint8arrayFromHexString(signedData);\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n return await subtle.verify(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n quorumKey,\n publicSignatureBuf,\n signedDataBuf\n );\n}\n\n/**\n * Function to send a message.\n *\n * If this page is embedded as an iframe we'll send a postMessage\n * in one of two ways depending on the version of @turnkey/iframe-stamper:\n * 1. newer versions (>=v2.1.0) pass a MessageChannel MessagePort from the parent frame for postMessages.\n * 2. older versions ( 0) {\n digits.push(carry % 58);\n carry = (carry / 58) | 0;\n }\n }\n // Convert digits to a base58 string\n for (let k = 0; k < digits.length; k++) {\n result = alphabet[digits[k]] + result;\n }\n\n // Add '1' for each leading 0 byte\n for (let i = 0; bytes[i] === 0 && i < bytes.length - 1; i++) {\n result = \"1\" + result;\n }\n return result;\n}\n\n/**\n * Decodes a base58-encoded string into a buffer\n * This function throws an error when the string contains invalid characters.\n * @param {string} s The base58-encoded string.\n * @return {Uint8Array} The decoded buffer.\n */\nfunction base58Decode(s) {\n // See https://en.bitcoin.it/wiki/Base58Check_encoding\n var alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n var decodedBytes = [];\n var leadingZeros = [];\n for (var i = 0; i < s.length; i++) {\n if (alphabet.indexOf(s[i]) === -1) {\n throw new Error(`cannot base58-decode: ${s[i]} isn't a valid character`);\n }\n var carry = alphabet.indexOf(s[i]);\n\n // If the current base58 digit is 0, append a 0 byte.\n // \"i == leadingZeros.length\" can only be true if we have not seen non-zero bytes so far.\n // If we had seen a non-zero byte, carry wouldn't be 0, and i would be strictly more than `leadingZeros.length`\n if (carry == 0 && i === leadingZeros.length) {\n leadingZeros.push(0);\n }\n\n var j = 0;\n while (j < decodedBytes.length || carry > 0) {\n var currentByte = decodedBytes[j];\n\n // shift the current byte 58 units and add the carry amount\n // (or just add the carry amount if this is a new byte -- undefined case)\n if (currentByte === undefined) {\n currentByte = carry;\n } else {\n currentByte = currentByte * 58 + carry;\n }\n\n // find the new carry amount (1-byte shift of current byte value)\n carry = currentByte >> 8;\n // reset the current byte to the remainder (the carry amount will pass on the overflow)\n decodedBytes[j] = currentByte % 256;\n j++;\n }\n }\n\n var result = leadingZeros.concat(decodedBytes.reverse());\n return new Uint8Array(result);\n}\n\n/**\n * Decodes a base58check-encoded string and verifies the checksum.\n * Base58Check encoding includes a 4-byte checksum at the end to detect errors.\n * The checksum is the first 4 bytes of SHA256(SHA256(payload)).\n * This function throws an error if the checksum is invalid.\n * @param {string} s The base58check-encoded string.\n * @return {Promise} The decoded payload (without checksum).\n */\nasync function base58CheckDecode(s) {\n const decoded = base58Decode(s);\n\n if (decoded.length < 5) {\n throw new Error(\n `invalid base58check length: expected at least 5 bytes, got ${decoded.length}`\n );\n }\n\n const payload = decoded.subarray(0, decoded.length - 4);\n const checksum = decoded.subarray(decoded.length - 4);\n\n const subtle = getSubtleCrypto();\n if (!subtle) {\n throw new Error(\"WebCrypto subtle API is unavailable\");\n }\n\n // Compute double SHA256 hash\n const hash1Buf = await subtle.digest(\"SHA-256\", payload);\n const hash1 = new Uint8Array(hash1Buf);\n const hash2Buf = await subtle.digest(\"SHA-256\", hash1);\n const hash2 = new Uint8Array(hash2Buf);\n const computedChecksum = hash2.subarray(0, 4);\n\n // Verify checksum\n const mismatch =\n (checksum[0] ^ computedChecksum[0]) |\n (checksum[1] ^ computedChecksum[1]) |\n (checksum[2] ^ computedChecksum[2]) |\n (checksum[3] ^ computedChecksum[3]);\n if (mismatch !== 0) {\n throw new Error(\"invalid base58check checksum\");\n }\n\n return payload;\n}\n\n/**\n * Returns private key bytes from a private key, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {string} privateKey\n * @param {string} keyFormat Can be \"HEXADECIMAL\", \"SUI_BECH32\", \"BITCOIN_MAINNET_WIF\", \"BITCOIN_TESTNET_WIF\" or \"SOLANA\"\n * @return {Promise}\n */\nasync function decodeKey(privateKey, keyFormat) {\n switch (keyFormat) {\n case \"SOLANA\": {\n const decodedKeyBytes = base58Decode(privateKey);\n if (decodedKeyBytes.length !== 64) {\n throw new Error(\n `invalid key length. Expected 64 bytes. Got ${decodedKeyBytes.length}.`\n );\n }\n return decodedKeyBytes.subarray(0, 32);\n }\n case \"HEXADECIMAL\":\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n case \"BITCOIN_MAINNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0x80 = mainnet\n if (version !== 0x80) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0x80 (mainnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"BITCOIN_TESTNET_WIF\": {\n const payload = await base58CheckDecode(privateKey);\n\n const version = payload[0];\n const keyAndFlags = payload.subarray(1);\n\n // 0xEF = testnet\n if (version !== 0xef) {\n throw new Error(\n `invalid WIF version byte: ${version}. Expected 0xEF (testnet).`\n );\n }\n\n // Check for common mistake: uncompressed keys\n if (keyAndFlags.length === 32) {\n throw new Error(\"uncompressed WIF keys not supported\");\n }\n\n // Validate compressed format\n if (keyAndFlags.length !== 33 || keyAndFlags[32] !== 0x01) {\n throw new Error(\"invalid WIF format: expected compressed private key\");\n }\n\n return keyAndFlags.subarray(0, 32);\n }\n case \"SUI_BECH32\": {\n const { prefix, words } = bech32.decode(privateKey);\n\n if (prefix !== \"suiprivkey\") {\n throw new Error(\n `invalid SUI private key human-readable part (HRP): expected \"suiprivkey\"`\n );\n }\n\n const bytes = bech32.fromWords(words);\n if (bytes.length !== 33) {\n throw new Error(\n `invalid SUI private key length: expected 33 bytes, got ${bytes.length}`\n );\n }\n\n const schemeFlag = bytes[0];\n const privkey = bytes.slice(1);\n\n // schemeFlag = 0 is Ed25519; We currently only support Ed25519 keys for SUI.\n if (schemeFlag !== 0) {\n throw new Error(\n `invalid SUI private key scheme flag: expected 0 (Ed25519). Turnkey only supports Ed25519 keys for SUI.`\n );\n }\n\n return new Uint8Array(privkey);\n }\n default:\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n if (privateKey.startsWith(\"0x\")) {\n return uint8arrayFromHexString(privateKey.slice(2));\n }\n return uint8arrayFromHexString(privateKey);\n }\n}\n\n/**\n * Returns a private key from private key bytes, represented in\n * the encoding and format specified by `keyFormat`. Defaults to\n * hex-encoding if `keyFormat` isn't passed.\n * @param {Uint8Array} privateKeyBytes\n * @param {string} keyFormat Can be \"HEXADECIMAL\" or \"SOLANA\"\n */\nasync function encodeKey(privateKeyBytes, keyFormat, publicKeyBytes) {\n switch (keyFormat) {\n case \"SOLANA\":\n if (!publicKeyBytes) {\n throw new Error(\"public key must be specified for SOLANA key format\");\n }\n if (privateKeyBytes.length !== 32) {\n throw new Error(\n `invalid private key length. Expected 32 bytes. Got ${privateKeyBytes.length}.`\n );\n }\n if (publicKeyBytes.length !== 32) {\n throw new Error(\n `invalid public key length. Expected 32 bytes. Got ${publicKeyBytes.length}.`\n );\n }\n {\n const concatenatedBytes = new Uint8Array(64);\n concatenatedBytes.set(privateKeyBytes, 0);\n concatenatedBytes.set(publicKeyBytes, 32);\n return base58Encode(concatenatedBytes);\n }\n case \"HEXADECIMAL\":\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n default:\n // keeping console.warn for debugging purposes.\n // eslint-disable-next-line no-console\n console.warn(\n `invalid key format: ${keyFormat}. Defaulting to HEXADECIMAL.`\n );\n return \"0x\" + uint8arrayToHexString(privateKeyBytes);\n }\n}\n\n// Helper to parse a private key into a Solana base58 private key.\n// To be used if a wallet account is exported without the `SOLANA` address format.\nfunction parsePrivateKey(privateKey) {\n if (Array.isArray(privateKey)) {\n return new Uint8Array(privateKey);\n }\n\n if (typeof privateKey === \"string\") {\n // Remove 0x prefix if present\n if (privateKey.startsWith(\"0x\")) {\n privateKey = privateKey.slice(2);\n }\n\n // Check if it's hex-formatted correctly (i.e. 64 hex chars)\n if (privateKey.length === 64 && /^[0-9a-fA-F]+$/.test(privateKey)) {\n return uint8arrayFromHexString(privateKey);\n }\n\n // Otherwise assume it's base58 format (for Solana)\n try {\n return base58Decode(privateKey);\n } catch (error) {\n throw new Error(\n \"Invalid private key format. Use hex (64 chars) or base58 format.\"\n );\n }\n }\n\n throw new Error(\"Private key must be a string (hex/base58) or number array\");\n}\n\n/**\n * Function to validate and sanitize the styles object using the accepted map of style keys and values (as regular expressions).\n * Any invalid style throws an error. Returns an object of valid styles.\n * @param {Object} styles\n * @param {HTMLElement} element - Optional element parameter (for import frame)\n * @return {Object}\n */\nfunction validateStyles(styles, element) {\n const validStyles = {};\n\n const cssValidationRegex = {\n padding: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n margin: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n borderWidth: \"^(\\\\d+(px|em|rem) ?){1,4}$\",\n borderStyle:\n \"^(none|solid|dashed|dotted|double|groove|ridge|inset|outset)$\",\n borderColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n borderRadius: \"^(\\\\d+(px|em|%|rem) ?){1,4}$\",\n fontSize: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax))$\",\n fontWeight: \"^(normal|bold|bolder|lighter|\\\\d{3})$\",\n fontFamily: '^[^\";<>]*$', // checks for the absence of some characters that could lead to CSS/HTML injection\n color:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n labelColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n backgroundColor:\n \"^(transparent|inherit|initial|#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)|hsla?\\\\(\\\\d{1,3}, \\\\d{1,3}%, \\\\d{1,3}%(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\))$\",\n width: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n height: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|auto)$\",\n maxWidth: \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n maxHeight:\n \"^(\\\\d+(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|none)$\",\n lineHeight:\n \"^(\\\\d+(\\\\.\\\\d+)?(px|em|rem|%|vh|vw|in|cm|mm|pt|pc|ex|ch|vmin|vmax)|normal)$\",\n boxShadow:\n \"^(none|(\\\\d+(px|em|rem) ?){2,4} (#[0-9a-f]{3,8}|rgba?\\\\(\\\\d{1,3}, \\\\d{1,3}, \\\\d{1,3}(, \\\\d?(\\\\.\\\\d{1,2})?)?\\\\)) ?(inset)?)$\",\n textAlign: \"^(left|right|center|justify|initial|inherit)$\",\n overflowWrap: \"^(normal|break-word|anywhere)$\",\n wordWrap: \"^(normal|break-word)$\",\n resize: \"^(none|both|horizontal|vertical|block|inline)$\",\n };\n\n Object.entries(styles).forEach(([property, value]) => {\n const styleProperty = property.trim();\n if (styleProperty.length === 0) {\n throw new Error(\"css style property cannot be empty\");\n }\n const styleRegexStr = cssValidationRegex[styleProperty];\n if (!styleRegexStr) {\n throw new Error(\n `invalid or unsupported css style property: \"${styleProperty}\"`\n );\n }\n const styleRegex = new RegExp(styleRegexStr);\n const styleValue = value.trim();\n if (styleValue.length == 0) {\n throw new Error(`css style for \"${styleProperty}\" is empty`);\n }\n const isValidStyle = styleRegex.test(styleValue);\n if (!isValidStyle) {\n throw new Error(\n `invalid css style value for property \"${styleProperty}\"`\n );\n }\n validStyles[styleProperty] = styleValue;\n });\n\n return validStyles;\n}\n\n// Export all shared functions\nexport {\n setCryptoProvider,\n getSubtleCrypto,\n isDoublyIframed,\n loadQuorumKey,\n loadTargetKey,\n initEmbeddedKey,\n generateTargetKey,\n getEmbeddedKey,\n setEmbeddedKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n onResetEmbeddedKey,\n resetTargetEmbeddedKey,\n setParentFrameMessageChannelPort,\n getSettings,\n setSettings,\n setItemWithExpiry,\n getItemWithExpiry,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n normalizePadding,\n additionalAssociatedData,\n fromDerSignature,\n verifyEnclaveSignature,\n sendMessageUp,\n logMessage,\n p256JWKPrivateToPublic,\n base58Encode,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n encodeKey,\n parsePrivateKey,\n validateStyles,\n};\n","import * as SharedTKHQ from \"@shared/turnkey-core.js\";\n\nconst {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n} = SharedTKHQ;\n\n/**\n * Function to apply settings on this page. For now, the only settings that can be applied\n * are for \"styles\". Upon successful application, return the valid, sanitized settings JSON string.\n * @param {string} settings\n * @return {string}\n */\nfunction applySettings(settings) {\n const validSettings = {};\n const settingsObj = JSON.parse(settings);\n\n const passphraseLabel = document.getElementById(\"passphrase-label\");\n const mnemonicLabel = document.getElementById(\"mnemonic-label\");\n const passphraseTextarea = document.getElementById(\"passphrase\");\n\n if (!passphraseLabel || !passphraseTextarea) {\n throw new Error(\"no passphrase HTML elements found to apply settings to.\");\n }\n const plaintextTextarea = document.getElementById(\"plaintext\");\n if (!plaintextTextarea) {\n throw new Error(\n \"no plaintext textarea HTML element found to apply settings to.\"\n );\n }\n\n // Apply enablePassphrase setting\n if (settingsObj.enablePassphrase === true) {\n passphraseLabel.style.display = \"inline-block\";\n passphraseTextarea.style.display = \"inline-block\";\n passphraseTextarea.style.border = \"solid 1px #ccc\";\n passphraseTextarea.style.borderRadius = \"4px\";\n\n mnemonicLabel.style.display = \"inline-block\";\n plaintextTextarea.style.border = \"solid 1px #ccc\";\n plaintextTextarea.style.borderRadius = \"4px\";\n\n validSettings[\"enablePassphrase\"] = true;\n } else {\n passphraseLabel.style.display = \"none\";\n passphraseTextarea.style.display = \"none\";\n mnemonicLabel.style.display = \"none\";\n\n plaintextTextarea.style.border = \"none\";\n validSettings[\"enablePassphrase\"] = false;\n }\n\n if (settingsObj.styles) {\n // Validate, sanitize, and apply the styles to the \"plaintext\" textarea.\n const validStyles = validateStyles(settingsObj.styles);\n Object.entries(validStyles).forEach(([key, value]) => {\n plaintextTextarea.style[key] = value;\n });\n\n if (validStyles.backgroundColor) {\n // Apply background color to document and body as well.\n document.documentElement.style.backgroundColor =\n validStyles.backgroundColor;\n document.body.style.backgroundColor = validStyles.backgroundColor;\n }\n\n if (validStyles.labelColor) {\n document.getElementById(\"mnemonic-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"styles\"] = validStyles;\n }\n\n if (settingsObj.passphraseStyles) {\n // Validate, sanitize, and apply the styles to the \"passphrase\" textarea.\n const validStyles = validateStyles(settingsObj.passphraseStyles);\n Object.entries(validStyles).forEach(([key, value]) => {\n passphraseTextarea.style[key] = value;\n });\n\n if (validStyles.labelColor) {\n document.getElementById(\"passphrase-label\").style.color =\n validStyles.labelColor;\n }\n\n validSettings[\"passphraseStyles\"] = validStyles;\n }\n\n return JSON.stringify(validSettings);\n}\n\nexport {\n setCryptoProvider,\n loadTargetKey,\n getTargetEmbeddedKey,\n setTargetEmbeddedKey,\n resetTargetEmbeddedKey,\n getSettings,\n setSettings,\n sendMessageUp,\n uint8arrayFromHexString,\n uint8arrayToHexString,\n base58Decode,\n base58CheckDecode,\n decodeKey,\n setParentFrameMessageChannelPort,\n normalizePadding,\n fromDerSignature,\n additionalAssociatedData,\n verifyEnclaveSignature,\n validateStyles,\n applySettings,\n};\n","/**\n * Crypto Utilities - Shared\n * Contains HPKE encryption and decryption functions\n */\n\nimport {\n p256JWKPrivateToPublic,\n additionalAssociatedData,\n uint8arrayToHexString,\n} from \"./turnkey-core.js\";\nimport {\n CipherSuite,\n DhkemP256HkdfSha256,\n HkdfSha256,\n Aes256Gcm,\n} from \"@hpke/core\";\n\n// Pre-compute const (for perf)\nconst TURNKEY_HPKE_INFO = new TextEncoder().encode(\"turnkey_hpke\");\n\n/**\n * Decrypt the ciphertext (ArrayBuffer) given an encapsulation key (ArrayBuffer)\n * and the receivers private key (JSON Web Key).\n */\nexport async function HpkeDecrypt({\n ciphertextBuf,\n encappedKeyBuf,\n receiverPrivJwk,\n}) {\n const kemContext = new DhkemP256HkdfSha256();\n var receiverPriv = await kemContext.importKey(\n \"jwk\",\n { ...receiverPrivJwk },\n false\n );\n\n var suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n var recipientCtx = await suite.createRecipientContext({\n recipientKey: receiverPriv,\n enc: encappedKeyBuf,\n info: TURNKEY_HPKE_INFO,\n });\n\n var receiverPubBuf = await p256JWKPrivateToPublic(receiverPrivJwk);\n var aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n var res;\n try {\n res = await recipientCtx.open(ciphertextBuf, aad);\n } catch (e) {\n throw new Error(\n \"unable to decrypt bundle using embedded key. the bundle may be incorrect. failed with error: \" +\n e.toString()\n );\n }\n return res;\n}\n\n/**\n * Encrypt plaintext using HPKE with the receiver's public key.\n * @param {Object} params\n * @param {Uint8Array} params.plaintextBuf - Plaintext to encrypt\n * @param {JsonWebKey} params.receiverPubJwk - Receiver's public key in JWK format\n * @returns {Promise} JSON stringified encrypted bundle with encappedPublic and ciphertext\n */\nexport async function HpkeEncrypt({ plaintextBuf, receiverPubJwk }) {\n const kemContext = new DhkemP256HkdfSha256();\n const receiverPub = await kemContext.importKey(\n \"jwk\",\n { ...receiverPubJwk },\n true\n );\n\n const suite = new CipherSuite({\n kem: kemContext,\n kdf: new HkdfSha256(),\n aead: new Aes256Gcm(),\n });\n\n const senderCtx = await suite.createSenderContext({\n recipientPublicKey: receiverPub,\n info: TURNKEY_HPKE_INFO,\n });\n\n // Need to import the key again as a JWK to export as a raw key, the format needed to\n // create the aad with the newly generated raw encapped key.\n const receiverPubCryptoKey = await crypto.subtle.importKey(\n \"jwk\",\n receiverPubJwk,\n {\n name: \"ECDSA\",\n namedCurve: \"P-256\",\n },\n true,\n []\n );\n const receiverPubRaw = await crypto.subtle.exportKey(\n \"raw\",\n receiverPubCryptoKey\n );\n const receiverPubBuf = new Uint8Array(receiverPubRaw);\n\n const encappedKeyBuf = new Uint8Array(senderCtx.enc);\n\n const aad = additionalAssociatedData(encappedKeyBuf, receiverPubBuf);\n\n var ciphertextBuf;\n try {\n ciphertextBuf = await senderCtx.seal(plaintextBuf, aad);\n } catch (e) {\n throw new Error(\"failed to encrypt import bundle: \" + e.toString());\n }\n\n const ciphertextHex = uint8arrayToHexString(new Uint8Array(ciphertextBuf));\n const encappedKeyBufHex = uint8arrayToHexString(encappedKeyBuf);\n const encryptedBundle = JSON.stringify({\n encappedPublic: encappedKeyBufHex,\n ciphertext: ciphertextHex,\n });\n return encryptedBundle;\n}\n"],"names":["e","t","r","Symbol","n","iterator","o","toStringTag","i","c","prototype","Generator","u","Object","create","_regeneratorDefine2","f","p","y","G","v","a","d","bind","length","l","TypeError","call","done","value","GeneratorFunction","GeneratorFunctionPrototype","getPrototypeOf","setPrototypeOf","__proto__","displayName","_regenerator","w","m","defineProperty","_invoke","enumerable","configurable","writable","_OverloadYield","k","_toConsumableArray","Array","isArray","_arrayLikeToArray","_arrayWithoutHoles","from","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","toString","slice","constructor","name","test","asyncGeneratorStep","Promise","resolve","then","_asyncToGenerator","arguments","apply","_next","_throw","TURNKEY_TARGET_EMBEDDED_KEY","TURNKEY_SETTINGS","parentFrameMessageChannelPort","cryptoProviderOverride","getSubtleCrypto","subtle","globalThis","crypto","window","global","setCryptoProvider","cryptoProvider","loadQuorumKey","_x","_loadQuorumKey","_regeneratorRuntime","mark","_callee","quorumPublic","wrap","_context","prev","next","Error","importKey","namedCurve","abrupt","sent","stop","loadTargetKey","_x2","_loadTargetKey","_callee2","targetPublic","targetKey","_context2","exportKey","getTargetEmbeddedKey","jwtKey","localStorage","getItem","JSON","parse","setTargetEmbeddedKey","setItem","stringify","resetTargetEmbeddedKey","removeItem","setParentFrameMessageChannelPort","port","getSettings","settings","setSettings","uint8arrayFromHexString","hexString","hexWithoutPrefix","startsWith","Uint8Array","match","map","h","parseInt","uint8arrayToHexString","buffer","x","padStart","join","normalizePadding","byteArray","targetLength","paddingLength","padding","fill","concat","expectedZeroCount","zeroCount","additionalAssociatedData","senderPubBuf","receiverPubBuf","s","fromDerSignature","derSignature","derSignatureBuf","index","rLength","sLength","rPadded","sPadded","verifyEnclaveSignature","_x3","_x4","_x5","_verifyEnclaveSignature","_callee5","enclaveQuorumPublic","publicSignature","signedData","TURNKEY_SIGNERS_ENCLAVES","environment","TURNKEY_SIGNER_ENCLAVE_QUORUM_PUBLIC_KEY","encryptionQuorumPublicBuf","quorumKey","publicSignatureBuf","signedDataBuf","_context5","prod","preprod","__TURNKEY_SIGNER_ENVIRONMENT__","undefined","verify","hash","sendMessageUp","type","requestId","message","postMessage","parent","content","messageLog","document","getElementById","createElement","innerText","appendChild","logMessage","base58Decode","alphabet","decodedBytes","leadingZeros","indexOf","carry","push","j","currentByte","result","reverse","base58CheckDecode","_x7","_base58CheckDecode","_callee7","decoded","payload","checksum","hash1Buf","hash1","hash2Buf","hash2","computedChecksum","_context7","subarray","digest","decodeKey","_x8","_x9","_decodeKey","_callee8","privateKey","keyFormat","decodedKeyBytes","version","keyAndFlags","_payload","_version","_keyAndFlags","_bech32$decode","prefix","words","bytes","schemeFlag","privkey","_context8","t0","bech32","decode","fromWords","console","warn","validateStyles","styles","element","validStyles","cssValidationRegex","margin","borderWidth","borderStyle","borderColor","borderRadius","fontSize","fontWeight","fontFamily","color","labelColor","backgroundColor","width","height","maxWidth","maxHeight","lineHeight","boxShadow","textAlign","overflowWrap","wordWrap","resize","entries","forEach","_ref","_ref2","_arrayWithHoles","_iterableToArrayLimit","_nonIterableRest","property","styleProperty","trim","styleRegexStr","styleRegex","RegExp","styleValue","SharedTKHQ","applySettings","validSettings","settingsObj","passphraseLabel","mnemonicLabel","passphraseTextarea","plaintextTextarea","enablePassphrase","style","display","border","_slicedToArray","key","documentElement","body","passphraseStyles","_ref3","_ref4","ownKeys","keys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","_objectSpread","_defineProperty","getOwnPropertyDescriptors","defineProperties","_typeof","toPrimitive","String","_toPrimitive","_toPropertyKey","TURNKEY_HPKE_INFO","TextEncoder","encode","HpkeEncrypt","_HpkeEncrypt","plaintextBuf","receiverPubJwk","kemContext","receiverPub","suite","senderCtx","receiverPubCryptoKey","receiverPubRaw","encappedKeyBuf","aad","ciphertextBuf","ciphertextHex","encappedKeyBufHex","encryptedBundle","DhkemP256HkdfSha256","CipherSuite","kem","kdf","HkdfSha256","aead","Aes256Gcm","createSenderContext","recipientPublicKey","info","enc","seal","encappedPublic","ciphertext"],"sourceRoot":""} \ No newline at end of file diff --git a/shared/turnkey-core.js b/shared/turnkey-core.js index 6c94460..131ca98 100644 --- a/shared/turnkey-core.js +++ b/shared/turnkey-core.js @@ -9,7 +9,6 @@ import { bech32 } from "bech32"; const TURNKEY_EMBEDDED_KEY = "TURNKEY_EMBEDDED_KEY"; const TURNKEY_TARGET_EMBEDDED_KEY = "TURNKEY_TARGET_EMBEDDED_KEY"; const TURNKEY_SETTINGS = "TURNKEY_SETTINGS"; -const TURNKEY_ENCRYPTED_BUNDLES = "TURNKEY_ENCRYPTED_BUNDLES"; /** 48 hours in milliseconds */ const TURNKEY_EMBEDDED_KEY_TTL_IN_MILLIS = 1000 * 60 * 60 * 48; const TURNKEY_EMBEDDED_KEY_ORIGIN = "TURNKEY_EMBEDDED_KEY_ORIGIN"; @@ -215,90 +214,6 @@ function setSettings(settings) { window.localStorage.setItem(TURNKEY_SETTINGS, JSON.stringify(settings)); } -/** - * Gets all encrypted bundles from localStorage. - * Returns an object mapping address -> {encappedPublic, ciphertext, organizationId, keyFormat} - * or null if no bundles are stored. - * @returns {Object|null} - */ -function getEncryptedBundles() { - const data = window.localStorage.getItem(TURNKEY_ENCRYPTED_BUNDLES); - if (!data) { - return null; - } - try { - return JSON.parse(data); - } catch (e) { - // If the stored data is corrupted or not valid JSON, remove it to self-heal. - window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES); - return null; - } -} - -/** - * Stores or updates an encrypted bundle for a given address. - * @param {string} address - The wallet address - * @param {Object} bundleData - {encappedPublic, ciphertext, organizationId, keyFormat} - */ -function setEncryptedBundle(address, bundleData) { - const bundles = getEncryptedBundles() || {}; - bundles[address] = bundleData; - window.localStorage.setItem( - TURNKEY_ENCRYPTED_BUNDLES, - JSON.stringify(bundles) - ); -} - -/** - * Removes a single encrypted bundle by address. - * Only removes the bundle if it belongs to the specified organization. - * @param {string} address - The wallet address to remove - * @param {string} organizationId - Only remove if the bundle belongs to this org - */ -function removeEncryptedBundle(address, organizationId) { - const bundles = getEncryptedBundles(); - if (!bundles || !bundles[address]) return; - - // Only remove if the bundle belongs to the specified organization - if (bundles[address].organizationId !== organizationId) return; - - delete bundles[address]; - if (Object.keys(bundles).length === 0) { - window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES); - } else { - window.localStorage.setItem( - TURNKEY_ENCRYPTED_BUNDLES, - JSON.stringify(bundles) - ); - } -} - -/** - * Removes all encrypted bundles belonging to the specified organization. - * Bundles from other organizations are preserved. - * @param {string} organizationId - Remove bundles belonging to this org - */ -function clearAllEncryptedBundles(organizationId) { - const bundles = getEncryptedBundles(); - if (!bundles) return; - - // Keep only bundles that do NOT belong to this organization - const remaining = Object.fromEntries( - Object.entries(bundles).filter( - ([, bundle]) => bundle.organizationId !== organizationId - ) - ); - - if (Object.keys(remaining).length === 0) { - window.localStorage.removeItem(TURNKEY_ENCRYPTED_BUNDLES); - } else { - window.localStorage.setItem( - TURNKEY_ENCRYPTED_BUNDLES, - JSON.stringify(remaining) - ); - } -} - /** * Set an item in localStorage with an expiration time * @param {string} key @@ -1016,8 +931,4 @@ export { encodeKey, parsePrivateKey, validateStyles, - getEncryptedBundles, - setEncryptedBundle, - removeEncryptedBundle, - clearAllEncryptedBundles, }; diff --git a/shared/turnkey-core.test.js b/shared/turnkey-core.test.js index 7c49d06..6ed8988 100644 --- a/shared/turnkey-core.test.js +++ b/shared/turnkey-core.test.js @@ -445,86 +445,4 @@ describe("Shared TKHQ Utilities", () => { expect(publicKey.length).toBe(65); // Uncompressed P-256 public key }); }); - - describe("Encrypted bundle org isolation", () => { - const orgA = "org-alpha"; - const orgB = "org-beta"; - - const bundleA1 = { - encappedPublic: "aa", - ciphertext: "bb", - organizationId: orgA, - keyFormat: "SOLANA", - }; - const bundleA2 = { - encappedPublic: "cc", - ciphertext: "dd", - organizationId: orgA, - keyFormat: "HEXADECIMAL", - }; - const bundleB1 = { - encappedPublic: "ee", - ciphertext: "ff", - organizationId: orgB, - keyFormat: "SOLANA", - }; - - beforeEach(() => { - SharedTKHQ.setEncryptedBundle("addrA1", bundleA1); - SharedTKHQ.setEncryptedBundle("addrA2", bundleA2); - SharedTKHQ.setEncryptedBundle("addrB1", bundleB1); - }); - - it("removeEncryptedBundle refuses to delete another org's bundle", () => { - // orgB tries to remove addrA1 (belongs to orgA) - SharedTKHQ.removeEncryptedBundle("addrA1", orgB); - - const bundles = SharedTKHQ.getEncryptedBundles(); - expect(bundles["addrA1"]).toEqual(bundleA1); // still present - expect(bundles["addrB1"]).toEqual(bundleB1); - }); - - it("removeEncryptedBundle succeeds when orgId matches", () => { - SharedTKHQ.removeEncryptedBundle("addrA1", orgA); - - const bundles = SharedTKHQ.getEncryptedBundles(); - expect(bundles["addrA1"]).toBeUndefined(); // gone - expect(bundles["addrA2"]).toEqual(bundleA2); // other orgA bundle untouched - expect(bundles["addrB1"]).toEqual(bundleB1); - }); - - it("clearAllEncryptedBundles only removes the target org's bundles", () => { - SharedTKHQ.clearAllEncryptedBundles(orgA); - - const bundles = SharedTKHQ.getEncryptedBundles(); - // orgA bundles are gone - expect(bundles["addrA1"]).toBeUndefined(); - expect(bundles["addrA2"]).toBeUndefined(); - // orgB bundle is still present - expect(bundles["addrB1"]).toEqual(bundleB1); - }); - - it("clearAllEncryptedBundles removes localStorage key when all remaining bundles are cleared", () => { - // Clear orgA first - SharedTKHQ.clearAllEncryptedBundles(orgA); - expect(SharedTKHQ.getEncryptedBundles()).not.toBeNull(); - - // Clear orgB — now nothing should remain - SharedTKHQ.clearAllEncryptedBundles(orgB); - expect(SharedTKHQ.getEncryptedBundles()).toBeNull(); - }); - - it("orgB cannot peek at orgA's bundle data via getEncryptedBundles", () => { - // getEncryptedBundles returns everything (it's a raw accessor), - // but the handler layer in event-handlers.js filters by orgId. - // At the storage layer, verify that removing orgB's data doesn't - // leak or corrupt orgA's entries. - SharedTKHQ.clearAllEncryptedBundles(orgB); - - const bundles = SharedTKHQ.getEncryptedBundles(); - expect(Object.keys(bundles)).toEqual(["addrA1", "addrA2"]); - expect(bundles["addrA1"]).toEqual(bundleA1); - expect(bundles["addrA2"]).toEqual(bundleA2); - }); - }); });