@safetech/inheriti-client-sdk 1.17.22 → 1.17.23
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/automation.js +1 -1
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +1 -1
- package/dist/inbox.js +1 -1
- package/dist/index.js +1 -1
- package/dist/inheriti-client-sdk.umd.js +35 -35
- package/dist/node-base.d.ts +1 -1
- package/dist/node-base.js +1 -1
- package/dist/node.js +1 -1
- package/dist/sdk-types.d.ts +24 -2
- package/dist/src/elements/elements-api-port.d.ts +2 -1
- package/dist/src/elements/elements-client.d.ts +2 -1
- package/dist/src/elements/http-elements-api-port.d.ts +2 -1
- package/dist/src/elements/plan-operation-codec.d.ts +2 -1
- package/dist/src/elements/plan-operations.d.ts +19 -0
- package/package.json +2 -2
package/dist/node.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createNodeSharedConfigurationSdk as _t,decodeAssetContainer as _r}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Dn,generateRSAOAEPKeyPair as Mn}from"@safetech/inheriti-core-sdk/crypto";var ke=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},Oe=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"}},z=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 Mn();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),d=this.options.sleep??(m=>new Promise(f=>setTimeout(f,m))),c=!0,l=!1,u,g=()=>u??=(async()=>{let m=new AbortController,f,K=new Promise((C,q)=>{f=setTimeout(()=>{m.abort(),q(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,m.signal),K])}finally{clearTimeout(f)}})(),w,D=new Promise((m,f)=>{w=()=>{c&&g().catch(()=>{}),f(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",w,{once:!0})});D.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(a),l=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let m=await Promise.race([this.options.api.readRelaySession(a.sessionId,e),D]);if(m.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(m.status==="DELIVERED"&&m.sealedMasterKey){let f=(await Dn(m.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(f))throw new Error("invalid_master_key_material");return f}if(m.status==="EXPIRED")throw new Oe(a.sessionId);await kn(d,s,e)}throw new ke(a.sessionId)}catch(m){if(c&&(!l||e?.aborted))try{await g()}catch(f){if(e?.aborted)throw new Ne(f)}throw m}finally{w&&e?.removeEventListener("abort",w)}}};async function kn(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 Ke(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||ot(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(On(e,r.applicationId)){let i=await r.source?.resolve();return i||ot(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return ot(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function On(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function ot(r,e,t,n,i){if((await e()).relayAvailable)return new z({...r.relay,api:Nn(r.api,t)}).resolve(n,i)}function Nn(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 X(r){return`${r.system}:${r.contextId}`}function he(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var j=class extends Error{constructor(t){super(`master_key_required:${X(t)}`);this.ref=t;this.name="MasterKeyRequired"}},dt=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(X(e),t),this}async resolve(e){return this.sources.get(X(e))?.resolve()}};var Ie=class{keys=new Map;async store(e,t){let n=X(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(X(e))?.slice()}async remove(e){let t=X(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var ye=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 Ue=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 Le=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var qe=["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"]},pt=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],v=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},M=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function ae(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new M("plan_material_field_unknown");if(ct(r.dataShards,"data_shards_invalid"),ct(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&ct(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new M("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new M("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new M("material_operation_invalid")}function ct(r,e){if(!Array.isArray(r))throw new M(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new M(e);if(t.data!==void 0&&typeof t.data!="string")throw new M(e)}}function J(r){if(ie(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Ln(r.idempotencyKey))throw new v("idempotency_key_invalid");if(!r.name?.trim())throw new v("plan_name_required");if(!r.assets.length)throw new v("assets_required");let e=new Set;for(let t of r.assets){if(ie(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 v("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!qe.includes(t.type))throw new v("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new v("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 v("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new v("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(a=>!a.trim()))throw new v("asset_field_names_invalid");if(Kn(t.matchOrigins),!t.isBinary){let a=lt[t.type];if(!a||i.some(s=>!a.includes(s)))throw new v("asset_field_name_not_canonical")}}if(!r.participants.length)throw new v("participants_required");for(let t of r.participants){if(ie(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Dt(t.routingEmail))throw new v("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new v("participant_relationships_invalid")}Un(r)}function Kn(r){if(r===void 0)return;if(!r.length)throw new v("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new v("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new v("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof v?n:new v("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new v("asset_match_origins_duplicated")}function Un(r){let e=r.policy;if(e&&ie(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new v("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){ie(e.authentication,["mode"],"plan_authentication_field_unknown");let a=e.authentication.mode;if(a!==void 0&&a!=="EXCLUSIVE"&&a!=="ALL_REQUIRED")throw new v("authentication_mode_invalid")}if(e.moderation){ie(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let a=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(a.length===0)throw new v("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>a.length))throw new v("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new v("approval_mode_invalid")}let t=e.dms;if(!t)return;ie(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!Dt(t.subjectEmail))throw new v("dms_subject_invalid");if(!r.participants.some(a=>Tt(a.routingEmail)===Tt(t.subjectEmail)))throw new v("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 v("dms_countdown_invalid")}function Ln(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 Dt(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Tt(r){return r.normalize("NFC").trim().toLowerCase()}function ie(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new v(t)}var fe=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)}},Pe=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),J(e),Ge(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={}){J(t);let s=await this.checkpoints.load(e);if(!s)throw new ve("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await Mt(t))throw new ve("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;Ge(a.signal),a.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:a.signal});Ge(a.signal),a.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:a.signal});Ge(a.signal),ae(c);let l=await this.api.supplyPlanCreationMaterial(e,c);return a.onProgress?.(l.stage),l.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,l),l}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 Mt(e),serverStage:t.stage})}},ve=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Mt(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 Ge(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function kt(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new Ue(n.stage);return r.authorizeRevealAction(e,t)}function qn(r){let e=r?.status;return e===400||e===401||e===403}async function Ot(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(a){if(!qn(a))throw a}return r.releaseRevealMaterial(e,t)}function Gn(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"?Vn(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":Fn.has(r.stage)?"ENDED":"CONTINUING"}var Fn=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function Vn(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 ut=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},T=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Lt(r,e,t={}){if(t.signal?.aborted)throw E();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"}):Nt(i.id);if(t.signal?.aborted||(await r.prepareReveal(e,t.signal,async d=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(d)}),t.signal?.aborted))throw E();let a=t.idempotencyKey??crypto.randomUUID(),s;try{s=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a})}catch(d){if(d?.code!=="merge_process_already_active")throw d;let c=await r.getActivePlanReveal(e);throw!c||c.planId!==e||c.mode!==(t.mode??"DIRECT")?d:Nt(c.id)}let o;try{if(t.signal?.aborted)throw E();let d=await Bn(r,s,t);if(t.signal?.aborted||(Z(t,"RELEASING_MATERIAL",d),t.signal?.aborted))throw E();let c=await r.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted||(d.mode==="GOVERNED"&&await r.markRevealSharesCollected(d.id),t.signal?.aborted))throw E();let l;try{l=await Qn(r,d,Yn(c),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(Z(t,"RECONSTRUCTING",d),t.signal?.aborted))throw E();try{o=await r.reconstructPlanMaterial(l)}catch(g){throw t.signal?.aborted?E():(await r.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:Wn(g)}),g)}if(t.signal?.aborted)throw E();let u=await r.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(Z(t,"OPEN",u),t.signal?.aborted))throw E();return new gt(r,u,n,o,t.signal)}catch(d){throw o?.fill(0),await qt(r,s.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function Nt(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var zn=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function Bn(r,e,t){let n=await Y(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw E();if(t.onSession?.(n),t.onProgress?.({phase:Gn(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(zn.has(n.stage))throw new mt(n.stage);await It(t.pollIntervalMs??1500,t.signal),n=await Y(()=>r.getReveal(e.id,t.signal),t.signal)}}var mt=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function Z(r,e,t){r.onProgress?.({phase:e,session:t})}function It(r,e){return e?.aborted?Promise.reject(E()):new Promise((t,n)=>{let i=setTimeout(s,Math.max(0,r)),a=()=>{clearTimeout(i),n(E())};function s(){e?.removeEventListener("abort",a),t()}e?.addEventListener("abort",a,{once:!0})})}var gt=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 ut;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 T("asset_selector_invalid");if(!this.client.assetDecoder)throw new T("asset_decoder_required");let n=e.map(({selector:a,options:s={}})=>{let o=$n(a),d=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!d)throw new T("asset_not_found");if(d.isBinary)throw new T("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new T("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,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(d=>d.id===s.asset.id||d.id===s.assetCode);if(!o)throw new T("asset_value_invalid");return{selector:s.selector,value:Hn(o.data,s.field,s.asset.type)}});await t(a)}catch(a){throw await Promise.all(i.map(s=>this.reportAction(s.id,"FAILED",Kt(a)))),a}await Promise.all(i.map(a=>this.reportAction(a.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new T("asset_selector_invalid");if(!this.client.assetDecoder)throw new T("asset_decoder_required");let n=this.plan.assets.find(s=>s.code===e||s.id===e);if(!n)throw new T("asset_not_found");if(!n.isBinary)throw new T("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 T("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",Kt(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=qt(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 $n(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new T("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new T("asset_selector_invalid");return{asset:r.asset,field:r.field}}function Hn(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new T("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new T("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?lt[t]:void 0)?.includes(e))return"";throw new T("asset_value_invalid")}return n[e]}function Kt(r){if(r instanceof T)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 Wn(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Qn(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await Y(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new Fe;let c=await Y(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(Ut(c,i.id,e.planId),!c.shares.includes(i.data))throw new H;Z(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:l}=await Y(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw E();if(!l?.trim())throw new H;if(await r.claimRevealCustodianShare(e.id,c.id,l),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw E();return{...t,shares:t.shares.filter(u=>u!==i).concat(c.shares.map((u,g)=>({id:`${c.id}:${g}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:u})))}}if(d!=="SK_MOBILE")throw new H;if(n.signal?.aborted)throw E();return await r.distributeRevealCustodianShare(e.id),Z(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let a=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;a.status==="PENDING"||a.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),Z(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await It(n.pollIntervalMs??1500,n.signal),a=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(a.status==="CLAIMED"&&a.deviceType==="SK_PRO"){if(!n.proDevice)throw new Fe;if(!a.shareId||!a.deviceId)throw new H;Z(n,"CONNECTING_SAFEKEY_PRO",e);let d=await Y(()=>n.proDevice.read({shareId:a.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw E();if(Ut(d,a.shareId,e.planId),d.deviceId!==a.deviceId)throw new H;if(await r.collectRevealCustodianShare(e.id,a.shareId),n.signal?.aborted)throw E();return{...t,shares:t.shares.concat(d.shares.map((c,l)=>({id:`${d.id}:${l}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(a.status!=="CLAIMED"||a.deviceType!=="SK_MOBILE")throw new H;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(s),Z(n,"WAITING_FOR_CUSTODIAN",s),n.signal?.aborted)throw E();await r.requestRevealCustodianRelease(e.id);let o=await jn(r,e.id,n);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,c)=>({id:`${o.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function Ut(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 H}async function Y(r,e){if(e?.aborted)throw E();if(!e)return r();let t,n=new Promise((i,a)=>{t=()=>a(E()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw E();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function jn(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await Y(()=>r.getRevealCustodianShare(e,t.signal),t.signal);if(i&&i.status!=="PENDING"){let a=i;if(a.shares?.length)return a;throw new H}if(Date.now()>=n)throw new ht;await It(t.pollIntervalMs??1500,t.signal)}}var H=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Fe=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},ht=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Yn(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function qt(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(s){if(!Xn(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 Xn(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function E(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var se=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 Ie,this.state=t.state??new ye,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??er(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 J(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 ae(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new P;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new fe){if(this.requireApplication(),!this.api)throw new P;return new Pe(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 j({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 Zn(i);let a=await this.masterKeys?.resolve(e,t,n);if(!a)throw new j(e);return await this.keyVault.store(e,Jn(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 Le;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 j({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=he(e);if(!i)throw new j({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 Lt(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 Ot(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 kt(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"})),d=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,d),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 yt;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new j({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},yt=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Jn(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 Zn(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function er(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 Ke({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return Ke({...e,organizationId:r.organizationId})}var tr=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],nr=["DIRECT","GOVERNED"],Ft=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],rr=["ACTIVE","REVOKED"],ir=["SK_MOBILE"],ar=["ACTIVE","INACTIVE"],sr=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Vt(r){let e=k(r);return{items:G(e.items).map(Bt),nextCursor:e.nextCursor===null?null:I(e.nextCursor,"nextCursor")}}function zt(r){let e=k(r);return{total:W(e.total,"total"),items:G(e.items).map(t=>{let n=k(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:I(n.id,"log.id"),planId:I(n.planId,"log.planId"),tenantId:I(n.tenantId,"log.tenantId"),event:I(n.event,"log.event"),occurredOn:I(n.occurredOn,"log.occurredOn"),status:ee(n.status),title:I(n.title,"log.title"),details:G(n.details).map(i=>{let a=k(i);return{label:I(a.label,"log.detail.label"),value:I(a.value,"log.detail.value")}})}})}}function Ve(r){let e=k(r),t=Bt(e),n=k(e.source),i=I(n.kind,"source.kind");return{...t,assets:G(e.assets).map(a=>{let s=k(a);return{id:I(s.id,"asset.id"),code:ee(s.code),type:U(I(s.type,"asset.type"),qe),name:I(s.name,"asset.name"),isBinary:dr(s.isBinary,"asset.isBinary"),fieldNames:G(s.fieldNames).map(o=>I(o,"asset.fieldNames")),fileName:ee(s.fileName),mimeType:ee(s.mimeType),size:s.size===void 0||s.size===null?void 0:W(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:G(s.matchOrigins).map(o=>I(o,"asset.matchOrigins"))}}),participants:G(e.participants).map(a=>{let s=k(a);return{id:I(s.id,"participant.id"),displayName:I(s.displayName,"participant.displayName"),relationships:G(s.relationships).map(o=>U(I(o,"relationship"),Ft)),lifecycle:U(I(s.lifecycle,"participant.lifecycle"),rr)}}),revealPolicy:(()=>{let a=k(e.revealPolicy);return{masterKeyRelease:U(I(a.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:U(I(a.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let a=k(e.dms);return{subjectEmail:I(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:U(I(n.system,"source.system"),["INHERITI_BUSINESS"]),status:U(I(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function be(r){let e=k(r);return{operationId:I(e.operationId,"operationId"),stage:U(I(e.stage,"stage"),pt),outcome:U(I(e.outcome,"outcome"),sr),planId:ee(e.planId),lastErrorCode:ee(e.lastErrorCode),participants:e.participants===void 0?void 0:G(e.participants).map(t=>{let n=k(t);return{clientParticipantRef:I(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:I(n.planParticipantId,"planParticipantId"),relationships:G(n.relationships).map(i=>or(I(i,"relationship"),Ft))}})}}function Bt(r){let e=k(r),t=k(e.assetSummary),n=k(e.governance),i=k(e.participantSummary);return{id:I(e.id,"id"),name:I(e.name,"name"),description:ee(e.description),status:U(I(e.status,"status"),tr),createdAt:I(e.createdAt,"createdAt"),configuredAt:ee(e.configuredAt),assetSummary:{count:W(t.count,"assetSummary.count"),types:G(t.types).map(a=>U(I(a,"assetType"),qe)),names:Gt(t.names).map(a=>I(a,"assetSummary.names"))},governance:{mode:U(I(n.mode,"governance.mode"),nr),minimumApprovals:W(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:W(i.owners,"owners"),mergers:W(i.mergers,"mergers"),moderators:W(i.moderators,"moderators")},authentication:Gt(e.authentication).map(a=>{let s=k(a);return{id:U(I(s.id,"authentication.id"),ir),status:U(I(s.status,"authentication.status"),ar)}})}}function U(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function or(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function k(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Gt(r){return r==null?[]:G(r)}function G(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function I(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function ee(r){return r==null?void 0:I(r,"optional")}function W(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function dr(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var ue=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function $t(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 cr(r,e){if(!e){if(r.length===0)throw new ue("organization_required");if(r.length>1)throw new ue("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new ue("organization_access_denied");return e}function lr(r){let e=b(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:y(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:y(e.participantRevision,1),createdAt:N(e.createdAt),...Ht(e)}}function Ht(r){if(r.recipientStatuses===void 0)return{};if(!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:r.recipientStatuses.map(e=>{let t=b(e);if(t.secrets!==void 0&&!Array.isArray(t.secrets))throw new Error("invalid_inbox_response");if(t.read!==void 0&&typeof t.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:N(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=b(n);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:y(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:N(i.revealedAt)}:{}}})}:{}}})}}function Wt(r){let e=b(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(lr),total:y(e.total,0),limit:y(e.limit,1),offset:y(e.offset,0),unreadCount:y(e.unreadCount,0),readThroughSequence:y(e.readThroughSequence,0)}}function Qt(r){let e=b(r);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:y(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:y(e.participantRevision,1),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:y(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=b(t);return{unitId:p(n.unitId),position:y(n.position,0),commitment:p(n.commitment),status:p(n.status)}})}}function ft(r){let e=b(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:y(e.sequence,1),status:e.status}}function jt(r){let e=b(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),parentId:p(e.parentId),participantRevision:y(e.participantRevision,1),recipients:e.recipients.map(Pt)}}function Yt(r){let e=b(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=b(t);return{parentId:p(n.parentId),sequence:y(n.sequence,1),senderMemberId:p(n.senderMemberId),senderDeviceId:p(n.senderDeviceId),participantRevision:y(n.participantRevision,1),createdAt:N(n.createdAt),...Ht(n)}}),total:y(e.total,0),limit:y(e.limit,1),offset:y(e.offset,0),unreadCount:y(e.unreadCount,0),readThroughSequence:y(e.readThroughSequence,0)}}function Xt(r){return{readThroughSequence:y(b(r).readThroughSequence,0)}}function Jt(r){return{clearedThroughSequence:y(b(r).clearedThroughSequence,0)}}function Zt(r){let e=b(r);return{parentId:p(e.parentId),sequence:y(e.sequence,1),senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:y(e.participantRevision,1),canonicalManifest:p(e.canonicalManifest),frame:p(e.frame),signature:p(e.signature),wrappedContentKey:p(e.wrappedContentKey),senderSigningPublicKey:p(e.senderSigningPublicKey)}}function b(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function p(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function N(r){let e=p(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function y(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Pt(r){let e=b(r);return{memberId:p(e.memberId),deviceId:p(e.deviceId),deviceVersion:y(e.deviceVersion,1),encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint)}}function me(r){let e=b(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:p(e.id),tenantId:p(e.tenantId),memberId:p(e.memberId),version:e.version,encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint),status:e.status,createdAt:N(e.createdAt),updatedAt:N(e.updatedAt)}}function ze(r){let e=b(r);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:p(e.id),tenantId:p(e.tenantId),creatorMemberId:p(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(p),participantRevision:e.participantRevision,status:e.status,createdAt:N(e.createdAt),updatedAt:N(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let n=b(e.latestMessage);if(n.contentKind!=="TEXT"&&n.contentKind!=="FILE"&&n.contentKind!=="NORMAL"&&n.contentKind!=="MIXED"&&n.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:n.contentKind,senderMemberId:p(n.senderMemberId),createdAt:N(n.createdAt)}}return t}function en(r){let e=b(r);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(ze),total:e.total,limit:e.limit,offset:e.offset}}function tn(r){let e=b(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=Pt(t);return{memberId:n.memberId,name:p(b(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:y(e.limit,1),offset:y(e.offset,0),nextOffset:e.nextOffset===null?null:y(e.nextOffset,0)}}function nn(r){let e=b(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=b(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(n.memberId),name:p(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:p(b(n.profilePicture).url)}}}}),limit:y(e.limit,1),offset:y(e.offset,0),nextOffset:e.nextOffset===null?null:y(e.nextOffset,0)}}function rn(r){let e=b(r);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),messageId:p(e.messageId),participantRevision:y(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Pt),shareLayers:e.shareLayers.map(t=>{let n=b(t),i=p(n.id),a=p(n.dataShareId),s=p(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:p(n.contractAddress),dataShareId:a,keyShareId:s};if(n.type==="INHERITI_VAULT"||n.type==="GOOGLE_DRIVE"||n.type==="DROPBOX"||n.type==="ONEDRIVE")return{id:i,type:n.type,dataShareId:a,keyShareId:s};throw new Error("invalid_inbox_response")})}}function Be(r){let e=b(r);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:p(e.messageId),status:e.status}}function an(r){let e=b(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=b(t);if(n.status!=="PREPARING"&&n.status!=="AVAILABLE"&&n.status!=="FAILED"&&n.status!=="DELETING")throw new Error("invalid_inbox_response");if(n.contentKind!==void 0&&n.contentKind!=="TEXT"&&n.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(n.recipientStatus!==void 0&&n.recipientStatus!=="UNREAD"&&n.recipientStatus!=="LEASED"&&n.recipientStatus!=="CONSUMED"&&n.recipientStatus!=="EXPIRED"&&n.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(n.recipientStatuses!==void 0&&!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:p(n.id),status:n.status,senderMemberId:p(n.senderMemberId),senderDeviceId:p(n.senderDeviceId),createdAt:N(n.createdAt),updatedAt:N(n.updatedAt),expiresAt:N(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(a=>{let s=b(a);if(s.status!=="UNREAD"&&s.status!=="LEASED"&&s.status!=="CONSUMED"&&s.status!=="EXPIRED"&&s.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:p(s.memberId),status:s.status,...s.consumedAt!==void 0?{consumedAt:s.consumedAt===null?null:N(s.consumedAt)}:{}}})),i}),total:y(e.total,0),limit:y(e.limit,1),offset:y(e.offset,0)}}function sn(r){let e=b(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:N(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:y(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let n=b(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:y(n.index,0),shareId:p(n.shareId),layerId:p(n.layerId),ciphertext:p(n.ciphertext)}})}}function on(r){let e=b(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:N(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:y(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let n=b(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:y(n.index,0),shareId:p(n.shareId),layerId:p(n.layerId)}})}}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 L=class extends Error{constructor(t,n,i,a){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.requestId=a;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ce=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;async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:me(t)}async getMemberInboxDevice(e,t){let n=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return n===null?null:me(n)}async registerInboxDevice(e){return me(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return me(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return me(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return ze(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return ze(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return en(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return tn(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return nn(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return rn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return jt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let n={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return ft(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return ft(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let a=i.size?`?${i}`:"";return Wt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${a}`,"GET",void 0,void 0,void 0,n))}async openInboxParent(e,t,n,i){let a=new URLSearchParams({deviceId:n});return Qt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${a}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return Jt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let a=i.size?`?${i}`:"";return Yt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${a}`,"GET",void 0,void 0,void 0,n))}async openNormalInboxMessage(e,t,n,i){let a=new URLSearchParams({deviceId:n});return Zt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${a}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,n){return Xt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,n))}async uploadInboxFileShare(e,t,n,i,a){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let s=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,o=await this.requestBinary(s,"PUT",i,a),d=await $e(o,a);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new L(o.status,oe(d),de(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,n))}async openInboxFile(e,t,n,i){return on(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:n},void 0,void 0,i))}async downloadInboxFileShare(e,t,n,i,a,s){let o=new URLSearchParams({deviceId:i,leaseId:a}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${o}`,c=await this.requestBinary(d,"GET",void 0,s);if(!c.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let l=Number(c.headers.get("content-length"));if(Number.isFinite(l)&&l>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!c.body)throw new Error("invalid_inbox_share_response");let u=c.body.getReader(),g=[],w=0;try{for(;;){s?.throwIfAborted();let f=await u.read();if(f.done)break;if(w+=f.value.length,w>14*1024*1024)throw new Error("invalid_inbox_share_size");g.push(f.value)}}catch(f){throw await u.cancel().catch(()=>{}),f}let D=new Uint8Array(w),m=0;for(let f of g)D.set(f,m),m+=f.length;return D}async listInboxMessages(e,t={},n){let i=new URLSearchParams;t.status&&i.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:t.status}])),t.limit!==void 0&&i.set("filter[limit]",String(t.limit)),t.offset!==void 0&&i.set("filter[skip]",String(t.offset));let a=i.size?`?${i}`:"";return an(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${a}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return sn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:n}))}async ackInboxMessage(e,t,n,i,a){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:n,leaseId:i},void 0,void 0,a)}async releaseInboxMessage(e,t,n,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:n,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then($t)}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 Vt(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Ve(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 zt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){J(e);let{idempotencyKey:t,...n}=e;return be(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return be(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return ae(t),be(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return be(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 d=new Headers({"x-elements-environment":this.environment});o&&d.set("authorization",`Bearer ${o}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&d.set("x-organization-id",this.business.organizationId),i?.requestId&&d.set("x-elements-step-up-request",i.requestId);for(let[w,D]of Object.entries(a??{}))d.set(w,D);n&&d.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l={method:t,headers:d,body:n?JSON.stringify(n):void 0};s&&(l.signal=s);let u=await this.transport(new URL(e,c),l);s?.throwIfAborted();let g=await $e(u,s);if(s?.throwIfAborted(),!u.ok)throw new L(u.status,oe(g),de(g),u.headers.get("x-request-id")??void 0);if(!g.ok||g.result===void 0)throw new L(u.status,oe(g),de(g),u.headers.get("x-request-id")??void 0);return g.result}async requestBinary(e,t,n,i){this.requireBusinessSelection(e),i?.throwIfAborted();let a=await this.getBearerToken();i?.throwIfAborted();let s=new Headers({"x-elements-environment":this.environment});a&&s.set("authorization",`Bearer ${a}`),this.business?.organizationId&&s.set("x-organization-id",this.business.organizationId),n&&s.set("content-type","application/octet-stream");let o=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,o),{method:t,headers:s,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let c=await $e(d,i);throw new L(d.status,oe(c),de(c),d.headers.get("x-request-id")??void 0)}return d}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 $e(s);if(!s.ok||!o.ok)throw new L(s.status,oe(o),de(o),s.headers.get("x-request-id")??void 0)}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new L(400,"organization_selection_required")}};async function $e(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{createNodeSsdpV2Processor as fr}from"@safetech/inheriti-core-sdk/node";async function vt(r,e){if(!e)throw new Error("master_key_required");let t=pr(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=ur(r),a=i.slice(0,12),s=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},n,s);return mr(new Uint8Array(o))}function pr(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 ur(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 mr(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var we=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await dn("plan_key_unwrap_failed",()=>vt(e.planKey,t)),i=await crypto.subtle.importKey("raw",bt(n),{name:"AES-GCM"},!1,["decrypt"]),a=[],s=[];for(let o of e.shares){let d=await dn("plan_share_decryption_failed",()=>yr(o.data,i));Ir(o.shareType)?s.push(d):a.push(d)}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",hr(o))}}},He=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},gr=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 hr(r){let e=r instanceof Error?r.message:void 0;if(e)return gr.has(e)?e:void 0}async function dn(r,e){try{return await e()}catch{throw new He(r)}}function Ir(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function yr(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=bt(r.slice(0,t)),i=bt(r.slice(t+1)),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(a)}function bt(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 le=class extends we{constructor(e){super(()=>fr(e))}};var Se=class{constructor(e,t,n){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=n}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return Ve(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,n){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,n)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...a}=n;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",a,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,n){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:n},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let n=this.firstRelayStates.get(e);return n?(this.firstRelayStates.delete(e),Promise.resolve(n)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,n,i=!0,a,s){s?.throwIfAborted();let o=await this.getAutomationBearerToken();if(s?.throwIfAborted(),!o)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${o}`,...a});n!==void 0&&d.set("content-type","application/json");let c=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:n===void 0?void 0:JSON.stringify(n),signal:s});s?.throwIfAborted();let l;try{l=await c.json()}catch{s?.throwIfAborted()}if(!c.ok||l&&l.ok===!1||i&&l?.result===void 0)throw new L(c.status,l&&oe(l),l&&de(l));return l?.result}};var x={invalidDeclaration:"plan_declaration_invalid",invalidShares:"plan_share_count_invalid",storageChanged:"plan_storage_context_changed",invalidMasterKeyContext:"invalid_master_key_context",reauthenticationRequired:"operator_reauthentication_required",relayFailed:"master_key_relay_failed",reconciliationRequired:"reconciliation_required"};var te=class extends Error{constructor(t,n){super(n??`plan_request_failed_${t}`);this.status=t;this.code=n}},Ee=class{constructor(e,t,n,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i}createContext(e){return this.request(e,"integrations/v1/plans/create-context","GET")}teams(e){return this.request(e,"integrations/v1/plans/create-teams","GET")}status(e,t){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}`,"GET")}create(e,t,n,i,a){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:n,...a?{description:a}:{}},type:"BACKUP",privacyMode:i?"PUBLIC":"PRIVATE",audience:i})}distribute(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:n.validatorShares,encryptedKey:n.encryptedKey})}preflight(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",cn(n))}configure(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",cn(n))}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(x.invalidMasterKeyContext);let i=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!i?.sessionId)throw new Error(x.relayFailed);return i}async readRelaySession(e,t){let n=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(x.relayFailed);return n}async request(e,t,n,i){let a=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),s=await this.getBearerToken();if(!s)throw new Error(x.reauthenticationRequired);a.set("authorization",`Bearer ${s}`),i!==void 0&&a.set("content-type","application/json");let o=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),d=o.pathname.endsWith("/integrations/")?t.replace(/^integrations\//,""):t,c=await this.transport(new URL(d,o),{method:n,headers:a,body:i===void 0?void 0:JSON.stringify(i)}),l={};try{l=await c.json()}catch{}if(!c.ok||l.ok!==!0)throw new te(c.status,l.error);return l.result}};function cn(r){return{protectionProtocol:r.protectionProtocol,operation:"FINALIZE",dataShards:r.dataShards,backupShards:r.backupShards,encryptedKey:r.encryptedKey,assetsMetadata:r.assetsMetadata,custodianPair:r.custodianShard}}var Re=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){xe(e.signal),vr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return xe(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){xe(e.signal);let t=e.encrypted.totalShares+1,n=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(xe(e.signal),!i.custodianPair)throw new M("custodian_share_required");let a=wt(i.keyShards),s=await this.sealer.encryptShares(a,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(wt(i.dataShards),s.symmetricKeyBase64),d=await this.sealer.encryptShares(wt(i.backupShards),s.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,s.symmetricKeyBase64);return xe(e.signal),{protectionProtocol:i.protocol,validatorShares:St(s.encryptedShares),dataShards:St(o.encryptedShares),backupShards:St(d.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:Pr(e.encrypted.assets,e.declaration),custodianShard:c,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:Et(n.encryptedShares[0]),dataShard:Et(n.encryptedShares[1])}}};function wt(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function St(r){return r.map(Et)}function Et(r){return{id:r.id,data:r.encryptedData}}function Pr(r,e){let t={};for(let n of r){let i=e.assets.find(a=>a.clientAssetRef===n.id);if(!i)throw new M("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.isMedia===void 0?{}:{isMedia:n.meta.isMedia},...n.meta.mimeType===void 0?{}:{mimeType:n.meta.mimeType},...n.meta.fileName===void 0?{}:{fileName:n.meta.fileName},...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function vr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new M("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new M("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new M("plan_secrets_declaration_mismatch");let t=new Map(r.assets.map(n=>[n.clientAssetRef,n]));for(let n of e.assets){let i=t.get(n.id);if(!i||i.type!==n.type)throw new M("plan_secrets_declaration_mismatch")}}function xe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function ln(r,e,t,n,i,a,s){let o=n.mergeThreshold-(n.withCustodian?1:0);if(typeof n.withCustodian!="boolean"||!Number.isInteger(n.mergeThreshold)||o<1||o>r.totalShares)throw new Error(x.invalidShares);let{assets:d,plan:c}=e;c.policy={custodian:n.withCustodian?"FORCE":"BYPASS"};let l=r.masterKeySource??new z({api:{startRelaySession:w=>i.startRelaySession(r.organizationId,t.masterKeyAcquisition,w),readRelaySession:w=>i.readRelaySession(r.organizationId,w)}}),u=new Re(a,l);s?.("encrypting");let g=await u.encrypt({planId:r.planId,declaration:c,secrets:{assets:d,totalShares:r.totalShares,threshold:o}});return s?.("generating_shares"),u.generateShares({planId:r.planId,declaration:c,encrypted:g})}import{PlanAssetDeclaration as br}from"@safetech/inheriti-core-sdk/node";function pn(r){let e=xt({planId:r.planId,title:r.title,assets:[r.asset]});return{asset:e.assets[0],plan:e.plan}}function xt(r){if(!r.assets.length)throw new v("assets_required");let e=r.assets.map(a=>{if(a.meta.isMedia!==!0)return;let s="data"in a.secret?a.secret.data:void 0,o;if(s instanceof Blob&&(o=s.size),typeof s=="string")try{o=atob(s).length}catch{throw new v("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new v("binary_asset_metadata_invalid");return o}),t=br.create(r.assets.map(({type:a,meta:s})=>({type:a,meta:s}))),n=t.complete(Object.fromEntries(t.entries.map((a,s)=>[a.id,r.assets[s].secret]))),i={idempotencyKey:r.planId,name:r.title,assets:n.map((a,s)=>{let o=a.meta.isMedia===!0;return{clientAssetRef:a.id,type:a.type,name:a.meta.name,fieldNames:o?[]:Object.keys(a.secret),isBinary:o,fileName:a.meta.fileName,mimeType:a.meta.mimeType,size:e[s]}}),participants:[]};return{assets:n,plan:i}}async function mn(r){let e=await Promise.all(r.assets.map(async t=>({type:t.type,meta:t.meta,secret:await Promise.all(Object.entries(t.secret).sort(([n],[i])=>n.localeCompare(i)).map(async([n,i])=>[n,i instanceof Blob?await un(new Uint8Array(await i.arrayBuffer())):i]))})));return un(new TextEncoder().encode(JSON.stringify({organizationId:r.organizationId,planId:r.planId,title:r.title,description:r.description??null,audience:r.audience??null,totalShares:r.totalShares,assets:e})))}async function un(r){let e=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}var Ae=class{constructor(e,t){this.port=e;this.coreSdk=t}material=new Map;flights=new Map;async createQuickPlan(e,t){return this.createPlan({...e,assets:[e.asset]},t)}async createPlan(e,t){if(!e.organizationId||!e.planId||!e.title.trim()||!Array.isArray(e.assets)||!e.assets.length||e.assets.some(s=>!s?.meta?.name?.trim()))throw new Error(x.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(x.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(x.invalidShares);let n=await mn(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==n)throw new Error(x.reconciliationRequired);return i.promise}let a=this.performCreate(e,n,t);this.flights.set(e.planId,{fingerprint:n,promise:a});try{return await a}finally{this.flights.delete(e.planId)}}async performCreate(e,t,n){let i=xt({planId:e.planId,title:e.title,assets:e.assets}),a=this.material.get(e.planId);if(a&&(a.fingerprint!==t||a.masterKeySource!==e.masterKeySource))throw new Error(x.reconciliationRequired);let s=await this.statusOrMissing(e.organizationId,e.planId);if(We(s))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(s&&!a)throw new Error(x.reconciliationRequired);if(!s&&a)throw new Error(x.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(x.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(x.invalidMasterKeyContext);if(!s){n?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience,e.description)}catch(l){if(s=await this.statusOrMissing(e.organizationId,e.planId),!s)throw l}}s??=await this.port.status(e.organizationId,e.planId);let d=a?.encrypted??await ln(e,i,o,s,this.port,this.coreSdk,n);a||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),n?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),n?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),n?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(l){if(!We(await this.statusOrMissing(e.organizationId,e.planId)))throw l}n?.("verifying");let c=await this.port.status(e.organizationId,e.planId);return We(c)&&this.material.delete(e.planId),{planId:e.planId,status:We(c)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(x.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(n){if(n instanceof te&&n.status===404)return;throw n}}};function We(r){return r?.status==="PROTECTED"||r?.status==="CONFIGURED"}var Qe=class{constructor(e,t,n,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i}start(e,t,n,i){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:n},i)}async listEligibleCandidates(e,t,n){let i=new URLSearchParams({status:"PROTECTED"});t&&i.set("cursor",t),n&&i.set("namePrefix",n);let a=await this.request(e,`plans/editable?${i}`,"GET");if(!this.isCandidatePage(a))throw new Error("invalid_plan_edit_candidates");return a}async context(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(n))throw new Error("invalid_plan_edit_context");return n}async moderatorNames(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}`,"GET");if(!n||typeof n!="object")throw new Error("invalid_plan_edit_participants");let i=n;if(i.id!==t||!Array.isArray(i.participants)||i.participants.length>1e3)throw new Error("invalid_plan_edit_participants");let a=new Map;for(let s of i.participants){if(!s||typeof s.id!="string"||!s.id||typeof s.displayName!="string"||!Array.isArray(s.relationships)||!s.relationships.every(o=>typeof o=="string")||typeof s.lifecycle!="string")throw new Error("invalid_plan_edit_participants");s.lifecycle==="ACTIVE"&&s.relationships.includes("MODERATOR")&&a.set(s.id,s.displayName)}return a}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(x.invalidMasterKeyContext);let i=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!i?.sessionId)throw new Error(x.relayFailed);return i}async readRelaySession(e,t){let n=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(x.relayFailed);return n}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(n))}commit(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(n))}abort(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"DELETE")}commitStatus(e,t){return this.request(e,`edits/${encodeURIComponent(t)}/commit-status`,"GET")}async request(e,t,n,i,a){let s=await this.getBearerToken();if(!s)throw new Error(x.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${s}`,"x-organization-id":e,"x-elements-environment":this.environment});i!==void 0&&o.set("content-type","application/json"),a&&o.set("idempotency-key",a);let d=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),c=d.pathname.endsWith("/integrations/")?`v1/${t}`:`integrations/v1/${t}`,l=await this.transport(new URL(c,d),{method:n,headers:o,body:i===void 0?void 0:JSON.stringify(i)}),u={};try{u=await l.json()}catch{}if(!l.ok||u.ok!==!0){let g=Array.isArray(u.validationErrors)?u.validationErrors.join("; "):void 0;throw new te(l.status,g||u.error)}return u.result}isCandidatePage(e){if(!e||typeof e!="object")return!1;let t=e;return!Array.isArray(t.items)||!(t.nextCursor===null||typeof t.nextCursor=="string")?!1:t.items.every(n=>!!n&&typeof n.id=="string"&&!!n.id&&typeof n.name=="string"&&n.status==="PROTECTED"&&typeof n.createdAt=="string"&&!!n.assetSummary&&Number.isSafeInteger(n.assetSummary.count)&&n.assetSummary.count>=0&&Array.isArray(n.assetSummary.types)&&n.assetSummary.types.every(i=>typeof i=="string")&&Array.isArray(n.assetSummary.names)&&n.assetSummary.names.every(i=>typeof i=="string")&&!!n.governance&&["DIRECT","GOVERNED"].includes(n.governance.mode)&&Number.isSafeInteger(n.governance.minimumApprovals)&&n.governance.minimumApprovals>=0)}isEditContext(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.idempotencyKey=="string"&&!!t.idempotencyKey&&(t.mode==="DIRECT"||t.mode==="GOVERNED")&&Number.isSafeInteger(t.totalShares)&&t.totalShares>0&&typeof t.masterKeyEncrypted=="boolean"&&t.masterKeyAcquisition?.system==="INHERITI_BUSINESS"&&typeof t.masterKeyAcquisition.contextId=="string"&&!!t.masterKeyAcquisition.contextId}reconfigureBody(e){return{mergeProcessId:e.mergeProcessId,protectionProtocol:e.protectionProtocol,validatorShares:e.validatorShares,dataShards:e.dataShards,backupShards:e.backupShards,encryptedKey:e.encryptedKey,assetsMetadata:e.assetsMetadata,custodianPair:e.custodianPair}}};var je=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.recoveryStore=n}revealedAssets;revealGeneration=0;clearRevealedAssets(e){this.revealGeneration++,this.revealedAssets?.planId===e&&(this.revealedAssets=void 0)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async loadAssets(e,t){this.assertNotAborted(e.signal);let n=this.revealGeneration;if(!e.organizationId||!e.planId||!e.editId)throw new Error("invalid_plan_edit_input");if(t?.("checking_edit"),await this.recoveryStore.load(e.planId)||await this.configurationRepository().findByPlanId(e.planId))throw this.clearRevealedAssets(e.planId),new Error("edit_recovery_required");let i=await this.assertEditSession(e),a=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!a)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let s=this.revealedAssets,o=s?.organizationId===e.organizationId&&s.planId===e.planId&&s.editId===e.editId&&s.expiresAt>Date.now();s&&!o&&(this.revealedAssets=void 0);let d=a.masterKeyEncrypted?e.masterKey??(o?s.masterKey:void 0):void 0;a.masterKeyEncrypted&&!d&&(t?.("acquiring_key"),d=await(e.acquireMasterKey?.()??this.resolveMasterKey(e)));let c=Date.now()+10*6e4;o||t?.("opening_plan");let l=o?s.assets:await this.revealAssets(e,d,a.withCustodian,t);if(this.assertNotAborted(e.signal),new Set(l.map(u=>u.id)).size!==l.length)throw new Error("duplicate_existing_asset_id");return!o&&n===this.revealGeneration&&i>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(i,c),assets:l,masterKey:d}),{plan:a,masterKey:d,assets:l}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),n=Date.parse(t.expiresAt);if(t.id!==e.editId||t.planId!==e.planId||["CANCELED","CLOSED"].includes(t.stage))throw this.clearRevealedAssets(e.planId),new Error("edit_session_not_open");if(t.stage==="EXPIRED"||!(n>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_expired");return n}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new z({api:{startRelaySession:n=>this.port.startRelaySession(e.organizationId,t,n),readRelaySession:n=>this.port.readRelaySession(e.organizationId,n)}}).resolve()}async revealAssets(e,t,n,i){let a=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),s=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=m=>{m!==o&&(o=m,i?.(m))},c=m=>{if(m.processId!==e.editId||m.planId&&m.planId!==e.planId)return;switch(m.status){case"PENDING_DMS":d("pending_dms");break;case"PENDING_APPROVALS":d("pending_approvals");break;case"PENDING_AUTH":d("pending_auth");break;case"PENDING_MODERATION":d("pending_moderation");break}let f=this.approvalError(m);if(f?.startsWith("edit_authentication_")&&d("pending_auth"),f?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!m.moderatorParticipants||m.requiredModeratorApprovals===void 0||!m.approvalProcess)return;let K=m.moderatorParticipants.map(C=>C.memberId??C.userId);K.some(C=>typeof C!="string"||!C)||new Set(K).size!==K.length||i?.(o,{requiredApprovals:m.requiredModeratorApprovals,approvedModerators:m.approvalProcess.approvedModerators,moderators:m.moderatorParticipants.map((C,q)=>{let A=K[q],$=C.flows.filter(ge=>ge.status==="PENDING"&&ge.expiresAt&&Number.isFinite(ge.expiresAt.getTime())).map(ge=>ge.expiresAt.getTime());return{id:A,displayName:s.get(A)||"Moderator",status:C.status,expiresAt:$.length?new Date(Math.min(...$)).toISOString():void 0}})})},l=await a.resume(e.planId,{onViewUpdate:c});if(l?.processId!==e.editId||l.planId&&l.planId!==e.planId)throw new Error("edit_merge_not_ready");c(l),this.assertApprovalOutcome(e.planId,l),l.status!=="READY_TO_REVEAL"&&l.status!=="REVEALED"&&await a.run(e.editId,{onViewUpdate:c,onApprovalsRequested:()=>d("pending_approvals")});let u=await a.getView(e.editId);if(u?.processId!==e.editId||u.planId&&u.planId!==e.planId)throw new Error("edit_merge_not_ready");c(u),this.assertApprovalOutcome(e.planId,u);let g=u?.status;if(g!=="READY_TO_REVEAL"&&g!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let w=null,D={onRevealed:m=>{w=m},onViewUpdate:c,onRevealStepUpdate:(m,f)=>{if(f==="IN_PROCESS")switch(m){case"DISTRIBUTING_CUSTODIAN_SHARE":break;case"COLLECTING_VALIDATOR_SHARES":d("collecting_validators");break;case"COLLECTING_SHARES":d("collecting_shares");break;case"RECONSTRUCTING":d("reconstructing");break;case"OPENING_WINDOW":d("opening_window");break;case"PREPARING_VIEW":d("preparing_view");break}}};if(n&&(D.onCustodianShareRequired=async(m,f)=>{switch(f.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let K=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),K==="SK_MOBILE")return a.distributeCustodianShareViaMobile(f.planId);if(K!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let C=e.proDevice;try{this.assertNotAborted(e.signal);let q=await a.getCustodianShareData(m);this.assertShare(q,f.planId),d("connecting_safekey_pro");let{deviceId:A}=await C.write(q,e.signal);if(this.assertNotAborted(e.signal),!A?.trim())throw new Error("custodian_share_unavailable");await a.recordCustodianShareClaim(f.planId,q.id,A,"SK_PRO"),this.assertNotAborted(e.signal),await a.markCustodianShareAsCollected(m,q.id);return}finally{C.clearPin?.()}}case"awaiting-claim":d("claiming_custodian_share");return;case"awaiting-release":d("releasing_custodian_share");return;case"collect-from-sk-pro":{if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let K=e.proDevice;try{if(this.assertNotAborted(e.signal),!f.shareId||!f.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let C=await K.read({shareId:f.shareId,planId:f.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(C,f.planId,f.shareId),C.deviceId!==f.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:C.shares}}finally{K.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),g==="REVEALED"?await a.resumeReveal(e.editId,D,t):await a.openRevealWindow(e.editId,{timeoutMinutes:10},D,t),this.assertNotAborted(e.signal),!w)throw new Error("edit_assets_unavailable");return w}assertApprovalOutcome(e,t){let n=this.approvalError(t);if(n)throw this.clearRevealedAssets(e),new Error(n)}approvalError(e){if(e?.isAuthenticationDenied)return"edit_authentication_denied";if(e?.isAuthenticationCanceled)return e.isExpired?"edit_authentication_expired":"edit_authentication_canceled";if(e?.isModerationDenied)return"edit_moderation_denied";if(e?.isModerationCanceled)return e.isExpired?"edit_moderation_expired":"edit_moderation_canceled";if(e?.isExpired)return"edit_session_expired"}assertShare(e,t,n){if(!e||!e.id||e.id!==(n??e.id)||e.planId!==t||!Array.isArray(e.shares)||!e.shares.length||e.shares.some(i=>typeof i!="string"||!i))throw new Error("custodian_share_unavailable")}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}};var wr=r=>JSON.stringify(r??null,(e,t)=>!t||typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([n],[i])=>n<i?-1:n>i?1:0))),Ye=class{constructor(e,t,n,i){this.port=e;this.coreSdk=t;this.recoveryStore=n;this.clearRevealedAssets=i}async saveAssets(e,t,n,i,a,s){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,n,i);s?.("preparing");let c=await o.prepare(d);this.assertNotAborted(e.signal);let l={mergeProcessId:e.editId,protectionProtocol:c.protectionProtocol,validatorShares:this.transportShares(c.validatorShares),dataShards:this.transportShares(c.dataShards),backupShards:this.transportShares(c.backupShards),encryptedKey:c.encryptedKey,assetsMetadata:c.assetsMetadata,custodianPair:c.custodianPair};if(s?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,l),this.assertNotAborted(e.signal),!await this.recoveryStore.save({organizationId:e.organizationId,planId:e.planId,editId:e.editId,assetId:a,material:l}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,a,l,o,d,s)}async recover(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId||t.planId!==e.planId||t.material.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let n=await this.configurationRepository().findByPlanId(e.planId),i=n?.editDistribution??n?.preparedDistribution;if(!t&&(!i||n?.editDistribution&&n.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let a=t?.material??{mergeProcessId:e.editId,protectionProtocol:i.protectionProtocol,validatorShares:i.validatorShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),dataShards:i.dataShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),backupShards:i.backupShards.map(s=>({id:s.id,data:s.data,replacedShareId:s.replacedShareId})),encryptedKey:i.encryptedKey,assetsMetadata:i.assetsMetadata,custodianPair:i.custodianPair};try{if(await this.isCommitted(e,a))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!n?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let s=await this.port.status(e.organizationId,e.editId);return s.id!==e.editId||s.planId!==e.planId||s.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,a),await this.port.commit(e.organizationId,e.planId,a),await this.isCommitted(e,a)?(await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}):{status:"RECOVERY_REQUIRED"})}catch{return{status:"RECOVERY_REQUIRED"}}}async discard(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId))throw new Error("edit_checkpoint_session_mismatch");let n=await this.configurationRepository().findByPlanId(e.planId);if(n?.editDistribution&&n.editDistribution.mergeProcessId!==e.editId)throw new Error("edit_checkpoint_session_mismatch");await this.port.abort(e.organizationId,e.editId),await this.clearCheckpoint(e.planId,e.editId)}discardLocal(e){return this.clearCheckpoint(e)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async clearCheckpoint(e,t){this.clearRevealedAssets(e);let n=this.coreSdk.getService("SharedMergingProcessLocalRepository"),i=await n.findByPlanId(e);if(t&&i&&i.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),i&&await n.delete(i.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,n,i){let a=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),s={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:n,masterKey:i,reconfigureContext:{mergeProcessId:e.editId}};return{configure:a,configuration:s}}transportShares(e){return e.map(t=>({id:t.id,data:t.data,replacedShareId:t.replacedShareId}))}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}async commit(e,t,n,i,a,s){let o,d=c=>{let l;switch(c.currentStep?.id){case"VALIDATOR_SHARES_DISTRIBUTION":l="distributing_validators";break;case"SHARES_DISTRIBUTION":l="distributing_data";break;case"FINALIZE":l="finalizing";break;default:return}l!==o&&(o=l,s?.(l))};try{await i.execute(a,{onLocalProcessUpdated:d})}catch(c){try{if(s?.("verifying"),await this.isCommitted(e,n))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}throw o&&s?.(o),c}try{if(s?.("verifying"),!await this.isCommitted(e,n))return{status:"RECOVERY_REQUIRED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}async isCommitted(e,t){let n=await this.port.commitStatus(e.organizationId,e.editId);if(n.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(n.status)||n.editStatus!=="COMPLETED")return!1;let i=new TextEncoder().encode(wr(t.assetsMetadata)),a=await globalThis.crypto.subtle.digest("SHA-256",i),s=Array.from(new Uint8Array(a),c=>c.toString(16).padStart(2,"0")).join("");if(n.assetsMetadataHash!==s)return!1;let o=[t.validatorShares,t.dataShards,t.backupShards].flat().map(c=>c.id);t.custodianPair&&o.push(t.custodianPair.keyShard.id,t.custodianPair.dataShard.id);let d=new Set(n.shares.map(c=>c.id));return!o.some(c=>!d.has(c))}};var Xe=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.assetAccess=new je(e,t,n),this.reconfiguration=new Ye(e,t,n,i=>this.clearRevealedAssets(i))}assetAccess;reconfiguration;activeEdits=new Set;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,n,i){return this.port.start(e,t,n,i)}async listAssets(e,t){let{assets:n}=await this.assetAccess.loadAssets(e,t);return n.map(i=>({id:i.id,type:i.type,name:i.meta.name,isMedia:this.isMedia(i)}))}async getAsset(e,t,n){let{assets:i}=await this.assetAccess.loadAssets(e,n),a=i.find(s=>s.id===t);if(!a)throw new Error("edit_asset_not_found");return structuredClone(a)}async replaceAsset(e,t){return this.withEditLock(e.planId,async()=>{if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:n,masterKey:i,assets:a}=await this.assetAccess.loadAssets(e,t),s=a.findIndex(l=>l.id===e.assetId);if(s<0)throw new Error("edit_asset_not_found");let o=a[s];if(o.type!==e.asset.type)throw new Error("edit_asset_type_mismatch");if(this.isMedia(o)&&!this.hasMediaData(e.asset.secret))throw new Error("edit_media_file_required");let d={id:o.id,type:o.type,meta:e.asset.meta,secret:e.asset.secret},c=a.map((l,u)=>u===s?d:l);return this.reconfiguration.saveAssets(e,c,n.withCustodian,i,o.id,t)})}async addAsset(e,t){return this.withEditLock(e.planId,async()=>{let{plan:n,masterKey:i,assets:a}=await this.assetAccess.loadAssets(e,t),s=pn({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(a.map(d=>d.id)).has(s.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,a.concat(s),n.withCustodian,i,s.id,t)})}async withEditLock(e,t){if(this.activeEdits.has(e))throw new Error("edit_in_progress");this.activeEdits.add(e);try{return await t()}finally{this.activeEdits.delete(e)}}isMedia(e){return["DOCUMENT","IMAGE","VIDEO","PDF"].includes(e.type)||e.meta.isMedia===!0}hasMediaData(e){let t=e.data;return typeof t=="string"?t.length>0:typeof Blob<"u"&&t instanceof Blob&&t.size>0}recover(e){return this.withEditLock(e.planId,()=>this.reconfiguration.recover(e))}discard(e){return this.withEditLock(e.planId,()=>this.reconfiguration.discard(e))}discardLocal(e){return this.withEditLock(e,()=>this.reconfiguration.discardLocal(e))}};function gn({apiUrl:r,organizationId:e,planId:t,editId:n,environment:i,transport:a}){return(s,o)=>{let d=new URL(s instanceof Request?s.url:s.toString()),c=new URL(r.endsWith("/")?r:`${r}/`);if(d.origin!==c.origin||!d.pathname.startsWith(c.pathname))throw new Error("unsupported_core_edit_route");let l=d.pathname.slice(c.pathname.replace(/\/$/,"").length).replace(/^\//,"");if(l===".well-known/encrypt-key"){if(d.search||o?.method&&o.method!=="GET")throw new Error("unsupported_core_edit_route");return a(d,o)}if(l==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let u=Sr(l,d.searchParams,t,n),g=new Headers(o?.headers);g.set("x-organization-id",e),g.set("x-elements-environment",i);let w=c.pathname.endsWith("/integrations/")?`v1/${u}`:`integrations/v1/${u}`;return a(new URL(w,c),Object.assign({},o,{headers:g}))}}function Sr(r,e,t,n){if(r==="shared-plans/merge/current-user/active"){if(t!==e.get("planIds[]"))throw new Error("edit_plan_id_mismatch");return`plans/${encodeURIComponent(t)}/edits/active`}let a=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(r);if(a){let o=a[2]??"",d={"":"process",approvals:"approvals","plans/assets-metadata":"assets-metadata","approvals/merger/request":"approvals/merger/request","approvals/moderators/request":"approvals/moderators/request","reveal/open":"reveal/open","validator-shares/collect":"validator-shares/collect","shares/collect":"shares/collect","shares/collected":"shares/collected","shares/reconstructed":"shares/reconstructed","data/revealed":"data/revealed","custodian-share/status":"custodian-share/status","custodian-share/data":"custodian-share/data","custodian-share/release":"custodian-share/release","custodian-share/collect":"custodian-share/collect","custodian-share/cancel-claim":"custodian-share/cancel-claim"};if(a[1]!==n||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(a[1])}/${d[o]}`}let s=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(r);if(s){if(s[1]!==t)throw new Error("edit_plan_id_mismatch");let o=s[2]??"";if(o==="")return`edits/${encodeURIComponent(n)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(s[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(n)}/${o}`}throw new Error("unsupported_core_edit_route")}import{decodeAssetContainer as Er}from"@safetech/inheriti-core-sdk/node";function hn(r){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let n=await r.api.planKeyReference(e),i=he(n);if(!n.masterKeyWrapped||!i||n.planId!==e)throw new Error("automation_plan_key_reference_invalid");let a=new z({api:{startRelaySession:o=>r.api.startMasterKeyRelaySession(crypto.randomUUID(),e,o),readRelaySession:(o,d)=>r.api.readMasterKeyRelaySession(o,d),cancelRelaySession:(o,d)=>r.api.cancelMasterKeyRelaySession(o,d)}});return new se(void 0,{api:r.api,reconstructor:r.reconstructor,assetDecoder:r.assetDecoder,masterKeys:{resolve:(o,d,c)=>{if(o.system!==i.system||o.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return a.resolve(d,c)}}}).openReveal(e,t)}}}function xr(r){let e=new Se(r.apiUrl,r.getBearerToken,r.transport??globalThis.fetch.bind(globalThis));return{...hn({api:e,reconstructor:new le(r.workerUrl),assetDecoder:Er}),getPlan:t=>e.getPlan(t)}}import{DataAssetDefinitionService as $s}from"@safetech/inheriti-core-sdk/node";function In(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Je=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),In(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return In(new Uint8Array(t))}},Ze=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 _e=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},Ce=class extends _e{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},S=class extends _e{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Rt(r){if(r instanceof _e)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var yn=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:ne(n,"issuer"),authorizationEndpoint:ne(n,"authorization_endpoint"),tokenEndpoint:ne(n,"token_endpoint"),deviceAuthorizationEndpoint:Q(n,"device_authorization_endpoint"),endSessionEndpoint:Q(n,"end_session_endpoint"),revocationEndpoint:Q(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:ne(t,"device_code"),userCode:ne(t,"user_code"),verificationUri:ne(t,"verification_uri"),verificationUriComplete:Q(t,"verification_uri_complete"),expiresInSeconds:fn(t,"expires_in"),intervalSeconds:At(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:ne(n,"access_token"),refreshToken:Q(n,"refresh_token"),idToken:Q(n,"id_token"),tokenType:ne(n,"token_type"),expiresInSeconds:fn(n,"expires_in"),refreshExpiresInSeconds:At(n,"refresh_expires_in"),scope:Q(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=Q(i,"error")??`oauth_http_${n.status}`;throw new S(a,Q(i,"error_description")??a)}return i}};function ne(r,e){let t=Q(r,e);if(!t)throw new S("invalid_oauth_response",`Missing ${e}`);return t}function Q(r,e){return typeof r[e]=="string"?r[e]:void 0}function fn(r,e){let t=At(r,e);if(t===void 0)throw new S("invalid_oauth_response",`Missing ${e}`);return t}function At(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Rr=600*1e3,et=5,Ar=5,Pn=class{constructor(e){this.options=e;this.crypto=e.crypto??new Je,this.clock=e.clock??new Ze}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()+Rr;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 S("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new S("authorization_transaction_expired");let i=new URL(e),a=new URL(n.redirectUri);if(i.origin!==a.origin||i.pathname!==a.pathname)throw new S("redirect_uri_mismatch");let s=i.searchParams.get("error");if(s)throw new S(s,i.searchParams.get("error_description")??s);if(i.searchParams.get("state")!==n.state)throw new S("state_mismatch");let o=i.searchParams.get("code");if(!o)throw new S("authorization_code_missing");let d=await this.getDiscovery(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),l=await this.acceptTokens(c,n.nonce);return await this.options.sessions.save(l),l}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new S("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(et,t.intervalSeconds??et),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 S("device_transaction_missing");let i=n,a=await this.getDiscovery(),s=Math.max(et,i.intervalSeconds??et),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 d=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(d);return await this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(d){let c=Rt(d);if(c==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(c==="slow_down"){s+=Ar,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new S("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 Ce;let t;try{let n=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:n.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(n){let i=Rt(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.options.sessions.clear(),new Ce):(this.isOfflineSession(e)||await this.options.sessions.clear(),n)}try{if(!t.refreshToken)throw new S("refresh_token_rotation_missing");let n=await this.acceptTokens(t,void 0,e);return await this.options.sessions.save(n),n}catch(n){throw await this.options.sessions.clear(),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(pe(e.issuer)!==pe(this.options.configuration.issuer))throw new S("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}|${pe(t)}|${n}|${i}`}async acceptTokens(e,t,n){if(e.tokenType.toLowerCase()!=="bearer")throw new S("unsupported_token_type");let i=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(i,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new S("id_token_validation_required");let o=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(o,t),o.subject!==i.subject||o.sessionId!==i.sessionId)throw new S("token_subject_mismatch")}let a=this.clock.now(),s=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?n?this.isOfflineSession(n):!0:e.scope.split(/\s+/u).includes("offline_access"));return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:a+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&s?void 0:a+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:s,principal:i}}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}assertPrincipal(e,t,n){let i=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(pe(e.issuer)!==pe(i.issuer))throw new S("issuer_mismatch");if(!a.includes(i.audience))throw new S("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new S("client_mismatch");if(e.environment!==i.environment)throw new S("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new S("required_claim_missing");if(n&&e.nonce!==t)throw new S("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(pe(e.issuer)!==pe(n.issuer))throw new S("issuer_mismatch");if(!i.includes(n.clientId))throw new S("client_mismatch");if(e.authorizedParty!==n.clientId)throw new S("client_mismatch");if(!e.subject||!e.sessionId)throw new S("required_claim_missing");if(e.nonce!==t)throw new S("nonce_mismatch")}};function pe(r){return r.replace(/\/+$/u,"")}var vn=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()}}};import{PassphraseMasterKeySource as Xs,RawMasterKeySource as Js,deriveMasterKey as Zs,generateHexSeed as eo,computePassphraseVerifier as to}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as ro}from"@safetech/inheriti-core-sdk/node";function Cs(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=(a,s)=>{let o=new Headers(s?.headers);return o.set("x-elements-environment",r.environment),e(a,Object.assign({},s,{headers:o}))},n=r.business?void 0:_t({apiUrl:r.apiUrl,getBearerToken:r.getBearerToken,transport:t,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners}),i=new ce(r.apiUrl,r.environment,r.getBearerToken,t,r.business?{organizationId:r.organizationId}:void 0);return new se(n,{keyVault:r.keyVault,state:r.state,api:i,reconstructor:new le(r.workerUrl),masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:_r})}function Ts(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=_t({apiUrl:new URL(r.apiUrl).origin,getBearerToken:r.getBearerToken,transport:e,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Ae(new Ee(r.apiUrl,r.environment,r.getBearerToken,e),t)}function Ds(r){if(!r.payloadStorage||!r.secureSessionStorage||!r.editRecoveryStore)throw new Error("protected_edit_checkpoint_required");let e=r.transport??globalThis.fetch.bind(globalThis),t=new URL(r.apiUrl).origin,n=_t({apiUrl:t,getBearerToken:r.getBearerToken,transport:gn({apiUrl:t,organizationId:r.organizationId,planId:r.planId,editId:r.editId,environment:r.environment,transport:e}),secureSessionStorage:r.secureSessionStorage,payloadStorage:r.payloadStorage,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Xe(new Qe(r.apiUrl,r.environment,r.getBearerToken,e),n,r.editRecoveryStore)}import{createHash as Cr,webcrypto as Tr}from"node:crypto";import{canonicalInboxManifest as Dr,decodeInboxManifest as Mr,decodeInboxContentFrame as kr,decodeInboxText as Or,decryptInboxShare as Nr,encodeInboxContentFrame as Ct,encodeInboxText as Kr,encryptInboxShare as bn,inboxProtectedUnitCommitment as Ur,inboxTextMetadataDigest as wn,openInboxContent as Lr,sealInboxContent as qr,signInboxFrame as Gr,unwrapInboxContentKey as Fr,unwrapInboxShareKey as Vr,verifyInboxFrame as Sn,wrapInboxContentKey as zr,wrapInboxShareKey as Br}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as $r}from"@safetech/inheriti-core-sdk/workers/inbox.node";var B=Tr,_=B,R=r=>{if(!/^[0-9a-fA-F]{64}$/.test(r))throw new Error("invalid_inbox_key");return Buffer.from(r,"hex")},h=r=>{let e=Buffer.from(r,"base64");if(!r||e.toString("base64")!==r)throw new Error("invalid_inbox_base64");return Uint8Array.from(e)},F=(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),tt=async r=>new Uint8Array(await _.subtle.digest("SHA-256",Uint8Array.from(r))),Te=r=>Cr("sha256").update(r).digest("hex"),re=class{constructor(e,t=new $r){this.api=e;this.worker=t}async send(e){let t=await this.prepare(e);return this.api.publishInboxMessage(e.conversationId,t.submission)}async prepare(e){let{preparation:t,sender:n}=await this.prepareSender(e),i=await this.textManifest(e,t,n),a=Dr(i),s=await tt(a),{contentKey:o,frame:d}=await qr(Kr(e.text),s,_),c=await this.signFrame(i,d,e.identity.signingPrivateKey,n.signingPublicKey),{shareKey:l,shares:u}=await this.protectShares(t,d,s),g=await this.wrapRecipientKeys(t,o,s),w=await Br(l,R(e.tenantKeyHex),s,i.tenantId,i.messageId,_);return{frame:Buffer.from(Ct(d)).toString("base64"),submission:{messageId:t.messageId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,expiresAt:e.expiresAt,idempotencyKey:t.messageId,canonicalManifest:Buffer.from(a).toString("base64"),signature:Buffer.from(c).toString("base64"),tenantWrappedShareKey:Buffer.from(w).toString("base64"),recipients:g,shares:u}}}async open(e){return this.openWithCommitment(e)}openCommitted(e,t){return this.openWithCommitment(e,t)}async openWithCommitment(e,t){let n=await this.api.openInboxMessage(e.conversationId,e.messageId,e.identity.deviceId),i;try{e.signal?.throwIfAborted();let{manifest:s,manifestDigest:o,senderPublicDer:d}=await this.verifyOpening(e,n),c=await this.recoverFrame(n,s,o,e.tenantKeyHex);if(t&&!F(t,await Ur(s,Ct(c),h(n.signature),_)))throw new Error("inbox_parent_unit_mismatch");i=await this.decryptText(n,c,s,o,d,e.identity.encryptionPrivateKey),e.signal?.throwIfAborted()}catch(s){try{await this.api.releaseInboxMessage(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId)}catch{}throw s}let a=await this.ack(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId,e.signal);return e.signal?.throwIfAborted(),{text:i,leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt,acknowledgement:a}}async ack(e,t,n,i,a){for(let s=0;s<2;s++){a?.throwIfAborted();try{return await this.api.ackInboxMessage(e,t,n,i,a),a?.throwIfAborted(),"ACKNOWLEDGED"}catch(o){if(a?.throwIfAborted(),o instanceof L&&o.status>=400&&o.status<500)throw o}}return"PENDING"}async prepareSender(e){let t=await this.api.getInboxSendPreparation(e.conversationId);if(t.conversationId!==e.conversationId||t.threshold!==t.total||t.total!==t.shareLayers.length||t.total<2)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId);if(!n||n.deviceId!==e.identity.deviceId||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||Te(h(n.signingPublicKey))!==n.signingKeyFingerprint||Te(h(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return{preparation:t,sender:n}}async textManifest(e,t,n){let i=Date.parse(e.expiresAt);if(!Number.isSafeInteger(i)||i<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:e.identity.tenantId,conversationId:e.conversationId,messageId:t.messageId,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:R(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(a=>({memberId:a.memberId,deviceId:a.deviceId,encryptionKeyFingerprint:R(a.encryptionKeyFingerprint)})),expiresAtEpochMs:i,metadataDigest:await wn(_)}}async signFrame(e,t,n,i){let a=await _.subtle.importKey("pkcs8",h(n),"Ed25519",!1,["sign"]),s=await Gr(e,t,a,_),o=await _.subtle.importKey("spki",h(i),"Ed25519",!1,["verify"]);if(!await Sn(e,t,s,o,_))throw new Error("inbox_identity_mismatch");return s}async protectShares(e,t,n){let i=await this.worker.split(Ct(t),{threshold:e.threshold,total:e.total,messageId:e.messageId,manifestDigest:n}),a=_.getRandomValues(new Uint8Array(32)),s=[];for(let o=0;o<e.total;o++){let d=e.shareLayers[o];s.push({kind:"DATA",index:o,shareId:d.dataShareId,layerId:d.id,ciphertext:Buffer.from(await bn(i.dataShares[o],a,n,e.messageId,_)).toString("base64")}),s.push({kind:"KEY",index:o,shareId:d.keyShareId,layerId:d.id,ciphertext:Buffer.from(await bn(i.keyShares[o],a,n,e.messageId,_)).toString("base64")})}return{shareKey:a,shares:s}}async wrapRecipientKeys(e,t,n){return Promise.all(e.recipients.map(async i=>{let a=h(i.encryptionPublicKey);if(Te(a)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await _.subtle.importKey("spki",a,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:Buffer.from(await zr(t,s,n,_)).toString("base64")}}))}async verifyOpening(e,t,n){let i=h(t.canonicalManifest),a=Mr(i);if(a.tenantId!==e.identity.tenantId||a.conversationId!==e.conversationId||a.messageId!==e.messageId||a.expiresAtEpochMs<=Date.now()||!F(a.metadataDigest,n??await wn(_)))throw new Error("inbox_manifest_mismatch");let s=a.recipients.find(d=>d.memberId===e.identity.memberId&&d.deviceId===e.identity.deviceId);if(!s||!F(s.encryptionKeyFingerprint,R(Te(h(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let o=h(t.senderSigningPublicKey);if(t.senderSigningKeyFingerprint!==Te(o)||!F(a.senderSigningKeyFingerprint,R(t.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return{manifest:a,manifestDigest:await tt(i),senderPublicDer:o}}async recoverFrame(e,t,n,i){let a=await Vr(h(e.tenantWrappedShareKey),R(i),n,t.tenantId,t.messageId,_),s=[],o=[],d=new Set;for(let l of e.shares){let u=`${l.kind}:${l.index}`;if(d.has(u))throw new Error("duplicate_inbox_share");d.add(u);let g=await Nr(h(l.ciphertext),a,n,t.messageId,l.kind==="DATA"?"data":"key",l.index,_);(l.kind==="DATA"?s:o).push(g)}if(s.length!==o.length||s.length<2)throw new Error("incomplete_inbox_shares");let c=await this.worker.reconstruct(s,o,{threshold:s.length,total:s.length,messageId:t.messageId,manifestDigest:n});return kr(c)}async decryptText(e,t,n,i,a,s){return Or(await this.decryptContent(e,t,n,i,a,s))}async decryptContent(e,t,n,i,a,s){let o=await _.subtle.importKey("spki",a,"Ed25519",!1,["verify"]);if(!await Sn(n,t,h(e.signature),o,_))throw new Error("inbox_signature_invalid");let d=await _.subtle.importKey("pkcs8",h(s),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await Fr(h(e.wrappedContentKey),d,i,_);return Lr(t,c,i,_)}};import{canonicalInboxManifest as Hr,decodeInboxContentFrame as Wr,decodeInboxFile as Qr,decryptInboxShare as jr,encodeInboxContentFrame as Yr,encodeInboxFile as Xr,encryptInboxShare as En,inboxFileMetadataDigest as xn,sealInboxContent as Jr,unwrapInboxShareKey as Zr,wrapInboxShareKey as ei}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var nt=class extends re{constructor(t){super(t);this.fileApi=t}async sendFile(t){t.signal?.throwIfAborted();let{preparation:n,sender:i}=await this.prepareSender(t),a=await this.fileManifest(t,n,i),s=Hr(a),o=await tt(s),d=Xr(t.file),c;try{c=await Jr(d,o,B)}finally{d.fill(0)}let{contentKey:l,frame:u}=c,g=await this.signFrame(a,u,t.identity.signingPrivateKey,i.signingPublicKey);t.signal?.throwIfAborted();let w=await this.worker.split(Yr(u),{threshold:n.threshold,total:n.total,messageId:n.messageId,manifestDigest:o},t.signal,A=>t.onProgress?.(0,n.total*2,A.stage));t.signal?.throwIfAborted();let D=B.getRandomValues(new Uint8Array(32)),m=[];for(let A=0;A<n.total;A++){let $=n.shareLayers[A];m.push({reference:{kind:"DATA",index:A,shareId:$.dataShareId,layerId:$.id},bytes:await En(w.dataShares[A],D,o,n.messageId,B)}),m.push({reference:{kind:"KEY",index:A,shareId:$.keyShareId,layerId:$.id},bytes:await En(w.keyShares[A],D,o,n.messageId,B)})}let f=await this.wrapRecipientKeys(n,l,o),K=await ei(D,R(t.tenantKeyHex),o,a.tenantId,a.messageId,B);t.signal?.throwIfAborted();let C=await this.fileApi.stageInboxFile(t.conversationId,{messageId:n.messageId,senderDeviceId:i.deviceId,participantRevision:n.participantRevision,expiresAt:t.expiresAt,idempotencyKey:n.messageId,canonicalManifest:Buffer.from(s).toString("base64"),signature:Buffer.from(g).toString("base64"),tenantWrappedShareKey:Buffer.from(K).toString("base64"),recipients:f,shares:m.map(A=>A.reference)},t.signal);if(C.messageId!==n.messageId||C.status!=="PREPARING")throw new Error("invalid_inbox_stage");for(let A=0;A<m.length;A++){t.signal?.throwIfAborted();let $=m[A];await this.fileApi.uploadInboxFileShare(t.conversationId,n.messageId,$.reference.shareId,$.bytes,t.signal),t.onProgress?.(A+1,m.length,"UPLOADING")}t.signal?.throwIfAborted();let q=await this.fileApi.publishInboxFile(t.conversationId,n.messageId,t.signal);if(q.messageId!==n.messageId||q.status!=="AVAILABLE")throw new Error("invalid_inbox_publish");return q}async openFile(t){t.signal?.throwIfAborted();let n=await this.fileApi.openInboxFile(t.conversationId,t.messageId,t.identity.deviceId,t.signal),i,a;try{let{manifest:o,manifestDigest:d,senderPublicDer:c}=await this.verifyOpening(t,n,await xn(B)),l=await this.recoverFileFrame(t,n,o,d);a=await this.decryptContent(n,l,o,d,c,t.identity.encryptionPrivateKey),i=Qr(a),t.signal?.throwIfAborted(),await t.save(i),t.signal?.throwIfAborted()}catch(o){try{await this.fileApi.releaseInboxMessage(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId)}catch{}throw o}finally{a?.fill(0)}let s=await this.ack(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId,t.signal);return t.signal?.throwIfAborted(),{name:i.name,mimeType:i.mimeType,size:i.bytes.length,leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt,acknowledgement:s}}async fileManifest(t,n,i){let a=Date.parse(t.expiresAt);if(!Number.isSafeInteger(a)||a<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:t.identity.tenantId,conversationId:t.conversationId,messageId:n.messageId,senderId:t.identity.memberId,senderDeviceId:i.deviceId,senderSigningKeyFingerprint:R(i.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(s=>({memberId:s.memberId,deviceId:s.deviceId,encryptionKeyFingerprint:R(s.encryptionKeyFingerprint)})),expiresAtEpochMs:a,metadataDigest:await xn(B)}}async recoverFileFrame(t,n,i,a){let s=await Zr(h(n.tenantWrappedShareKey),R(t.tenantKeyHex),a,i.tenantId,i.messageId,B),o=[],d=[],c=new Set;for(let u=0;u<n.shares.length;u++){t.signal?.throwIfAborted();let g=n.shares[u],w=`${g.kind}:${g.index}`;if(c.has(w))throw new Error("duplicate_inbox_share");c.add(w);let D=await this.fileApi.downloadInboxFileShare(t.conversationId,t.messageId,g.shareId,t.identity.deviceId,n.leaseId,t.signal),m=await jr(D,s,a,i.messageId,g.kind==="DATA"?"data":"key",g.index,B);(g.kind==="DATA"?o:d).push(m),t.onProgress?.(u+1,n.shares.length,"DOWNLOADING")}if(o.length!==d.length||o.length<2)throw new Error("incomplete_inbox_shares");t.signal?.throwIfAborted();let l=await this.worker.reconstruct(o,d,{threshold:o.length,total:o.length,messageId:i.messageId,manifestDigest:a},t.signal,u=>t.onProgress?.(n.shares.length,n.shares.length,u.stage));return t.signal?.throwIfAborted(),Wr(l)}};import{createHash as An,webcrypto as ti}from"node:crypto";import{canonicalInboxParentManifest as ni,decodeInboxParentManifest as ri,encodeInboxParentNormalFrame as ii,decodeInboxParentNormalFrame as ai,sealInboxParentNormalBody as si,openInboxParentNormalBody as oi,wrapInboxParentNormalKey as di,unwrapInboxParentNormalKey as ci,signInboxParentNormalFrame as li,verifyInboxParentNormalFrame as Rn,encodeInboxText as pi,decodeInboxText as ui}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var V=ti,De=r=>An("sha256").update(r).digest("hex"),rt=r=>Buffer.from(r).toString("base64"),it=class{constructor(e){this.api=e}pending=new Map;async send(e){let t=this.digestInput(e),n=e.parentId?this.pending.get(e.parentId):void 0;if(n){if(n.inputDigest!==t)throw new Error("inbox_idempotency_conflict");let c=await this.api.publishNormalInboxMessage(e.conversationId,n.submission);return this.pending.delete(e.parentId),c}let i=await this.api.getNormalInboxSendPreparation(e.conversationId),a=this.validatePreparation(e,i),s=this.createManifest(e,i,a),o=await this.createSubmission(e,i,a,s);this.rememberSubmission(s.parentId,t,o);let d=await this.api.publishNormalInboxMessage(e.conversationId,o);return this.pending.delete(s.parentId),d}digestInput(e){return An("sha256").update(JSON.stringify([e.conversationId,e.parentId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.text])).digest("hex")}validatePreparation(e,t){if(t.conversationId!==e.conversationId||t.recipients.length<2||t.recipients.length>50)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||De(h(n.signingPublicKey))!==n.signingKeyFingerprint||De(h(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return n}createManifest(e,t,n){return{mode:"NORMAL",tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:e.parentId??t.parentId,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:R(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,encryptionKeyFingerprint:R(i.encryptionKeyFingerprint)})),protectedUnits:[]}}async createSubmission(e,t,n,i){let a=ni(i),{contentKey:s,frame:o}=await si(pi(e.text),i,V),d=await V.subtle.importKey("pkcs8",h(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),c=await li(i,o,d,V),l=await V.subtle.importKey("spki",h(n.signingPublicKey),"Ed25519",!1,["verify"]);if(!await Rn(i,o,c,l,V))throw new Error("inbox_identity_mismatch");let u=await Promise.all(t.recipients.map(g=>this.wrapRecipientKey(g,s,i)));return{parentId:i.parentId,idempotencyKey:i.parentId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,canonicalManifest:rt(a),frame:rt(ii(o)),signature:rt(c),recipients:u}}async wrapRecipientKey(e,t,n){let i=h(e.encryptionPublicKey);if(De(i)!==e.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await V.subtle.importKey("spki",i,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:e.memberId,deviceId:e.deviceId,deviceVersion:e.deviceVersion,keyFingerprint:e.encryptionKeyFingerprint,wrappedContentKey:rt(await di(t,a,n,V))}}rememberSubmission(e,t,n){if(this.pending.size>=32){let i=this.pending.keys().next().value;i&&this.pending.delete(i)}this.pending.set(e,{inputDigest:t,submission:n})}list(e,t,n){return this.api.listNormalInboxMessages(e,t,n)}async open(e){e.signal?.throwIfAborted();let t=await this.api.openNormalInboxMessage(e.conversationId,e.parentId,e.identity.deviceId,e.signal),n=ri(h(t.canonicalManifest));if(n.mode!=="NORMAL"||n.tenantId!==e.identity.tenantId||n.conversationId!==e.conversationId||n.parentId!==e.parentId||n.senderId!==t.senderMemberId||n.senderDeviceId!==t.senderDeviceId||n.participantRevision!==t.participantRevision)throw new Error("inbox_manifest_mismatch");let i=n.recipients.find(u=>u.memberId===e.identity.memberId&&u.deviceId===e.identity.deviceId);if(!i||!F(i.encryptionKeyFingerprint,R(De(h(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let a=h(t.senderSigningPublicKey);if(!F(n.senderSigningKeyFingerprint,R(De(a))))throw new Error("inbox_sender_key_mismatch");let s=ai(h(t.frame)),o=await V.subtle.importKey("spki",a,"Ed25519",!1,["verify"]);if(!await Rn(n,s,h(t.signature),o,V))throw new Error("inbox_signature_invalid");let d=await V.subtle.importKey("pkcs8",h(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await ci(h(t.wrappedContentKey),d,n,V),l=ui(await oi(s,c,n,V));return e.signal?.throwIfAborted(),{text:l,parentId:t.parentId,sequence:t.sequence}}markRead(e){return this.api.markNormalInboxMessageRead(e.conversationId,e.parentId,e.identity.deviceId)}};import{createHash as Tn,webcrypto as mi}from"node:crypto";import{canonicalInboxParentManifest as gi,decodeInboxParentManifest as hi,decodeInboxManifest as Ii,encodeInboxParentNormalFrame as yi,decodeInboxParentNormalFrame as fi,sealInboxParentNormalBody as Pi,openInboxParentNormalBody as vi,wrapInboxParentNormalKey as bi,unwrapInboxParentNormalKey as wi,signInboxParentNormalFrame as Si,verifyInboxParentNormalFrame as _n,signInboxProtectedParent as Ei,verifyInboxProtectedParent as Cn,inboxProtectedUnitCommitment as xi,encodeInboxText as Ri,decodeInboxText as Ai}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var O=mi,at=r=>Buffer.from(r).toString("base64"),Me=r=>Tn("sha256").update(r).digest("hex"),st=class{constructor(e,t){this.api=e;this.child=t??new re(e)}pending=new Map;child;async send(e){let t=Tn("sha256").update(JSON.stringify([e.conversationId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.segments])).digest("hex"),n=e.parentId?[e.parentId,this.pending.get(e.parentId)]:[...this.pending.entries()].find(([,o])=>o.digest===t),i=n?.[1];if(i){if(i.digest!==t)throw new Error("inbox_idempotency_conflict");try{e.onProgress?.(i.submission.protectedUnits.length,i.submission.protectedUnits.length)}catch{}let o=await this.api.publishInboxParent(e.conversationId,i.submission);return this.pending.delete(n[0]),o}let a=await this.prepare(e);this.pending.size>=32&&this.pending.delete(this.pending.keys().next().value),this.pending.set(a.parentId,{digest:t,submission:a});let s=await this.api.publishInboxParent(e.conversationId,a);return this.pending.delete(a.parentId),s}async prepare(e){if(!e.segments.length||e.segments.length>9)throw new Error("invalid_inbox_parent_segments");let t=e.segments.filter(w=>"protectedText"in w).length;if(t<1||t>4)throw new Error("invalid_inbox_parent_segments");let n=e.segments.length===1&&t===1?"PROTECTED":"MIXED";if(n==="MIXED"&&!e.segments.some(w=>"text"in w))throw new Error("invalid_inbox_parent_segments");let i=await this.api.getNormalInboxSendPreparation(e.conversationId),a=this.validateSender(e,i),s=e.parentId??i.parentId,{protectedUnits:o,manifestUnits:d}=await this.prepareChildren(e,i,a),c=this.parentManifest(e,i,a,s,n,d),{frame:l,signature:u,recipients:g}=await this.signAndWrap(e,i,a,c);return{parentId:s,idempotencyKey:s,senderDeviceId:a.deviceId,mode:n,participantRevision:i.participantRevision,canonicalManifest:at(gi(c)),signature:at(u),frame:l,recipients:g,protectedUnits:o}}async prepareChildren(e,t,n){let i=[],a=[],s=e.segments.filter(o=>"protectedText"in o).length;for(let o=0;o<e.segments.length;o++){let d=e.segments[o];if(!("protectedText"in d))continue;let c=await this.child.prepare({conversationId:e.conversationId,text:d.protectedText,expiresAt:d.expiresAt,identity:e.identity,tenantKeyHex:e.tenantKeyHex}),l=Ii(h(c.submission.canonicalManifest));this.validateChildSnapshot(l,e,t,n);let u=await xi(l,h(c.frame),h(c.submission.signature),O);i.push({position:o,frame:c.frame,child:c.submission}),a.push({unitId:c.submission.messageId,position:o,commitment:u});try{e.onProgress?.(i.length,s)}catch{}}return{protectedUnits:i,manifestUnits:a}}validateChildSnapshot(e,t,n,i){if(e.tenantId!==t.identity.tenantId||e.conversationId!==t.conversationId||e.senderId!==t.identity.memberId||e.senderDeviceId!==i.deviceId||e.participantRevision!==n.participantRevision||e.recipients.length!==n.recipients.length||e.recipients.some(a=>!n.recipients.some(s=>s.memberId===a.memberId&&s.deviceId===a.deviceId&&F(a.encryptionKeyFingerprint,R(s.encryptionKeyFingerprint)))))throw new Error("inbox_child_snapshot_mismatch")}parentManifest(e,t,n,i,a,s){return{mode:a,tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:i,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:R(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(o=>({memberId:o.memberId,deviceId:o.deviceId,encryptionKeyFingerprint:R(o.encryptionKeyFingerprint)})),protectedUnits:s}}async signAndWrap(e,t,n,i){let a=await O.subtle.importKey("pkcs8",h(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),s=await O.subtle.importKey("spki",h(n.signingPublicKey),"Ed25519",!1,["verify"]);if(i.mode==="PROTECTED")return{signature:await this.signProtectedParent(i,a,s),recipients:this.recipientReferences(t)};let{frame:o,signature:d,contentKey:c}=await this.sealMixedParent(e,i,a,s);return{frame:o,signature:d,recipients:await this.wrapRecipients(t,c,i)}}async signProtectedParent(e,t,n){let i=await Ei(e,t,O);if(!await Cn(e,i,n,O))throw new Error("inbox_identity_mismatch");return i}async sealMixedParent(e,t,n,i){let a=e.segments.map((d,c)=>"text"in d?{text:d.text}:{unitId:t.protectedUnits.find(l=>l.position===c).unitId}),s=await Pi(Ri(JSON.stringify(a)),t,O),o=await Si(t,s.frame,n,O);if(!await _n(t,s.frame,o,i,O))throw new Error("inbox_identity_mismatch");return{frame:at(yi(s.frame)),signature:o,contentKey:s.contentKey}}recipientReferences(e){return e.recipients.map(t=>({memberId:t.memberId,deviceId:t.deviceId,deviceVersion:t.deviceVersion,keyFingerprint:t.encryptionKeyFingerprint}))}async wrapRecipients(e,t,n){return Promise.all(e.recipients.map(async i=>{let a=h(i.encryptionPublicKey);if(Me(a)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await O.subtle.importKey("spki",a,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:at(await bi(t,s,n,O))}}))}validateSender(e,t){if(t.conversationId!==e.conversationId||t.recipients.length<2||t.recipients.length>50)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||Me(h(n.signingPublicKey))!==n.signingKeyFingerprint||Me(h(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return n}list(e,t,n){return this.api.listInboxParents(e,t,n)}clearHistory(e,t){return this.api.clearInboxHistory(e,t)}async open(e){let{opened:t,manifest:n,segments:i}=await this.openAndVerify(e);return{parentId:t.parentId,sequence:t.sequence,mode:n.mode,segments:i}}async openAndVerify(e){e.signal?.throwIfAborted();let t=await this.api.openInboxParent(e.conversationId,e.parentId,e.identity.deviceId,e.signal),{manifest:n,senderKey:i}=await this.verifyOpening(e,t),a=n.mode==="PROTECTED"?await this.openProtectedParent(t,n,i):await this.openMixedParent(e,t,n,i);return e.signal?.throwIfAborted(),{opened:t,manifest:n,segments:a}}async verifyOpening(e,t){let n=hi(h(t.canonicalManifest));return this.verifyManifestContext(e,t,n),this.verifyManifestUnits(t,n),this.verifyRecipient(e,n),{manifest:n,senderKey:await this.senderKey(t,n)}}verifyManifestContext(e,t,n){if(n.mode!==t.mode||n.tenantId!==e.identity.tenantId||n.conversationId!==e.conversationId||n.parentId!==e.parentId||n.senderId!==t.senderMemberId||n.senderDeviceId!==t.senderDeviceId||n.participantRevision!==t.participantRevision)throw new Error("inbox_manifest_mismatch")}verifyManifestUnits(e,t){if(t.protectedUnits.length!==e.protectedUnits.length||t.protectedUnits.some((n,i)=>n.unitId!==e.protectedUnits[i].unitId||n.position!==e.protectedUnits[i].position||!F(n.commitment,R(e.protectedUnits[i].commitment))))throw new Error("inbox_manifest_mismatch")}verifyRecipient(e,t){let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||!F(n.encryptionKeyFingerprint,R(Me(h(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch")}async senderKey(e,t){let n=h(e.senderSigningPublicKey);if(Me(n)!==e.senderSigningKeyFingerprint||!F(t.senderSigningKeyFingerprint,R(e.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return O.subtle.importKey("spki",n,"Ed25519",!1,["verify"])}async openProtectedParent(e,t,n){if(e.frame!==null||e.wrappedContentKey!==null||!await Cn(t,h(e.signature),n,O))throw new Error("inbox_signature_invalid");return[{unitId:t.protectedUnits[0].unitId,position:0,status:e.protectedUnits[0].status}]}async openMixedParent(e,t,n,i){if(!t.frame||!t.wrappedContentKey)throw new Error("inbox_missing_normal_body");let a=fi(h(t.frame));if(!await _n(n,a,h(t.signature),i,O))throw new Error("inbox_signature_invalid");let s=await O.subtle.importKey("pkcs8",h(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=await wi(h(t.wrappedContentKey),s,n,O),d=JSON.parse(Ai(await vi(a,o,n,O)));return this.decodeSegments(d,t,n)}decodeSegments(e,t,n){if(!Array.isArray(e))throw new Error("invalid_inbox_parent_body");let i=e.map((a,s)=>{if(!a||typeof a!="object"||Array.isArray(a))throw new Error("invalid_inbox_parent_body");let o=a;if(typeof o.text=="string"&&Object.keys(o).length===1)return{text:o.text};let d=n.protectedUnits.find(c=>c.position===s);if(!d||o.unitId!==d.unitId||Object.keys(o).length!==1)throw new Error("invalid_inbox_parent_body");return{unitId:d.unitId,position:s,status:t.protectedUnits.find(c=>c.unitId===d.unitId).status}});if(n.protectedUnits.some(a=>!i[a.position]||!("unitId"in i[a.position])))throw new Error("invalid_inbox_parent_body");return i}async revealUnit(e){let{manifest:t,segments:n}=await this.openAndVerify(e);if(!n.some(a=>"unitId"in a&&a.unitId===e.unitId))throw new Error("inbox_parent_unit_mismatch");let i=t.protectedUnits.find(a=>a.unitId===e.unitId);return this.child.openCommitted({conversationId:e.conversationId,messageId:e.unitId,identity:e.identity,tenantKeyHex:e.tenantKeyHex,signal:e.signal},i.commitment)}};export{ue as BusinessOrganizationSelectionError,Re as CorePlanMaterialBuilder,$s as DataAssetDefinitionService,L as ElementsApiRequestFailed,se as ElementsClient,ve as GuidedCreateRecoveryError,Pe as GuidedPlanCreator,Se as HttpAutomationRevealApiPort,ce as HttpElementsApiPort,yn as HttpOperatorAuthTransport,Qe as HttpPlanEditPort,Ee as HttpQuickPlanPort,v as InvalidPlanDeclaration,M as InvalidPlanMaterial,Ne as MasterKeyRelayCancellationFailed,Oe as MasterKeyRelayExpired,ke as MasterKeyRelayTimedOut,j as MasterKeyRequired,fe as MemoryGuidedCreateCheckpointStore,Ie as MemoryKeyVault,ye as MemoryStatePort,nt as NodeInboxFile,it as NodeInboxNormal,st as NodeInboxParent,re as NodeInboxText,S as OAuthProtocolError,Pn as OperatorAuthClient,_e as OperatorAuthError,Ce as OperatorReauthenticationRequired,vn as OperatorSessionController,pt as PLAN_CREATION_SERVER_STAGES,Xs as PassphraseMasterKeySource,ro as PlanAssetDeclaration,te as PlanRequestFailed,Ae as QuickPlanCreator,Xe as QuickPlanEditor,Js as RawMasterKeySource,z as RelayMasterKeySource,dt as StaticMasterKeyResolver,Ze as SystemOAuthClock,Je as WebOAuthCrypto,to as computePassphraseVerifier,Ke as createMasterKeyResolver,xr as createNodeAutomationRevealClient,Cs as createNodeElementsClient,Ts as createNodeQuickPlanCreator,Ds as createNodeQuickPlanEditor,_r as decodeAssetContainer,Zs as deriveMasterKey,eo as generateHexSeed,he as masterKeyRefFor,X as masterKeyRefKey,Rt as oauthErrorCode,cr as selectBusinessOrganization,vt as unwrapDekWithMasterKey,J as validatePlanCreationInput,ae as validatePlanCreationMaterial};
|
|
1
|
+
import{createNodeSharedConfigurationSdk as _t,decodeAssetContainer as Cr}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Dn,generateRSAOAEPKeyPair as kn}from"@safetech/inheriti-core-sdk/crypto";var ke=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},Oe=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"}},z=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 kn();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(n),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(m=>new Promise(P=>setTimeout(P,m))),c=!0,l=!1,u,g=()=>u??=(async()=>{let m=new AbortController,P,K=new Promise((C,G)=>{P=setTimeout(()=>{m.abort(),G(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(s.sessionId,m.signal),K])}finally{clearTimeout(P)}})(),w,D=new Promise((m,P)=>{w=()=>{c&&g().catch(()=>{}),P(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",w,{once:!0})});D.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),l=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let m=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),D]);if(m.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(m.status==="DELIVERED"&&m.sealedMasterKey){let P=(await Dn(m.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(P))throw new Error("invalid_master_key_material");return P}if(m.status==="EXPIRED")throw new Oe(s.sessionId);await On(d,a,e)}throw new ke(s.sessionId)}catch(m){if(c&&(!l||e?.aborted))try{await g()}catch(P){if(e?.aborted)throw new Ne(P)}throw m}finally{w&&e?.removeEventListener("abort",w)}}};async function On(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 s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),r(e).then(n,i).finally(()=>t.removeEventListener("abort",s))})}function Ke(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||ot(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(Nn(e,r.applicationId)){let i=await r.source?.resolve();return i||ot(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return ot(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function Nn(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function ot(r,e,t,n,i){if((await e()).relayAvailable)return new z({...r.relay,api:Kn(r.api,t)}).resolve(n,i)}function Kn(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 J(r){return`${r.system}:${r.contextId}`}function he(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var j=class extends Error{constructor(t){super(`master_key_required:${J(t)}`);this.ref=t;this.name="MasterKeyRequired"}},dt=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(J(e),t),this}async resolve(e){return this.sources.get(J(e))?.resolve()}};var Ie=class{keys=new Map;async store(e,t){let n=J(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(J(e))?.slice()}async remove(e){let t=J(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var ye=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 Ue=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},y=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var Le=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var qe=["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"]},pt=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],b=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},k=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function se(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new k("plan_material_field_unknown");if(ct(r.dataShards,"data_shards_invalid"),ct(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&ct(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new k("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new k("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new k("material_operation_invalid")}function ct(r,e){if(!Array.isArray(r))throw new k(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new k(e);if(t.data!==void 0&&typeof t.data!="string")throw new k(e)}}function Z(r){if(ie(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!qn(r.idempotencyKey))throw new b("idempotency_key_invalid");if(!r.name?.trim())throw new b("plan_name_required");if(!r.assets.length)throw new b("assets_required");let e=new Set;for(let t of r.assets){if(ie(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 b("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!qe.includes(t.type))throw new b("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new b("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 b("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new b("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new b("asset_field_names_invalid");if(Un(t.matchOrigins),!t.isBinary){let s=lt[t.type];if(!s||i.some(a=>!s.includes(a)))throw new b("asset_field_name_not_canonical")}}if(!r.participants.length)throw new b("participants_required");for(let t of r.participants){if(ie(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Mt(t.routingEmail))throw new b("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new b("participant_relationships_invalid")}Ln(r)}function Un(r){if(r===void 0)return;if(!r.length)throw new b("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new b("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new b("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof b?n:new b("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new b("asset_match_origins_duplicated")}function Ln(r){let e=r.policy;if(e&&ie(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new b("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){ie(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new b("authentication_mode_invalid")}if(e.moderation){ie(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new b("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new b("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new b("approval_mode_invalid")}let t=e.dms;if(!t)return;ie(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!Mt(t.subjectEmail))throw new b("dms_subject_invalid");if(!r.participants.some(s=>Tt(s.routingEmail)===Tt(t.subjectEmail)))throw new b("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 b("dms_countdown_invalid")}function qn(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 Mt(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Tt(r){return r.normalize("NFC").trim().toLowerCase()}function ie(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new b(t)}var fe=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)}},Pe=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),Z(e),Ge(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,s={}){Z(t);let a=await this.checkpoints.load(e);if(!a)throw new be("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await Dt(t))throw new be("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(s.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;Ge(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:s.signal});Ge(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});Ge(s.signal),se(c);let l=await this.api.supplyPlanCreationMaterial(e,c);return s.onProgress?.(l.stage),l.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,l),l}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 Dt(e),serverStage:t.stage})}},be=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Dt(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 Ge(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function kt(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new Ue(n.stage);return r.authorizeRevealAction(e,t)}function Gn(r){let e=r?.status;return e===400||e===401||e===403}async function Ot(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!Gn(s))throw s}return r.releaseRevealMaterial(e,t)}function Fn(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"?zn(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":Vn.has(r.stage)?"ENDED":"CONTINUING"}var Vn=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function zn(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 ut=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},T=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Lt(r,e,t={}){if(t.signal?.aborted)throw E();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"}):Nt(i.id);if(t.signal?.aborted||(await r.prepareReveal(e,t.signal,async d=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(d)}),t.signal?.aborted))throw E();let s=t.idempotencyKey??crypto.randomUUID(),a;try{a=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:s})}catch(d){if(d?.code!=="merge_process_already_active")throw d;let c=await r.getActivePlanReveal(e);throw!c||c.planId!==e||c.mode!==(t.mode??"DIRECT")?d:Nt(c.id)}let o;try{if(t.signal?.aborted)throw E();let d=await $n(r,a,t);if(t.signal?.aborted||(ee(t,"RELEASING_MATERIAL",d),t.signal?.aborted))throw E();let c=await r.releaseRevealMaterial(d.id,d.materialVersion??"1");if(t.signal?.aborted||(d.mode==="GOVERNED"&&await r.markRevealSharesCollected(d.id),t.signal?.aborted))throw E();let l;try{l=await jn(r,d,Xn(c),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(ee(t,"RECONSTRUCTING",d),t.signal?.aborted))throw E();try{o=await r.reconstructPlanMaterial(l)}catch(g){throw t.signal?.aborted?E():(await r.reportRevealReconstruction(d.id,{status:"FAILED",errorCode:Qn(g)}),g)}if(t.signal?.aborted)throw E();let u=await r.reportRevealReconstruction(d.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(ee(t,"OPEN",u),t.signal?.aborted))throw E();return new gt(r,u,n,o,t.signal)}catch(d){throw o?.fill(0),await qt(r,a.id,t.signal?.aborted?"CANCELED":"ERROR"),d}}function Nt(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var Bn=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function $n(r,e,t){let n=await Y(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw E();if(t.onSession?.(n),t.onProgress?.({phase:Fn(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(Bn.has(n.stage))throw new mt(n.stage);await It(t.pollIntervalMs??1500,t.signal),n=await Y(()=>r.getReveal(e.id,t.signal),t.signal)}}var mt=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function ee(r,e,t){r.onProgress?.({phase:e,session:t})}function It(r,e){return e?.aborted?Promise.reject(E()):new Promise((t,n)=>{let i=setTimeout(a,Math.max(0,r)),s=()=>{clearTimeout(i),n(E())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var gt=class{constructor(e,t,n,i,s){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let a=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(a,2147483647)),this.abortListener=s?()=>{this.close("CANCELED").catch(()=>{})}:void 0,s&&this.abortListener&&s.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new ut;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 T("asset_selector_invalid");if(!this.client.assetDecoder)throw new T("asset_decoder_required");let n=e.map(({selector:s,options:a={}})=>{let o=Hn(s),d=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!d)throw new T("asset_not_found");if(d.isBinary)throw new T("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new T("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:d,field:o.field,options:a}}),i=[];try{for(let a of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:a.options.idempotencyKey??crypto.randomUUID(),assetId:a.asset.id,fieldName:a.field,action:a.options.action??"VIEW_FIELD",...a.options.destination===void 0?{}:{destination:a.options.destination},...a.options.origin===void 0?{}:{origin:a.options.origin}}));let s=n.map(a=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===a.asset.id||d.id===a.assetCode);if(!o)throw new T("asset_value_invalid");return{selector:a.selector,value:Wn(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",Kt(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new T("asset_selector_invalid");if(!this.client.assetDecoder)throw new T("asset_decoder_required");let n=this.plan.assets.find(a=>a.code===e||a.id===e);if(!n)throw new T("asset_not_found");if(!n.isBinary)throw new T("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),s;try{let a=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!a||!(a.data instanceof Uint8Array))throw new T("asset_value_invalid");s=a.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:s})}catch(a){throw await this.reportAction(i.id,"FAILED",Kt(a)),a}finally{s?.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=qt(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 Hn(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new T("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new T("asset_selector_invalid");return{asset:r.asset,field:r.field}}function Wn(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new T("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new T("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?lt[t]:void 0)?.includes(e))return"";throw new T("asset_value_invalid")}return n[e]}function Kt(r){if(r instanceof T)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 Qn(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function jn(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await Y(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new Fe;let c=await Y(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(Ut(c,i.id,e.planId),!c.shares.includes(i.data))throw new W;ee(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:l}=await Y(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw E();if(!l?.trim())throw new W;if(await r.claimRevealCustodianShare(e.id,c.id,l),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw E();return{...t,shares:t.shares.filter(u=>u!==i).concat(c.shares.map((u,g)=>({id:`${c.id}:${g}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:u})))}}if(d!=="SK_MOBILE")throw new W;if(n.signal?.aborted)throw E();return await r.distributeRevealCustodianShare(e.id),ee(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(d),ee(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await It(n.pollIntervalMs??1500,n.signal),s=await Y(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new Fe;if(!s.shareId||!s.deviceId)throw new W;ee(n,"CONNECTING_SAFEKEY_PRO",e);let d=await Y(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw E();if(Ut(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new W;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw E();return{...t,shares:t.shares.concat(d.shares.map((c,l)=>({id:`${d.id}:${l}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:c})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new W;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(a),ee(n,"WAITING_FOR_CUSTODIAN",a),n.signal?.aborted)throw E();await r.requestRevealCustodianRelease(e.id);let o=await Yn(r,e.id,n);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,c)=>({id:`${o.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function Ut(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 W}async function Y(r,e){if(e?.aborted)throw E();if(!e)return r();let t,n=new Promise((i,s)=>{t=()=>s(E()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw E();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function Yn(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await Y(()=>r.getRevealCustodianShare(e,t.signal),t.signal);if(i&&i.status!=="PENDING"){let s=i;if(s.shares?.length)return s;throw new W}if(Date.now()>=n)throw new ht;await It(t.pollIntervalMs??1500,t.signal)}}var W=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Fe=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},ht=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Xn(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function qt(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(a){if(!Jn(a))throw a}return}let n=new AbortController,i,s=new Promise((a,o)=>{i=setTimeout(()=>{n.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([r.closeReveal(e,t,n.signal),s]);if(!["CANCELED","CLOSED","EXPIRED","FAILED","DENIED","PARTICIPANT_REVOKED"].includes(a.stage))throw new Error("reveal_cancellation_unconfirmed")}catch(a){if(a?.code!=="reveal_expired")throw Object.assign(new Error("reveal_cancellation_failed",{cause:a}),{code:"reveal_cancellation_failed"})}finally{clearTimeout(i)}}function Jn(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function E(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var ae=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 Ie,this.state=t.state??new ye,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??tr(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 y;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new y;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new y;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new y;return this.api.listMemberLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new y;return Z(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new y;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new y;return se(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new y;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new fe){if(this.requireApplication(),!this.api)throw new y;return new Pe(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 j({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 er(i);let s=await this.masterKeys?.resolve(e,t,n);if(!s)throw new j(e);return await this.keyVault.store(e,Zn(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new y;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 y;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new Le;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 j({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=he(e);if(!i)throw new j({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new y;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new y;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new y;return this.api.startReveal(e,t)}getActivePlanReveal(e){if(!this.api)throw new y;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new y;return this.api.getReveal(e,t)}openReveal(e,t){return Lt(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let s=await n(i);return await i.close("COMPLETED"),s}catch(s){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new y;return Ot(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new y;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new y;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new y;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new y;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new y;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new y;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new y;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new y;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new y;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new y;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new y;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new y;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new y;return kt(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new y;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new y;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new y;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new y;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new y;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new y;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 s=n.validatorShares.map(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),a=i.dataShards.map(c=>Object.assign({},c,{shareType:"DATA_SHARD"})),o=i.backupShards.map(c=>Object.assign({},c,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(c=>Object.assign({},c,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||n.dek,shares:s.concat(a,o,d),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 y;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 yt;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new j({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},yt=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Zn(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 er(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function tr(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 Ke({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return Ke({...e,organizationId:r.organizationId})}var nr=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],rr=["DIRECT","GOVERNED"],Ft=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],ir=["ACTIVE","REVOKED"],sr=["SK_MOBILE"],ar=["ACTIVE","INACTIVE"],or=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Vt(r){let e=M(r);return{items:L(e.items).map($t),nextCursor:e.nextCursor===null?null:I(e.nextCursor,"nextCursor")}}function zt(r){let e=M(r);return{total:B(e.total,"total"),items:L(e.items).map(t=>{let n=M(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:I(n.id,"log.id"),planId:I(n.planId,"log.planId"),tenantId:I(n.tenantId,"log.tenantId"),event:I(n.event,"log.event"),occurredOn:I(n.occurredOn,"log.occurredOn"),status:X(n.status),title:I(n.title,"log.title"),details:L(n.details).map(i=>{let s=M(i);return{label:I(s.label,"log.detail.label"),value:I(s.value,"log.detail.value")}})}})}}function Bt(r){let e=M(r);return{total:B(e.total,"total"),items:L(e.items).map(t=>{let n=M(t);if("eventData"in n)throw new Error("invalid_elements_response");let i=I(n.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:I(n.id,"log.id"),memberId:I(n.memberId,"log.memberId"),source:i,event:I(n.event,"log.event"),occurredOn:I(n.occurredOn,"log.occurredOn"),status:X(n.status)}})}}function Ve(r){let e=M(r),t=$t(e),n=M(e.source),i=I(n.kind,"source.kind");return{...t,assets:L(e.assets).map(s=>{let a=M(s);return{id:I(a.id,"asset.id"),code:X(a.code),type:U(I(a.type,"asset.type"),qe),name:I(a.name,"asset.name"),isBinary:cr(a.isBinary,"asset.isBinary"),fieldNames:L(a.fieldNames).map(o=>I(o,"asset.fieldNames")),fileName:X(a.fileName),mimeType:X(a.mimeType),size:a.size===void 0||a.size===null?void 0:B(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:L(a.matchOrigins).map(o=>I(o,"asset.matchOrigins"))}}),participants:L(e.participants).map(s=>{let a=M(s);return{id:I(a.id,"participant.id"),displayName:I(a.displayName,"participant.displayName"),relationships:L(a.relationships).map(o=>U(I(o,"relationship"),Ft)),lifecycle:U(I(a.lifecycle,"participant.lifecycle"),ir)}}),revealPolicy:(()=>{let s=M(e.revealPolicy);return{masterKeyRelease:U(I(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:U(I(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=M(e.dms);return{subjectEmail:I(s.subjectEmail,"dms.subjectEmail"),countdownDays:B(s.countdownDays,"dms.countdownDays"),countdownHours:B(s.countdownHours,"dms.countdownHours"),countdownMinutes:B(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:U(I(n.system,"source.system"),["INHERITI_BUSINESS"]),status:U(I(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function ve(r){let e=M(r);return{operationId:I(e.operationId,"operationId"),stage:U(I(e.stage,"stage"),pt),outcome:U(I(e.outcome,"outcome"),or),planId:X(e.planId),lastErrorCode:X(e.lastErrorCode),participants:e.participants===void 0?void 0:L(e.participants).map(t=>{let n=M(t);return{clientParticipantRef:I(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:I(n.planParticipantId,"planParticipantId"),relationships:L(n.relationships).map(i=>dr(I(i,"relationship"),Ft))}})}}function $t(r){let e=M(r),t=M(e.assetSummary),n=M(e.governance),i=M(e.participantSummary);return{id:I(e.id,"id"),name:I(e.name,"name"),description:X(e.description),status:U(I(e.status,"status"),nr),createdAt:I(e.createdAt,"createdAt"),configuredAt:X(e.configuredAt),assetSummary:{count:B(t.count,"assetSummary.count"),types:L(t.types).map(s=>U(I(s,"assetType"),qe)),names:Gt(t.names).map(s=>I(s,"assetSummary.names"))},governance:{mode:U(I(n.mode,"governance.mode"),rr),minimumApprovals:B(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:B(i.owners,"owners"),mergers:B(i.mergers,"mergers"),moderators:B(i.moderators,"moderators")},authentication:Gt(e.authentication).map(s=>{let a=M(s);return{id:U(I(a.id,"authentication.id"),sr),status:U(I(a.status,"authentication.status"),ar)}})}}function U(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function dr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function M(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Gt(r){return r==null?[]:L(r)}function L(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function I(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function X(r){return r==null?void 0:I(r,"optional")}function B(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function cr(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var ue=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function Ht(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 lr(r,e){if(!e){if(r.length===0)throw new ue("organization_required");if(r.length>1)throw new ue("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new ue("organization_access_denied");return e}function pr(r){let e=v(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:f(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:f(e.participantRevision,1),createdAt:N(e.createdAt),...Wt(e)}}function Wt(r){if(r.recipientStatuses===void 0)return{};if(!Array.isArray(r.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:r.recipientStatuses.map(e=>{let t=v(e);if(t.secrets!==void 0&&!Array.isArray(t.secrets))throw new Error("invalid_inbox_response");if(t.read!==void 0&&typeof t.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:N(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=v(n);if(i.status!=="UNREAD"&&i.status!=="LEASED"&&i.status!=="CONSUMED"&&i.status!=="EXPIRED"&&i.status!=="REVOKED"&&i.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:f(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:N(i.revealedAt)}:{}}})}:{}}})}}function Qt(r){let e=v(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(pr),total:f(e.total,0),limit:f(e.limit,1),offset:f(e.offset,0),unreadCount:f(e.unreadCount,0),readThroughSequence:f(e.readThroughSequence,0)}}function jt(r){let e=v(r);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:f(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:f(e.participantRevision,1),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:f(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=v(t);return{unitId:p(n.unitId),position:f(n.position,0),commitment:p(n.commitment),status:p(n.status)}})}}function ft(r){let e=v(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:p(e.parentId),sequence:f(e.sequence,1),status:e.status}}function Yt(r){let e=v(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),parentId:p(e.parentId),participantRevision:f(e.participantRevision,1),recipients:e.recipients.map(Pt)}}function Xt(r){let e=v(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=v(t);return{parentId:p(n.parentId),sequence:f(n.sequence,1),senderMemberId:p(n.senderMemberId),senderDeviceId:p(n.senderDeviceId),participantRevision:f(n.participantRevision,1),createdAt:N(n.createdAt),...Wt(n)}}),total:f(e.total,0),limit:f(e.limit,1),offset:f(e.offset,0),unreadCount:f(e.unreadCount,0),readThroughSequence:f(e.readThroughSequence,0)}}function Jt(r){return{readThroughSequence:f(v(r).readThroughSequence,0)}}function Zt(r){return{clearedThroughSequence:f(v(r).clearedThroughSequence,0)}}function en(r){let e=v(r);return{parentId:p(e.parentId),sequence:f(e.sequence,1),senderMemberId:p(e.senderMemberId),senderDeviceId:p(e.senderDeviceId),participantRevision:f(e.participantRevision,1),canonicalManifest:p(e.canonicalManifest),frame:p(e.frame),signature:p(e.signature),wrappedContentKey:p(e.wrappedContentKey),senderSigningPublicKey:p(e.senderSigningPublicKey)}}function v(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function p(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function N(r){let e=p(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function f(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Pt(r){let e=v(r);return{memberId:p(e.memberId),deviceId:p(e.deviceId),deviceVersion:f(e.deviceVersion,1),encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint)}}function me(r){let e=v(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:p(e.id),tenantId:p(e.tenantId),memberId:p(e.memberId),version:e.version,encryptionPublicKey:p(e.encryptionPublicKey),encryptionKeyFingerprint:p(e.encryptionKeyFingerprint),signingPublicKey:p(e.signingPublicKey),signingKeyFingerprint:p(e.signingKeyFingerprint),status:e.status,createdAt:N(e.createdAt),updatedAt:N(e.updatedAt)}}function ze(r){let e=v(r);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let t={id:p(e.id),tenantId:p(e.tenantId),creatorMemberId:p(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(p),participantRevision:e.participantRevision,status:e.status,createdAt:N(e.createdAt),updatedAt:N(e.updatedAt)};if(e.unreadCount!==void 0&&(t.unreadCount=e.unreadCount),e.latestMessage===null&&(t.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let n=v(e.latestMessage);if(n.contentKind!=="TEXT"&&n.contentKind!=="FILE"&&n.contentKind!=="NORMAL"&&n.contentKind!=="MIXED"&&n.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");t.latestMessage={contentKind:n.contentKind,senderMemberId:p(n.senderMemberId),createdAt:N(n.createdAt)}}return t}function tn(r){let e=v(r);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(ze),total:e.total,limit:e.limit,offset:e.offset}}function nn(r){let e=v(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=Pt(t);return{memberId:n.memberId,name:p(v(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:f(e.limit,1),offset:f(e.offset,0),nextOffset:e.nextOffset===null?null:f(e.nextOffset,0)}}function rn(r){let e=v(r);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=v(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:p(n.memberId),name:p(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:p(v(n.profilePicture).url)}}}}),limit:f(e.limit,1),offset:f(e.offset,0),nextOffset:e.nextOffset===null?null:f(e.nextOffset,0)}}function sn(r){let e=v(r);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:p(e.conversationId),messageId:p(e.messageId),participantRevision:f(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Pt),shareLayers:e.shareLayers.map(t=>{let n=v(t),i=p(n.id),s=p(n.dataShareId),a=p(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:p(n.contractAddress),dataShareId:s,keyShareId:a};if(n.type==="INHERITI_VAULT"||n.type==="GOOGLE_DRIVE"||n.type==="DROPBOX"||n.type==="ONEDRIVE")return{id:i,type:n.type,dataShareId:s,keyShareId:a};throw new Error("invalid_inbox_response")})}}function Be(r){let e=v(r);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:p(e.messageId),status:e.status}}function an(r){let e=v(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=v(t);if(n.status!=="PREPARING"&&n.status!=="AVAILABLE"&&n.status!=="FAILED"&&n.status!=="DELETING")throw new Error("invalid_inbox_response");if(n.contentKind!==void 0&&n.contentKind!=="TEXT"&&n.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(n.recipientStatus!==void 0&&n.recipientStatus!=="UNREAD"&&n.recipientStatus!=="LEASED"&&n.recipientStatus!=="CONSUMED"&&n.recipientStatus!=="EXPIRED"&&n.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(n.recipientStatuses!==void 0&&!Array.isArray(n.recipientStatuses))throw new Error("invalid_inbox_response");let i={id:p(n.id),status:n.status,senderMemberId:p(n.senderMemberId),senderDeviceId:p(n.senderDeviceId),createdAt:N(n.createdAt),updatedAt:N(n.updatedAt),expiresAt:N(n.expiresAt)};return n.contentKind&&(i.contentKind=n.contentKind),n.recipientStatus&&(i.recipientStatus=n.recipientStatus),Array.isArray(n.recipientStatuses)&&(i.recipientStatuses=n.recipientStatuses.map(s=>{let a=v(s);if(a.status!=="UNREAD"&&a.status!=="LEASED"&&a.status!=="CONSUMED"&&a.status!=="EXPIRED"&&a.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:p(a.memberId),status:a.status,...a.consumedAt!==void 0?{consumedAt:a.consumedAt===null?null:N(a.consumedAt)}:{}}})),i}),total:f(e.total,0),limit:f(e.limit,1),offset:f(e.offset,0)}}function on(r){let e=v(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:N(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:f(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let n=v(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:f(n.index,0),shareId:p(n.shareId),layerId:p(n.layerId),ciphertext:p(n.ciphertext)}})}}function dn(r){let e=v(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:p(e.leaseId),leaseExpiresAt:N(e.leaseExpiresAt),senderSigningPublicKey:p(e.senderSigningPublicKey),senderSigningKeyFingerprint:p(e.senderSigningKeyFingerprint),senderDeviceVersion:f(e.senderDeviceVersion,1),canonicalManifest:p(e.canonicalManifest),signature:p(e.signature),tenantWrappedShareKey:p(e.tenantWrappedShareKey),wrappedContentKey:p(e.wrappedContentKey),shares:e.shares.map(t=>{let n=v(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:f(n.index,0),shareId:p(n.shareId),layerId:p(n.layerId)}})}}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 q=class extends Error{constructor(t,n,i,s){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ce=class{constructor(e,t,n,i,s){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=s?Object.freeze({...s}):void 0}business;async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:me(t)}async getMemberInboxDevice(e,t){let n=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t);return n===null?null:me(n)}async registerInboxDevice(e){return me(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return me(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return me(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return ze(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return ze(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:t.action,memberId:t.memberId,expectedRevision:t.expectedRevision}))}async listInboxConversations(e={},t){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return tn(await this.request(`v1/inbox/conversations${i}`,"GET",void 0,void 0,void 0,t))}async listInboxParticipants(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return nn(await this.request(`v1/inbox/participants${i}`,"GET",void 0,void 0,void 0,t))}async listInboxMembers(e={},t){let n=new URLSearchParams;e.q!==void 0&&n.set("q",e.q),e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset));let i=n.size?`?${n}`:"";return rn(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return sn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return Yt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,t))}async publishInboxMessage(e,t){let n={messageId:t.messageId,senderDeviceId:t.senderDeviceId,participantRevision:t.participantRevision,expiresAt:t.expiresAt,idempotencyKey:t.idempotencyKey,canonicalManifest:t.canonicalManifest,signature:t.signature,tenantWrappedShareKey:t.tenantWrappedShareKey,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.keyFingerprint,wrappedContentKey:i.wrappedContentKey})),shares:t.shares.map(i=>({kind:i.kind,index:i.index,shareId:i.shareId,layerId:i.layerId,ciphertext:i.ciphertext}))};return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return ft(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return ft(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",t))}async listInboxParents(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return Qt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxParent(e,t,n,i){let s=new URLSearchParams({deviceId:n});return jt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async clearInboxHistory(e,t){return Zt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,t))}async listNormalInboxMessages(e,t={},n){let i=new URLSearchParams;t.limit!==void 0&&i.set("limit",String(t.limit)),t.offset!==void 0&&i.set("offset",String(t.offset));let s=i.size?`?${i}`:"";return Xt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,n))}async openNormalInboxMessage(e,t,n,i){let s=new URLSearchParams({deviceId:n});return en(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}?${s}`,"GET",void 0,void 0,void 0,i))}async markNormalInboxMessageRead(e,t,n){return Jt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",t,void 0,void 0,n))}async uploadInboxFileShare(e,t,n,i,s){if(i.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let a=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}`,o=await this.requestBinary(a,"PUT",i,s),d=await $e(o,s);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new q(o.status,oe(d),de(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return Be(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/publish`,"POST",void 0,void 0,void 0,n))}async openInboxFile(e,t,n,i){return dn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open/file`,"POST",{deviceId:n},void 0,void 0,i))}async downloadInboxFileShare(e,t,n,i,s,a){let o=new URLSearchParams({deviceId:i,leaseId:s}),d=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/shares/${encodeURIComponent(n)}?${o}`,c=await this.requestBinary(d,"GET",void 0,a);if(!c.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let l=Number(c.headers.get("content-length"));if(Number.isFinite(l)&&l>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!c.body)throw new Error("invalid_inbox_share_response");let u=c.body.getReader(),g=[],w=0;try{for(;;){a?.throwIfAborted();let P=await u.read();if(P.done)break;if(w+=P.value.length,w>14*1024*1024)throw new Error("invalid_inbox_share_size");g.push(P.value)}}catch(P){throw await u.cancel().catch(()=>{}),P}let D=new Uint8Array(w),m=0;for(let P of g)D.set(P,m),m+=P.length;return D}async listInboxMessages(e,t={},n){let i=new URLSearchParams;t.status&&i.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:t.status}])),t.limit!==void 0&&i.set("filter[limit]",String(t.limit)),t.offset!==void 0&&i.set("filter[skip]",String(t.offset));let s=i.size?`?${i}`:"";return an(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return on(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/open`,"POST",{deviceId:n}))}async ackInboxMessage(e,t,n,i,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/ack`,"POST",{deviceId:n,leaseId:i},void 0,void 0,s)}async releaseInboxMessage(e,t,n,i){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/release`,"POST",{deviceId:n,leaseId:i})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(Ht)}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 Vt(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Ve(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 zt(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listMemberLogs(e,t={}){let n=new URLSearchParams;t.source&&n.set("source",t.source),t.from&&n.set("from",t.from),t.to&&n.set("to",t.to),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 Bt(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){Z(e);let{idempotencyKey:t,...n}=e;return ve(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return ve(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return se(t),ve(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return ve(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,...s}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,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,s,a){this.requireBusinessSelection(e),a?.throwIfAborted();let o=await this.getBearerToken();a?.throwIfAborted();let d=new Headers({"x-elements-environment":this.environment});o&&d.set("authorization",`Bearer ${o}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&d.set("x-organization-id",this.business.organizationId),i?.requestId&&d.set("x-elements-step-up-request",i.requestId);for(let[w,D]of Object.entries(s??{}))d.set(w,D);n&&d.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l={method:t,headers:d,body:n?JSON.stringify(n):void 0};a&&(l.signal=a);let u=await this.transport(new URL(e,c),l);a?.throwIfAborted();let g=await $e(u,a);if(a?.throwIfAborted(),!u.ok)throw new q(u.status,oe(g),de(g),u.headers.get("x-request-id")??void 0);if(!g.ok||g.result===void 0)throw new q(u.status,oe(g),de(g),u.headers.get("x-request-id")??void 0);return g.result}async requestBinary(e,t,n,i){this.requireBusinessSelection(e),i?.throwIfAborted();let s=await this.getBearerToken();i?.throwIfAborted();let a=new Headers({"x-elements-environment":this.environment});s&&a.set("authorization",`Bearer ${s}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId),n&&a.set("content-type","application/octet-stream");let o=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,o),{method:t,headers:a,body:n?Buffer.from(n):void 0,signal:i});if(i?.throwIfAborted(),!d.ok){let c=await $e(d,i);throw new q(d.status,oe(c),de(c),d.headers.get("x-request-id")??void 0)}return d}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 s=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,a=await this.transport(new URL(e,s),{method:"POST",headers:i,body:t?JSON.stringify(t):void 0}),o=await $e(a);if(!a.ok||!o.ok)throw new q(a.status,oe(o),de(o),a.headers.get("x-request-id")??void 0)}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new q(400,"organization_selection_required")}};async function $e(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{createNodeSsdpV2Processor as Pr}from"@safetech/inheriti-core-sdk/node";async function bt(r,e){if(!e)throw new Error("master_key_required");let t=ur(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=mr(r),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,a);return gr(new Uint8Array(o))}function ur(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 mr(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 gr(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var we=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await cn("plan_key_unwrap_failed",()=>bt(e.planKey,t)),i=await crypto.subtle.importKey("raw",vt(n),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await cn("plan_share_decryption_failed",()=>fr(o.data,i));yr(o.shareType)?a.push(d):s.push(d)}try{return await this.processor().reconstruct(s,{planId:e.planId,threshold:e.mergeThreshold,keyShares:a}).result}catch(o){throw new He("plan_share_reconstruction_failed",Ir(o))}}},He=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},hr=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 Ir(r){let e=r instanceof Error?r.message:void 0;if(e)return hr.has(e)?e:void 0}async function cn(r,e){try{return await e()}catch{throw new He(r)}}function yr(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function fr(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=vt(r.slice(0,t)),i=vt(r.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(s)}function vt(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 le=class extends we{constructor(e){super(()=>Pr(e))}};var Se=class{constructor(e,t,n){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=n}firstRelayStates=new Map;async startReveal(e,t){return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey},!1),this.request(`automation/reveals/by-key/${encodeURIComponent(t.idempotencyKey)}?planId=${encodeURIComponent(e)}`,"GET")}getReveal(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}async getPlan(e){return Ve(await this.request(`automation/reveals/plans/${encodeURIComponent(e)}`,"GET"))}planKeyReference(e){return this.request(`automation/reveals/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}releaseRevealMaterial(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/shares-collected`,"POST",void 0,!1)}distributeRevealCustodianShare(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/distribute`,"POST",void 0,!1)}requestRevealCustodianRelease(e){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/release`,"POST",void 0,!1)}getRevealCustodianAccess(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,!0,void 0,t)}getRevealCustodianShare(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,!0,void 0,t)}reportRevealReconstruction(e,t){return this.request(`automation/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",{status:t.status})}closeReveal(e,t,n){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,n)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...s}=n;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,n){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:n},!1);try{let i=await this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET");if(!i.expiresAt)throw new Error("master_key_relay_expiry_missing");return this.firstRelayStates.set(e,i),{sessionId:e,expiresAt:i.expiresAt}}catch(i){throw await this.cancelMasterKeyRelaySession(e).catch(()=>{}),i}}readMasterKeyRelaySession(e,t){t?.throwIfAborted();let n=this.firstRelayStates.get(e);return n?(this.firstRelayStates.delete(e),Promise.resolve(n)):this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,!0,void 0,t)}cancelMasterKeyRelaySession(e,t){return this.firstRelayStates.delete(e),this.request(`automation/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,!1,void 0,t)}async request(e,t,n,i=!0,s,a){a?.throwIfAborted();let o=await this.getAutomationBearerToken();if(a?.throwIfAborted(),!o)throw new Error("automation_bearer_token_required");let d=new Headers({authorization:`Bearer ${o}`,...s});n!==void 0&&d.set("content-type","application/json");let c=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:n===void 0?void 0:JSON.stringify(n),signal:a});a?.throwIfAborted();let l;try{l=await c.json()}catch{a?.throwIfAborted()}if(!c.ok||l&&l.ok===!1||i&&l?.result===void 0)throw new q(c.status,l&&oe(l),l&&de(l));return l?.result}};var x={invalidDeclaration:"plan_declaration_invalid",invalidShares:"plan_share_count_invalid",storageChanged:"plan_storage_context_changed",invalidMasterKeyContext:"invalid_master_key_context",reauthenticationRequired:"operator_reauthentication_required",relayFailed:"master_key_relay_failed",reconciliationRequired:"reconciliation_required"};var te=class extends Error{constructor(t,n){super(n??`plan_request_failed_${t}`);this.status=t;this.code=n}},Ee=class{constructor(e,t,n,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i}createContext(e){return this.request(e,"integrations/v1/plans/create-context","GET")}teams(e){return this.request(e,"integrations/v1/plans/create-teams","GET")}status(e,t){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}`,"GET")}create(e,t,n,i,s){return this.request(e,"integrations/v1/plans","POST",{id:t,details:{name:n,...s?{description:s}:{}},type:"BACKUP",privacyMode:i?"PUBLIC":"PRIVATE",audience:i})}distribute(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/validator-shares/distribute`,"POST",{validatorShares:n.validatorShares,encryptedKey:n.encryptedKey})}preflight(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/capacity-preflight`,"POST",ln(n))}configure(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",ln(n))}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(x.invalidMasterKeyContext);let i=await this.request(e,"integrations/v1/master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!i?.sessionId)throw new Error(x.relayFailed);return i}async readRelaySession(e,t){let n=await this.request(e,`integrations/v1/master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(x.relayFailed);return n}async request(e,t,n,i){let s=new Headers({"x-organization-id":e,"x-elements-environment":this.environment}),a=await this.getBearerToken();if(!a)throw new Error(x.reauthenticationRequired);s.set("authorization",`Bearer ${a}`),i!==void 0&&s.set("content-type","application/json");let o=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),d=o.pathname.endsWith("/integrations/")?t.replace(/^integrations\//,""):t,c=await this.transport(new URL(d,o),{method:n,headers:s,body:i===void 0?void 0:JSON.stringify(i)}),l={};try{l=await c.json()}catch{}if(!c.ok||l.ok!==!0)throw new te(c.status,l.error);return l.result}};function ln(r){return{protectionProtocol:r.protectionProtocol,operation:"FINALIZE",dataShards:r.dataShards,backupShards:r.backupShards,encryptedKey:r.encryptedKey,assetsMetadata:r.assetsMetadata,custodianPair:r.custodianShard}}var Re=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){xe(e.signal),vr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return xe(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){xe(e.signal);let t=e.encrypted.totalShares+1,n=e.encrypted.threshold+1,i=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(xe(e.signal),!i.custodianPair)throw new k("custodian_share_required");let s=wt(i.keyShards),a=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(wt(i.dataShards),a.symmetricKeyBase64),d=await this.sealer.encryptShares(wt(i.backupShards),a.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,a.symmetricKeyBase64);return xe(e.signal),{protectionProtocol:i.protocol,validatorShares:St(a.encryptedShares),dataShards:St(o.encryptedShares),backupShards:St(d.encryptedShares),encryptedKey:a.encryptedKey,assetsMetadata:br(e.encrypted.assets,e.declaration),custodianShard:c,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:Et(n.encryptedShares[0]),dataShard:Et(n.encryptedShares[1])}}};function wt(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function St(r){return r.map(Et)}function Et(r){return{id:r.id,data:r.encryptedData}}function br(r,e){let t={};for(let n of r){let i=e.assets.find(s=>s.clientAssetRef===n.id);if(!i)throw new k("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.isMedia===void 0?{}:{isMedia:n.meta.isMedia},...n.meta.mimeType===void 0?{}:{mimeType:n.meta.mimeType},...n.meta.fileName===void 0?{}:{fileName:n.meta.fileName},...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...i.fieldNames??[]],isBinary:i.isBinary,...i.fileName===void 0?{}:{fileName:i.fileName},...i.mimeType===void 0?{}:{mimeType:i.mimeType},...i.size===void 0?{}:{size:i.size}}}return t}function vr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new k("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new k("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new k("plan_secrets_declaration_mismatch");let t=new Map(r.assets.map(n=>[n.clientAssetRef,n]));for(let n of e.assets){let i=t.get(n.id);if(!i||i.type!==n.type)throw new k("plan_secrets_declaration_mismatch")}}function xe(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function pn(r,e,t,n,i,s,a){let o=n.mergeThreshold-(n.withCustodian?1:0);if(typeof n.withCustodian!="boolean"||!Number.isInteger(n.mergeThreshold)||o<1||o>r.totalShares)throw new Error(x.invalidShares);let{assets:d,plan:c}=e;c.policy={custodian:n.withCustodian?"FORCE":"BYPASS"};let l=r.masterKeySource??new z({api:{startRelaySession:w=>i.startRelaySession(r.organizationId,t.masterKeyAcquisition,w),readRelaySession:w=>i.readRelaySession(r.organizationId,w)}}),u=new Re(s,l);a?.("encrypting");let g=await u.encrypt({planId:r.planId,declaration:c,secrets:{assets:d,totalShares:r.totalShares,threshold:o}});return a?.("generating_shares"),u.generateShares({planId:r.planId,declaration:c,encrypted:g})}import{PlanAssetDeclaration as wr}from"@safetech/inheriti-core-sdk/node";function un(r){let e=xt({planId:r.planId,title:r.title,assets:[r.asset]});return{asset:e.assets[0],plan:e.plan}}function xt(r){if(!r.assets.length)throw new b("assets_required");let e=r.assets.map(s=>{if(s.meta.isMedia!==!0)return;let a="data"in s.secret?s.secret.data:void 0,o;if(a instanceof Blob&&(o=a.size),typeof a=="string")try{o=atob(a).length}catch{throw new b("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new b("binary_asset_metadata_invalid");return o}),t=wr.create(r.assets.map(({type:s,meta:a})=>({type:s,meta:a}))),n=t.complete(Object.fromEntries(t.entries.map((s,a)=>[s.id,r.assets[a].secret]))),i={idempotencyKey:r.planId,name:r.title,assets:n.map((s,a)=>{let o=s.meta.isMedia===!0;return{clientAssetRef:s.id,type:s.type,name:s.meta.name,fieldNames:o?[]:Object.keys(s.secret),isBinary:o,fileName:s.meta.fileName,mimeType:s.meta.mimeType,size:e[a]}}),participants:[]};return{assets:n,plan:i}}async function gn(r){let e=await Promise.all(r.assets.map(async t=>({type:t.type,meta:t.meta,secret:await Promise.all(Object.entries(t.secret).sort(([n],[i])=>n.localeCompare(i)).map(async([n,i])=>[n,i instanceof Blob?await mn(new Uint8Array(await i.arrayBuffer())):i]))})));return mn(new TextEncoder().encode(JSON.stringify({organizationId:r.organizationId,planId:r.planId,title:r.title,description:r.description??null,audience:r.audience??null,totalShares:r.totalShares,assets:e})))}async function mn(r){let e=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}var Ae=class{constructor(e,t){this.port=e;this.coreSdk=t}material=new Map;flights=new Map;async createQuickPlan(e,t){return this.createPlan({...e,assets:[e.asset]},t)}async createPlan(e,t){if(!e.organizationId||!e.planId||!e.title.trim()||!Array.isArray(e.assets)||!e.assets.length||e.assets.some(a=>!a?.meta?.name?.trim()))throw new Error(x.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(x.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(x.invalidShares);let n=await gn(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==n)throw new Error(x.reconciliationRequired);return i.promise}let s=this.performCreate(e,n,t);this.flights.set(e.planId,{fingerprint:n,promise:s});try{return await s}finally{this.flights.delete(e.planId)}}async performCreate(e,t,n){let i=xt({planId:e.planId,title:e.title,assets:e.assets}),s=this.material.get(e.planId);if(s&&(s.fingerprint!==t||s.masterKeySource!==e.masterKeySource))throw new Error(x.reconciliationRequired);let a=await this.statusOrMissing(e.organizationId,e.planId);if(We(a))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(a&&!s)throw new Error(x.reconciliationRequired);if(!a&&s)throw new Error(x.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(x.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(x.invalidMasterKeyContext);if(!a){n?.("creating_plan");try{await this.port.create(e.organizationId,e.planId,e.title,e.audience,e.description)}catch(l){if(a=await this.statusOrMissing(e.organizationId,e.planId),!a)throw l}}a??=await this.port.status(e.organizationId,e.planId);let d=s?.encrypted??await pn(e,i,o,a,this.port,this.coreSdk,n);s||this.material.set(e.planId,{fingerprint:t,masterKeySource:e.masterKeySource,encrypted:d}),n?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,d),n?.("distributing"),await this.port.distribute(e.organizationId,e.planId,d),n?.("configuring");try{await this.port.configure(e.organizationId,e.planId,d)}catch(l){if(!We(await this.statusOrMissing(e.organizationId,e.planId)))throw l}n?.("verifying");let c=await this.port.status(e.organizationId,e.planId);return We(c)&&this.material.delete(e.planId),{planId:e.planId,status:We(c)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(x.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(n){if(n instanceof te&&n.status===404)return;throw n}}};function We(r){return r?.status==="PROTECTED"||r?.status==="CONFIGURED"}var Qe=class{constructor(e,t,n,i=globalThis.fetch.bind(globalThis)){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i}start(e,t,n,i){return this.request(e,`plans/${encodeURIComponent(t)}/edits`,"POST",{mode:n},i)}async listEligibleCandidates(e,t,n){let i=new URLSearchParams({status:"PROTECTED"});t&&i.set("cursor",t),n&&i.set("namePrefix",n);let s=await this.request(e,`plans/editable?${i}`,"GET");if(!this.isCandidatePage(s))throw new Error("invalid_plan_edit_candidates");return s}async context(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}/edit-context`,"GET");if(!this.isEditContext(n))throw new Error("invalid_plan_edit_context");return n}async moderatorNames(e,t){let n=await this.request(e,`plans/${encodeURIComponent(t)}`,"GET");if(!n||typeof n!="object")throw new Error("invalid_plan_edit_participants");let i=n;if(i.id!==t||!Array.isArray(i.participants)||i.participants.length>1e3)throw new Error("invalid_plan_edit_participants");let s=new Map;for(let a of i.participants){if(!a||typeof a.id!="string"||!a.id||typeof a.displayName!="string"||!Array.isArray(a.relationships)||!a.relationships.every(o=>typeof o=="string")||typeof a.lifecycle!="string")throw new Error("invalid_plan_edit_participants");a.lifecycle==="ACTIVE"&&a.relationships.includes("MODERATOR")&&s.set(a.id,a.displayName)}return s}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(x.invalidMasterKeyContext);let i=await this.request(e,"master-key/relay-sessions","POST",{system:t.system,contextId:t.contextId,clientPublicKey:n});if(!i?.sessionId)throw new Error(x.relayFailed);return i}async readRelaySession(e,t){let n=await this.request(e,`master-key/relay-sessions/${encodeURIComponent(t)}`,"GET");if(!n?.status)throw new Error(x.relayFailed);return n}status(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"GET")}preflight(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure-capacity-preflight`,"POST",this.reconfigureBody(n))}commit(e,t,n){return this.request(e,`plans/${encodeURIComponent(t)}/reconfigure`,"POST",this.reconfigureBody(n))}abort(e,t){return this.request(e,`edits/${encodeURIComponent(t)}`,"DELETE")}commitStatus(e,t){return this.request(e,`edits/${encodeURIComponent(t)}/commit-status`,"GET")}async request(e,t,n,i,s){let a=await this.getBearerToken();if(!a)throw new Error(x.reauthenticationRequired);let o=new Headers({authorization:`Bearer ${a}`,"x-organization-id":e,"x-elements-environment":this.environment});i!==void 0&&o.set("content-type","application/json"),s&&o.set("idempotency-key",s);let d=new URL(this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),c=d.pathname.endsWith("/integrations/")?`v1/${t}`:`integrations/v1/${t}`,l=await this.transport(new URL(c,d),{method:n,headers:o,body:i===void 0?void 0:JSON.stringify(i)}),u={};try{u=await l.json()}catch{}if(!l.ok||u.ok!==!0){let g=Array.isArray(u.validationErrors)?u.validationErrors.join("; "):void 0;throw new te(l.status,g||u.error)}return u.result}isCandidatePage(e){if(!e||typeof e!="object")return!1;let t=e;return!Array.isArray(t.items)||!(t.nextCursor===null||typeof t.nextCursor=="string")?!1:t.items.every(n=>!!n&&typeof n.id=="string"&&!!n.id&&typeof n.name=="string"&&n.status==="PROTECTED"&&typeof n.createdAt=="string"&&!!n.assetSummary&&Number.isSafeInteger(n.assetSummary.count)&&n.assetSummary.count>=0&&Array.isArray(n.assetSummary.types)&&n.assetSummary.types.every(i=>typeof i=="string")&&Array.isArray(n.assetSummary.names)&&n.assetSummary.names.every(i=>typeof i=="string")&&!!n.governance&&["DIRECT","GOVERNED"].includes(n.governance.mode)&&Number.isSafeInteger(n.governance.minimumApprovals)&&n.governance.minimumApprovals>=0)}isEditContext(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.idempotencyKey=="string"&&!!t.idempotencyKey&&(t.mode==="DIRECT"||t.mode==="GOVERNED")&&Number.isSafeInteger(t.totalShares)&&t.totalShares>0&&typeof t.masterKeyEncrypted=="boolean"&&t.masterKeyAcquisition?.system==="INHERITI_BUSINESS"&&typeof t.masterKeyAcquisition.contextId=="string"&&!!t.masterKeyAcquisition.contextId}reconfigureBody(e){return{mergeProcessId:e.mergeProcessId,protectionProtocol:e.protectionProtocol,validatorShares:e.validatorShares,dataShards:e.dataShards,backupShards:e.backupShards,encryptedKey:e.encryptedKey,assetsMetadata:e.assetsMetadata,custodianPair:e.custodianPair}}};var je=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.recoveryStore=n}revealedAssets;revealGeneration=0;clearRevealedAssets(e){this.revealGeneration++,this.revealedAssets?.planId===e&&(this.revealedAssets=void 0)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async loadAssets(e,t){this.assertNotAborted(e.signal);let n=this.revealGeneration;if(!e.organizationId||!e.planId||!e.editId)throw new Error("invalid_plan_edit_input");if(t?.("checking_edit"),await this.recoveryStore.load(e.planId)||await this.configurationRepository().findByPlanId(e.planId))throw this.clearRevealedAssets(e.planId),new Error("edit_recovery_required");let i=await this.assertEditSession(e),s=await this.coreSdk.getService("GetSharedProtectionPlanUseCase").execute(e.planId);if(!s)throw this.clearRevealedAssets(e.planId),new Error("edit_plan_not_found");let a=this.revealedAssets,o=a?.organizationId===e.organizationId&&a.planId===e.planId&&a.editId===e.editId&&a.expiresAt>Date.now();a&&!o&&(this.revealedAssets=void 0);let d=s.masterKeyEncrypted?e.masterKey??(o?a.masterKey:void 0):void 0;s.masterKeyEncrypted&&!d&&(t?.("acquiring_key"),d=await(e.acquireMasterKey?.()??this.resolveMasterKey(e)));let c=Date.now()+10*6e4;o||t?.("opening_plan");let l=o?a.assets:await this.revealAssets(e,d,s.withCustodian,t);if(this.assertNotAborted(e.signal),new Set(l.map(u=>u.id)).size!==l.length)throw new Error("duplicate_existing_asset_id");return!o&&n===this.revealGeneration&&i>Date.now()&&(this.revealedAssets={organizationId:e.organizationId,planId:e.planId,editId:e.editId,expiresAt:Math.min(i,c),assets:l,masterKey:d}),{plan:s,masterKey:d,assets:l}}async assertEditSession(e){let t=await this.port.status(e.organizationId,e.editId),n=Date.parse(t.expiresAt);if(t.id!==e.editId||t.planId!==e.planId||["CANCELED","CLOSED"].includes(t.stage))throw this.clearRevealedAssets(e.planId),new Error("edit_session_not_open");if(t.stage==="EXPIRED"||!(n>Date.now()))throw this.clearRevealedAssets(e.planId),new Error("edit_session_expired");return n}async resolveMasterKey(e){let t=(await this.port.context(e.organizationId,e.planId)).masterKeyAcquisition;return new z({api:{startRelaySession:n=>this.port.startRelaySession(e.organizationId,t,n),readRelaySession:n=>this.port.readRelaySession(e.organizationId,n)}}).resolve()}async revealAssets(e,t,n,i){let s=this.coreSdk.getService("MergeSharedProtectionPlanUseCase"),a=i?await this.port.moderatorNames(e.organizationId,e.planId):new Map,o,d=m=>{m!==o&&(o=m,i?.(m))},c=m=>{if(m.processId!==e.editId||m.planId&&m.planId!==e.planId)return;switch(m.status){case"PENDING_DMS":d("pending_dms");break;case"PENDING_APPROVALS":d("pending_approvals");break;case"PENDING_AUTH":d("pending_auth");break;case"PENDING_MODERATION":d("pending_moderation");break}let P=this.approvalError(m);if(P?.startsWith("edit_authentication_")&&d("pending_auth"),P?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!m.moderatorParticipants||m.requiredModeratorApprovals===void 0||!m.approvalProcess)return;let K=m.moderatorParticipants.map(C=>C.memberId??C.userId);K.some(C=>typeof C!="string"||!C)||new Set(K).size!==K.length||i?.(o,{requiredApprovals:m.requiredModeratorApprovals,approvedModerators:m.approvalProcess.approvedModerators,moderators:m.moderatorParticipants.map((C,G)=>{let A=K[G],H=C.flows.filter(ge=>ge.status==="PENDING"&&ge.expiresAt&&Number.isFinite(ge.expiresAt.getTime())).map(ge=>ge.expiresAt.getTime());return{id:A,displayName:a.get(A)||"Moderator",status:C.status,expiresAt:H.length?new Date(Math.min(...H)).toISOString():void 0}})})},l=await s.resume(e.planId,{onViewUpdate:c});if(l?.processId!==e.editId||l.planId&&l.planId!==e.planId)throw new Error("edit_merge_not_ready");c(l),this.assertApprovalOutcome(e.planId,l),l.status!=="READY_TO_REVEAL"&&l.status!=="REVEALED"&&await s.run(e.editId,{onViewUpdate:c,onApprovalsRequested:()=>d("pending_approvals")});let u=await s.getView(e.editId);if(u?.processId!==e.editId||u.planId&&u.planId!==e.planId)throw new Error("edit_merge_not_ready");c(u),this.assertApprovalOutcome(e.planId,u);let g=u?.status;if(g!=="READY_TO_REVEAL"&&g!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let w=null,D={onRevealed:m=>{w=m},onViewUpdate:c,onRevealStepUpdate:(m,P)=>{if(P==="IN_PROCESS")switch(m){case"DISTRIBUTING_CUSTODIAN_SHARE":break;case"COLLECTING_VALIDATOR_SHARES":d("collecting_validators");break;case"COLLECTING_SHARES":d("collecting_shares");break;case"RECONSTRUCTING":d("reconstructing");break;case"OPENING_WINDOW":d("opening_window");break;case"PREPARING_VIEW":d("preparing_view");break}}};if(n&&(D.onCustodianShareRequired=async(m,P)=>{switch(P.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let K=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),K==="SK_MOBILE")return s.distributeCustodianShareViaMobile(P.planId);if(K!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let C=e.proDevice;try{this.assertNotAborted(e.signal);let G=await s.getCustodianShareData(m);this.assertShare(G,P.planId),d("connecting_safekey_pro");let{deviceId:A}=await C.write(G,e.signal);if(this.assertNotAborted(e.signal),!A?.trim())throw new Error("custodian_share_unavailable");await s.recordCustodianShareClaim(P.planId,G.id,A,"SK_PRO"),this.assertNotAborted(e.signal),await s.markCustodianShareAsCollected(m,G.id);return}finally{C.clearPin?.()}}case"awaiting-claim":d("claiming_custodian_share");return;case"awaiting-release":d("releasing_custodian_share");return;case"collect-from-sk-pro":{if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let K=e.proDevice;try{if(this.assertNotAborted(e.signal),!P.shareId||!P.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let C=await K.read({shareId:P.shareId,planId:P.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(C,P.planId,P.shareId),C.deviceId!==P.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:C.shares}}finally{K.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),g==="REVEALED"?await s.resumeReveal(e.editId,D,t):await s.openRevealWindow(e.editId,{timeoutMinutes:10},D,t),this.assertNotAborted(e.signal),!w)throw new Error("edit_assets_unavailable");return w}assertApprovalOutcome(e,t){let n=this.approvalError(t);if(n)throw this.clearRevealedAssets(e),new Error(n)}approvalError(e){if(e?.isAuthenticationDenied)return"edit_authentication_denied";if(e?.isAuthenticationCanceled)return e.isExpired?"edit_authentication_expired":"edit_authentication_canceled";if(e?.isModerationDenied)return"edit_moderation_denied";if(e?.isModerationCanceled)return e.isExpired?"edit_moderation_expired":"edit_moderation_canceled";if(e?.isExpired)return"edit_session_expired"}assertShare(e,t,n){if(!e||!e.id||e.id!==(n??e.id)||e.planId!==t||!Array.isArray(e.shares)||!e.shares.length||e.shares.some(i=>typeof i!="string"||!i))throw new Error("custodian_share_unavailable")}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}};var Sr=r=>JSON.stringify(r??null,(e,t)=>!t||typeof t!="object"||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([n],[i])=>n<i?-1:n>i?1:0))),Ye=class{constructor(e,t,n,i){this.port=e;this.coreSdk=t;this.recoveryStore=n;this.clearRevealedAssets=i}async saveAssets(e,t,n,i,s,a){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error("invalid_plan_edit_input");let{configure:o,configuration:d}=this.prepareConfiguration(e,t,n,i);a?.("preparing");let c=await o.prepare(d);this.assertNotAborted(e.signal);let l={mergeProcessId:e.editId,protectionProtocol:c.protectionProtocol,validatorShares:this.transportShares(c.validatorShares),dataShards:this.transportShares(c.dataShards),backupShards:this.transportShares(c.backupShards),encryptedKey:c.encryptedKey,assetsMetadata:c.assetsMetadata,custodianPair:c.custodianPair};if(a?.("preflighting"),await this.port.preflight(e.organizationId,e.planId,l),this.assertNotAborted(e.signal),!await this.recoveryStore.save({organizationId:e.organizationId,planId:e.planId,editId:e.editId,assetId:s,material:l}))throw new Error("protected_edit_recovery_unavailable");return this.commit(e,s,l,o,d,a)}async recover(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId||t.planId!==e.planId||t.material.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let n=await this.configurationRepository().findByPlanId(e.planId),i=n?.editDistribution??n?.preparedDistribution;if(!t&&(!i||n?.editDistribution&&n.editDistribution.mergeProcessId!==e.editId))return{status:"RECOVERY_REQUIRED"};let s=t?.material??{mergeProcessId:e.editId,protectionProtocol:i.protectionProtocol,validatorShares:i.validatorShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),dataShards:i.dataShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),backupShards:i.backupShards.map(a=>({id:a.id,data:a.data,replacedShareId:a.replacedShareId})),encryptedKey:i.encryptedKey,assetsMetadata:i.assetsMetadata,custodianPair:i.custodianPair};try{if(await this.isCommitted(e,s))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}}catch{return{status:"RECOVERY_REQUIRED"}}if(!n?.editDistribution)return{status:"RECOVERY_REQUIRED"};try{let a=await this.port.status(e.organizationId,e.editId);return a.id!==e.editId||a.planId!==e.planId||a.stage!=="ACTIONS_OPEN"?{status:"RECOVERY_REQUIRED"}:(await this.port.preflight(e.organizationId,e.planId,s),await this.port.commit(e.organizationId,e.planId,s),await this.isCommitted(e,s)?(await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED"}):{status:"RECOVERY_REQUIRED"})}catch{return{status:"RECOVERY_REQUIRED"}}}async discard(e){this.clearRevealedAssets(e.planId);let t=await this.recoveryStore.load(e.planId);if(t&&(t.organizationId!==e.organizationId||t.editId!==e.editId))throw new Error("edit_checkpoint_session_mismatch");let n=await this.configurationRepository().findByPlanId(e.planId);if(n?.editDistribution&&n.editDistribution.mergeProcessId!==e.editId)throw new Error("edit_checkpoint_session_mismatch");await this.port.abort(e.organizationId,e.editId),await this.clearCheckpoint(e.planId,e.editId)}discardLocal(e){return this.clearCheckpoint(e)}configurationRepository(){return this.coreSdk.getService("SharedConfigurationProcessRepository")}async clearCheckpoint(e,t){this.clearRevealedAssets(e);let n=this.coreSdk.getService("SharedMergingProcessLocalRepository"),i=await n.findByPlanId(e);if(t&&i&&i.id!==t)throw new Error("edit_checkpoint_session_mismatch");await this.configurationRepository().delete(e),i&&await n.delete(i.id),await this.recoveryStore.remove(e)}prepareConfiguration(e,t,n,i){let s=this.coreSdk.getService("ConfigureSharedProtectionPlanUseCase"),a={planId:e.planId,assets:t,totalShares:e.totalShares,withCustodian:n,masterKey:i,reconfigureContext:{mergeProcessId:e.editId}};return{configure:s,configuration:a}}transportShares(e){return e.map(t=>({id:t.id,data:t.data,replacedShareId:t.replacedShareId}))}assertNotAborted(e){if(e?.aborted)throw new DOMException("Aborted","AbortError")}async commit(e,t,n,i,s,a){let o,d=c=>{let l;switch(c.currentStep?.id){case"VALIDATOR_SHARES_DISTRIBUTION":l="distributing_validators";break;case"SHARES_DISTRIBUTION":l="distributing_data";break;case"FINALIZE":l="finalizing";break;default:return}l!==o&&(o=l,a?.(l))};try{await i.execute(s,{onLocalProcessUpdated:d})}catch(c){try{if(a?.("verifying"),await this.isCommitted(e,n))return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}throw o&&a?.(o),c}try{if(a?.("verifying"),!await this.isCommitted(e,n))return{status:"RECOVERY_REQUIRED",assetId:t}}catch{return{status:"RECOVERY_REQUIRED",assetId:t}}return await this.clearCheckpoint(e.planId,e.editId),{status:"UPDATED",assetId:t}}async isCommitted(e,t){let n=await this.port.commitStatus(e.organizationId,e.editId);if(n.planId!==e.planId||!["PROTECTED","CONFIGURED"].includes(n.status)||n.editStatus!=="COMPLETED")return!1;let i=new TextEncoder().encode(Sr(t.assetsMetadata)),s=await globalThis.crypto.subtle.digest("SHA-256",i),a=Array.from(new Uint8Array(s),c=>c.toString(16).padStart(2,"0")).join("");if(n.assetsMetadataHash!==a)return!1;let o=[t.validatorShares,t.dataShards,t.backupShards].flat().map(c=>c.id);t.custodianPair&&o.push(t.custodianPair.keyShard.id,t.custodianPair.dataShard.id);let d=new Set(n.shares.map(c=>c.id));return!o.some(c=>!d.has(c))}};var Xe=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.assetAccess=new je(e,t,n),this.reconfiguration=new Ye(e,t,n,i=>this.clearRevealedAssets(i))}assetAccess;reconfiguration;activeEdits=new Set;clearRevealedAssets(e){this.assetAccess.clearRevealedAssets(e)}start(e,t,n,i){return this.port.start(e,t,n,i)}async listAssets(e,t){let{assets:n}=await this.assetAccess.loadAssets(e,t);return n.map(i=>({id:i.id,type:i.type,name:i.meta.name,isMedia:this.isMedia(i)}))}async getAsset(e,t,n){let{assets:i}=await this.assetAccess.loadAssets(e,n),s=i.find(a=>a.id===t);if(!s)throw new Error("edit_asset_not_found");return structuredClone(s)}async replaceAsset(e,t){return this.withEditLock(e.planId,async()=>{if(!e.assetId)throw new Error("invalid_plan_edit_input");let{plan:n,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=s.findIndex(l=>l.id===e.assetId);if(a<0)throw new Error("edit_asset_not_found");let o=s[a];if(o.type!==e.asset.type)throw new Error("edit_asset_type_mismatch");if(this.isMedia(o)&&!this.hasMediaData(e.asset.secret))throw new Error("edit_media_file_required");let d={id:o.id,type:o.type,meta:e.asset.meta,secret:e.asset.secret},c=s.map((l,u)=>u===a?d:l);return this.reconfiguration.saveAssets(e,c,n.withCustodian,i,o.id,t)})}async addAsset(e,t){return this.withEditLock(e.planId,async()=>{let{plan:n,masterKey:i,assets:s}=await this.assetAccess.loadAssets(e,t),a=un({planId:e.planId,title:"Added asset",asset:e.asset}).asset;if(new Set(s.map(d=>d.id)).has(a.id))throw new Error("duplicate_new_asset_id");return this.reconfiguration.saveAssets(e,s.concat(a),n.withCustodian,i,a.id,t)})}async withEditLock(e,t){if(this.activeEdits.has(e))throw new Error("edit_in_progress");this.activeEdits.add(e);try{return await t()}finally{this.activeEdits.delete(e)}}isMedia(e){return["DOCUMENT","IMAGE","VIDEO","PDF"].includes(e.type)||e.meta.isMedia===!0}hasMediaData(e){let t=e.data;return typeof t=="string"?t.length>0:typeof Blob<"u"&&t instanceof Blob&&t.size>0}recover(e){return this.withEditLock(e.planId,()=>this.reconfiguration.recover(e))}discard(e){return this.withEditLock(e.planId,()=>this.reconfiguration.discard(e))}discardLocal(e){return this.withEditLock(e,()=>this.reconfiguration.discardLocal(e))}};function hn({apiUrl:r,organizationId:e,planId:t,editId:n,environment:i,transport:s}){return(a,o)=>{let d=new URL(a instanceof Request?a.url:a.toString()),c=new URL(r.endsWith("/")?r:`${r}/`);if(d.origin!==c.origin||!d.pathname.startsWith(c.pathname))throw new Error("unsupported_core_edit_route");let l=d.pathname.slice(c.pathname.replace(/\/$/,"").length).replace(/^\//,"");if(l===".well-known/encrypt-key"){if(d.search||o?.method&&o.method!=="GET")throw new Error("unsupported_core_edit_route");return s(d,o)}if(l==="shared-plans/errors")return Promise.resolve(new Response(JSON.stringify({ok:!0}),{status:200,headers:{"content-type":"application/json"}}));let u=Er(l,d.searchParams,t,n),g=new Headers(o?.headers);g.set("x-organization-id",e),g.set("x-elements-environment",i);let w=c.pathname.endsWith("/integrations/")?`v1/${u}`:`integrations/v1/${u}`;return s(new URL(w,c),Object.assign({},o,{headers:g}))}}function Er(r,e,t,n){if(r==="shared-plans/merge/current-user/active"){if(t!==e.get("planIds[]"))throw new Error("edit_plan_id_mismatch");return`plans/${encodeURIComponent(t)}/edits/active`}let s=/^shared-plans\/merge\/([^/]+)(?:\/(.*))?$/.exec(r);if(s){let o=s[2]??"",d={"":"process",approvals:"approvals","plans/assets-metadata":"assets-metadata","approvals/merger/request":"approvals/merger/request","approvals/moderators/request":"approvals/moderators/request","reveal/open":"reveal/open","validator-shares/collect":"validator-shares/collect","shares/collect":"shares/collect","shares/collected":"shares/collected","shares/reconstructed":"shares/reconstructed","data/revealed":"data/revealed","custodian-share/status":"custodian-share/status","custodian-share/data":"custodian-share/data","custodian-share/release":"custodian-share/release","custodian-share/collect":"custodian-share/collect","custodian-share/cancel-claim":"custodian-share/cancel-claim"};if(s[1]!==n||!(o in d))throw new Error("unsupported_core_edit_route");return`edits/${encodeURIComponent(s[1])}/${d[o]}`}let a=/^shared-plans\/([^/]+)(?:\/(.*))?$/.exec(r);if(a){if(a[1]!==t)throw new Error("edit_plan_id_mismatch");let o=a[2]??"";if(o==="")return`edits/${encodeURIComponent(n)}/plan`;if(o==="reconfigure")return`plans/${encodeURIComponent(a[1])}/reconfigure`;if(o==="custodian-share/distribute"||o==="custodian-share/claim")return`edits/${encodeURIComponent(n)}/${o}`}throw new Error("unsupported_core_edit_route")}import{decodeAssetContainer as xr}from"@safetech/inheriti-core-sdk/node";function In(r){return{async openReveal(e,t={}){if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let n=await r.api.planKeyReference(e),i=he(n);if(!n.masterKeyWrapped||!i||n.planId!==e)throw new Error("automation_plan_key_reference_invalid");let s=new z({api:{startRelaySession:o=>r.api.startMasterKeyRelaySession(crypto.randomUUID(),e,o),readRelaySession:(o,d)=>r.api.readMasterKeyRelaySession(o,d),cancelRelaySession:(o,d)=>r.api.cancelMasterKeyRelaySession(o,d)}});return new ae(void 0,{api:r.api,reconstructor:r.reconstructor,assetDecoder:r.assetDecoder,masterKeys:{resolve:(o,d,c)=>{if(o.system!==i.system||o.contextId!==i.contextId)throw new Error("automation_plan_key_reference_mismatch");return s.resolve(d,c)}}}).openReveal(e,t)}}}function Rr(r){let e=new Se(r.apiUrl,r.getBearerToken,r.transport??globalThis.fetch.bind(globalThis));return{...In({api:e,reconstructor:new le(r.workerUrl),assetDecoder:xr}),getPlan:t=>e.getPlan(t)}}import{DataAssetDefinitionService as Ha}from"@safetech/inheriti-core-sdk/node";function yn(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var Je=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),yn(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return yn(new Uint8Array(t))}},Ze=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 s=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(s),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var _e=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},Ce=class extends _e{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},S=class extends _e{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Rt(r){if(r instanceof _e)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var fn=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:ne(n,"issuer"),authorizationEndpoint:ne(n,"authorization_endpoint"),tokenEndpoint:ne(n,"token_endpoint"),deviceAuthorizationEndpoint:Q(n,"device_authorization_endpoint"),endSessionEndpoint:Q(n,"end_session_endpoint"),revocationEndpoint:Q(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:ne(t,"device_code"),userCode:ne(t,"user_code"),verificationUri:ne(t,"verification_uri"),verificationUriComplete:Q(t,"verification_uri_complete"),expiresInSeconds:Pn(t,"expires_in"),intervalSeconds:At(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:ne(n,"access_token"),refreshToken:Q(n,"refresh_token"),idToken:Q(n,"id_token"),tokenType:ne(n,"token_type"),expiresInSeconds:Pn(n,"expires_in"),refreshExpiresInSeconds:At(n,"refresh_expires_in"),scope:Q(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 s=Q(i,"error")??`oauth_http_${n.status}`;throw new S(s,Q(i,"error_description")??s)}return i}};function ne(r,e){let t=Q(r,e);if(!t)throw new S("invalid_oauth_response",`Missing ${e}`);return t}function Q(r,e){return typeof r[e]=="string"?r[e]:void 0}function Pn(r,e){let t=At(r,e);if(t===void 0)throw new S("invalid_oauth_response",`Missing ${e}`);return t}function At(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Ar=600*1e3,et=5,_r=5,bn=class{constructor(e){this.options=e;this.crypto=e.crypto??new Je,this.clock=e.clock??new Ze}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),s=await this.crypto.sha256UrlSafe(i),a=this.clock.now()+Ar;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:i,redirectUri:this.options.configuration.redirectUri,expiresAt:a});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",s),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:a}}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 S("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new S("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new S("redirect_uri_mismatch");let a=i.searchParams.get("error");if(a)throw new S(a,i.searchParams.get("error_description")??a);if(i.searchParams.get("state")!==n.state)throw new S("state_mismatch");let o=i.searchParams.get("code");if(!o)throw new S("authorization_code_missing");let d=await this.getDiscovery(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:d.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),l=await this.acceptTokens(c,n.nonce);return await this.options.sessions.save(l),l}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new S("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(et,t.intervalSeconds??et),i=this.clock.now(),s={...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"),s),s}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 S("device_transaction_missing");let i=n,s=await this.getDiscovery(),a=Math.max(et,i.intervalSeconds??et),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 d=await this.options.transport.pollDeviceToken({tokenEndpoint:s.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let c=await this.acceptTokens(d);return await this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(d){let c=Rt(d);if(c==="authorization_pending"){o=this.clock.now()+a*1e3;continue}if(c==="slow_down"){a+=_r,o=this.clock.now()+a*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new S("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 Ce;let t;try{let n=await this.getDiscovery();t=await this.options.transport.refresh({tokenEndpoint:n.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken})}catch(n){let i=Rt(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.options.sessions.clear(),new Ce):(this.isOfflineSession(e)||await this.options.sessions.clear(),n)}try{if(!t.refreshToken)throw new S("refresh_token_rotation_missing");let n=await this.acceptTokens(t,void 0,e);return await this.options.sessions.save(n),n}catch(n){throw await this.options.sessions.clear(),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(pe(e.issuer)!==pe(this.options.configuration.issuer))throw new S("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}|${pe(t)}|${n}|${i}`}async acceptTokens(e,t,n){if(e.tokenType.toLowerCase()!=="bearer")throw new S("unsupported_token_type");let i=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(i,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new S("id_token_validation_required");let o=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(o,t),o.subject!==i.subject||o.sessionId!==i.sessionId)throw new S("token_subject_mismatch")}let s=this.clock.now(),a=this.options.configuration.scopes.includes("offline_access")&&(e.scope===void 0?n?this.isOfflineSession(n):!0:e.scope.split(/\s+/u).includes("offline_access"));return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:s+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0||e.refreshExpiresInSeconds===0&&a?void 0:s+e.refreshExpiresInSeconds*1e3,offlineAccessGranted:a,principal:i}}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(pe(e.issuer)!==pe(i.issuer))throw new S("issuer_mismatch");if(!s.includes(i.audience))throw new S("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new S("client_mismatch");if(e.environment!==i.environment)throw new S("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new S("required_claim_missing");if(n&&e.nonce!==t)throw new S("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(pe(e.issuer)!==pe(n.issuer))throw new S("issuer_mismatch");if(!i.includes(n.clientId))throw new S("client_mismatch");if(e.authorizedParty!==n.clientId)throw new S("client_mismatch");if(!e.subject||!e.sessionId)throw new S("required_claim_missing");if(e.nonce!==t)throw new S("nonce_mismatch")}};function pe(r){return r.replace(/\/+$/u,"")}var vn=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()}}};import{PassphraseMasterKeySource as Ja,RawMasterKeySource as Za,deriveMasterKey as eo,generateHexSeed as to,computePassphraseVerifier as no}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as io}from"@safetech/inheriti-core-sdk/node";function Ta(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=(s,a)=>{let o=new Headers(a?.headers);return o.set("x-elements-environment",r.environment),e(s,Object.assign({},a,{headers:o}))},n=r.business?void 0:_t({apiUrl:r.apiUrl,getBearerToken:r.getBearerToken,transport:t,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners}),i=new ce(r.apiUrl,r.environment,r.getBearerToken,t,r.business?{organizationId:r.organizationId}:void 0);return new ae(n,{keyVault:r.keyVault,state:r.state,api:i,reconstructor:new le(r.workerUrl),masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:Cr})}function Ma(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=_t({apiUrl:new URL(r.apiUrl).origin,getBearerToken:r.getBearerToken,transport:e,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Ae(new Ee(r.apiUrl,r.environment,r.getBearerToken,e),t)}function Da(r){if(!r.payloadStorage||!r.secureSessionStorage||!r.editRecoveryStore)throw new Error("protected_edit_checkpoint_required");let e=r.transport??globalThis.fetch.bind(globalThis),t=new URL(r.apiUrl).origin,n=_t({apiUrl:t,getBearerToken:r.getBearerToken,transport:hn({apiUrl:t,organizationId:r.organizationId,planId:r.planId,editId:r.editId,environment:r.environment,transport:e}),secureSessionStorage:r.secureSessionStorage,payloadStorage:r.payloadStorage,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new Xe(new Qe(r.apiUrl,r.environment,r.getBearerToken,e),n,r.editRecoveryStore)}import{createHash as Tr,webcrypto as Mr}from"node:crypto";import{canonicalInboxManifest as Dr,decodeInboxManifest as kr,decodeInboxContentFrame as Or,decodeInboxText as Nr,decryptInboxShare as Kr,encodeInboxContentFrame as Ct,encodeInboxText as Ur,encryptInboxShare as wn,inboxProtectedUnitCommitment as Lr,inboxTextMetadataDigest as Sn,openInboxContent as qr,sealInboxContent as Gr,signInboxFrame as Fr,unwrapInboxContentKey as Vr,unwrapInboxShareKey as zr,verifyInboxFrame as En,wrapInboxContentKey as Br,wrapInboxShareKey as $r}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as Hr}from"@safetech/inheriti-core-sdk/workers/inbox.node";var $=Mr,_=$,R=r=>{if(!/^[0-9a-fA-F]{64}$/.test(r))throw new Error("invalid_inbox_key");return Buffer.from(r,"hex")},h=r=>{let e=Buffer.from(r,"base64");if(!r||e.toString("base64")!==r)throw new Error("invalid_inbox_base64");return Uint8Array.from(e)},F=(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),tt=async r=>new Uint8Array(await _.subtle.digest("SHA-256",Uint8Array.from(r))),Te=r=>Tr("sha256").update(r).digest("hex"),re=class{constructor(e,t=new Hr){this.api=e;this.worker=t}async send(e){let t=await this.prepare(e);return this.api.publishInboxMessage(e.conversationId,t.submission)}async prepare(e){let{preparation:t,sender:n}=await this.prepareSender(e),i=await this.textManifest(e,t,n),s=Dr(i),a=await tt(s),{contentKey:o,frame:d}=await Gr(Ur(e.text),a,_),c=await this.signFrame(i,d,e.identity.signingPrivateKey,n.signingPublicKey),{shareKey:l,shares:u}=await this.protectShares(t,d,a),g=await this.wrapRecipientKeys(t,o,a),w=await $r(l,R(e.tenantKeyHex),a,i.tenantId,i.messageId,_);return{frame:Buffer.from(Ct(d)).toString("base64"),submission:{messageId:t.messageId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,expiresAt:e.expiresAt,idempotencyKey:t.messageId,canonicalManifest:Buffer.from(s).toString("base64"),signature:Buffer.from(c).toString("base64"),tenantWrappedShareKey:Buffer.from(w).toString("base64"),recipients:g,shares:u}}}async open(e){return this.openWithCommitment(e)}openCommitted(e,t){return this.openWithCommitment(e,t)}async openWithCommitment(e,t){let n=await this.api.openInboxMessage(e.conversationId,e.messageId,e.identity.deviceId),i;try{e.signal?.throwIfAborted();let{manifest:a,manifestDigest:o,senderPublicDer:d}=await this.verifyOpening(e,n),c=await this.recoverFrame(n,a,o,e.tenantKeyHex);if(t&&!F(t,await Lr(a,Ct(c),h(n.signature),_)))throw new Error("inbox_parent_unit_mismatch");i=await this.decryptText(n,c,a,o,d,e.identity.encryptionPrivateKey),e.signal?.throwIfAborted()}catch(a){try{await this.api.releaseInboxMessage(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId)}catch{}throw a}let s=await this.ack(e.conversationId,e.messageId,e.identity.deviceId,n.leaseId,e.signal);return e.signal?.throwIfAborted(),{text:i,leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt,acknowledgement:s}}async ack(e,t,n,i,s){for(let a=0;a<2;a++){s?.throwIfAborted();try{return await this.api.ackInboxMessage(e,t,n,i,s),s?.throwIfAborted(),"ACKNOWLEDGED"}catch(o){if(s?.throwIfAborted(),o instanceof q&&o.status>=400&&o.status<500)throw o}}return"PENDING"}async prepareSender(e){let t=await this.api.getInboxSendPreparation(e.conversationId);if(t.conversationId!==e.conversationId||t.threshold!==t.total||t.total!==t.shareLayers.length||t.total<2)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId);if(!n||n.deviceId!==e.identity.deviceId||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||Te(h(n.signingPublicKey))!==n.signingKeyFingerprint||Te(h(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return{preparation:t,sender:n}}async textManifest(e,t,n){let i=Date.parse(e.expiresAt);if(!Number.isSafeInteger(i)||i<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:e.identity.tenantId,conversationId:e.conversationId,messageId:t.messageId,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:R(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(s=>({memberId:s.memberId,deviceId:s.deviceId,encryptionKeyFingerprint:R(s.encryptionKeyFingerprint)})),expiresAtEpochMs:i,metadataDigest:await Sn(_)}}async signFrame(e,t,n,i){let s=await _.subtle.importKey("pkcs8",h(n),"Ed25519",!1,["sign"]),a=await Fr(e,t,s,_),o=await _.subtle.importKey("spki",h(i),"Ed25519",!1,["verify"]);if(!await En(e,t,a,o,_))throw new Error("inbox_identity_mismatch");return a}async protectShares(e,t,n){let i=await this.worker.split(Ct(t),{threshold:e.threshold,total:e.total,messageId:e.messageId,manifestDigest:n}),s=_.getRandomValues(new Uint8Array(32)),a=[];for(let o=0;o<e.total;o++){let d=e.shareLayers[o];a.push({kind:"DATA",index:o,shareId:d.dataShareId,layerId:d.id,ciphertext:Buffer.from(await wn(i.dataShares[o],s,n,e.messageId,_)).toString("base64")}),a.push({kind:"KEY",index:o,shareId:d.keyShareId,layerId:d.id,ciphertext:Buffer.from(await wn(i.keyShares[o],s,n,e.messageId,_)).toString("base64")})}return{shareKey:s,shares:a}}async wrapRecipientKeys(e,t,n){return Promise.all(e.recipients.map(async i=>{let s=h(i.encryptionPublicKey);if(Te(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await _.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:Buffer.from(await Br(t,a,n,_)).toString("base64")}}))}async verifyOpening(e,t,n){let i=h(t.canonicalManifest),s=kr(i);if(s.tenantId!==e.identity.tenantId||s.conversationId!==e.conversationId||s.messageId!==e.messageId||s.expiresAtEpochMs<=Date.now()||!F(s.metadataDigest,n??await Sn(_)))throw new Error("inbox_manifest_mismatch");let a=s.recipients.find(d=>d.memberId===e.identity.memberId&&d.deviceId===e.identity.deviceId);if(!a||!F(a.encryptionKeyFingerprint,R(Te(h(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let o=h(t.senderSigningPublicKey);if(t.senderSigningKeyFingerprint!==Te(o)||!F(s.senderSigningKeyFingerprint,R(t.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return{manifest:s,manifestDigest:await tt(i),senderPublicDer:o}}async recoverFrame(e,t,n,i){let s=await zr(h(e.tenantWrappedShareKey),R(i),n,t.tenantId,t.messageId,_),a=[],o=[],d=new Set;for(let l of e.shares){let u=`${l.kind}:${l.index}`;if(d.has(u))throw new Error("duplicate_inbox_share");d.add(u);let g=await Kr(h(l.ciphertext),s,n,t.messageId,l.kind==="DATA"?"data":"key",l.index,_);(l.kind==="DATA"?a:o).push(g)}if(a.length!==o.length||a.length<2)throw new Error("incomplete_inbox_shares");let c=await this.worker.reconstruct(a,o,{threshold:a.length,total:a.length,messageId:t.messageId,manifestDigest:n});return Or(c)}async decryptText(e,t,n,i,s,a){return Nr(await this.decryptContent(e,t,n,i,s,a))}async decryptContent(e,t,n,i,s,a){let o=await _.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await En(n,t,h(e.signature),o,_))throw new Error("inbox_signature_invalid");let d=await _.subtle.importKey("pkcs8",h(a),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await Vr(h(e.wrappedContentKey),d,i,_);return qr(t,c,i,_)}};import{canonicalInboxManifest as Wr,decodeInboxContentFrame as Qr,decodeInboxFile as jr,decryptInboxShare as Yr,encodeInboxContentFrame as Xr,encodeInboxFile as Jr,encryptInboxShare as xn,inboxFileMetadataDigest as Rn,sealInboxContent as Zr,unwrapInboxShareKey as ei,wrapInboxShareKey as ti}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var nt=class extends re{constructor(t){super(t);this.fileApi=t}async sendFile(t){t.signal?.throwIfAborted();let{preparation:n,sender:i}=await this.prepareSender(t),s=await this.fileManifest(t,n,i),a=Wr(s),o=await tt(a),d=Jr(t.file),c;try{c=await Zr(d,o,$)}finally{d.fill(0)}let{contentKey:l,frame:u}=c,g=await this.signFrame(s,u,t.identity.signingPrivateKey,i.signingPublicKey);t.signal?.throwIfAborted();let w=await this.worker.split(Xr(u),{threshold:n.threshold,total:n.total,messageId:n.messageId,manifestDigest:o},t.signal,A=>t.onProgress?.(0,n.total*2,A.stage));t.signal?.throwIfAborted();let D=$.getRandomValues(new Uint8Array(32)),m=[];for(let A=0;A<n.total;A++){let H=n.shareLayers[A];m.push({reference:{kind:"DATA",index:A,shareId:H.dataShareId,layerId:H.id},bytes:await xn(w.dataShares[A],D,o,n.messageId,$)}),m.push({reference:{kind:"KEY",index:A,shareId:H.keyShareId,layerId:H.id},bytes:await xn(w.keyShares[A],D,o,n.messageId,$)})}let P=await this.wrapRecipientKeys(n,l,o),K=await ti(D,R(t.tenantKeyHex),o,s.tenantId,s.messageId,$);t.signal?.throwIfAborted();let C=await this.fileApi.stageInboxFile(t.conversationId,{messageId:n.messageId,senderDeviceId:i.deviceId,participantRevision:n.participantRevision,expiresAt:t.expiresAt,idempotencyKey:n.messageId,canonicalManifest:Buffer.from(a).toString("base64"),signature:Buffer.from(g).toString("base64"),tenantWrappedShareKey:Buffer.from(K).toString("base64"),recipients:P,shares:m.map(A=>A.reference)},t.signal);if(C.messageId!==n.messageId||C.status!=="PREPARING")throw new Error("invalid_inbox_stage");for(let A=0;A<m.length;A++){t.signal?.throwIfAborted();let H=m[A];await this.fileApi.uploadInboxFileShare(t.conversationId,n.messageId,H.reference.shareId,H.bytes,t.signal),t.onProgress?.(A+1,m.length,"UPLOADING")}t.signal?.throwIfAborted();let G=await this.fileApi.publishInboxFile(t.conversationId,n.messageId,t.signal);if(G.messageId!==n.messageId||G.status!=="AVAILABLE")throw new Error("invalid_inbox_publish");return G}async openFile(t){t.signal?.throwIfAborted();let n=await this.fileApi.openInboxFile(t.conversationId,t.messageId,t.identity.deviceId,t.signal),i,s;try{let{manifest:o,manifestDigest:d,senderPublicDer:c}=await this.verifyOpening(t,n,await Rn($)),l=await this.recoverFileFrame(t,n,o,d);s=await this.decryptContent(n,l,o,d,c,t.identity.encryptionPrivateKey),i=jr(s),t.signal?.throwIfAborted(),await t.save(i),t.signal?.throwIfAborted()}catch(o){try{await this.fileApi.releaseInboxMessage(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId)}catch{}throw o}finally{s?.fill(0)}let a=await this.ack(t.conversationId,t.messageId,t.identity.deviceId,n.leaseId,t.signal);return t.signal?.throwIfAborted(),{name:i.name,mimeType:i.mimeType,size:i.bytes.length,leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt,acknowledgement:a}}async fileManifest(t,n,i){let s=Date.parse(t.expiresAt);if(!Number.isSafeInteger(s)||s<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:t.identity.tenantId,conversationId:t.conversationId,messageId:n.messageId,senderId:t.identity.memberId,senderDeviceId:i.deviceId,senderSigningKeyFingerprint:R(i.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(a=>({memberId:a.memberId,deviceId:a.deviceId,encryptionKeyFingerprint:R(a.encryptionKeyFingerprint)})),expiresAtEpochMs:s,metadataDigest:await Rn($)}}async recoverFileFrame(t,n,i,s){let a=await ei(h(n.tenantWrappedShareKey),R(t.tenantKeyHex),s,i.tenantId,i.messageId,$),o=[],d=[],c=new Set;for(let u=0;u<n.shares.length;u++){t.signal?.throwIfAborted();let g=n.shares[u],w=`${g.kind}:${g.index}`;if(c.has(w))throw new Error("duplicate_inbox_share");c.add(w);let D=await this.fileApi.downloadInboxFileShare(t.conversationId,t.messageId,g.shareId,t.identity.deviceId,n.leaseId,t.signal),m=await Yr(D,a,s,i.messageId,g.kind==="DATA"?"data":"key",g.index,$);(g.kind==="DATA"?o:d).push(m),t.onProgress?.(u+1,n.shares.length,"DOWNLOADING")}if(o.length!==d.length||o.length<2)throw new Error("incomplete_inbox_shares");t.signal?.throwIfAborted();let l=await this.worker.reconstruct(o,d,{threshold:o.length,total:o.length,messageId:i.messageId,manifestDigest:s},t.signal,u=>t.onProgress?.(n.shares.length,n.shares.length,u.stage));return t.signal?.throwIfAborted(),Qr(l)}};import{createHash as _n,webcrypto as ni}from"node:crypto";import{canonicalInboxParentManifest as ri,decodeInboxParentManifest as ii,encodeInboxParentNormalFrame as si,decodeInboxParentNormalFrame as ai,sealInboxParentNormalBody as oi,openInboxParentNormalBody as di,wrapInboxParentNormalKey as ci,unwrapInboxParentNormalKey as li,signInboxParentNormalFrame as pi,verifyInboxParentNormalFrame as An,encodeInboxText as ui,decodeInboxText as mi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var V=ni,Me=r=>_n("sha256").update(r).digest("hex"),rt=r=>Buffer.from(r).toString("base64"),it=class{constructor(e){this.api=e}pending=new Map;async send(e){let t=this.digestInput(e),n=e.parentId?this.pending.get(e.parentId):void 0;if(n){if(n.inputDigest!==t)throw new Error("inbox_idempotency_conflict");let c=await this.api.publishNormalInboxMessage(e.conversationId,n.submission);return this.pending.delete(e.parentId),c}let i=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validatePreparation(e,i),a=this.createManifest(e,i,s),o=await this.createSubmission(e,i,s,a);this.rememberSubmission(a.parentId,t,o);let d=await this.api.publishNormalInboxMessage(e.conversationId,o);return this.pending.delete(a.parentId),d}digestInput(e){return _n("sha256").update(JSON.stringify([e.conversationId,e.parentId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.text])).digest("hex")}validatePreparation(e,t){if(t.conversationId!==e.conversationId||t.recipients.length<2||t.recipients.length>50)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||Me(h(n.signingPublicKey))!==n.signingKeyFingerprint||Me(h(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return n}createManifest(e,t,n){return{mode:"NORMAL",tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:e.parentId??t.parentId,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:R(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,encryptionKeyFingerprint:R(i.encryptionKeyFingerprint)})),protectedUnits:[]}}async createSubmission(e,t,n,i){let s=ri(i),{contentKey:a,frame:o}=await oi(ui(e.text),i,V),d=await V.subtle.importKey("pkcs8",h(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),c=await pi(i,o,d,V),l=await V.subtle.importKey("spki",h(n.signingPublicKey),"Ed25519",!1,["verify"]);if(!await An(i,o,c,l,V))throw new Error("inbox_identity_mismatch");let u=await Promise.all(t.recipients.map(g=>this.wrapRecipientKey(g,a,i)));return{parentId:i.parentId,idempotencyKey:i.parentId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,canonicalManifest:rt(s),frame:rt(si(o)),signature:rt(c),recipients:u}}async wrapRecipientKey(e,t,n){let i=h(e.encryptionPublicKey);if(Me(i)!==e.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await V.subtle.importKey("spki",i,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:e.memberId,deviceId:e.deviceId,deviceVersion:e.deviceVersion,keyFingerprint:e.encryptionKeyFingerprint,wrappedContentKey:rt(await ci(t,s,n,V))}}rememberSubmission(e,t,n){if(this.pending.size>=32){let i=this.pending.keys().next().value;i&&this.pending.delete(i)}this.pending.set(e,{inputDigest:t,submission:n})}list(e,t,n){return this.api.listNormalInboxMessages(e,t,n)}async open(e){e.signal?.throwIfAborted();let t=await this.api.openNormalInboxMessage(e.conversationId,e.parentId,e.identity.deviceId,e.signal),n=ii(h(t.canonicalManifest));if(n.mode!=="NORMAL"||n.tenantId!==e.identity.tenantId||n.conversationId!==e.conversationId||n.parentId!==e.parentId||n.senderId!==t.senderMemberId||n.senderDeviceId!==t.senderDeviceId||n.participantRevision!==t.participantRevision)throw new Error("inbox_manifest_mismatch");let i=n.recipients.find(u=>u.memberId===e.identity.memberId&&u.deviceId===e.identity.deviceId);if(!i||!F(i.encryptionKeyFingerprint,R(Me(h(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let s=h(t.senderSigningPublicKey);if(!F(n.senderSigningKeyFingerprint,R(Me(s))))throw new Error("inbox_sender_key_mismatch");let a=ai(h(t.frame)),o=await V.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await An(n,a,h(t.signature),o,V))throw new Error("inbox_signature_invalid");let d=await V.subtle.importKey("pkcs8",h(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await li(h(t.wrappedContentKey),d,n,V),l=mi(await di(a,c,n,V));return e.signal?.throwIfAborted(),{text:l,parentId:t.parentId,sequence:t.sequence}}markRead(e){return this.api.markNormalInboxMessageRead(e.conversationId,e.parentId,e.identity.deviceId)}};import{createHash as Mn,webcrypto as gi}from"node:crypto";import{canonicalInboxParentManifest as hi,decodeInboxParentManifest as Ii,decodeInboxManifest as yi,encodeInboxParentNormalFrame as fi,decodeInboxParentNormalFrame as Pi,sealInboxParentNormalBody as bi,openInboxParentNormalBody as vi,wrapInboxParentNormalKey as wi,unwrapInboxParentNormalKey as Si,signInboxParentNormalFrame as Ei,verifyInboxParentNormalFrame as Cn,signInboxProtectedParent as xi,verifyInboxProtectedParent as Tn,inboxProtectedUnitCommitment as Ri,encodeInboxText as Ai,decodeInboxText as _i}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var O=gi,st=r=>Buffer.from(r).toString("base64"),De=r=>Mn("sha256").update(r).digest("hex"),at=class{constructor(e,t){this.api=e;this.child=t??new re(e)}pending=new Map;child;async send(e){let t=Mn("sha256").update(JSON.stringify([e.conversationId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.segments])).digest("hex"),n=e.parentId?[e.parentId,this.pending.get(e.parentId)]:[...this.pending.entries()].find(([,o])=>o.digest===t),i=n?.[1];if(i){if(i.digest!==t)throw new Error("inbox_idempotency_conflict");try{e.onProgress?.(i.submission.protectedUnits.length,i.submission.protectedUnits.length)}catch{}let o=await this.api.publishInboxParent(e.conversationId,i.submission);return this.pending.delete(n[0]),o}let s=await this.prepare(e);this.pending.size>=32&&this.pending.delete(this.pending.keys().next().value),this.pending.set(s.parentId,{digest:t,submission:s});let a=await this.api.publishInboxParent(e.conversationId,s);return this.pending.delete(s.parentId),a}async prepare(e){if(!e.segments.length||e.segments.length>9)throw new Error("invalid_inbox_parent_segments");let t=e.segments.filter(w=>"protectedText"in w).length;if(t<1||t>4)throw new Error("invalid_inbox_parent_segments");let n=e.segments.length===1&&t===1?"PROTECTED":"MIXED";if(n==="MIXED"&&!e.segments.some(w=>"text"in w))throw new Error("invalid_inbox_parent_segments");let i=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validateSender(e,i),a=e.parentId??i.parentId,{protectedUnits:o,manifestUnits:d}=await this.prepareChildren(e,i,s),c=this.parentManifest(e,i,s,a,n,d),{frame:l,signature:u,recipients:g}=await this.signAndWrap(e,i,s,c);return{parentId:a,idempotencyKey:a,senderDeviceId:s.deviceId,mode:n,participantRevision:i.participantRevision,canonicalManifest:st(hi(c)),signature:st(u),frame:l,recipients:g,protectedUnits:o}}async prepareChildren(e,t,n){let i=[],s=[],a=e.segments.filter(o=>"protectedText"in o).length;for(let o=0;o<e.segments.length;o++){let d=e.segments[o];if(!("protectedText"in d))continue;let c=await this.child.prepare({conversationId:e.conversationId,text:d.protectedText,expiresAt:d.expiresAt,identity:e.identity,tenantKeyHex:e.tenantKeyHex}),l=yi(h(c.submission.canonicalManifest));this.validateChildSnapshot(l,e,t,n);let u=await Ri(l,h(c.frame),h(c.submission.signature),O);i.push({position:o,frame:c.frame,child:c.submission}),s.push({unitId:c.submission.messageId,position:o,commitment:u});try{e.onProgress?.(i.length,a)}catch{}}return{protectedUnits:i,manifestUnits:s}}validateChildSnapshot(e,t,n,i){if(e.tenantId!==t.identity.tenantId||e.conversationId!==t.conversationId||e.senderId!==t.identity.memberId||e.senderDeviceId!==i.deviceId||e.participantRevision!==n.participantRevision||e.recipients.length!==n.recipients.length||e.recipients.some(s=>!n.recipients.some(a=>a.memberId===s.memberId&&a.deviceId===s.deviceId&&F(s.encryptionKeyFingerprint,R(a.encryptionKeyFingerprint)))))throw new Error("inbox_child_snapshot_mismatch")}parentManifest(e,t,n,i,s,a){return{mode:s,tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:i,senderId:e.identity.memberId,senderDeviceId:n.deviceId,senderSigningKeyFingerprint:R(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(o=>({memberId:o.memberId,deviceId:o.deviceId,encryptionKeyFingerprint:R(o.encryptionKeyFingerprint)})),protectedUnits:a}}async signAndWrap(e,t,n,i){let s=await O.subtle.importKey("pkcs8",h(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),a=await O.subtle.importKey("spki",h(n.signingPublicKey),"Ed25519",!1,["verify"]);if(i.mode==="PROTECTED")return{signature:await this.signProtectedParent(i,s,a),recipients:this.recipientReferences(t)};let{frame:o,signature:d,contentKey:c}=await this.sealMixedParent(e,i,s,a);return{frame:o,signature:d,recipients:await this.wrapRecipients(t,c,i)}}async signProtectedParent(e,t,n){let i=await xi(e,t,O);if(!await Tn(e,i,n,O))throw new Error("inbox_identity_mismatch");return i}async sealMixedParent(e,t,n,i){let s=e.segments.map((d,c)=>"text"in d?{text:d.text}:{unitId:t.protectedUnits.find(l=>l.position===c).unitId}),a=await bi(Ai(JSON.stringify(s)),t,O),o=await Ei(t,a.frame,n,O);if(!await Cn(t,a.frame,o,i,O))throw new Error("inbox_identity_mismatch");return{frame:st(fi(a.frame)),signature:o,contentKey:a.contentKey}}recipientReferences(e){return e.recipients.map(t=>({memberId:t.memberId,deviceId:t.deviceId,deviceVersion:t.deviceVersion,keyFingerprint:t.encryptionKeyFingerprint}))}async wrapRecipients(e,t,n){return Promise.all(e.recipients.map(async i=>{let s=h(i.encryptionPublicKey);if(De(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await O.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:i.memberId,deviceId:i.deviceId,deviceVersion:i.deviceVersion,keyFingerprint:i.encryptionKeyFingerprint,wrappedContentKey:st(await wi(t,a,n,O))}}))}validateSender(e,t){if(t.conversationId!==e.conversationId||t.recipients.length<2||t.recipients.length>50)throw new Error("invalid_inbox_preparation");let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||n.signingPublicKey!==e.identity.signingPublicKey||n.encryptionPublicKey!==e.identity.encryptionPublicKey||De(h(n.signingPublicKey))!==n.signingKeyFingerprint||De(h(n.encryptionPublicKey))!==n.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return n}list(e,t,n){return this.api.listInboxParents(e,t,n)}clearHistory(e,t){return this.api.clearInboxHistory(e,t)}async open(e){let{opened:t,manifest:n,segments:i}=await this.openAndVerify(e);return{parentId:t.parentId,sequence:t.sequence,mode:n.mode,segments:i}}async openAndVerify(e){e.signal?.throwIfAborted();let t=await this.api.openInboxParent(e.conversationId,e.parentId,e.identity.deviceId,e.signal),{manifest:n,senderKey:i}=await this.verifyOpening(e,t),s=n.mode==="PROTECTED"?await this.openProtectedParent(t,n,i):await this.openMixedParent(e,t,n,i);return e.signal?.throwIfAborted(),{opened:t,manifest:n,segments:s}}async verifyOpening(e,t){let n=Ii(h(t.canonicalManifest));return this.verifyManifestContext(e,t,n),this.verifyManifestUnits(t,n),this.verifyRecipient(e,n),{manifest:n,senderKey:await this.senderKey(t,n)}}verifyManifestContext(e,t,n){if(n.mode!==t.mode||n.tenantId!==e.identity.tenantId||n.conversationId!==e.conversationId||n.parentId!==e.parentId||n.senderId!==t.senderMemberId||n.senderDeviceId!==t.senderDeviceId||n.participantRevision!==t.participantRevision)throw new Error("inbox_manifest_mismatch")}verifyManifestUnits(e,t){if(t.protectedUnits.length!==e.protectedUnits.length||t.protectedUnits.some((n,i)=>n.unitId!==e.protectedUnits[i].unitId||n.position!==e.protectedUnits[i].position||!F(n.commitment,R(e.protectedUnits[i].commitment))))throw new Error("inbox_manifest_mismatch")}verifyRecipient(e,t){let n=t.recipients.find(i=>i.memberId===e.identity.memberId&&i.deviceId===e.identity.deviceId);if(!n||!F(n.encryptionKeyFingerprint,R(De(h(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch")}async senderKey(e,t){let n=h(e.senderSigningPublicKey);if(De(n)!==e.senderSigningKeyFingerprint||!F(t.senderSigningKeyFingerprint,R(e.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return O.subtle.importKey("spki",n,"Ed25519",!1,["verify"])}async openProtectedParent(e,t,n){if(e.frame!==null||e.wrappedContentKey!==null||!await Tn(t,h(e.signature),n,O))throw new Error("inbox_signature_invalid");return[{unitId:t.protectedUnits[0].unitId,position:0,status:e.protectedUnits[0].status}]}async openMixedParent(e,t,n,i){if(!t.frame||!t.wrappedContentKey)throw new Error("inbox_missing_normal_body");let s=Pi(h(t.frame));if(!await Cn(n,s,h(t.signature),i,O))throw new Error("inbox_signature_invalid");let a=await O.subtle.importKey("pkcs8",h(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=await Si(h(t.wrappedContentKey),a,n,O),d=JSON.parse(_i(await vi(s,o,n,O)));return this.decodeSegments(d,t,n)}decodeSegments(e,t,n){if(!Array.isArray(e))throw new Error("invalid_inbox_parent_body");let i=e.map((s,a)=>{if(!s||typeof s!="object"||Array.isArray(s))throw new Error("invalid_inbox_parent_body");let o=s;if(typeof o.text=="string"&&Object.keys(o).length===1)return{text:o.text};let d=n.protectedUnits.find(c=>c.position===a);if(!d||o.unitId!==d.unitId||Object.keys(o).length!==1)throw new Error("invalid_inbox_parent_body");return{unitId:d.unitId,position:a,status:t.protectedUnits.find(c=>c.unitId===d.unitId).status}});if(n.protectedUnits.some(s=>!i[s.position]||!("unitId"in i[s.position])))throw new Error("invalid_inbox_parent_body");return i}async revealUnit(e){let{manifest:t,segments:n}=await this.openAndVerify(e);if(!n.some(s=>"unitId"in s&&s.unitId===e.unitId))throw new Error("inbox_parent_unit_mismatch");let i=t.protectedUnits.find(s=>s.unitId===e.unitId);return this.child.openCommitted({conversationId:e.conversationId,messageId:e.unitId,identity:e.identity,tenantKeyHex:e.tenantKeyHex,signal:e.signal},i.commitment)}};export{ue as BusinessOrganizationSelectionError,Re as CorePlanMaterialBuilder,Ha as DataAssetDefinitionService,q as ElementsApiRequestFailed,ae as ElementsClient,be as GuidedCreateRecoveryError,Pe as GuidedPlanCreator,Se as HttpAutomationRevealApiPort,ce as HttpElementsApiPort,fn as HttpOperatorAuthTransport,Qe as HttpPlanEditPort,Ee as HttpQuickPlanPort,b as InvalidPlanDeclaration,k as InvalidPlanMaterial,Ne as MasterKeyRelayCancellationFailed,Oe as MasterKeyRelayExpired,ke as MasterKeyRelayTimedOut,j as MasterKeyRequired,fe as MemoryGuidedCreateCheckpointStore,Ie as MemoryKeyVault,ye as MemoryStatePort,nt as NodeInboxFile,it as NodeInboxNormal,at as NodeInboxParent,re as NodeInboxText,S as OAuthProtocolError,bn as OperatorAuthClient,_e as OperatorAuthError,Ce as OperatorReauthenticationRequired,vn as OperatorSessionController,pt as PLAN_CREATION_SERVER_STAGES,Ja as PassphraseMasterKeySource,io as PlanAssetDeclaration,te as PlanRequestFailed,Ae as QuickPlanCreator,Xe as QuickPlanEditor,Za as RawMasterKeySource,z as RelayMasterKeySource,dt as StaticMasterKeyResolver,Ze as SystemOAuthClock,Je as WebOAuthCrypto,no as computePassphraseVerifier,Ke as createMasterKeyResolver,Rr as createNodeAutomationRevealClient,Ta as createNodeElementsClient,Ma as createNodeQuickPlanCreator,Da as createNodeQuickPlanEditor,Cr as decodeAssetContainer,eo as deriveMasterKey,to as generateHexSeed,he as masterKeyRefFor,J as masterKeyRefKey,Rt as oauthErrorCode,lr as selectBusinessOrganization,bt as unwrapDekWithMasterKey,Z as validatePlanCreationInput,se as validatePlanCreationMaterial};
|