@safetech/inheriti-client-sdk 1.17.13 → 1.17.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -1 +1 @@
1
- import{decodeAssetContainer as Wt}from"@safetech/inheriti-core-sdk/core/protocols/ssdp+";import{decryptRSAOAEP as nt,generateRSAOAEPKeyPair as it}from"@safetech/inheriti-core-sdk/crypto";var J=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ee=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},te=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},V=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:n,privateKey:i}=await it();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let a=await this.options.api.startRelaySession(n),s=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),l=this.options.sleep??(I=>new Promise(T=>setTimeout(T,I))),c=!0,h=!1,P,A=()=>P??=Promise.resolve().then(()=>this.options.api.cancelRelaySession?.(a.sessionId)),Z,rt=new Promise((I,T)=>{Z=()=>{c&&A().catch(()=>{}),T(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",Z,{once:!0})});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(a),h=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let I=await Promise.race([this.options.api.readRelaySession(a.sessionId),rt]);if(I.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(I.status==="DELIVERED"&&I.sealedMasterKey){let T=(await nt(I.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(T))throw new Error("invalid_master_key_material");return T}if(I.status==="EXPIRED")throw new ee(a.sessionId);await at(l,s,e)}throw new J(a.sessionId)}catch(I){if(c&&(!h||e?.aborted))try{await A()}catch(T){if(e?.aborted)throw new te(T)}throw I}finally{Z&&e?.removeEventListener("abort",Z)}}};async function at(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,i)=>{let a=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",a,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",a))})}function re(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let i=await r.source?.resolve();return i||fe(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(st(e,r.applicationId)){let i=await r.source?.resolve();return i||fe(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return fe(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function st(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function fe(r,e,t,n,i){if((await e()).relayAvailable)return new V({...r.relay,api:ot(r.api,t)}).resolve(n,i)}function ot(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:t=>r.readMasterKeyRelaySession(t),cancelRelaySession:t=>r.cancelMasterKeyRelaySession(t)}}function O(r){return`${r.system}:${r.contextId}`}function Re(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var _=class extends Error{constructor(t){super(`master_key_required:${O(t)}`);this.ref=t;this.name="MasterKeyRequired"}},ve=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(O(e),t),this}async resolve(e){return this.sources.get(O(e))?.resolve()}};var B=class{keys=new Map;async store(e,t){this.keys.set(O(e),t.slice())}async load(e){return this.keys.get(O(e))?.slice()}async remove(e){this.keys.delete(O(e))}};var F=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var ne=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},p=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var H=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var ie=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],lt={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},ke=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],m=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},C=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function U(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new C("plan_material_field_unknown");if(Pe(r.dataShards,"data_shards_invalid"),Pe(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&Pe(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new C("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new C("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new C("material_operation_invalid")}function Pe(r,e){if(!Array.isArray(r))throw new C(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new C(e);if(t.data!==void 0&&typeof t.data!="string")throw new C(e)}}function k(r){if(M(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!pt(r.idempotencyKey))throw new m("idempotency_key_invalid");if(!r.name?.trim())throw new m("plan_name_required");if(!r.assets.length)throw new m("assets_required");let e=new Set;for(let t of r.assets){if(M(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new m("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!ie.includes(t.type))throw new m("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new m("asset_binary_representation_invalid");let i=t.fieldNames??[];if(t.isBinary&&(i.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new m("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new m("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(a=>!a.trim()))throw new m("asset_field_names_invalid");if(ct(t.matchOrigins),!t.isBinary){let a=lt[t.type];if(!a||i.some(s=>!a.includes(s)))throw new m("asset_field_name_not_canonical")}}if(!r.participants.length)throw new m("participants_required");for(let t of r.participants){if(M(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Ne(t.routingEmail))throw new m("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new m("participant_relationships_invalid")}dt(r)}function ct(r){if(r===void 0)return;if(!r.length)throw new m("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new m("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new m("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof m?n:new m("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new m("asset_match_origins_duplicated")}function dt(r){let e=r.policy;if(e&&M(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new m("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){M(e.authentication,["mode"],"plan_authentication_field_unknown");let a=e.authentication.mode;if(a!==void 0&&a!=="EXCLUSIVE"&&a!=="ALL_REQUIRED")throw new m("authentication_mode_invalid")}if(e.moderation){M(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let a=r.participants.filter(l=>l.relationships.includes("MODERATOR"));if(a.length===0)throw new m("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>a.length))throw new m("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new m("approval_mode_invalid")}let t=e.dms;if(!t)return;M(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!Ne(t.subjectEmail))throw new m("dms_subject_invalid");if(!r.participants.some(a=>Me(a.routingEmail)===Me(t.subjectEmail)))throw new m("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(i)||t.countdownDays<0||n<0||n>23||i<0||i>59||t.countdownDays+n+i===0)throw new m("dms_countdown_invalid")}function pt(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function Ne(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Me(r){return r.normalize("NFC").trim().toLowerCase()}function M(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new m(t)}var se=class{checkpoints=new Map;async load(e){return this.checkpoints.get(e)}async save(e){this.checkpoints.set(e.operationId,e)}async remove(e){this.checkpoints.delete(e)}},oe=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),k(e),ae(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,i,a={}){k(t);let s=await this.checkpoints.load(e);if(!s)throw new le("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await Ke(t))throw new le("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(a.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;ae(a.signal),a.onProgress?.("ENCRYPTING");let l=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:a.signal});ae(a.signal),a.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:l,signal:a.signal});ae(a.signal),U(c);let h=await this.api.supplyPlanCreationMaterial(e,c);return a.onProgress?.(h.stage),h.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,h),h}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await Ke(e),serverStage:t.stage})}},le=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Ke(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,i)=>n.clientAssetRef.localeCompare(i.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,i)=>n.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function ae(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Ue(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new ne(n.stage);return r.authorizeRevealAction(e,t)}function ut(r){let e=r?.status;return e===400||e===401||e===403}async function Le(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(a){if(!ut(a))throw a}return r.releaseRevealMaterial(e,t)}function Ve(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?ht(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":mt.has(r.stage)?"ENDED":"CONTINUING"}var mt=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function ht(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var de=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},y=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function we(r,e,t={}){if(t.signal?.aborted)throw g();let n=await r.getPlan(e),i=await r.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Ge(i.id);if(t.signal?.aborted||(t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await r.prepareReveal(e,t.signal,t.onRelaySession),t.signal?.aborted))throw g();let a=t.idempotencyKey??crypto.randomUUID(),s;try{s=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a})}catch(l){if(l?.code!=="merge_process_already_active")throw l;let c=await r.getActivePlanReveal(e);throw!c||c.planId!==e||c.mode!==(t.mode??"DIRECT")?l:Ge(c.id)}let o;try{if(t.signal?.aborted)throw g();let l=await gt(r,s,t);if(t.signal?.aborted)throw g();D(t,"RELEASING_MATERIAL",l);let c=await r.releaseRevealMaterial(l.id,l.materialVersion??"1");if(t.signal?.aborted)throw g();l.mode==="GOVERNED"&&await r.markRevealSharesCollected(l.id);let h;try{h=await Rt(r,l,It(c),t)}finally{t.proDevice?.clearPin?.()}D(t,"RECONSTRUCTING",l);try{o=await r.reconstructPlanMaterial(h)}catch(A){throw await r.reportRevealReconstruction(l.id,{status:"FAILED",errorCode:vt(A)}),A}let P=await r.reportRevealReconstruction(l.id,{status:"SUCCEEDED"});return D(t,"OPEN",P),new Ie(r,P,n,o,t.signal)}catch(l){throw o?.fill(0),await Et(r,s.id,t.signal?.aborted?"CANCELED":"ERROR"),l}}function Ge(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var yt=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function gt(r,e,t){let n=await r.getReveal(e.id);for(;;){if(t.signal?.aborted)throw g();if(t.onSession?.(n),t.onProgress?.({phase:Ve(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(yt.has(n.stage))throw new pe(n.stage);await Se(t.pollIntervalMs??1500,t.signal),n=await r.getReveal(e.id)}}var pe=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function D(r,e,t){r.onProgress?.({phase:e,session:t})}function Se(r,e){return e?.aborted?Promise.reject(g()):new Promise((t,n)=>{let i=setTimeout(s,Math.max(0,r)),a=()=>{clearTimeout(i),n(g())};function s(){e?.removeEventListener("abort",a),t()}e?.addEventListener("abort",a,{once:!0})})}var Ie=class{constructor(e,t,n,i,a){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let s=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(s,2147483647)),this.abortListener=a?()=>{this.close("CANCELED")}:void 0,a&&this.abortListener&&a.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new de;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([i])=>{n=i?.value}),n}async consumeFields(e,t){if(e.length===0)throw new y("asset_selector_invalid");if(!this.client.assetDecoder)throw new y("asset_decoder_required");let n=e.map(({selector:a,options:s={}})=>{let o=Be(a),l=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!l)throw new y("asset_not_found");if(l.isBinary)throw new y("action_not_allowed");if(!l.fieldNames.includes(o.field))throw new y("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:l,field:o.field,options:s}}),i=[];try{for(let s of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:s.options.idempotencyKey??crypto.randomUUID(),assetId:s.asset.id,fieldName:s.field,action:s.options.action??"VIEW_FIELD",...s.options.destination===void 0?{}:{destination:s.options.destination},...s.options.origin===void 0?{}:{origin:s.options.origin}}));let a=n.map(s=>{let o=this.client.assetDecoder(this.material).find(l=>l.id===s.asset.id||l.id===s.assetCode);if(!o)throw new y("asset_value_invalid");return{selector:s.selector,value:ft(o.data,s.field,s.asset.type)}});await t(a)}catch(a){throw await Promise.all(i.map(s=>this.reportAction(s.id,"FAILED",ze(a)))),a}await Promise.all(i.map(a=>this.reportAction(a.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new y("asset_selector_invalid");if(!this.client.assetDecoder)throw new y("asset_decoder_required");let n=this.plan.assets.find(s=>s.code===e||s.id===e);if(!n)throw new y("asset_not_found");if(!n.isBinary)throw new y("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),a;try{let s=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!s||!(s.data instanceof Uint8Array))throw new y("asset_value_invalid");a=s.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:a})}catch(s){throw await this.reportAction(i.id,"FAILED",ze(s)),s}finally{a?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=this.client.closeReveal(this.session.id,e).then(()=>{}).catch(t=>{if(!Fe(t))throw t}),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function Be(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new y("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new y("asset_selector_invalid");return{asset:r.asset,field:r.field}}function ft(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new y("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new y("asset_value_invalid");if(!(e in n)){if(t==="USER-PSWD"&&["appOrWebsite","email","username","password"].includes(e))return"";throw new y("asset_value_invalid")}return n[e]}function ze(r){if(r instanceof y)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function vt(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Rt(r,e,t,n){let i=t.shares.find(l=>l.shareType==="CUSTODIAN_KEY_SHARD");if(i){let l=await ce(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(l==="SK_PRO"){if(!n.proDevice)throw new ue;let c=await ce(()=>r.getRevealCustodianClaimable(e.id),n.signal);if(qe(c,i.id,e.planId),!c.shares.includes(i.data))throw new E;D(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:h}=await ce(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw g();if(!h?.trim())throw new E;if(await r.claimRevealCustodianShare(e.id,c.id,h),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw g();return{...t,shares:t.shares.filter(P=>P!==i).concat(c.shares.map((P,A)=>({id:`${c.id}:${A}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:P})))}}if(l!=="SK_MOBILE")throw new E;return await r.distributeRevealCustodianShare(e.id),D(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let a=await r.getRevealCustodianAccess(e.id);for(;a.status==="PENDING"||a.status==="DISTRIBUTED";){let l={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(l),D(n,"WAITING_FOR_CUSTODIAN_CLAIM",l),await Se(n.pollIntervalMs??1500,n.signal),a=await r.getRevealCustodianAccess(e.id)}if(a.status==="CLAIMED"&&a.deviceType==="SK_PRO"){if(!n.proDevice)throw new ue;if(!a.shareId||!a.deviceId)throw new E;D(n,"CONNECTING_SAFEKEY_PRO",e);let l=await ce(()=>n.proDevice.read({shareId:a.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw g();if(qe(l,a.shareId,e.planId),l.deviceId!==a.deviceId)throw new E;if(await r.collectRevealCustodianShare(e.id,a.shareId),n.signal?.aborted)throw g();return{...t,shares:t.shares.concat(l.shares.map((c,h)=>({id:`${l.id}:${h}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(a.status!=="CLAIMED"||a.deviceType!=="SK_MOBILE")throw new E;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};n.onSession?.(s),D(n,"WAITING_FOR_CUSTODIAN",s),await r.requestRevealCustodianRelease(e.id);let o=await Pt(r,e.id,n);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((l,c)=>({id:`${o.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:l})))})}function qe(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new E}async function ce(r,e){if(e?.aborted)throw g();if(!e)return r();let t,n=new Promise((i,a)=>{t=()=>a(g()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw g();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function Pt(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await r.getRevealCustodianShare(e);if(i&&i.status!=="PENDING"){let a=i;if(a.shares?.length)return a;throw new E}if(Date.now()>=n)throw new Ee;await Se(t.pollIntervalMs??1500,t.signal)}}var E=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},ue=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Ee=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function It(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function Et(r,e,t){try{await r.closeReveal(e,t)}catch(n){if(!Fe(n))throw n}}function Fe(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function g(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var W=class{constructor(e,t={}){this.coreSdk=e;if(t.applicationId!==void 0&&t.organizationId!==void 0)throw new Error("application_and_business_context_conflict");if(t.organizationId!==void 0&&!t.organizationId.trim())throw new Error("organization_id_required");this.keyVault=t.keyVault??new B,this.state=t.state??new F,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??At(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new p;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new p;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new p;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return k(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new p;return U(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new se){if(this.requireApplication(),!this.api)throw new p;return new oe(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new _({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,n){let i=await this.keyVault.load(e);if(i)return St(i);let a=await this.masterKeys?.resolve(e,t,n);if(!a)throw new _(e);return await this.keyVault.store(e,wt(a)),a}async prepareReveal(e,t,n){if(!this.api)throw new p;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,n)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new p;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new H;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,n){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new _({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=Re(e);if(!i)throw new _({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new p;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new p;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new p;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new p;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e){if(!this.api)throw new p;return this.api.getReveal(e)}openReveal(e,t){return we(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let a=await n(i);return await i.close("COMPLETED"),a}catch(a){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),a}}async releaseRevealMaterial(e,t){if(!this.api)throw new p;return Le(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new p;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new p;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new p;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e){if(!this.api)throw new p;return this.api.getRevealCustodianAccess(e)}getRevealCustodianShare(e){if(!this.api)throw new p;return this.api.getRevealCustodianShare(e)}getRevealCustodianClaimable(e){if(!this.api)throw new p;return this.api.getRevealCustodianClaimable(e)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new p;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new p;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new p;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t){if(!this.api)throw new p;return this.api.closeReveal(e,t)}abortPlanAccess(e,t){if(!this.api)throw new p;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e){if(!this.api)throw new p;return this.api.cancelMasterKeyRelaySession(e)}async authorizeRevealAction(e,t){if(!this.api)throw new p;return Ue(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new p;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new p;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new p;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new p;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new p;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new p;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),i=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let a=n.validatorShares.map(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),s=i.dataShards.map(c=>Object.assign({},c,{shareType:"DATA_SHARD"})),o=i.backupShards.map(c=>Object.assign({},c,{shareType:"BACKUP_SHARD"})),l=i.keyShards.map(c=>Object.assign({},c,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||n.dek,shares:a.concat(s,o,l),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new p;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new me;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new _({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},me=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function wt(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function St(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function At(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return re({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return re({...e,organizationId:r.organizationId})}import{createBrowserSsdpV2WorkerFactory as Mt,createSsdpV2Processor as kt}from"@safetech/inheriti-core-sdk/workers/ssdp-v2";async function Ae(r,e){if(!e)throw new Error("master_key_required");let t=_t(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=Ct(r),a=i.slice(0,12),s=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},n,s);return Tt(new Uint8Array(o))}function _t(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Ct(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function Tt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var $=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await He("plan_key_unwrap_failed",()=>Ae(e.planKey,t)),i=await crypto.subtle.importKey("raw",_e(n),{name:"AES-GCM"},!1,["decrypt"]),a=[],s=[];for(let o of e.shares){let l=await He("plan_share_decryption_failed",()=>bt(o.data,i));xt(o.shareType)?s.push(l):a.push(l)}try{return await this.processor().reconstruct(a,{planId:e.planId,threshold:e.mergeThreshold,keyShares:s}).result}catch(o){throw new he("plan_share_reconstruction_failed",Dt(o))}}},he=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},Ot=new Set(["insufficient_valid_data_shards","insufficient_valid_key_shards","mixed_share_sets","threshold_metadata_mismatch","duplicate_data_shard","duplicate_key_shard","plan_binding_mismatch","ciphertext_digest_mismatch","v2_authentication_failed","shard_kind_mismatch","envelope_truncated","invalid_envelope_magic","unsupported_envelope_version","invalid_shard_kind","unsupported_v2_suite","invalid_envelope_length","crc32c_mismatch","invalid_envelope_metadata","invalid_envelope_threshold","invalid_data_shard_length","invalid_base64url","insufficient_shards","insufficient_key_shards","conflicting_key_shards","duplicate_shard","invalid_shard_index","invalid_key_shard_index","invalid_shard_length","invalid_key_length","plaintext_length_mismatch","ssdp_v2_worker_failed","ssdp_v2_worker_not_configured","unexpected_ssdp_v2_worker_response"]);function Dt(r){let e=r instanceof Error?r.message:void 0;if(e)return Ot.has(e)?e:void 0}async function He(r,e){try{return await e()}catch{throw new he(r)}}function xt(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function bt(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=_e(r.slice(0,t)),i=_e(r.slice(t+1)),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(a)}function _e(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return t}var j=class extends ${constructor(e={}){let t=e.processor??kt(e.workerUrl!==void 0&&typeof Worker<"u"?{workerFactory:Mt(e.workerUrl),allowMainThreadFallback:!0}:{allowMainThreadFallback:!0});super(()=>t)}};var Nt=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Kt=["DIRECT","GOVERNED"],$e=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],Ut=["ACTIVE","REVOKED"],Lt=["SK_MOBILE"],Gt=["ACTIVE","INACTIVE"],zt=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function je(r){let e=f(r);return{items:R(e.items).map(Xe),nextCursor:e.nextCursor===null?null:d(e.nextCursor,"nextCursor")}}function Ye(r){let e=f(r);return{total:w(e.total,"total"),items:R(e.items).map(t=>{let n=f(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:d(n.id,"log.id"),planId:d(n.planId,"log.planId"),tenantId:d(n.tenantId,"log.tenantId"),event:d(n.event,"log.event"),occurredOn:d(n.occurredOn,"log.occurredOn"),status:x(n.status),title:d(n.title,"log.title"),details:R(n.details).map(i=>{let a=f(i);return{label:d(a.label,"log.detail.label"),value:d(a.value,"log.detail.value")}})}})}}function Qe(r){let e=f(r),t=Xe(e),n=f(e.source),i=d(n.kind,"source.kind");return{...t,assets:R(e.assets).map(a=>{let s=f(a);return{id:d(s.id,"asset.id"),code:x(s.code),type:v(d(s.type,"asset.type"),ie),name:d(s.name,"asset.name"),isBinary:Vt(s.isBinary,"asset.isBinary"),fieldNames:R(s.fieldNames).map(o=>d(o,"asset.fieldNames")),fileName:x(s.fileName),mimeType:x(s.mimeType),size:s.size===void 0||s.size===null?void 0:w(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:R(s.matchOrigins).map(o=>d(o,"asset.matchOrigins"))}}),participants:R(e.participants).map(a=>{let s=f(a);return{id:d(s.id,"participant.id"),displayName:d(s.displayName,"participant.displayName"),relationships:R(s.relationships).map(o=>v(d(o,"relationship"),$e)),lifecycle:v(d(s.lifecycle,"participant.lifecycle"),Ut)}}),revealPolicy:(()=>{let a=f(e.revealPolicy);return{masterKeyRelease:v(d(a.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:v(d(a.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let a=f(e.dms);return{subjectEmail:d(a.subjectEmail,"dms.subjectEmail"),countdownDays:w(a.countdownDays,"dms.countdownDays"),countdownHours:w(a.countdownHours,"dms.countdownHours"),countdownMinutes:w(a.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:v(d(n.system,"source.system"),["INHERITI_BUSINESS"]),status:v(d(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function Y(r){let e=f(r);return{operationId:d(e.operationId,"operationId"),stage:v(d(e.stage,"stage"),ke),outcome:v(d(e.outcome,"outcome"),zt),planId:x(e.planId),lastErrorCode:x(e.lastErrorCode),participants:e.participants===void 0?void 0:R(e.participants).map(t=>{let n=f(t);return{clientParticipantRef:d(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:d(n.planParticipantId,"planParticipantId"),relationships:R(n.relationships).map(i=>qt(d(i,"relationship"),$e))}})}}function Xe(r){let e=f(r),t=f(e.assetSummary),n=f(e.governance),i=f(e.participantSummary);return{id:d(e.id,"id"),name:d(e.name,"name"),description:x(e.description),status:v(d(e.status,"status"),Nt),createdAt:d(e.createdAt,"createdAt"),configuredAt:x(e.configuredAt),assetSummary:{count:w(t.count,"assetSummary.count"),types:R(t.types).map(a=>v(d(a,"assetType"),ie)),names:We(t.names).map(a=>d(a,"assetSummary.names"))},governance:{mode:v(d(n.mode,"governance.mode"),Kt),minimumApprovals:w(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:w(i.owners,"owners"),mergers:w(i.mergers,"mergers"),moderators:w(i.moderators,"moderators")},authentication:We(e.authentication).map(a=>{let s=f(a);return{id:v(d(s.id,"authentication.id"),Lt),status:v(d(s.status,"authentication.status"),Gt)}})}}function v(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function qt(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function f(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function We(r){return r==null?[]:R(r)}function R(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function d(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function x(r){return r==null?void 0:d(r,"optional")}function w(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function Vt(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var L=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function Ze(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function Bt(r,e){if(!e){if(r.length===0)throw new L("organization_required");if(r.length>1)throw new L("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new L("organization_access_denied");return e}function Ce(r){return typeof r.error=="string"?/^[a-z][a-z0-9_]*$/.test(r.error)?r.error:typeof r.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(r.validationErrors)?r.validationErrors:r.error||void 0:r.error?.code??r.name??r.message}function Te(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var N=class extends Error{constructor(t,n,i){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},G=class{constructor(e,t,n,i,a){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=a?Object.freeze({...a}):void 0}business;listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(Ze)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return je(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Qe(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return Ye(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){k(e);let{idempotencyKey:t,...n}=e;return Y(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return Y(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return U(t),Y(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return Y(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET")}async cancelMasterKeyRelaySession(e){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE")}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":n})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET")}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET")}getRevealCustodianShare(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET")}getRevealCustodianClaimable(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET")}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t})}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...a}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",a,void 0,{"idempotency-key":i})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,i,a){this.requireBusinessSelection(e);let s=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});s&&o.set("authorization",`Bearer ${s}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&o.set("x-organization-id",this.business.organizationId),i?.requestId&&o.set("x-elements-step-up-request",i.requestId);for(let[P,A]of Object.entries(a??{}))o.set(P,A);n&&o.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,l),{method:t,headers:o,body:n?JSON.stringify(n):void 0}),h=await Je(c);if(!c.ok)throw new N(c.status,Ce(h),Te(h));if(!h.ok||h.result===void 0)throw new N(c.status,Ce(h),Te(h));return h.result}async requestWithoutResult(e,t){this.requireBusinessSelection(e);let n=await this.getBearerToken(),i=new Headers({"x-elements-environment":this.environment});n&&i.set("authorization",`Bearer ${n}`),this.business?.organizationId&&i.set("x-organization-id",this.business.organizationId),t&&i.set("content-type","application/json");let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,s=await this.transport(new URL(e,a),{method:"POST",headers:i,body:t?JSON.stringify(t):void 0}),o=await Je(s);if(!s.ok||!o.ok)throw new N(s.status,Ce(o),Te(o))}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new N(400,"organization_selection_required")}};async function Je(r){try{return await r.json()}catch{return{ok:!1}}}import{PassphraseMasterKeySource as en,RawMasterKeySource as tn,computePassphraseVerifier as rn,deriveMasterKey as nn,generateHexSeed as an}from"@safetech/inheriti-core-sdk/crypto";function et(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Q=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),et(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return et(new Uint8Array(t))}},X=class{now(){return Date.now()}sleep(e,t){return new Promise((n,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let a=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(a),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var z=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},q=class extends z{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},u=class extends z{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function ye(r){if(r instanceof z)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var Oe=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:b(n,"issuer"),authorizationEndpoint:b(n,"authorization_endpoint"),tokenEndpoint:b(n,"token_endpoint"),deviceAuthorizationEndpoint:S(n,"device_authorization_endpoint"),endSessionEndpoint:S(n,"end_session_endpoint"),revocationEndpoint:S(n,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:b(t,"device_code"),userCode:b(t,"user_code"),verificationUri:b(t,"verification_uri"),verificationUriComplete:S(t,"verification_uri_complete"),expiresInSeconds:tt(t,"expires_in"),intervalSeconds:De(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async token(e,t){let n=await this.form(e,t);return{accessToken:b(n,"access_token"),refreshToken:S(n,"refresh_token"),idToken:S(n,"id_token"),tokenType:b(n,"token_type"),expiresInSeconds:tt(n,"expires_in"),refreshExpiresInSeconds:De(n,"refresh_expires_in"),scope:S(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await n.json()}catch{}if(!n.ok){let a=S(i,"error")??`oauth_http_${n.status}`;throw new u(a,S(i,"error_description")??a)}return i}};function b(r,e){let t=S(r,e);if(!t)throw new u("invalid_oauth_response",`Missing ${e}`);return t}function S(r,e){return typeof r[e]=="string"?r[e]:void 0}function tt(r,e){let t=De(r,e);if(t===void 0)throw new u("invalid_oauth_response",`Missing ${e}`);return t}function De(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Ft=600*1e3,ge=5,Ht=5,xe=class{constructor(e){this.options=e;this.crypto=e.crypto??new Q,this.clock=e.clock??new X}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(i),s=this.clock.now()+Ft;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:i,redirectUri:this.options.configuration.redirectUri,expiresAt:s});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",n),o.searchParams.set("code_challenge",a),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:s}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new u("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new u("authorization_transaction_expired");let i=new URL(e),a=new URL(n.redirectUri);if(i.origin!==a.origin||i.pathname!==a.pathname)throw new u("redirect_uri_mismatch");let s=i.searchParams.get("error");if(s)throw new u(s,i.searchParams.get("error_description")??s);if(i.searchParams.get("state")!==n.state)throw new u("state_mismatch");let o=i.searchParams.get("code");if(!o)throw new u("authorization_code_missing");let l=await this.getDiscovery(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:l.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),h=await this.acceptTokens(c,n.nonce);return await this.options.sessions.save(h),h}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new u("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(ge,t.intervalSeconds??ge),i=this.clock.now(),a={...t,kind:"device-code",intervalSeconds:n,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),a),a}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new u("device_transaction_missing");let i=n,a=await this.getDiscovery(),s=Math.max(ge,i.intervalSeconds??ge),o=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(o>=i.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let l=await this.options.transport.pollDeviceToken({tokenEndpoint:a.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let c=await this.acceptTokens(l);return await this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(l){let c=ye(l);if(c==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(c==="slow_down"){s+=Ht,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),l}}throw await this.options.transactions.remove(t),new u("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new q;try{let t=await this.getDiscovery(),n=await this.options.transport.refresh({tokenEndpoint:t.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken});if(!n.refreshToken)throw new u("refresh_token_rotation_missing");let i=await this.acceptTokens(n);return await this.options.sessions.save(i),i}catch(t){await this.options.sessions.clear();let n=ye(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new q:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(K(e.issuer)!==K(this.options.configuration.issuer))throw new u("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:i}=this.options.configuration;return`${e}|${K(t)}|${n}|${i}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new u("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new u("id_token_validation_required");let a=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(a,t),a.subject!==n.subject||a.sessionId!==n.sessionId)throw new u("token_subject_mismatch")}let i=this.clock.now();return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:i+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0?void 0:i+e.refreshExpiresInSeconds*1e3,principal:n}}assertPrincipal(e,t,n){let i=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(K(e.issuer)!==K(i.issuer))throw new u("issuer_mismatch");if(!a.includes(i.audience))throw new u("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new u("client_mismatch");if(e.environment!==i.environment)throw new u("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new u("required_claim_missing");if(n&&e.nonce!==t)throw new u("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(K(e.issuer)!==K(n.issuer))throw new u("issuer_mismatch");if(!i.includes(n.clientId))throw new u("client_mismatch");if(e.authorizedParty!==n.clientId)throw new u("client_mismatch");if(!e.subject||!e.sessionId)throw new u("required_claim_missing");if(e.nonce!==t)throw new u("nonce_mismatch")}};function K(r){return r.replace(/\/+$/u,"")}var be=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};function Hr(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=new G(r.apiUrl,r.environment,r.getBearerToken,e,r.business?{organizationId:r.organizationId}:void 0);return new W(void 0,{api:t,applicationId:r.applicationId,organizationId:r.organizationId,masterKeys:r.masterKeys,masterKey:r.masterKey,assetDecoder:Wt,reconstructor:r.reconstructor??new j(r.reconstruction??{}),...r.keyVault===void 0?{}:{keyVault:r.keyVault},...r.state===void 0?{}:{state:r.state}})}export{j as BrowserPlanMaterialReconstructor,L as BusinessOrganizationSelectionError,me as CoreSdkContainerRequired,N as ElementsApiRequestFailed,W as ElementsClient,G as HttpElementsApiPort,Oe as HttpOperatorAuthTransport,te as MasterKeyRelayCancellationFailed,ee as MasterKeyRelayExpired,J as MasterKeyRelayTimedOut,_ as MasterKeyRequired,B as MemoryKeyVault,F as MemoryStatePort,u as OAuthProtocolError,xe as OperatorAuthClient,z as OperatorAuthError,q as OperatorReauthenticationRequired,be as OperatorSessionController,en as PassphraseMasterKeySource,H as PlanMaterialReconstructorRequired,tn as RawMasterKeySource,V as RelayMasterKeySource,pe as RevealAuthorizationEnded,y as RevealFieldAccessError,de as RevealHandleClosed,ve as StaticMasterKeyResolver,X as SystemOAuthClock,Q as WebOAuthCrypto,rn as computePassphraseVerifier,Hr as createBrowserElementsClient,re as createMasterKeyResolver,Wt as decodeAssetContainer,nn as deriveMasterKey,an as generateHexSeed,Re as masterKeyRefFor,O as masterKeyRefKey,ye as oauthErrorCode,we as openScopedReveal,Be as parseAssetFieldSelector,Ve as revealPhaseOf,Bt as selectBusinessOrganization,Ae as unwrapDekWithMasterKey};
1
+ import{decodeAssetContainer as jt}from"@safetech/inheriti-core-sdk/core/protocols/ssdp+";import{decryptRSAOAEP as st,generateRSAOAEPKeyPair as ot}from"@safetech/inheriti-core-sdk/crypto";var te=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},re=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},ne=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},B=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:n,privateKey:i}=await ot();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let a=await this.options.api.startRelaySession(n),s=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),l=this.options.sleep??(I=>new Promise(w=>setTimeout(w,I))),c=!0,g=!1,P,v=()=>P??=(async()=>{let I=new AbortController,w,it=new Promise((Yt,at)=>{w=setTimeout(()=>{I.abort(),at(new Error("master_key_relay_cancellation_timed_out"))},5e3)});try{if(!this.options.api.cancelRelaySession)throw new Error("master_key_relay_cancellation_unavailable");await Promise.race([this.options.api.cancelRelaySession(a.sessionId,I.signal),it])}finally{clearTimeout(w)}})(),L,ee=new Promise((I,w)=>{L=()=>{c&&v().catch(()=>{}),w(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",L,{once:!0})});ee.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(a),g=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let I=await Promise.race([this.options.api.readRelaySession(a.sessionId,e),ee]);if(I.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(I.status==="DELIVERED"&&I.sealedMasterKey){let w=(await st(I.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(w))throw new Error("invalid_master_key_material");return w}if(I.status==="EXPIRED")throw new re(a.sessionId);await lt(l,s,e)}throw new te(a.sessionId)}catch(I){if(c&&(!g||e?.aborted))try{await v()}catch(w){if(e?.aborted)throw new ne(w)}throw I}finally{L&&e?.removeEventListener("abort",L)}}};async function lt(r,e,t){if(!t)return r(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((n,i)=>{let a=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",a,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",a))})}function ie(r){return{resolve:async(e,t,n)=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let i=await r.source?.resolve();return i||ve(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(ct(e,r.applicationId)){let i=await r.source?.resolve();return i||ve(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return ve(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function ct(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function ve(r,e,t,n,i){if((await e()).relayAvailable)return new B({...r.relay,api:dt(r.api,t)}).resolve(n,i)}function dt(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:(t,n)=>r.readMasterKeyRelaySession(t,n),cancelRelaySession:(t,n)=>r.cancelMasterKeyRelaySession(t,n)}}function D(r){return`${r.system}:${r.contextId}`}function Pe(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var C=class extends Error{constructor(t){super(`master_key_required:${D(t)}`);this.ref=t;this.name="MasterKeyRequired"}},Re=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(D(e),t),this}async resolve(e){return this.sources.get(D(e))?.resolve()}};var H=class{keys=new Map;async store(e,t){let n=D(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(D(e))?.slice()}async remove(e){let t=D(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var W=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var ae=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},p=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var $=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var se=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],Ee={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},Ke=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],m=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},T=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function G(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new T("plan_material_field_unknown");if(Ie(r.dataShards,"data_shards_invalid"),Ie(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&Ie(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new T("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new T("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new T("material_operation_invalid")}function Ie(r,e){if(!Array.isArray(r))throw new T(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new T(e);if(t.data!==void 0&&typeof t.data!="string")throw new T(e)}}function k(r){if(M(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!mt(r.idempotencyKey))throw new m("idempotency_key_invalid");if(!r.name?.trim())throw new m("plan_name_required");if(!r.assets.length)throw new m("assets_required");let e=new Set;for(let t of r.assets){if(M(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new m("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!se.includes(t.type))throw new m("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new m("asset_binary_representation_invalid");let i=t.fieldNames??[];if(t.isBinary&&(i.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new m("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new m("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(a=>!a.trim()))throw new m("asset_field_names_invalid");if(pt(t.matchOrigins),!t.isBinary){let a=Ee[t.type];if(!a||i.some(s=>!a.includes(s)))throw new m("asset_field_name_not_canonical")}}if(!r.participants.length)throw new m("participants_required");for(let t of r.participants){if(M(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Ue(t.routingEmail))throw new m("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new m("participant_relationships_invalid")}ut(r)}function pt(r){if(r===void 0)return;if(!r.length)throw new m("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new m("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new m("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof m?n:new m("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new m("asset_match_origins_duplicated")}function ut(r){let e=r.policy;if(e&&M(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new m("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){M(e.authentication,["mode"],"plan_authentication_field_unknown");let a=e.authentication.mode;if(a!==void 0&&a!=="EXCLUSIVE"&&a!=="ALL_REQUIRED")throw new m("authentication_mode_invalid")}if(e.moderation){M(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let a=r.participants.filter(l=>l.relationships.includes("MODERATOR"));if(a.length===0)throw new m("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>a.length))throw new m("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new m("approval_mode_invalid")}let t=e.dms;if(!t)return;M(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!Ue(t.subjectEmail))throw new m("dms_subject_invalid");if(!r.participants.some(a=>ke(a.routingEmail)===ke(t.subjectEmail)))throw new m("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(i)||t.countdownDays<0||n<0||n>23||i<0||i>59||t.countdownDays+n+i===0)throw new m("dms_countdown_invalid")}function mt(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function Ue(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function ke(r){return r.normalize("NFC").trim().toLowerCase()}function M(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new m(t)}var le=class{checkpoints=new Map;async load(e){return this.checkpoints.get(e)}async save(e){this.checkpoints.set(e.operationId,e)}async remove(e){this.checkpoints.delete(e)}},ce=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),k(e),oe(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,i,a={}){k(t);let s=await this.checkpoints.load(e);if(!s)throw new de("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await Le(t))throw new de("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(a.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;oe(a.signal),a.onProgress?.("ENCRYPTING");let l=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:a.signal});oe(a.signal),a.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:l,signal:a.signal});oe(a.signal),G(c);let g=await this.api.supplyPlanCreationMaterial(e,c);return a.onProgress?.(g.stage),g.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,g),g}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await Le(e),serverStage:t.stage})}},de=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Le(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,i)=>n.clientAssetRef.localeCompare(i.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,i)=>n.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function oe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Ge(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new ae(n.stage);return r.authorizeRevealAction(e,t)}function ht(r){let e=r?.status;return e===400||e===401||e===403}async function ze(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(a){if(!ht(a))throw a}return r.releaseRevealMaterial(e,t)}function Be(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?yt(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":gt.has(r.stage)?"ENDED":"CONTINUING"}var gt=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function yt(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var pe=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},y=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Se(r,e,t={}){if(t.signal?.aborted)throw h();let n=await r.getPlan(e),i=await r.getActivePlanReveal(e);if(i)throw i.planId!==e||i.mode!==(t.mode??"DIRECT")?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):qe(i.id);if(t.signal?.aborted||(await r.prepareReveal(e,t.signal,async l=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(l)}),t.signal?.aborted))throw h();let a=t.idempotencyKey??crypto.randomUUID(),s;try{s=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a})}catch(l){if(l?.code!=="merge_process_already_active")throw l;let c=await r.getActivePlanReveal(e);throw!c||c.planId!==e||c.mode!==(t.mode??"DIRECT")?l:qe(c.id)}let o;try{if(t.signal?.aborted)throw h();let l=await vt(r,s,t);if(t.signal?.aborted||(b(t,"RELEASING_MATERIAL",l),t.signal?.aborted))throw h();let c=await r.releaseRevealMaterial(l.id,l.materialVersion??"1");if(t.signal?.aborted||(l.mode==="GOVERNED"&&await r.markRevealSharesCollected(l.id),t.signal?.aborted))throw h();let g;try{g=await It(r,l,wt(c),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(b(t,"RECONSTRUCTING",l),t.signal?.aborted))throw h();try{o=await r.reconstructPlanMaterial(g)}catch(v){throw t.signal?.aborted?h():(await r.reportRevealReconstruction(l.id,{status:"FAILED",errorCode:Pt(v)}),v)}if(t.signal?.aborted)throw h();let P=await r.reportRevealReconstruction(l.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(b(t,"OPEN",P),t.signal?.aborted))throw h();return new we(r,P,n,o,t.signal)}catch(l){throw o?.fill(0),await We(r,s.id,t.signal?.aborted?"CANCELED":"ERROR"),l}}function qe(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var ft=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function vt(r,e,t){let n=await O(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw h();if(t.onSession?.(n),t.onProgress?.({phase:Be(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(ft.has(n.stage))throw new ue(n.stage);await _e(t.pollIntervalMs??1500,t.signal),n=await O(()=>r.getReveal(e.id,t.signal),t.signal)}}var ue=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function b(r,e,t){r.onProgress?.({phase:e,session:t})}function _e(r,e){return e?.aborted?Promise.reject(h()):new Promise((t,n)=>{let i=setTimeout(s,Math.max(0,r)),a=()=>{clearTimeout(i),n(h())};function s(){e?.removeEventListener("abort",a),t()}e?.addEventListener("abort",a,{once:!0})})}var we=class{constructor(e,t,n,i,a){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let s=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(s,2147483647)),this.abortListener=a?()=>{this.close("CANCELED").catch(()=>{})}:void 0,a&&this.abortListener&&a.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new pe;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([i])=>{n=i?.value}),n}async consumeFields(e,t){if(e.length===0)throw new y("asset_selector_invalid");if(!this.client.assetDecoder)throw new y("asset_decoder_required");let n=e.map(({selector:a,options:s={}})=>{let o=He(a),l=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!l)throw new y("asset_not_found");if(l.isBinary)throw new y("action_not_allowed");if(!l.fieldNames.includes(o.field))throw new y("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:l,field:o.field,options:s}}),i=[];try{for(let s of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:s.options.idempotencyKey??crypto.randomUUID(),assetId:s.asset.id,fieldName:s.field,action:s.options.action??"VIEW_FIELD",...s.options.destination===void 0?{}:{destination:s.options.destination},...s.options.origin===void 0?{}:{origin:s.options.origin}}));let a=n.map(s=>{let o=this.client.assetDecoder(this.material).find(l=>l.id===s.asset.id||l.id===s.assetCode);if(!o)throw new y("asset_value_invalid");return{selector:s.selector,value:Rt(o.data,s.field,s.asset.type)}});await t(a)}catch(a){throw await Promise.all(i.map(s=>this.reportAction(s.id,"FAILED",Ve(a)))),a}await Promise.all(i.map(a=>this.reportAction(a.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new y("asset_selector_invalid");if(!this.client.assetDecoder)throw new y("asset_decoder_required");let n=this.plan.assets.find(s=>s.code===e||s.id===e);if(!n)throw new y("asset_not_found");if(!n.isBinary)throw new y("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),a;try{let s=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!s||!(s.data instanceof Uint8Array))throw new y("asset_value_invalid");a=s.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:a})}catch(s){throw await this.reportAction(i.id,"FAILED",Ve(s)),s}finally{a?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=We(this.client,this.session.id,e),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function He(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new y("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new y("asset_selector_invalid");return{asset:r.asset,field:r.field}}function Rt(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new y("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new y("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?Ee[t]:void 0)?.includes(e))return"";throw new y("asset_value_invalid")}return n[e]}function Ve(r){if(r instanceof y)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function Pt(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function It(r,e,t,n){let i=t.shares.find(l=>l.shareType==="CUSTODIAN_KEY_SHARD");if(i){let l=await O(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(l==="SK_PRO"){if(!n.proDevice)throw new me;let c=await O(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(Fe(c,i.id,e.planId),!c.shares.includes(i.data))throw new A;b(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:g}=await O(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw h();if(!g?.trim())throw new A;if(await r.claimRevealCustodianShare(e.id,c.id,g),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw h();return{...t,shares:t.shares.filter(P=>P!==i).concat(c.shares.map((P,v)=>({id:`${c.id}:${v}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:P})))}}if(l!=="SK_MOBILE")throw new A;if(n.signal?.aborted)throw h();return await r.distributeRevealCustodianShare(e.id),b(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let a=await O(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;a.status==="PENDING"||a.status==="DISTRIBUTED";){let l={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(l),b(n,"WAITING_FOR_CUSTODIAN_CLAIM",l),await _e(n.pollIntervalMs??1500,n.signal),a=await O(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(a.status==="CLAIMED"&&a.deviceType==="SK_PRO"){if(!n.proDevice)throw new me;if(!a.shareId||!a.deviceId)throw new A;b(n,"CONNECTING_SAFEKEY_PRO",e);let l=await O(()=>n.proDevice.read({shareId:a.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw h();if(Fe(l,a.shareId,e.planId),l.deviceId!==a.deviceId)throw new A;if(await r.collectRevealCustodianShare(e.id,a.shareId),n.signal?.aborted)throw h();return{...t,shares:t.shares.concat(l.shares.map((c,g)=>({id:`${l.id}:${g}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(a.status!=="CLAIMED"||a.deviceType!=="SK_MOBILE")throw new A;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(s),b(n,"WAITING_FOR_CUSTODIAN",s),n.signal?.aborted)throw h();await r.requestRevealCustodianRelease(e.id);let o=await Et(r,e.id,n);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((l,c)=>({id:`${o.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:l})))})}function Fe(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new A}async function O(r,e){if(e?.aborted)throw h();if(!e)return r();let t,n=new Promise((i,a)=>{t=()=>a(h()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw h();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function Et(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await O(()=>r.getRevealCustodianShare(e,t.signal),t.signal);if(i&&i.status!=="PENDING"){let a=i;if(a.shares?.length)return a;throw new A}if(Date.now()>=n)throw new Ae;await _e(t.pollIntervalMs??1500,t.signal)}}var A=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},me=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Ae=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function wt(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function We(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(s){if(!At(s))throw s}return}let n=new AbortController,i,a=new Promise((s,o)=>{i=setTimeout(()=>{n.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let s=await Promise.race([r.closeReveal(e,t,n.signal),a]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(s.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(s){if(s?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:s}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function At(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function h(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var j=class{constructor(e,t={}){this.coreSdk=e;if(t.applicationId!==void 0&&t.organizationId!==void 0)throw new Error("application_and_business_context_conflict");if(t.organizationId!==void 0&&!t.organizationId.trim())throw new Error("organization_id_required");this.keyVault=t.keyVault??new H,this.state=t.state??new W,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Ct(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new p;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new p;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new p;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return k(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new p;return G(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new le){if(this.requireApplication(),!this.api)throw new p;return new ce(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new C({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,n){let i=await this.keyVault.load(e);if(i)return _t(i);let a=await this.masterKeys?.resolve(e,t,n);if(!a)throw new C(e);return await this.keyVault.store(e,St(a)),a}async prepareReveal(e,t,n){if(!this.api)throw new p;let i=await this.api.planKeyReference(e);if(!i.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(i,t,n)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new p;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new $;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:this.organizationId?{system:"INHERITI_BUSINESS",contextId:this.organizationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e,t,n){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new C({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=Pe(e);if(!i)throw new C({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new p;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new p;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new p;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new p;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new p;return this.api.getReveal(e,t)}openReveal(e,t){return Se(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let a=await n(i);return await i.close("COMPLETED"),a}catch(a){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),a}}async releaseRevealMaterial(e,t){if(!this.api)throw new p;return ze(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new p;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new p;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new p;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new p;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new p;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new p;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new p;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new p;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new p;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new p;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new p;return Ge(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new p;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new p;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new p;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new p;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new p;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new p;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),i=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let a=n.validatorShares.map(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),s=i.dataShards.map(c=>Object.assign({},c,{shareType:"DATA_SHARD"})),o=i.backupShards.map(c=>Object.assign({},c,{shareType:"BACKUP_SHARD"})),l=i.keyShards.map(c=>Object.assign({},c,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||n.dek,shares:a.concat(s,o,l),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new p;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new he;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new C({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},he=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function St(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function _t(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Ct(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return ie({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return ie({...e,organizationId:r.organizationId})}import{createBrowserSsdpV2WorkerFactory as kt,createSsdpV2Processor as Kt}from"@safetech/inheriti-core-sdk/workers/ssdp-v2";async function Ce(r,e){if(!e)throw new Error("master_key_required");let t=Tt(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=Ot(r),a=i.slice(0,12),s=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},n,s);return Dt(new Uint8Array(o))}function Tt(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Ot(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function Dt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var Y=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await $e("plan_key_unwrap_failed",()=>Ce(e.planKey,t)),i=await crypto.subtle.importKey("raw",Te(n),{name:"AES-GCM"},!1,["decrypt"]),a=[],s=[];for(let o of e.shares){let l=await $e("plan_share_decryption_failed",()=>Mt(o.data,i));Nt(o.shareType)?s.push(l):a.push(l)}try{return await this.processor().reconstruct(a,{planId:e.planId,threshold:e.mergeThreshold,keyShares:s}).result}catch(o){throw new ge("plan_share_reconstruction_failed",xt(o))}}},ge=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},bt=new Set(["insufficient_valid_data_shards","insufficient_valid_key_shards","mixed_share_sets","threshold_metadata_mismatch","duplicate_data_shard","duplicate_key_shard","plan_binding_mismatch","ciphertext_digest_mismatch","v2_authentication_failed","shard_kind_mismatch","envelope_truncated","invalid_envelope_magic","unsupported_envelope_version","invalid_shard_kind","unsupported_v2_suite","invalid_envelope_length","crc32c_mismatch","invalid_envelope_metadata","invalid_envelope_threshold","invalid_data_shard_length","invalid_base64url","insufficient_shards","insufficient_key_shards","conflicting_key_shards","duplicate_shard","invalid_shard_index","invalid_key_shard_index","invalid_shard_length","invalid_key_length","plaintext_length_mismatch","ssdp_v2_worker_failed","ssdp_v2_worker_not_configured","unexpected_ssdp_v2_worker_response"]);function xt(r){let e=r instanceof Error?r.message:void 0;if(e)return bt.has(e)?e:void 0}async function $e(r,e){try{return await e()}catch{throw new ge(r)}}function Nt(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function Mt(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=Te(r.slice(0,t)),i=Te(r.slice(t+1)),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(a)}function Te(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return t}var X=class extends Y{constructor(e={}){let t=e.processor??Kt(e.workerUrl!==void 0&&typeof Worker<"u"?{workerFactory:kt(e.workerUrl),allowMainThreadFallback:!0}:{allowMainThreadFallback:!0});super(()=>t)}};var Ut=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Lt=["DIRECT","GOVERNED"],Ye=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],Gt=["ACTIVE","REVOKED"],zt=["SK_MOBILE"],qt=["ACTIVE","INACTIVE"],Vt=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Xe(r){let e=f(r);return{items:E(e.items).map(Je),nextCursor:e.nextCursor===null?null:d(e.nextCursor,"nextCursor")}}function Qe(r){let e=f(r);return{total:S(e.total,"total"),items:E(e.items).map(t=>{let n=f(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:d(n.id,"log.id"),planId:d(n.planId,"log.planId"),tenantId:d(n.tenantId,"log.tenantId"),event:d(n.event,"log.event"),occurredOn:d(n.occurredOn,"log.occurredOn"),status:x(n.status),title:d(n.title,"log.title"),details:E(n.details).map(i=>{let a=f(i);return{label:d(a.label,"log.detail.label"),value:d(a.value,"log.detail.value")}})}})}}function Ze(r){let e=f(r),t=Je(e),n=f(e.source),i=d(n.kind,"source.kind");return{...t,assets:E(e.assets).map(a=>{let s=f(a);return{id:d(s.id,"asset.id"),code:x(s.code),type:R(d(s.type,"asset.type"),se),name:d(s.name,"asset.name"),isBinary:Bt(s.isBinary,"asset.isBinary"),fieldNames:E(s.fieldNames).map(o=>d(o,"asset.fieldNames")),fileName:x(s.fileName),mimeType:x(s.mimeType),size:s.size===void 0||s.size===null?void 0:S(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:E(s.matchOrigins).map(o=>d(o,"asset.matchOrigins"))}}),participants:E(e.participants).map(a=>{let s=f(a);return{id:d(s.id,"participant.id"),displayName:d(s.displayName,"participant.displayName"),relationships:E(s.relationships).map(o=>R(d(o,"relationship"),Ye)),lifecycle:R(d(s.lifecycle,"participant.lifecycle"),Gt)}}),revealPolicy:(()=>{let a=f(e.revealPolicy);return{masterKeyRelease:R(d(a.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:R(d(a.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let a=f(e.dms);return{subjectEmail:d(a.subjectEmail,"dms.subjectEmail"),countdownDays:S(a.countdownDays,"dms.countdownDays"),countdownHours:S(a.countdownHours,"dms.countdownHours"),countdownMinutes:S(a.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:R(d(n.system,"source.system"),["INHERITI_BUSINESS"]),status:R(d(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function Q(r){let e=f(r);return{operationId:d(e.operationId,"operationId"),stage:R(d(e.stage,"stage"),Ke),outcome:R(d(e.outcome,"outcome"),Vt),planId:x(e.planId),lastErrorCode:x(e.lastErrorCode),participants:e.participants===void 0?void 0:E(e.participants).map(t=>{let n=f(t);return{clientParticipantRef:d(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:d(n.planParticipantId,"planParticipantId"),relationships:E(n.relationships).map(i=>Ft(d(i,"relationship"),Ye))}})}}function Je(r){let e=f(r),t=f(e.assetSummary),n=f(e.governance),i=f(e.participantSummary);return{id:d(e.id,"id"),name:d(e.name,"name"),description:x(e.description),status:R(d(e.status,"status"),Ut),createdAt:d(e.createdAt,"createdAt"),configuredAt:x(e.configuredAt),assetSummary:{count:S(t.count,"assetSummary.count"),types:E(t.types).map(a=>R(d(a,"assetType"),se)),names:je(t.names).map(a=>d(a,"assetSummary.names"))},governance:{mode:R(d(n.mode,"governance.mode"),Lt),minimumApprovals:S(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:S(i.owners,"owners"),mergers:S(i.mergers,"mergers"),moderators:S(i.moderators,"moderators")},authentication:je(e.authentication).map(a=>{let s=f(a);return{id:R(d(s.id,"authentication.id"),zt),status:R(d(s.status,"authentication.status"),qt)}})}}function R(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function Ft(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function f(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function je(r){return r==null?[]:E(r)}function E(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function d(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function x(r){return r==null?void 0:d(r,"optional")}function S(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function Bt(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var z=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function et(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function Ht(r,e){if(!e){if(r.length===0)throw new z("organization_required");if(r.length>1)throw new z("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new z("organization_access_denied");return e}function Oe(r){return typeof r.error=="string"?/^[a-z][a-z0-9_]*$/.test(r.error)?r.error:typeof r.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(r.validationErrors)?r.validationErrors:r.error||void 0:r.error?.code??r.name??r.message}function De(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var K=class extends Error{constructor(t,n,i){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},q=class{constructor(e,t,n,i,a){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=a?Object.freeze({...a}):void 0}business;listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(et)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return Xe(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Ze(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return Qe(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){k(e);let{idempotencyKey:t,...n}=e;return Q(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return Q(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return G(t),Q(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return Q(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e,t){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}async cancelMasterKeyRelaySession(e,t){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,t)}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":n})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,t)}getRevealCustodianClaimable(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,t)}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},void 0,void 0,n)}abortPlanAccess(e,t){let n=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(t?`${n}?revealId=${encodeURIComponent(t)}`:n,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...a}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",a,void 0,{"idempotency-key":i})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,i,a,s){this.requireBusinessSelection(e),s?.throwIfAborted();let o=await this.getBearerToken();s?.throwIfAborted();let l=new Headers({"x-elements-environment":this.environment});o&&l.set("authorization",`Bearer ${o}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&l.set("x-organization-id",this.business.organizationId),i?.requestId&&l.set("x-elements-step-up-request",i.requestId);for(let[L,ee]of Object.entries(a??{}))l.set(L,ee);n&&l.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,g={method:t,headers:l,body:n?JSON.stringify(n):void 0};s&&(g.signal=s);let P=await this.transport(new URL(e,c),g);s?.throwIfAborted();let v=await tt(P,s);if(s?.throwIfAborted(),!P.ok)throw new K(P.status,Oe(v),De(v));if(!v.ok||v.result===void 0)throw new K(P.status,Oe(v),De(v));return v.result}async requestWithoutResult(e,t){this.requireBusinessSelection(e);let n=await this.getBearerToken(),i=new Headers({"x-elements-environment":this.environment});n&&i.set("authorization",`Bearer ${n}`),this.business?.organizationId&&i.set("x-organization-id",this.business.organizationId),t&&i.set("content-type","application/json");let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,s=await this.transport(new URL(e,a),{method:"POST",headers:i,body:t?JSON.stringify(t):void 0}),o=await tt(s);if(!s.ok||!o.ok)throw new K(s.status,Oe(o),De(o))}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new K(400,"organization_selection_required")}};async function tt(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{PassphraseMasterKeySource as an,RawMasterKeySource as sn,computePassphraseVerifier as on,deriveMasterKey as ln,generateHexSeed as cn}from"@safetech/inheriti-core-sdk/crypto";function rt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Z=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),rt(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return rt(new Uint8Array(t))}},J=class{now(){return Date.now()}sleep(e,t){return new Promise((n,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let a=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(a),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var V=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},F=class extends V{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},u=class extends V{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function ye(r){if(r instanceof V)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var be=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:N(n,"issuer"),authorizationEndpoint:N(n,"authorization_endpoint"),tokenEndpoint:N(n,"token_endpoint"),deviceAuthorizationEndpoint:_(n,"device_authorization_endpoint"),endSessionEndpoint:_(n,"end_session_endpoint"),revocationEndpoint:_(n,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:N(t,"device_code"),userCode:N(t,"user_code"),verificationUri:N(t,"verification_uri"),verificationUriComplete:_(t,"verification_uri_complete"),expiresInSeconds:nt(t,"expires_in"),intervalSeconds:xe(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async token(e,t){let n=await this.form(e,t);return{accessToken:N(n,"access_token"),refreshToken:_(n,"refresh_token"),idToken:_(n,"id_token"),tokenType:N(n,"token_type"),expiresInSeconds:nt(n,"expires_in"),refreshExpiresInSeconds:xe(n,"refresh_expires_in"),scope:_(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await n.json()}catch{}if(!n.ok){let a=_(i,"error")??`oauth_http_${n.status}`;throw new u(a,_(i,"error_description")??a)}return i}};function N(r,e){let t=_(r,e);if(!t)throw new u("invalid_oauth_response",`Missing ${e}`);return t}function _(r,e){return typeof r[e]=="string"?r[e]:void 0}function nt(r,e){let t=xe(r,e);if(t===void 0)throw new u("invalid_oauth_response",`Missing ${e}`);return t}function xe(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Wt=600*1e3,fe=5,$t=5,Ne=class{constructor(e){this.options=e;this.crypto=e.crypto??new Z,this.clock=e.clock??new J}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(i),s=this.clock.now()+Wt;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:i,redirectUri:this.options.configuration.redirectUri,expiresAt:s});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",n),o.searchParams.set("code_challenge",a),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:s}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new u("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new u("authorization_transaction_expired");let i=new URL(e),a=new URL(n.redirectUri);if(i.origin!==a.origin||i.pathname!==a.pathname)throw new u("redirect_uri_mismatch");let s=i.searchParams.get("error");if(s)throw new u(s,i.searchParams.get("error_description")??s);if(i.searchParams.get("state")!==n.state)throw new u("state_mismatch");let o=i.searchParams.get("code");if(!o)throw new u("authorization_code_missing");let l=await this.getDiscovery(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:l.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),g=await this.acceptTokens(c,n.nonce);return await this.options.sessions.save(g),g}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new u("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(fe,t.intervalSeconds??fe),i=this.clock.now(),a={...t,kind:"device-code",intervalSeconds:n,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),a),a}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new u("device_transaction_missing");let i=n,a=await this.getDiscovery(),s=Math.max(fe,i.intervalSeconds??fe),o=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(o>=i.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let l=await this.options.transport.pollDeviceToken({tokenEndpoint:a.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let c=await this.acceptTokens(l);return await this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(l){let c=ye(l);if(c==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(c==="slow_down"){s+=$t,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),l}}throw await this.options.transactions.remove(t),new u("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new F;try{let t=await this.getDiscovery(),n=await this.options.transport.refresh({tokenEndpoint:t.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken});if(!n.refreshToken)throw new u("refresh_token_rotation_missing");let i=await this.acceptTokens(n);return await this.options.sessions.save(i),i}catch(t){await this.options.sessions.clear();let n=ye(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new F:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(U(e.issuer)!==U(this.options.configuration.issuer))throw new u("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:i}=this.options.configuration;return`${e}|${U(t)}|${n}|${i}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new u("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new u("id_token_validation_required");let a=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(a,t),a.subject!==n.subject||a.sessionId!==n.sessionId)throw new u("token_subject_mismatch")}let i=this.clock.now();return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:i+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0?void 0:i+e.refreshExpiresInSeconds*1e3,principal:n}}assertPrincipal(e,t,n){let i=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(U(e.issuer)!==U(i.issuer))throw new u("issuer_mismatch");if(!a.includes(i.audience))throw new u("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new u("client_mismatch");if(e.environment!==i.environment)throw new u("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new u("required_claim_missing");if(n&&e.nonce!==t)throw new u("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(U(e.issuer)!==U(n.issuer))throw new u("issuer_mismatch");if(!i.includes(n.clientId))throw new u("client_mismatch");if(e.authorizedParty!==n.clientId)throw new u("client_mismatch");if(!e.subject||!e.sessionId)throw new u("required_claim_missing");if(e.nonce!==t)throw new u("nonce_mismatch")}};function U(r){return r.replace(/\/+$/u,"")}var Me=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};function Yr(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=new q(r.apiUrl,r.environment,r.getBearerToken,e,r.business?{organizationId:r.organizationId}:void 0);return new j(void 0,{api:t,applicationId:r.applicationId,organizationId:r.organizationId,masterKeys:r.masterKeys,masterKey:r.masterKey,assetDecoder:jt,reconstructor:r.reconstructor??new X(r.reconstruction??{}),...r.keyVault===void 0?{}:{keyVault:r.keyVault},...r.state===void 0?{}:{state:r.state}})}export{X as BrowserPlanMaterialReconstructor,z as BusinessOrganizationSelectionError,he as CoreSdkContainerRequired,K as ElementsApiRequestFailed,j as ElementsClient,q as HttpElementsApiPort,be as HttpOperatorAuthTransport,ne as MasterKeyRelayCancellationFailed,re as MasterKeyRelayExpired,te as MasterKeyRelayTimedOut,C as MasterKeyRequired,H as MemoryKeyVault,W as MemoryStatePort,u as OAuthProtocolError,Ne as OperatorAuthClient,V as OperatorAuthError,F as OperatorReauthenticationRequired,Me as OperatorSessionController,an as PassphraseMasterKeySource,$ as PlanMaterialReconstructorRequired,sn as RawMasterKeySource,B as RelayMasterKeySource,ue as RevealAuthorizationEnded,y as RevealFieldAccessError,pe as RevealHandleClosed,Re as StaticMasterKeyResolver,J as SystemOAuthClock,Z as WebOAuthCrypto,on as computePassphraseVerifier,Yr as createBrowserElementsClient,ie as createMasterKeyResolver,jt as decodeAssetContainer,ln as deriveMasterKey,cn as generateHexSeed,Pe as masterKeyRefFor,D as masterKeyRefKey,ye as oauthErrorCode,Se as openScopedReveal,He as parseAssetFieldSelector,Be as revealPhaseOf,Ht as selectBusinessOrganization,Ce as unwrapDekWithMasterKey};