@safetech/inheriti-client-sdk 1.17.31 → 1.17.32
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.js +1 -1
- package/dist/inbox.js +1 -1
- package/dist/index.js +1 -1
- package/dist/inheriti-client-sdk.umd.js +23 -23
- package/dist/node-base.js +1 -1
- package/dist/node.js +1 -1
- package/dist/sdk-types.d.ts +5 -9
- package/dist/src/business/inbox/types.d.ts +5 -9
- package/package.json +2 -2
package/dist/node.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createNodeSharedConfigurationSdk as Ht,decodeAssetContainer as ai}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as nr,generateRSAOAEPKeyPair as rr}from"@safetech/inheriti-core-sdk/crypto";var Fe=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},qe=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},ze=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},Q=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 rr();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??(g=>new Promise(b=>setTimeout(b,g))),c=!0,l=!1,p,m=()=>p??=(async()=>{let g=new AbortController,b,O=new Promise((A,N)=>{b=setTimeout(()=>{g.abort(),N(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,g.signal),O])}finally{clearTimeout(b)}})(),f,w=new Promise((g,b)=>{f=()=>{c&&m().catch(()=>{}),b(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",f,{once:!0})});w.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 g=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),w]);if(g.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(g.status==="DELIVERED"&&g.sealedMasterKey){let b=(await nr(g.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(b))throw new Error("invalid_master_key_material");return b}if(g.status==="EXPIRED")throw new qe(s.sessionId);await ir(d,a,e)}throw new Fe(s.sessionId)}catch(g){if(c&&(!l||e?.aborted))try{await m()}catch(b){if(e?.aborted)throw new ze(b)}throw g}finally{f&&e?.removeEventListener("abort",f)}}};async function ir(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 Ge(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||Pt(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(sr(e,r.applicationId)){let i=await r.source?.resolve();return i||Pt(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return Pt(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function sr(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Pt(r,e,t,n,i){if((await e()).relayAvailable)return new Q({...r.relay,api:ar(r.api,t)}).resolve(n,i)}function ar(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 ie(r){return`${r.system}:${r.contextId}`}function we(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var te=class extends Error{constructor(t){super(`master_key_required:${ie(t)}`);this.ref=t;this.name="MasterKeyRequired"}},wt=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(ie(e),t),this}async resolve(e){return this.sources.get(ie(e))?.resolve()}};var Se=class{keys=new Map;async store(e,t){let n=ie(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(ie(e))?.slice()}async remove(e){let t=ie(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var Ee=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 Be=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},h=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var Ve=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var $e=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],Et={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","ipSource","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"]},xt=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],S=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},U=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function ue(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new U("plan_material_field_unknown");if(St(r.dataShards,"data_shards_invalid"),St(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&St(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new U("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new U("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new U("material_operation_invalid")}function St(r,e){if(!Array.isArray(r))throw new U(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new U(e);if(t.data!==void 0&&typeof t.data!="string")throw new U(e)}}function se(r){if(pe(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!cr(r.idempotencyKey))throw new S("idempotency_key_invalid");if(!r.name?.trim())throw new S("plan_name_required");if(!r.assets.length)throw new S("assets_required");let e=new Set;for(let t of r.assets){if(pe(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 S("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!$e.includes(t.type))throw new S("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new S("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 S("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new S("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new S("asset_field_names_invalid");if(or(t.matchOrigins),!t.isBinary){let s=Et[t.type];if(!s||i.some(a=>!s.includes(a)))throw new S("asset_field_name_not_canonical")}}if(!r.participants.length)throw new S("participants_required");for(let t of r.participants){if(pe(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Qt(t.routingEmail))throw new S("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new S("participant_relationships_invalid")}dr(r)}function or(r){if(r===void 0)return;if(!r.length)throw new S("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new S("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new S("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof S?n:new S("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new S("asset_match_origins_duplicated")}function dr(r){let e=r.policy;if(e&&pe(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new S("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){pe(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new S("authentication_mode_invalid")}if(e.moderation){pe(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new S("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new S("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new S("approval_mode_invalid")}let t=e.dms;if(!t)return;pe(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!Qt(t.subjectEmail))throw new S("dms_subject_invalid");if(!r.participants.some(s=>jt(s.routingEmail)===jt(t.subjectEmail)))throw new S("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 S("dms_countdown_invalid")}function cr(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 Qt(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function jt(r){return r.normalize("NFC").trim().toLowerCase()}function pe(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new S(t)}var xe=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)}},Ae=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),se(e),He(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={}){se(t);let a=await this.checkpoints.load(e);if(!a)throw new Re("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await Yt(t))throw new Re("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;He(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:s.signal});He(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});He(s.signal),ue(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 Yt(e),serverStage:t.stage})}},Re=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Yt(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 He(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Xt(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new Be(n.stage);return r.authorizeRevealAction(e,t)}function lr(r){let e=r?.status;return e===400||e===401||e===403}async function Jt(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!lr(s))throw s}return r.releaseRevealMaterial(e,t)}var At={reason:500,commitSha:64,workflow:200,pipeline:300,target:200,image:300,version:100};function ae(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("operation_context_invalid");let e=r;for(let n of Object.keys(e))if(!Object.hasOwn(At,n))throw new Error("operation_context_invalid");let t={};for(let n of Object.keys(At)){if(!Object.hasOwn(e,n))continue;let i=e[n];if(typeof i!="string"||!i.trim()||i.length>At[n]||/[\x00-\x1f\x7f-\x9f]/.test(i)||n==="commitSha"&&(i.length<7||!/^[0-9a-fA-F]+$/.test(i)))throw new Error("operation_context_invalid");t[n]=i.trim()}return t}function pr(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"?mr(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":ur.has(r.stage)?"ENDED":"CONTINUING"}var ur=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function mr(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 Rt=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},M=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Qe(r,e,t={},n=!1){let i=t.operationContext===void 0?void 0:ae(t.operationContext);if(i!==void 0&&!n)throw new Error("operation_context_automation_only");if(t.signal?.aborted)throw x();let s=await r.getPlan(e),a=await r.getActivePlanReveal(e);if(a)throw a.planId!==e||a.mode!==(t.mode??"DIRECT")||a.protectedCopy!==void 0&&a.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Zt(a.id);if(t.signal?.aborted)throw x();let o=()=>r.prepareReveal(e,t.signal,async p=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(p)});if(n||await o(),t.signal?.aborted)throw x();let d=t.idempotencyKey??crypto.randomUUID(),c;try{c=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:d,...t.protectedCopy?{protectedCopy:!0}:{},...i!==void 0?{operationContext:i}:{}})}catch(p){if(p?.code!=="merge_process_already_active")throw p;let m=await r.getActivePlanReveal(e);throw!m||m.planId!==e||m.mode!==(t.mode??"DIRECT")||m.protectedCopy!==void 0&&m.protectedCopy!==(t.protectedCopy??!1)?p:Zt(m.id)}if(c.protectedCopy!==void 0&&c.protectedCopy!==(t.protectedCopy??!1))throw await r.closeReveal(c.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let l;try{if(t.signal?.aborted)throw x();let p=await hr(r,c,t);if(t.signal?.aborted||(n&&await o(),t.signal?.aborted)||(oe(t,"RELEASING_MATERIAL",p),t.signal?.aborted))throw x();let m=await r.releaseRevealMaterial(p.id,p.materialVersion??"1");if(t.signal?.aborted||(p.mode==="GOVERNED"&&await r.markRevealSharesCollected(p.id),t.signal?.aborted))throw x();let f;try{f=await br(r,p,Pr(m),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(oe(t,"RECONSTRUCTING",p),t.signal?.aborted))throw x();try{l=await r.reconstructPlanMaterial(f)}catch(g){throw t.signal?.aborted?x():(await r.reportRevealReconstruction(p.id,{status:"FAILED",errorCode:fr(g)}),g)}if(t.signal?.aborted)throw x();let w=await r.reportRevealReconstruction(p.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(oe(t,"OPEN",w),t.signal?.aborted))throw x();return new Ct(r,w,s,l,t.signal)}catch(p){throw l?.fill(0),await nn(r,c.id,t.signal?.aborted?"CANCELED":"ERROR"),p}}function Zt(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var gr=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function hr(r,e,t){let n=await ne(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw x();if(t.onSession?.(n),t.onProgress?.({phase:pr(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(gr.has(n.stage))throw new _t(n.stage);await Tt(t.pollIntervalMs??1500,t.signal),n=await ne(()=>r.getReveal(e.id,t.signal),t.signal)}}var _t=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function oe(r,e,t){r.onProgress?.({phase:e,session:t})}function Tt(r,e){return e?.aborted?Promise.reject(x()):new Promise((t,n)=>{let i=setTimeout(a,Math.max(0,r)),s=()=>{clearTimeout(i),n(x())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var Ct=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 Rt;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 M("asset_selector_invalid");if(!this.client.assetDecoder)throw new M("asset_decoder_required");let n=e.map(({selector:s,options:a={}})=>{let o=Ir(s),d=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!d)throw new M("asset_not_found");if(d.isBinary)throw new M("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new M("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 M("asset_value_invalid");return{selector:a.selector,value:yr(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",en(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new M("asset_selector_invalid");if(!this.client.assetDecoder)throw new M("asset_decoder_required");let n=this.plan.assets.find(a=>a.code===e||a.id===e);if(!n)throw new M("asset_not_found");if(!n.isBinary)throw new M("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 M("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",en(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=nn(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 Ir(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new M("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new M("asset_selector_invalid");return{asset:r.asset,field:r.field}}function yr(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new M("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new M("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?Et[t]:void 0)?.includes(e))return"";throw new M("asset_value_invalid")}return n[e]}function en(r){if(r instanceof M)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 fr(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function br(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await ne(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new We;let c=await ne(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(tn(c,i.id,e.planId),!c.shares.includes(i.data))throw new Z;oe(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:l}=await ne(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw x();if(!l?.trim())throw new Z;if(await r.claimRevealCustodianShare(e.id,c.id,l),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw x();return{...t,shares:t.shares.filter(p=>p!==i).concat(c.shares.map((p,m)=>({id:`${c.id}:${m}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:p})))}}if(d!=="SK_MOBILE")throw new Z;if(n.signal?.aborted)throw x();return await r.distributeRevealCustodianShare(e.id),oe(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await ne(()=>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),oe(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await Tt(n.pollIntervalMs??1500,n.signal),s=await ne(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new We;if(!s.shareId||!s.deviceId)throw new Z;oe(n,"CONNECTING_SAFEKEY_PRO",e);let d=await ne(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw x();if(tn(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new Z;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw x();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 Z;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(a),oe(n,"WAITING_FOR_CUSTODIAN",a),n.signal?.aborted)throw x();await r.requestRevealCustodianRelease(e.id);let o=await vr(r,e,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 tn(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 Z}async function ne(r,e){if(e?.aborted)throw x();if(!e)return r();let t,n=new Promise((i,s)=>{t=()=>s(x()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw x();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function vr(r,e,t){let n=Date.parse(e.expiresAt),i=Number.isFinite(n)?Math.min(n,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new je;let s=await ne(()=>r.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new je;if(s&&s.status!=="PENDING"){let a=s;if(a.shares?.length)return a;throw new Z}await Tt(t.pollIntervalMs??1500,t.signal)}}var Z=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},We=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},je=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Pr(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function nn(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(a){if(!wr(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 wr(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function x(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var me=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 Se,this.state=t.state??new Ee,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??xr(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 h;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new h;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new h;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new h;return this.api.listMemberLogs(e,t)}listOrganizationMembers(e){if(!this.api)throw new h;return this.api.listOrganizationMembers(e)}listOrganizationAuditTrail(e){if(!this.api)throw new h;return this.api.listOrganizationAuditTrail(e)}getOrganizationInsights(e){if(!this.api)throw new h;return this.api.getOrganizationInsights(e)}getPlanResponsibilities(e){if(!this.api)throw new h;return this.api.getPlanResponsibilities(e)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return se(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new h;return ue(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new xe){if(this.requireApplication(),!this.api)throw new h;return new Ae(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 te({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 te(e);return await this.keyVault.store(e,Sr(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new h;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 h;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new Ve;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 te({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=we(e);if(!i)throw new te({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new h;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new h;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new h;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,n){if(!this.api)throw new h;return this.api.createRevealFileAccess(e,t,n)}cancelRevealFileAccess(e,t,n){if(!this.api)throw new h;return this.api.cancelRevealFileAccess(e,t,n)}getActivePlanReveal(e){if(!this.api)throw new h;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new h;return this.api.getReveal(e,t)}openReveal(e,t){return Qe(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 h;return Jt(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new h;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new h;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new h;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new h;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new h;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new h;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new h;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new h;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new h;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new h;return Xt(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new h;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new h;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new h;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new h;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new h;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new h;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 h;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 Ot;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new te({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},Ot=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Sr(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 xr(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 Ge({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return Ge({...e,organizationId:r.organizationId})}var Ar=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Rr=["DIRECT","GOVERNED"],sn=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],_r=["ACTIVE","REVOKED"],Cr=["SK_MOBILE"],Tr=["ACTIVE","INACTIVE"],Or=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function an(r){let e=D(r);return{items:$(e.items).map(cn),nextCursor:e.nextCursor===null?null:y(e.nextCursor,"nextCursor")}}function on(r){let e=D(r);return{total:Y(e.total,"total"),items:$(e.items).map(t=>{let n=D(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:y(n.id,"log.id"),planId:y(n.planId,"log.planId"),tenantId:y(n.tenantId,"log.tenantId"),event:y(n.event,"log.event"),occurredOn:y(n.occurredOn,"log.occurredOn"),status:re(n.status),title:y(n.title,"log.title"),details:$(n.details).map(i=>{let s=D(i);return{label:y(s.label,"log.detail.label"),value:y(s.value,"log.detail.value")}})}})}}function dn(r){let e=D(r);return{total:Y(e.total,"total"),items:$(e.items).map(t=>{let n=D(t);if("eventData"in n)throw new Error("invalid_elements_response");let i=y(n.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:y(n.id,"log.id"),memberId:y(n.memberId,"log.memberId"),source:i,event:y(n.event,"log.event"),occurredOn:y(n.occurredOn,"log.occurredOn"),status:re(n.status)}})}}function Ye(r){let e=D(r),t=cn(e),n=D(e.source),i=y(n.kind,"source.kind");return{...t,assets:$(e.assets).map(s=>{let a=D(s);return{id:y(a.id,"asset.id"),code:re(a.code),type:B(y(a.type,"asset.type"),$e),name:y(a.name,"asset.name"),isBinary:Mr(a.isBinary,"asset.isBinary"),fieldNames:$(a.fieldNames).map(o=>y(o,"asset.fieldNames")),fileName:re(a.fileName),mimeType:re(a.mimeType),size:a.size===void 0||a.size===null?void 0:Y(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:$(a.matchOrigins).map(o=>y(o,"asset.matchOrigins"))}}),participants:$(e.participants).map(s=>{let a=D(s);return{id:y(a.id,"participant.id"),displayName:y(a.displayName,"participant.displayName"),relationships:$(a.relationships).map(o=>B(y(o,"relationship"),sn)),lifecycle:B(y(a.lifecycle,"participant.lifecycle"),_r)}}),revealPolicy:(()=>{let s=D(e.revealPolicy);return{masterKeyRelease:B(y(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:B(y(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=D(e.dms);return{subjectEmail:y(s.subjectEmail,"dms.subjectEmail"),countdownDays:Y(s.countdownDays,"dms.countdownDays"),countdownHours:Y(s.countdownHours,"dms.countdownHours"),countdownMinutes:Y(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:B(y(n.system,"source.system"),["INHERITI_BUSINESS"]),status:B(y(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function _e(r){let e=D(r);return{operationId:y(e.operationId,"operationId"),stage:B(y(e.stage,"stage"),xt),outcome:B(y(e.outcome,"outcome"),Or),planId:re(e.planId),lastErrorCode:re(e.lastErrorCode),participants:e.participants===void 0?void 0:$(e.participants).map(t=>{let n=D(t);return{clientParticipantRef:y(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:y(n.planParticipantId,"planParticipantId"),relationships:$(n.relationships).map(i=>kr(y(i,"relationship"),sn))}})}}function cn(r){let e=D(r),t=D(e.assetSummary),n=D(e.governance),i=D(e.participantSummary);return{id:y(e.id,"id"),name:y(e.name,"name"),description:re(e.description),status:B(y(e.status,"status"),Ar),createdAt:y(e.createdAt,"createdAt"),configuredAt:re(e.configuredAt),assetSummary:{count:Y(t.count,"assetSummary.count"),types:$(t.types).map(s=>B(y(s,"assetType"),$e)),names:rn(t.names).map(s=>y(s,"assetSummary.names"))},governance:{mode:B(y(n.mode,"governance.mode"),Rr),minimumApprovals:Y(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:Y(i.owners,"owners"),mergers:Y(i.mergers,"mergers"),moderators:Y(i.moderators,"moderators")},authentication:rn(e.authentication).map(s=>{let a=D(s);return{id:B(y(a.id,"authentication.id"),Cr),status:B(y(a.status,"authentication.status"),Tr)}})}}function B(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function kr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function D(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function rn(r){return r==null?[]:$(r)}function $(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function y(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function re(r){return r==null?void 0:y(r,"optional")}function Y(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function Mr(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}function H(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function ge(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function _(r){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function kt(r){return r==null?void 0:_(r)}function K(r){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function Dr(r){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}function ln(r){let e=H(r);return{total:K(e.total),items:ge(e.items).map(t=>{let n=H(t);return{id:_(n.id),displayName:_(n.displayName),role:_(n.role),status:_(n.status)}})}}function pn(r){let e=H(r);return{total:K(e.total),shownCount:K(e.shownCount),totalCount:K(e.totalCount),nextCursor:e.nextCursor==null?null:_(e.nextCursor),hasMore:Dr(e.hasMore),items:ge(e.items).map(t=>{let n=H(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:_(n.id),occurredOn:_(n.occurredOn),actorName:_(n.actorName),actorRole:_(n.actorRole),category:_(n.category),action:_(n.action),subject:_(n.subject),status:_(n.status),sourceEvent:_(n.sourceEvent),planId:kt(n.planId),planName:kt(n.planName),responsibleMemberName:kt(n.responsibleMemberName)}})}}function un(r){let e=H(r),t=H(e.stats),n=H(e.planAccessResults);return{stats:{totalPlans:K(t.totalPlans),plansCreatedThisMonth:K(t.plansCreatedThisMonth),activeMembers:K(t.activeMembers),totalSeats:t.totalSeats==null?null:K(t.totalSeats),accessRequests30d:K(t.accessRequests30d),accessRequestsPrevious30d:K(t.accessRequestsPrevious30d),pendingApprovals:K(t.pendingApprovals)},plansOverTime:ge(e.plansOverTime).map(i=>{let s=H(i);return{month:_(s.month),count:K(s.count)}}),planTypes:ge(e.planTypes).map(i=>{let s=H(i);return{type:_(s.type),count:K(s.count)}}),accessModerationActivity:ge(e.accessModerationActivity).map(i=>{let s=H(i);return{week:_(s.week),requests:K(s.requests),approvals:K(s.approvals)}}),planAccessResults:{success:K(n.success),aborted:K(n.aborted),expired:K(n.expired)}}}function mn(r){let e=H(r);return{planId:_(e.planId),participants:ge(e.participants).map(t=>{let n=H(t);return{id:_(n.id),displayName:_(n.displayName),relationships:ge(n.relationships).map(i=>_(i)),lifecycle:_(n.lifecycle)}})}}function Xe(r,e){if(Object.keys(r).some(t=>!e.includes(t)))throw new Error("organization_query_field_unknown")}var be=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function gn(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 Nr(r,e){if(!e){if(r.length===0)throw new be("organization_required");if(r.length>1)throw new be("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new be("organization_access_denied");return e}function Kr(r){let e=E(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:P(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:P(e.participantRevision,1),createdAt:z(e.createdAt),...hn(e)}}function hn(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=E(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:u(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:z(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=E(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:P(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:z(i.revealedAt)}:{}}})}:{}}})}}function In(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(Kr),total:P(e.total,0),limit:P(e.limit,1),offset:P(e.offset,0),unreadCount:P(e.unreadCount,0),readThroughSequence:P(e.readThroughSequence,0)}}function yn(r){let e=E(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:u(e.parentId),sequence:P(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:P(e.participantRevision,1),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=E(t);return{unitId:u(n.unitId),position:P(n.position,0),commitment:u(n.commitment),status:u(n.status)}})}}function Mt(r){let e=E(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:P(e.sequence,1),status:e.status}}function fn(r){let e=E(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:u(e.conversationId),parentId:u(e.parentId),participantRevision:P(e.participantRevision,1),recipients:e.recipients.map(Dt)}}function bn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);return{parentId:u(n.parentId),sequence:P(n.sequence,1),senderMemberId:u(n.senderMemberId),senderDeviceId:u(n.senderDeviceId),participantRevision:P(n.participantRevision,1),createdAt:z(n.createdAt),...hn(n)}}),total:P(e.total,0),limit:P(e.limit,1),offset:P(e.offset,0),unreadCount:P(e.unreadCount,0),readThroughSequence:P(e.readThroughSequence,0)}}function vn(r){return{readThroughSequence:P(E(r).readThroughSequence,0)}}function Pn(r){return{clearedThroughSequence:P(E(r).clearedThroughSequence,0)}}function wn(r){let e=E(r);return{parentId:u(e.parentId),sequence:P(e.sequence,1),senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:P(e.participantRevision,1),canonicalManifest:u(e.canonicalManifest),frame:u(e.frame),signature:u(e.signature),wrappedContentKey:u(e.wrappedContentKey),senderSigningPublicKey:u(e.senderSigningPublicKey)}}function E(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function u(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function z(r){let e=u(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function P(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Dt(r){let e=E(r);return{memberId:u(e.memberId),deviceId:u(e.deviceId),deviceVersion:P(e.deviceVersion,1),encryptionPublicKey:u(e.encryptionPublicKey),encryptionKeyFingerprint:u(e.encryptionKeyFingerprint),signingPublicKey:u(e.signingPublicKey),signingKeyFingerprint:u(e.signingKeyFingerprint)}}function ve(r){let e=E(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:u(e.id),tenantId:u(e.tenantId),memberId:u(e.memberId),version:e.version,encryptionPublicKey:u(e.encryptionPublicKey),encryptionKeyFingerprint:u(e.encryptionKeyFingerprint),signingPublicKey:u(e.signingPublicKey),signingKeyFingerprint:u(e.signingKeyFingerprint),status:e.status,createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)}}function Je(r){let e=E(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:u(e.id),tenantId:u(e.tenantId),creatorMemberId:u(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(u),participantRevision:e.participantRevision,status:e.status,createdAt:z(e.createdAt),updatedAt:z(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=E(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:u(n.senderMemberId),createdAt:z(n.createdAt)}}return t}function Sn(r){let e=E(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(Je),total:e.total,limit:e.limit,offset:e.offset}}function En(r){let e=E(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=Dt(t);return{memberId:n.memberId,name:u(E(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:P(e.limit,1),offset:P(e.offset,0),nextOffset:e.nextOffset===null?null:P(e.nextOffset,0)}}function xn(r){let e=E(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=E(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:u(n.memberId),name:u(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:u(E(n.profilePicture).url)}}}}),limit:P(e.limit,1),offset:P(e.offset,0),nextOffset:e.nextOffset===null?null:P(e.nextOffset,0)}}function An(r){let e=E(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:u(e.conversationId),messageId:u(e.messageId),participantRevision:P(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Dt),shareLayers:e.shareLayers.map(t=>{let n=E(t),i=u(n.id),s=u(n.dataShareId),a=u(n.keyShareId);if(n.type==="INHERITI_CHAIN")return{id:i,type:n.type,contractAddress:u(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 Ze(r){let e=E(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:u(e.messageId),status:e.status}}function Rn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(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:u(n.id),status:n.status,senderMemberId:u(n.senderMemberId),senderDeviceId:u(n.senderDeviceId),createdAt:z(n.createdAt),updatedAt:z(n.updatedAt),expiresAt:z(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=E(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:u(a.memberId),status:a.status,...a.consumedAt!==void 0?{consumedAt:a.consumedAt===null?null:z(a.consumedAt)}:{}}})),i}),total:P(e.total,0),limit:P(e.limit,1),offset:P(e.offset,0)}}function _n(r){let e=E(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:u(e.leaseId),leaseExpiresAt:z(e.leaseExpiresAt),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),tenantWrappedShareKey:u(e.tenantWrappedShareKey),wrappedContentKey:u(e.wrappedContentKey),shares:e.shares.map(t=>{let n=E(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:P(n.index,0),shareId:u(n.shareId),layerId:u(n.layerId),ciphertext:u(n.ciphertext)}})}}function Cn(r){let e=E(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:u(e.leaseId),leaseExpiresAt:z(e.leaseExpiresAt),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),tenantWrappedShareKey:u(e.tenantWrappedShareKey),wrappedContentKey:u(e.wrappedContentKey),shares:e.shares.map(t=>{let n=E(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:P(n.index,0),shareId:u(n.shareId),layerId:u(n.layerId)}})}}function et(r){return typeof r=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(r)&&Number.isFinite(Date.parse(r))}function he(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 Ie(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var V=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}},ye=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;getFileAccess(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}requestFileAccessOpening(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings`,"POST",t)}readFileAccessOpening(e,t,n,i){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}`,"GET",void 0,void 0,{"x-client-key-hash":n},i)}confirmFileAccessDelivery(e,t,n){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}/confirm-delivery`,void 0,{"x-client-key-hash":n})}createInboxFileAccess(e,t,n,i){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses`,"POST",n,void 0,void 0,i)}createRevealFileAccess(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",t,void 0,void 0,n)}cancelRevealFileAccess(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",n)}cancelInboxFileAccess(e,t,n,i){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses/${encodeURIComponent(n)}`,void 0,void 0,"DELETE",i)}async getOwnFileAccessIdentityKey(e){let t=await this.request("v1/inbox/devices/me/identity-key","GET",void 0,void 0,void 0,e);if(t===null)return null;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid_file_access_identity_key");let n=t;if(typeof n.publicKey!="string"||!n.publicKey||typeof n.fingerprint!="string"||!n.fingerprint||n.status!=="ACTIVE"&&n.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:n.publicKey,fingerprint:n.fingerprint,status:n.status}}async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:ve(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:ve(n)}async registerInboxDevice(e){return ve(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return ve(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return ve(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return Je(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return Je(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 Sn(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 En(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 xn(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return An(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return fn(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 Ze(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return Mt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return Mt(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 In(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 yn(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 Pn(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 bn(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 wn(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 vn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return Ze(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 tt(o,s);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new V(o.status,he(d),Ie(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return Ze(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 Cn(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 p=c.body.getReader(),m=[],f=0;try{for(;;){a?.throwIfAborted();let b=await p.read();if(b.done)break;if(f+=b.value.length,f>14*1024*1024)throw new Error("invalid_inbox_share_size");m.push(b.value)}}catch(b){throw await p.cancel().catch(()=>{}),b}let w=new Uint8Array(f),g=0;for(let b of m)w.set(b,g),g+=b.length;return w}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 Rn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return _n(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(gn)}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 an(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Ye(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 on(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.q&&n.set("q",t.q),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 dn(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listOrganizationMembers(e={}){if(this.requireOrganizationSelection(),Xe(e,["limit","offset"]),e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>100))throw new Error("organization_query_limit_invalid");if(e.offset!==void 0&&(!Number.isSafeInteger(e.offset)||e.offset<0))throw new Error("organization_query_offset_invalid");let t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),ln(await this.request(`v1/organization/members${t.size?`?${t}`:""}`,"GET"))}async listOrganizationAuditTrail(e){if(this.requireOrganizationSelection(),Xe(e,["from","to","limit","cursor","category","memberId","responsibleMemberId"]),!et(e.from)||!et(e.to)||Date.parse(e.from)>Date.parse(e.to))throw new Error("organization_query_date_invalid");if(e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>500))throw new Error("organization_query_limit_invalid");if(e.cursor!==void 0&&!/^[1-9]\d*$/.test(e.cursor))throw new Error("organization_query_cursor_invalid");let t=new URLSearchParams({from:e.from,to:e.to});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor!==void 0&&t.set("cursor",e.cursor),e.category!==void 0&&t.set("category",e.category),e.memberId!==void 0&&t.set("memberId",e.memberId),e.responsibleMemberId!==void 0&&t.set("responsibleMemberId",e.responsibleMemberId),pn(await this.request(`v1/organization/audit-trail?${t}`,"GET"))}async getOrganizationInsights(e={}){if(this.requireOrganizationSelection(),Xe(e,["from","to"]),e.from===void 0!=(e.to===void 0)||e.from!==void 0&&(!et(e.from)||!et(e.to)||Date.parse(e.from)>Date.parse(e.to)))throw new Error("organization_query_date_invalid");let t=new URLSearchParams;return e.from!==void 0&&e.to!==void 0&&(t.set("from",e.from),t.set("to",e.to)),un(await this.request(`v1/organization/insights${t.size?`?${t}`:""}`,"GET"))}async getPlanResponsibilities(e){if(this.requireOrganizationSelection(),!e)throw new Error("plan_id_required");return mn(await this.request(`v1/plans/${encodeURIComponent(e)}/responsibilities`,"GET"))}async startPlanCreation(e){se(e);let{idempotencyKey:t,...n}=e;return _e(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return _e(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return ue(t),_e(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return _e(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){if(t.operationContext!==void 0)throw new Error("operation_context_automation_only");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[f,w]of Object.entries(s??{}))d.set(f,w);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 p=await this.transport(new URL(e,c),l);a?.throwIfAborted();let m=await tt(p,a);if(a?.throwIfAborted(),!p.ok)throw new V(p.status,he(m),Ie(m),p.headers.get("x-request-id")??void 0);if(!m.ok||m.result===void 0)throw new V(p.status,he(m),Ie(m),p.headers.get("x-request-id")??void 0);return m.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 tt(d,i);throw new V(d.status,he(c),Ie(c),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,n,i="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let a=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});a&&o.set("authorization",`Bearer ${a}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId);for(let[p,m]of Object.entries(n??{}))o.set(p,m);t&&o.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,d),{method:i,headers:o,body:t?JSON.stringify(t):void 0,signal:s}),l=await tt(c,s);if(s?.throwIfAborted(),!c.ok||!l.ok)throw new V(c.status,he(l),Ie(l),c.headers.get("x-request-id")??void 0)}requireOrganizationSelection(){if(!this.business?.organizationId)throw new V(400,"organization_selection_required")}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new V(400,"organization_selection_required")}};async function tt(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{createNodeSsdpV2Processor as Vr}from"@safetech/inheriti-core-sdk/node";async function Nt(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=Lr(r),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,a);return Fr(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 Lr(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 Fr(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var Ce=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await Tn("plan_key_unwrap_failed",()=>Nt(e.planKey,t)),i=await crypto.subtle.importKey("raw",Kt(n),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await Tn("plan_share_decryption_failed",()=>Br(o.data,i));Gr(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 nt("plan_share_reconstruction_failed",zr(o))}}},nt=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},qr=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 zr(r){let e=r instanceof Error?r.message:void 0;if(e)return qr.has(e)?e:void 0}async function Tn(r,e){try{return await e()}catch{throw new nt(r)}}function Gr(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function Br(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=Kt(r.slice(0,t)),i=Kt(r.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(s)}function Kt(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 fe=class extends Ce{constructor(e){super(()=>Vr(e))}};var Te=class{constructor(e,t,n){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=n}firstRelayStates=new Map;async startReveal(e,t){let n=t.operationContext===void 0?void 0:ae(t.operationContext);return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey,...n===void 0?{}:{operationContext:n}},!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 Ye(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 V(c.status,l&&he(l),l&&Ie(l));return l?.result}};var C={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 de=class extends Error{constructor(t,n){super(n??`plan_request_failed_${t}`);this.status=t;this.code=n}},Oe=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",On(n))}configure(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",On(n))}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(C.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(C.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(C.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(C.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 de(c.status,l.error);return l.result}};function On(r){return{protectionProtocol:r.protectionProtocol,operation:"FINALIZE",dataShards:r.dataShards,backupShards:r.backupShards,encryptedKey:r.encryptedKey,assetsMetadata:r.assetsMetadata,custodianPair:r.custodianShard}}var Me=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){ke(e.signal),Hr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return ke(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){ke(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(ke(e.signal),!i.custodianPair)throw new U("custodian_share_required");let s=Ut(i.keyShards),a=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(Ut(i.dataShards),a.symmetricKeyBase64),d=await this.sealer.encryptShares(Ut(i.backupShards),a.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,a.symmetricKeyBase64);return ke(e.signal),{protectionProtocol:i.protocol,validatorShares:Lt(a.encryptedShares),dataShards:Lt(o.encryptedShares),backupShards:Lt(d.encryptedShares),encryptedKey:a.encryptedKey,assetsMetadata:$r(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:Ft(n.encryptedShares[0]),dataShard:Ft(n.encryptedShares[1])}}};function Ut(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function Lt(r){return r.map(Ft)}function Ft(r){return{id:r.id,data:r.encryptedData}}function $r(r,e){let t={};for(let n of r){let i=e.assets.find(s=>s.clientAssetRef===n.id);if(!i)throw new U("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 Hr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new U("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new U("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new U("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 U("plan_secrets_declaration_mismatch")}}function ke(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function kn(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(C.invalidShares);let{assets:d,plan:c}=e;c.policy={custodian:n.withCustodian?"FORCE":"BYPASS"};let l=r.masterKeySource??new Q({api:{startRelaySession:f=>i.startRelaySession(r.organizationId,t.masterKeyAcquisition,f),readRelaySession:f=>i.readRelaySession(r.organizationId,f)}}),p=new Me(s,l);a?.("encrypting");let m=await p.encrypt({planId:r.planId,declaration:c,secrets:{assets:d,totalShares:r.totalShares,threshold:o}});return a?.("generating_shares"),p.generateShares({planId:r.planId,declaration:c,encrypted:m})}import{PlanAssetDeclaration as Wr}from"@safetech/inheriti-core-sdk/node";function Mn(r){let e=qt({planId:r.planId,title:r.title,assets:[r.asset]});return{asset:e.assets[0],plan:e.plan}}function qt(r){if(!r.assets.length)throw new S("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 S("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new S("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 Nn(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 Dn(new Uint8Array(await i.arrayBuffer())):i]))})));return Dn(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 Dn(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 De=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(C.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(C.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(C.invalidShares);let n=await Nn(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==n)throw new Error(C.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=qt({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(C.reconciliationRequired);let a=await this.statusOrMissing(e.organizationId,e.planId);if(rt(a))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(a&&!s)throw new Error(C.reconciliationRequired);if(!a&&s)throw new Error(C.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(C.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(C.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 kn(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(!rt(await this.statusOrMissing(e.organizationId,e.planId)))throw l}n?.("verifying");let c=await this.port.status(e.organizationId,e.planId);return rt(c)&&this.material.delete(e.planId),{planId:e.planId,status:rt(c)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(C.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(n){if(n instanceof de&&n.status===404)return;throw n}}};function rt(r){return r?.status==="PROTECTED"||r?.status==="CONFIGURED"}var it=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(C.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(C.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(C.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(C.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)}),p={};try{p=await l.json()}catch{}if(!l.ok||p.ok!==!0){let m=Array.isArray(p.validationErrors)?p.validationErrors.join("; "):void 0;throw new de(l.status,m||p.error)}return p.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 st=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(p=>p.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 Q({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=g=>{g!==o&&(o=g,i?.(g))},c=g=>{if(g.processId!==e.editId||g.planId&&g.planId!==e.planId)return;switch(g.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 b=this.approvalError(g);if(b?.startsWith("edit_authentication_")&&d("pending_auth"),b?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!g.moderatorParticipants||g.requiredModeratorApprovals===void 0||!g.approvalProcess)return;let O=g.moderatorParticipants.map(A=>A.memberId??A.userId);O.some(A=>typeof A!="string"||!A)||new Set(O).size!==O.length||i?.(o,{requiredApprovals:g.requiredModeratorApprovals,approvedModerators:g.approvalProcess.approvedModerators,moderators:g.moderatorParticipants.map((A,N)=>{let R=O[N],J=A.flows.filter(Pe=>Pe.status==="PENDING"&&Pe.expiresAt&&Number.isFinite(Pe.expiresAt.getTime())).map(Pe=>Pe.expiresAt.getTime());return{id:R,displayName:a.get(R)||"Moderator",status:A.status,expiresAt:J.length?new Date(Math.min(...J)).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 p=await s.getView(e.editId);if(p?.processId!==e.editId||p.planId&&p.planId!==e.planId)throw new Error("edit_merge_not_ready");c(p),this.assertApprovalOutcome(e.planId,p);let m=p?.status;if(m!=="READY_TO_REVEAL"&&m!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let f=null,w={onRevealed:g=>{f=g},onViewUpdate:c,onRevealStepUpdate:(g,b)=>{if(b==="IN_PROCESS")switch(g){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&&(w.onCustodianShareRequired=async(g,b)=>{switch(b.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let O=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),O==="SK_MOBILE")return s.distributeCustodianShareViaMobile(b.planId);if(O!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let A=e.proDevice;try{this.assertNotAborted(e.signal);let N=await s.getCustodianShareData(g);this.assertShare(N,b.planId),d("connecting_safekey_pro");let{deviceId:R}=await A.write(N,e.signal);if(this.assertNotAborted(e.signal),!R?.trim())throw new Error("custodian_share_unavailable");await s.recordCustodianShareClaim(b.planId,N.id,R,"SK_PRO"),this.assertNotAborted(e.signal),await s.markCustodianShareAsCollected(g,N.id);return}finally{A.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 O=e.proDevice;try{if(this.assertNotAborted(e.signal),!b.shareId||!b.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let A=await O.read({shareId:b.shareId,planId:b.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(A,b.planId,b.shareId),A.deviceId!==b.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:A.shares}}finally{O.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),m==="REVEALED"?await s.resumeReveal(e.editId,w,t):await s.openRevealWindow(e.editId,{timeoutMinutes:10},w,t),this.assertNotAborted(e.signal),!f)throw new Error("edit_assets_unavailable");return f}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 jr=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))),at=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(jr(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 ot=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.assetAccess=new st(e,t,n),this.reconfiguration=new at(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,p)=>p===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=Mn({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 Kn({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 p=Qr(l,d.searchParams,t,n),m=new Headers(o?.headers);m.set("x-organization-id",e),m.set("x-elements-environment",i);let f=c.pathname.endsWith("/integrations/")?`v1/${p}`:`integrations/v1/${p}`;return s(new URL(f,c),Object.assign({},o,{headers:m}))}}function Qr(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 Yr}from"@safetech/inheriti-core-sdk/node";function Un(r){return{async openReveal(e,t={}){let n=t.operationContext===void 0?void 0:ae(t.operationContext);if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let i=await r.api.planKeyReference(e),s=we(i);if(!i.masterKeyWrapped||!s||i.planId!==e)throw new Error("automation_plan_key_reference_invalid");let a=new Q({api:{startRelaySession:d=>r.api.startMasterKeyRelaySession(crypto.randomUUID(),e,d),readRelaySession:(d,c)=>r.api.readMasterKeyRelaySession(d,c),cancelRelaySession:(d,c)=>r.api.cancelMasterKeyRelaySession(d,c)}}),o=new me(void 0,{api:r.api,reconstructor:r.reconstructor,assetDecoder:r.assetDecoder,masterKeys:{resolve:(d,c,l)=>{if(d.system!==s.system||d.contextId!==s.contextId)throw new Error("automation_plan_key_reference_mismatch");return a.resolve(c,l)}}});return Qe(o,e,{...t,...n===void 0?{}:{operationContext:n}},!0)}}}function Xr(r){let e=new Te(r.apiUrl,r.getBearerToken,r.transport??globalThis.fetch.bind(globalThis));return{supportsOperationContext:!0,...Un({api:e,reconstructor:new fe(r.workerUrl),assetDecoder:Yr}),getPlan:t=>e.getPlan(t)}}import{generateInheritiFileKey as dt,sealInheritiFile as ct,readInheritiFileHeader as zt,openInheritiFile as Gt,InheritiFileInvalid as Jr,MAX_INHERITI_FILE_BYTES as Bt}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as lt,openInheritiFileKey as Vt}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";async function Zr(r){let{reveal:e,api:t,signal:n}=r;if(e.session.protectedCopy!==!0)throw new Error("protected_reveal_required");let i=await t.getOwnFileAccessIdentityKey(n);if(!i||i.status!=="ACTIVE")throw new Error("file_access_identity_unavailable");let s=Date.parse(e.session.expiresAt);if(!Number.isFinite(s)||s<=Date.now())throw new Error("reveal_expired");let a=r.openLimit??1;if(!Number.isSafeInteger(a)||a<1||a>4294967295)throw new Error("invalid_open_limit");await e.exportAsset(r.selector,async o=>{if(!(o.bytes instanceof Uint8Array)||o.bytes.length<1||o.bytes.length>Bt-1024*1024)throw new Error("unsupported_protected_asset");let d=dt(),c,l=!1,p=!1;try{n?.throwIfAborted();let m=await lt(d,i.publicKey);l=!0;let f=await t.createRevealFileAccess(e.session.id,{copyId:r.copyId,envelopeId:r.envelopeId,assetId:o.id,identityKeyFingerprint:i.fingerprint,sealedFileKey:m,openLimit:a},n);if(f.copyId!==r.copyId||f.status!=="PENDING")throw new Error("file_access_create_invalid");let w=await t.getFileAccess(r.copyId,n);for(;w.status==="PENDING";){if(n?.throwIfAborted(),Date.now()>=s)throw new Error("reveal_expired");await new Promise((b,O)=>{let A=()=>{clearTimeout(N),O(n?.reason)},N=setTimeout(()=>{n?.removeEventListener("abort",A),b()},Math.min(500,Math.max(1,s-Date.now())));n?.addEventListener("abort",A,{once:!0})}),w=await t.getFileAccess(r.copyId,n)}if(w.status!=="READY"||w.origin!=="REVEAL"||w.copyId!==r.copyId||w.allowedUses!==a||!w.recipient||!w.deployment||w.expiresAt!==null&&(!Number.isFinite(Date.parse(w.expiresAt))||Date.parse(w.expiresAt)>s||Date.parse(w.expiresAt)<=Date.now()))throw new Error("file_access_binding_invalid");let g=await ct({plaintext:o.bytes,fileKey:d,mimeType:o.mimeType,binding:w});g.fileKey.fill(0),c=g.fileBytes,n?.throwIfAborted(),await r.save({fileName:o.fileName,fileBytes:c}),p=!0}catch(m){if(l&&!p)try{await t.cancelRevealFileAccess(e.session.id,r.copyId)}catch(f){throw new AggregateError([m,f],"protected_asset_export_and_cleanup_failed",{cause:m})}throw m}finally{d.fill(0),c?.fill(0)}})}import{DataAssetDefinitionService as Vo}from"@safetech/inheriti-core-sdk/node";function Ln(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var pt=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Ln(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Ln(new Uint8Array(t))}},ut=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 Ne=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},G=class extends Ne{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},v=class extends Ne{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function mt(r){if(r instanceof Ne)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:L(n,"issuer"),authorizationEndpoint:L(n,"authorization_endpoint"),tokenEndpoint:L(n,"token_endpoint"),deviceAuthorizationEndpoint:ee(n,"device_authorization_endpoint"),endSessionEndpoint:ee(n,"end_session_endpoint"),revocationEndpoint:ee(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:L(t,"device_code"),userCode:L(t,"user_code"),verificationUri:L(t,"verification_uri"),verificationUriComplete:ee(t,"verification_uri_complete"),expiresInSeconds:qn(t,"expires_in"),intervalSeconds:$t(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 revoke(e){let t=await this.http(new URL(e.endpoint),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,token:e.refreshToken,token_type_hint:"refresh_token"}),signal:e.signal});if(!t.ok)throw new v(`oauth_http_${t.status}`)}async exchangeBusinessSession(e){return this.businessSession(e.apiUrl,"exchange",{providerAccessToken:e.providerAccessToken})}async refreshBusinessSession(e){return this.businessSession(e.apiUrl,"refresh",{refreshToken:e.refreshToken})}async revokeBusinessSession(e){await this.businessRequest(e.apiUrl,"revoke",{refreshToken:e.refreshToken},e.signal)}async businessSession(e,t,n){let i=await this.businessRequest(e,t,n);return{accessToken:L(i,"accessToken"),refreshToken:L(i,"refreshToken"),accessExpiresAt:L(i,"accessExpiresAt"),sessionExpiresAt:L(i,"sessionExpiresAt"),familyId:L(i,"familyId"),environment:ti(i,"environment"),clientId:L(i,"clientId"),providerIssuer:L(i,"providerIssuer"),providerSubject:L(i,"providerSubject")}}async businessRequest(e,t,n,i){let s=e.endsWith("/")?e:`${e}/`,a=new URL(`operator-sessions/${t}`,s),o=await this.http(a,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},credentials:"omit",signal:i,body:JSON.stringify(n)}),d={};try{d=await o.json()}catch{}if(!o.ok)throw new v(`business_http_${o.status}`);if(d.ok!==!0||!ei(d.result))throw new v("invalid_business_response");return d.result}async token(e,t){let n=await this.form(e,t);return{accessToken:L(n,"access_token"),refreshToken:ee(n,"refresh_token"),idToken:ee(n,"id_token"),tokenType:L(n,"token_type"),expiresInSeconds:qn(n,"expires_in"),refreshExpiresInSeconds:$t(n,"refresh_expires_in"),scope:ee(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=ee(i,"error")??`oauth_http_${n.status}`;throw new v(s,ee(i,"error_description")??s)}return i}};function ei(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function ti(r,e){let t=L(r,e);if(t!=="TEST"&&t!=="LIVE")throw new v("invalid_business_response");return t}function L(r,e){let t=ee(r,e);if(!t)throw new v("invalid_oauth_response",`Missing ${e}`);return t}function ee(r,e){return typeof r[e]=="string"?r[e]:void 0}function qn(r,e){let t=$t(r,e);if(t===void 0)throw new v("invalid_oauth_response",`Missing ${e}`);return t}function $t(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var ni=600*1e3,gt=5,ri=5,zn=5e3,ii=new WeakMap,si=new WeakMap;async function Bn(r,e,t){let n=r.get(e),i,s=new Promise(a=>{i=a});r.set(e,s),n&&await n;try{return await t()}finally{r.get(e)===s&&r.delete(e),i()}}function ce(r,e){return Bn(ii,r,e)}var Gn=class{constructor(e){this.options=e;if(e.businessAuthority&&!e.businessApiUrl)throw new v("business_api_url_required");this.crypto=e.crypto??new pt,this.clock=e.clock??new ut}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(e){let t=await this.getDiscovery(),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(32),s=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(s),o=this.clock.now()+ni;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:n,nonce:i,codeVerifier:s,redirectUri:this.options.configuration.redirectUri,expiresAt:o});let d=new URL(t.authorizationEndpoint);return d.searchParams.set("response_type","code"),d.searchParams.set("client_id",this.options.configuration.clientId),d.searchParams.set("redirect_uri",this.options.configuration.redirectUri),d.searchParams.set("scope",this.options.configuration.scopes.join(" ")),d.searchParams.set("state",n),d.searchParams.set("nonce",i),d.searchParams.set("code_challenge",a),d.searchParams.set("code_challenge_method","S256"),e?.prompt&&d.searchParams.set("prompt",e.prompt),{authorizationUrl:d.toString(),expiresAt:o}}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 v("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new v("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new v("redirect_uri_mismatch");if(i.searchParams.get("state")!==n.state)throw new v("state_mismatch");let a=i.searchParams.get("error");if(a)throw new v(a,i.searchParams.get("error_description")??a);let o=i.searchParams.get("code");if(!o)throw new v("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 ce(this.options.sessions,()=>this.options.sessions.save(l)),l}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new v("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(gt,t.intervalSeconds??gt),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 v("device_transaction_missing");let i=n,s=await this.getDiscovery(),a=Math.max(gt,i.intervalSeconds??gt),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 ce(this.options.sessions,()=>this.options.sessions.save(c)),await this.options.transactions.remove(t),c}catch(d){let c=mt(d);if(c==="authorization_pending"){o=this.clock.now()+a*1e3;continue}if(c==="slow_down"){a+=ri,o=this.clock.now()+a*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new v("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e){if(this.isSafeIdBusinessMode()&&!this.isValidSafeIdBusinessSession(e))throw await this.clearIfUnchanged(e),new G;if(!this.options.businessApiUrl&&(e.kind==="business"||e.kind==="safeid-oidc-business"))throw await this.clearIfUnchanged(e),new G;if(this.options.businessApiUrl&&!this.isSafeIdBusinessMode()&&!this.isValidBusinessSession(e))throw await this.clearIfUnchanged(e),new G;return e.expiresAt>this.clock.now()?e.accessToken:(await this.refreshExpired(e)).accessToken}}refresh(){return this.refreshExpired()}refreshExpired(e){if(this.refreshFlight)return this.refreshFlight;let t=this.performRefresh(e).finally(()=>{this.refreshFlight===t&&(this.refreshFlight=void 0)});return this.refreshFlight=t,t}async clear(){let e;if(await ce(this.options.sessions,async()=>{try{e=await this.options.sessions.load()}finally{await this.options.sessions.clear()}}),this.isSafeIdBusinessMode()&&e&&this.isValidSafeIdBusinessSession(e)&&e.refreshToken){let i=new AbortController,s;try{await Promise.race([(async()=>{let a=await this.getDiscovery();a.revocationEndpoint&&this.options.transport.revoke&&await this.options.transport.revoke({endpoint:a.revocationEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken,signal:i.signal})})(),new Promise((a,o)=>{s=setTimeout(()=>{i.abort(),this.discovery=void 0,o(new v("provider_revoke_timeout"))},zn)})])}finally{s&&clearTimeout(s)}return}if(!this.options.businessApiUrl||!e||!this.isValidBusinessSession(e))return;let t=new AbortController,n;try{await Promise.race([this.options.transport.revokeBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:e.refreshToken,signal:t.signal}),new Promise((i,s)=>{n=setTimeout(()=>{t.abort(),s(new v("business_revoke_timeout"))},zn)})])}finally{n&&clearTimeout(n)}}async performRefresh(e){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.performProviderRefresh(e);let t=await this.options.sessions.load();if(!t||!this.isValidBusinessSession(t))throw t&&await this.clearIfUnchanged(t),new G;if(t.sessionExpiresAt<=this.clock.now())throw await this.clearIfCurrent(t),new G;let n;try{n=await this.options.transport.refreshBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:t.refreshToken})}catch(i){let s=mt(i);if(s==="business_http_409"){let a=await ce(this.options.sessions,async()=>{let o=await this.options.sessions.load();if(o&&this.isValidBusinessSession(o)&&o.refreshToken!==t.refreshToken&&o.familyId===t.familyId&&o.principal.subject===t.principal.subject)return o;o&&this.sameCredential(o,t)&&await this.options.sessions.clear()});if(a)return a;throw new G}throw s==="business_http_401"?(await this.clearIfCurrent(t),new G):i}try{let i=this.businessSession(n,t.principal,t);if(i.refreshToken===t.refreshToken)throw new v("refresh_token_rotation_missing");return await ce(this.options.sessions,async()=>{let s=await this.options.sessions.load();if(s&&this.isValidBusinessSession(s)&&s.familyId===t.familyId&&s.principal.subject===t.principal.subject&&s.refreshToken!==t.refreshToken)return s;if(!s||!this.sameCredential(s,t))throw new G;return await this.options.sessions.save(i),i})}catch(i){throw await this.clearIfCurrent(t),i}}sameCredential(e,t){return this.isValidBusinessSession(e)&&e.familyId===t.familyId&&e.refreshToken===t.refreshToken&&e.principal.subject===t.principal.subject}async clearIfUnchanged(e){await ce(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&t.kind===e.kind&&t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken&&t.principal?.subject===e.principal?.subject&&await this.options.sessions.clear()})}async clearIfCurrent(e){await ce(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&this.sameCredential(t,e)&&await this.options.sessions.clear()})}async performProviderRefresh(e){return e??=await this.options.sessions.load(),Bn(si,this.options.sessions,async()=>{let t=await this.options.sessions.load();if(e&&t&&t.kind===e.kind&&t.refreshToken!==e.refreshToken&&t.expiresAt>this.clock.now()&&t.principal?.subject===e.principal?.subject&&t.principal?.sessionId===e.principal?.sessionId){if(this.isSafeIdBusinessMode()){if(this.isValidSafeIdBusinessSession(t))return t}else if(t.kind!=="business"&&t.kind!=="safeid-oidc-business")return t}return this.refreshProviderUnderLock()})}async refreshProviderUnderLock(){let e=await this.options.sessions.load();if(!e||(this.isSafeIdBusinessMode()?!this.isValidSafeIdBusinessSession(e):e.kind==="business"||e.kind==="safeid-oidc-business")||!e.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw e&&await this.clearIfUnchanged(e),new G;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=mt(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.clearIfUnchanged(e),new G):(this.isOfflineSession(e)||await this.clearIfUnchanged(e),n)}try{if(!t.refreshToken)throw new v("refresh_token_rotation_missing");let n=await this.acceptProviderTokens(t,void 0,e);return await ce(this.options.sessions,async()=>{let i=await this.options.sessions.load();if(!i||i.kind!==e.kind||i.refreshToken!==e.refreshToken||i.accessToken!==e.accessToken)throw new G;return await this.options.sessions.save(n),n})}catch(n){throw await this.clearIfUnchanged(e),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(F(e.issuer)!==F(this.options.configuration.issuer))throw new v("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}|${F(t)}|${n}|${i}|${this.options.businessApiUrl?this.isSafeIdBusinessMode()?"safeid-oidc":"business":"provider"}|${this.options.configuration.audience}`}async acceptTokens(e,t){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.acceptProviderTokens(e,t);let n=await this.validateProviderTokens(e,t),i=await this.options.transport.exchangeBusinessSession({apiUrl:this.options.businessApiUrl,providerAccessToken:e.accessToken});return this.businessSession(i,n)}async validateProviderTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new v("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new v("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==n.subject||i.sessionId!==n.sessionId)throw new v("token_subject_mismatch")}return n}async acceptProviderTokens(e,t,n){let i=await this.validateProviderTokens(e,t);if(this.isSafeIdBusinessMode()&&!e.refreshToken)throw new G;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")),o={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};return this.isSafeIdBusinessMode()?{kind:"safeid-oidc-business",accessToken:o.accessToken,refreshToken:o.refreshToken,idToken:o.idToken,tokenType:o.tokenType,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt,offlineAccessGranted:o.offlineAccessGranted,principal:o.principal,businessApiUrl:this.options.businessApiUrl,audience:this.options.configuration.audience,clientId:this.options.configuration.clientId,issuer:F(this.options.configuration.issuer),environment:this.options.configuration.environment}:o}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}isSafeIdBusinessMode(){return this.options.businessAuthority==="safeid-oidc"}isValidSafeIdBusinessSession(e){let t=e,n=t.principal;return t.kind==="safeid-oidc-business"&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&(t.refreshExpiresAt===void 0||Number.isFinite(t.refreshExpiresAt))&&typeof t.issuer=="string"&&typeof t.businessApiUrl=="string"&&typeof t.audience=="string"&&typeof t.clientId=="string"&&(t.environment==="TEST"||t.environment==="LIVE")&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&typeof n.authorizedParty=="string"&&(n.environment==="TEST"||n.environment==="LIVE")&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&t.businessApiUrl===this.options.businessApiUrl&&e.audience===this.options.configuration.audience&&e.clientId===this.options.configuration.clientId&&F(t.issuer)===F(this.options.configuration.issuer)&&e.environment===this.options.configuration.environment&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment&&F(n.issuer)===F(this.options.configuration.issuer)&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)}businessSession(e,t,n){if(F(e.providerIssuer)!==F(t.issuer)||e.providerSubject!==t.subject||e.clientId!==this.options.configuration.clientId||e.environment!==this.options.configuration.environment||n&&e.familyId!==n.familyId)throw new v("business_identity_mismatch");let i=Date.parse(e.accessExpiresAt),s=Date.parse(e.sessionExpiresAt);if(!Number.isFinite(i)||!Number.isFinite(s)||i<=this.clock.now()||s<=this.clock.now()||i>s)throw new v("invalid_business_expiry");return{kind:"business",familyId:e.familyId,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenType:"Bearer",expiresAt:i,sessionExpiresAt:s,principal:{issuer:t.issuer,audience:t.audience,authorizedParty:t.authorizedParty,environment:t.environment,subject:t.subject,sessionId:t.sessionId,tokenId:t.tokenId,scopes:t.scopes,nonce:t.nonce}}}isValidBusinessSession(e){let t=e,n=t.principal;return t.kind==="business"&&typeof t.familyId=="string"&&t.familyId.length>0&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&Number.isFinite(t.sessionExpiresAt)&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&F(n.issuer)===F(this.options.configuration.issuer)&&typeof n.subject=="string"&&n.subject.length>0&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(F(e.issuer)!==F(i.issuer))throw new v("issuer_mismatch");if(!s.includes(i.audience))throw new v("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new v("client_mismatch");if(e.environment!==i.environment)throw new v("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new v("required_claim_missing");if(n&&e.nonce!==t)throw new v("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(F(e.issuer)!==F(n.issuer))throw new v("issuer_mismatch");if(!i.includes(n.clientId))throw new v("client_mismatch");if(e.authorizedParty!==n.clientId)throw new v("client_mismatch");if(!e.subject||!e.sessionId)throw new v("required_claim_missing");if(e.nonce!==t)throw new v("nonce_mismatch")}};function F(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 Yo,RawMasterKeySource as Xo,deriveMasterKey as Jo,generateHexSeed as Zo,computePassphraseVerifier as ed}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as nd}from"@safetech/inheriti-core-sdk/node";function Ao(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:Ht({apiUrl:r.apiUrl,getBearerToken:r.getBearerToken,transport:t,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners}),i=new ye(r.apiUrl,r.environment,r.getBearerToken,t,r.business?{organizationId:r.organizationId}:void 0);return new me(n,{keyVault:r.keyVault,state:r.state,api:i,reconstructor:new fe(r.workerUrl),masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:ai})}function Ro(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=Ht({apiUrl:new URL(r.apiUrl).origin,getBearerToken:r.getBearerToken,transport:e,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new De(new Oe(r.apiUrl,r.environment,r.getBearerToken,e),t)}function _o(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=Ht({apiUrl:t,getBearerToken:r.getBearerToken,transport:Kn({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 ot(new it(r.apiUrl,r.environment,r.getBearerToken,e),n,r.editRecoveryStore)}import{createHash as oi}from"node:crypto";import{generateRSAOAEPKeyPair as di}from"@safetech/inheriti-core-sdk/crypto";async function $n(r){let e=zt(r.fileBytes);if(!/^[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(e.copyId))throw new Error("invalid_startup_file");if(r.signal?.aborted)throw new Error("opening_cancelled");let t=await r.api.getFileAccess(e.copyId,r.signal);if(e.deployment!==t.deployment||e.origin!==t.origin||e.copyId!==t.copyId||e.recipient!==t.recipient||e.expiresAt!==t.expiresAt||e.allowedUses!==t.allowedUses)throw new Error("file_binding_mismatch");return{header:e,access:t}}async function ci(r){let{api:e,sessionId:t,signal:n}=r;if(!/^[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(t))throw new Error("invalid_opening_session");let i=Uint8Array.from(r.fileBytes),s,a,o=()=>{if(n?.aborted)throw new Error("opening_cancelled")};try{let{access:d}=await $n({fileBytes:i,api:e,signal:n});if(d.status!=="READY"||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now())throw new Error("file_access_unavailable");if(r.delivery==="REVEAL"&&d.origin!=="REVEAL")throw new Error("file_access_unavailable");o();let{publicKeyBase64:c,privateKey:l}=await di(),p=oi("sha256").update(c).digest("hex");o();let m=await e.requestFileAccessOpening(d.copyId,{sessionId:t,clientPublicKey:c,...r.delivery==="REVEAL"?{delivery:"REVEAL"}:{}});r.delivery==="REVEAL"&&r.onPairingCode?.(p.slice(0,12));let f=Math.min(Date.parse(m.expiresAt),Date.now()+3e5);if(!Number.isFinite(f))throw new Error("file_opening_expired");let w;for(;!n?.aborted&&Date.now()<f;){let O=await e.readFileAccessOpening(d.copyId,t,p,n);if(O.status==="READY"&&O.encryptedFileKey){w=O.encryptedFileKey;break}if(O.status==="EXPIRED"||O.status==="DELIVERY_CONFIRMED")throw new Error("file_opening_expired");o(),await new Promise(A=>{let N=()=>{clearTimeout(R),n?.removeEventListener("abort",N),A()},R=setTimeout(N,1e3);n?.addEventListener("abort",N,{once:!0})})}if(o(),!w)throw new Error("file_opening_expired");s=await Vt(w,l),o(),await e.confirmFileAccessDelivery(d.copyId,t,p);let g=await Gt(i,s,d);a=g.plaintext,o();let b={plaintext:a,header:g.header};return a=void 0,b}finally{i.fill(0),s?.fill(0),a?.fill(0)}}import{createHash as li,webcrypto as pi}from"node:crypto";import{canonicalInboxManifest as ui,decodeInboxManifest as mi,decodeInboxContentFrame as gi,decodeInboxText as hi,decryptInboxShare as Ii,encodeInboxContentFrame as Wt,encodeInboxText as yi,encryptInboxShare as Hn,inboxProtectedUnitCommitment as fi,inboxTextMetadataDigest as Wn,openInboxContent as bi,sealInboxContent as vi,signInboxFrame as Pi,unwrapInboxContentKey as wi,unwrapInboxShareKey as Si,verifyInboxFrame as jn,wrapInboxContentKey as Ei,wrapInboxShareKey as xi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as Ai}from"@safetech/inheriti-core-sdk/workers/inbox.node";var X=pi,k=X,T=r=>{if(!/^[0-9a-fA-F]{64}$/.test(r))throw new Error("invalid_inbox_key");return Buffer.from(r,"hex")},I=r=>{let e=Buffer.from(r,"base64");if(!r||e.toString("base64")!==r)throw new Error("invalid_inbox_base64");return Uint8Array.from(e)},W=(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),ht=async r=>new Uint8Array(await k.subtle.digest("SHA-256",Uint8Array.from(r))),Ke=r=>li("sha256").update(r).digest("hex"),le=class{constructor(e,t=new Ai){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=ui(i),a=await ht(s),{contentKey:o,frame:d}=await vi(yi(e.text),a,k),c=await this.signFrame(i,d,e.identity.signingPrivateKey,n.signingPublicKey),{shareKey:l,shares:p}=await this.protectShares(t,d,a),m=await this.wrapRecipientKeys(t,o,a),f=await xi(l,T(e.tenantKeyHex),a,i.tenantId,i.messageId,k);return{frame:Buffer.from(Wt(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(f).toString("base64"),recipients:m,shares:p}}}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&&!W(t,await fi(a,Wt(c),I(n.signature),k)))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 V&&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||Ke(I(n.signingPublicKey))!==n.signingKeyFingerprint||Ke(I(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:T(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(s=>({memberId:s.memberId,deviceId:s.deviceId,encryptionKeyFingerprint:T(s.encryptionKeyFingerprint)})),expiresAtEpochMs:i,metadataDigest:await Wn(k)}}async signFrame(e,t,n,i){let s=await k.subtle.importKey("pkcs8",I(n),"Ed25519",!1,["sign"]),a=await Pi(e,t,s,k),o=await k.subtle.importKey("spki",I(i),"Ed25519",!1,["verify"]);if(!await jn(e,t,a,o,k))throw new Error("inbox_identity_mismatch");return a}async protectShares(e,t,n){let i=await this.worker.split(Wt(t),{threshold:e.threshold,total:e.total,messageId:e.messageId,manifestDigest:n}),s=k.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 Hn(i.dataShares[o],s,n,e.messageId,k)).toString("base64")}),a.push({kind:"KEY",index:o,shareId:d.keyShareId,layerId:d.id,ciphertext:Buffer.from(await Hn(i.keyShares[o],s,n,e.messageId,k)).toString("base64")})}return{shareKey:s,shares:a}}async wrapRecipientKeys(e,t,n){return Promise.all(e.recipients.map(async i=>{let s=I(i.encryptionPublicKey);if(Ke(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await k.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 Ei(t,a,n,k)).toString("base64")}}))}async verifyOpening(e,t,n){let i=I(t.canonicalManifest),s=mi(i);if(s.tenantId!==e.identity.tenantId||s.conversationId!==e.conversationId||s.messageId!==e.messageId||s.expiresAtEpochMs<=Date.now()||!W(s.metadataDigest,n??await Wn(k)))throw new Error("inbox_manifest_mismatch");let a=s.recipients.find(d=>d.memberId===e.identity.memberId&&d.deviceId===e.identity.deviceId);if(!a||!W(a.encryptionKeyFingerprint,T(Ke(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let o=I(t.senderSigningPublicKey);if(t.senderSigningKeyFingerprint!==Ke(o)||!W(s.senderSigningKeyFingerprint,T(t.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return{manifest:s,manifestDigest:await ht(i),senderPublicDer:o}}async recoverFrame(e,t,n,i){let s=await Si(I(e.tenantWrappedShareKey),T(i),n,t.tenantId,t.messageId,k),a=[],o=[],d=new Set;for(let l of e.shares){let p=`${l.kind}:${l.index}`;if(d.has(p))throw new Error("duplicate_inbox_share");d.add(p);let m=await Ii(I(l.ciphertext),s,n,t.messageId,l.kind==="DATA"?"data":"key",l.index,k);(l.kind==="DATA"?a:o).push(m)}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 gi(c)}async decryptText(e,t,n,i,s,a){return hi(await this.decryptContent(e,t,n,i,s,a))}async decryptContent(e,t,n,i,s,a){let o=await k.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await jn(n,t,I(e.signature),o,k))throw new Error("inbox_signature_invalid");let d=await k.subtle.importKey("pkcs8",I(a),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await wi(I(e.wrappedContentKey),d,i,k);return bi(t,c,i,k)}};import{canonicalInboxManifest as Ri,decodeInboxContentFrame as _i,decodeInboxFile as Ci,decryptInboxShare as Ti,encodeInboxContentFrame as Oi,encodeInboxFile as ki,encryptInboxShare as Qn,inboxFileMetadataDigest as Yn,sealInboxContent as Mi,unwrapInboxShareKey as Di,wrapInboxShareKey as Ni}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var It=class extends le{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=Ri(s),o=await ht(a),d=ki(t.file),c;try{c=await Mi(d,o,X)}finally{d.fill(0)}let{contentKey:l,frame:p}=c,m=await this.signFrame(s,p,t.identity.signingPrivateKey,i.signingPublicKey);t.signal?.throwIfAborted();let f=await this.worker.split(Oi(p),{threshold:n.threshold,total:n.total,messageId:n.messageId,manifestDigest:o},t.signal,R=>t.onProgress?.(0,n.total*2,R.stage));t.signal?.throwIfAborted();let w=X.getRandomValues(new Uint8Array(32)),g=[];for(let R=0;R<n.total;R++){let J=n.shareLayers[R];g.push({reference:{kind:"DATA",index:R,shareId:J.dataShareId,layerId:J.id},bytes:await Qn(f.dataShares[R],w,o,n.messageId,X)}),g.push({reference:{kind:"KEY",index:R,shareId:J.keyShareId,layerId:J.id},bytes:await Qn(f.keyShares[R],w,o,n.messageId,X)})}let b=await this.wrapRecipientKeys(n,l,o),O=await Ni(w,T(t.tenantKeyHex),o,s.tenantId,s.messageId,X);t.signal?.throwIfAborted();let A=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(m).toString("base64"),tenantWrappedShareKey:Buffer.from(O).toString("base64"),recipients:b,shares:g.map(R=>R.reference)},t.signal);if(A.messageId!==n.messageId||A.status!=="PREPARING")throw new Error("invalid_inbox_stage");for(let R=0;R<g.length;R++){t.signal?.throwIfAborted();let J=g[R];await this.fileApi.uploadInboxFileShare(t.conversationId,n.messageId,J.reference.shareId,J.bytes,t.signal),t.onProgress?.(R+1,g.length,"UPLOADING")}t.signal?.throwIfAborted();let N=await this.fileApi.publishInboxFile(t.conversationId,n.messageId,t.signal);if(N.messageId!==n.messageId||N.status!=="AVAILABLE")throw new Error("invalid_inbox_publish");return N}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 Yn(X)),l=await this.recoverFileFrame(t,n,o,d);s=await this.decryptContent(n,l,o,d,c,t.identity.encryptionPrivateKey),i=Ci(s),t.signal?.throwIfAborted(),await t.save(i,{leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt}),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:T(i.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(a=>({memberId:a.memberId,deviceId:a.deviceId,encryptionKeyFingerprint:T(a.encryptionKeyFingerprint)})),expiresAtEpochMs:s,metadataDigest:await Yn(X)}}async recoverFileFrame(t,n,i,s){let a=await Di(I(n.tenantWrappedShareKey),T(t.tenantKeyHex),s,i.tenantId,i.messageId,X),o=[],d=[],c=new Set;for(let p=0;p<n.shares.length;p++){t.signal?.throwIfAborted();let m=n.shares[p],f=`${m.kind}:${m.index}`;if(c.has(f))throw new Error("duplicate_inbox_share");c.add(f);let w=await this.fileApi.downloadInboxFileShare(t.conversationId,t.messageId,m.shareId,t.identity.deviceId,n.leaseId,t.signal),g=await Ti(w,a,s,i.messageId,m.kind==="DATA"?"data":"key",m.index,X);(m.kind==="DATA"?o:d).push(g),t.onProgress?.(p+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,p=>t.onProgress?.(n.shares.length,n.shares.length,p.stage));return t.signal?.throwIfAborted(),_i(l)}};import{createHash as Jn,webcrypto as Ki}from"node:crypto";import{canonicalInboxParentManifest as Ui,decodeInboxParentManifest as Li,encodeInboxParentNormalFrame as Fi,decodeInboxParentNormalFrame as qi,sealInboxParentNormalBody as zi,openInboxParentNormalBody as Gi,wrapInboxParentNormalKey as Bi,unwrapInboxParentNormalKey as Vi,signInboxParentNormalFrame as $i,verifyInboxParentNormalFrame as Xn,encodeInboxText as Hi,decodeInboxText as Wi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var j=Ki,Ue=r=>Jn("sha256").update(r).digest("hex"),yt=r=>Buffer.from(r).toString("base64"),ft=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 Jn("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||Ue(I(n.signingPublicKey))!==n.signingKeyFingerprint||Ue(I(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:T(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,encryptionKeyFingerprint:T(i.encryptionKeyFingerprint)})),protectedUnits:[]}}async createSubmission(e,t,n,i){let s=Ui(i),{contentKey:a,frame:o}=await zi(Hi(e.text),i,j),d=await j.subtle.importKey("pkcs8",I(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),c=await $i(i,o,d,j),l=await j.subtle.importKey("spki",I(n.signingPublicKey),"Ed25519",!1,["verify"]);if(!await Xn(i,o,c,l,j))throw new Error("inbox_identity_mismatch");let p=await Promise.all(t.recipients.map(m=>this.wrapRecipientKey(m,a,i)));return{parentId:i.parentId,idempotencyKey:i.parentId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,canonicalManifest:yt(s),frame:yt(Fi(o)),signature:yt(c),recipients:p}}async wrapRecipientKey(e,t,n){let i=I(e.encryptionPublicKey);if(Ue(i)!==e.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await j.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:yt(await Bi(t,s,n,j))}}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=Li(I(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(p=>p.memberId===e.identity.memberId&&p.deviceId===e.identity.deviceId);if(!i||!W(i.encryptionKeyFingerprint,T(Ue(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let s=I(t.senderSigningPublicKey);if(!W(n.senderSigningKeyFingerprint,T(Ue(s))))throw new Error("inbox_sender_key_mismatch");let a=qi(I(t.frame)),o=await j.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Xn(n,a,I(t.signature),o,j))throw new Error("inbox_signature_invalid");let d=await j.subtle.importKey("pkcs8",I(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await Vi(I(t.wrappedContentKey),d,n,j),l=Wi(await Gi(a,c,n,j));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 tr,webcrypto as ji}from"node:crypto";import{canonicalInboxParentManifest as Qi,decodeInboxParentManifest as Yi,decodeInboxManifest as Xi,encodeInboxParentNormalFrame as Ji,decodeInboxParentNormalFrame as Zi,sealInboxParentNormalBody as es,openInboxParentNormalBody as ts,wrapInboxParentNormalKey as ns,unwrapInboxParentNormalKey as rs,signInboxParentNormalFrame as is,verifyInboxParentNormalFrame as Zn,signInboxProtectedParent as ss,verifyInboxProtectedParent as er,inboxProtectedUnitCommitment as as,encodeInboxText as os,decodeInboxText as ds}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var q=ji,bt=r=>Buffer.from(r).toString("base64"),Le=r=>tr("sha256").update(r).digest("hex"),vt=class{constructor(e,t){this.api=e;this.child=t??new le(e)}pending=new Map;child;async send(e){let t=tr("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(f=>"protectedText"in f).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(f=>"text"in f))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:p,recipients:m}=await this.signAndWrap(e,i,s,c);return{parentId:a,idempotencyKey:a,senderDeviceId:s.deviceId,mode:n,participantRevision:i.participantRevision,canonicalManifest:bt(Qi(c)),signature:bt(p),frame:l,recipients:m,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=Xi(I(c.submission.canonicalManifest));this.validateChildSnapshot(l,e,t,n);let p=await as(l,I(c.frame),I(c.submission.signature),q);i.push({position:o,frame:c.frame,child:c.submission}),s.push({unitId:c.submission.messageId,position:o,commitment:p});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&&W(s.encryptionKeyFingerprint,T(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:T(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(o=>({memberId:o.memberId,deviceId:o.deviceId,encryptionKeyFingerprint:T(o.encryptionKeyFingerprint)})),protectedUnits:a}}async signAndWrap(e,t,n,i){let s=await q.subtle.importKey("pkcs8",I(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),a=await q.subtle.importKey("spki",I(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 ss(e,t,q);if(!await er(e,i,n,q))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 es(os(JSON.stringify(s)),t,q),o=await is(t,a.frame,n,q);if(!await Zn(t,a.frame,o,i,q))throw new Error("inbox_identity_mismatch");return{frame:bt(Ji(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=I(i.encryptionPublicKey);if(Le(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await q.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:bt(await ns(t,a,n,q))}}))}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||Le(I(n.signingPublicKey))!==n.signingKeyFingerprint||Le(I(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=Yi(I(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||!W(n.commitment,T(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||!W(n.encryptionKeyFingerprint,T(Le(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch")}async senderKey(e,t){let n=I(e.senderSigningPublicKey);if(Le(n)!==e.senderSigningKeyFingerprint||!W(t.senderSigningKeyFingerprint,T(e.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return q.subtle.importKey("spki",n,"Ed25519",!1,["verify"])}async openProtectedParent(e,t,n){if(e.frame!==null||e.wrappedContentKey!==null||!await er(t,I(e.signature),n,q))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=Zi(I(t.frame));if(!await Zn(n,s,I(t.signature),i,q))throw new Error("inbox_signature_invalid");let a=await q.subtle.importKey("pkcs8",I(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=await rs(I(t.wrappedContentKey),a,n,q),d=JSON.parse(ds(await ts(s,o,n,q)));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{be as BusinessOrganizationSelectionError,Me as CorePlanMaterialBuilder,Vo as DataAssetDefinitionService,V as ElementsApiRequestFailed,me as ElementsClient,Re as GuidedCreateRecoveryError,Ae as GuidedPlanCreator,Te as HttpAutomationRevealApiPort,ye as HttpElementsApiPort,Fn as HttpOperatorAuthTransport,it as HttpPlanEditPort,Oe as HttpQuickPlanPort,Jr as InheritiFileInvalid,S as InvalidPlanDeclaration,U as InvalidPlanMaterial,Bt as MAX_INHERITI_FILE_BYTES,ze as MasterKeyRelayCancellationFailed,qe as MasterKeyRelayExpired,Fe as MasterKeyRelayTimedOut,te as MasterKeyRequired,xe as MemoryGuidedCreateCheckpointStore,Se as MemoryKeyVault,Ee as MemoryStatePort,It as NodeInboxFile,ft as NodeInboxNormal,vt as NodeInboxParent,le as NodeInboxText,v as OAuthProtocolError,Gn as OperatorAuthClient,Ne as OperatorAuthError,G as OperatorReauthenticationRequired,Vn as OperatorSessionController,xt as PLAN_CREATION_SERVER_STAGES,Yo as PassphraseMasterKeySource,nd as PlanAssetDeclaration,de as PlanRequestFailed,De as QuickPlanCreator,ot as QuickPlanEditor,Xo as RawMasterKeySource,Q as RelayMasterKeySource,wt as StaticMasterKeyResolver,ut as SystemOAuthClock,pt as WebOAuthCrypto,ed as computePassphraseVerifier,Ge as createMasterKeyResolver,Xr as createNodeAutomationRevealClient,Ao as createNodeElementsClient,Ro as createNodeQuickPlanCreator,_o as createNodeQuickPlanEditor,ai as decodeAssetContainer,Jo as deriveMasterKey,Zr as exportProtectedRevealAsset,Zo as generateHexSeed,dt as generateInheritiFileKey,$n as inspectInheritiFileAccess,we as masterKeyRefFor,ie as masterKeyRefKey,mt as oauthErrorCode,Gt as openInheritiFile,ci as openInheritiFileAccess,Vt as openInheritiFileKey,zt as readInheritiFileHeader,ct as sealInheritiFile,lt as sealInheritiFileKey,Nr as selectBusinessOrganization,Nt as unwrapDekWithMasterKey,ae as validateOperationContext,se as validatePlanCreationInput,ue as validatePlanCreationMaterial};
|
|
1
|
+
import{createNodeSharedConfigurationSdk as Ht,decodeAssetContainer as ai}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as nr,generateRSAOAEPKeyPair as rr}from"@safetech/inheriti-core-sdk/crypto";var Fe=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},qe=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},ze=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},Q=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 rr();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??(g=>new Promise(b=>setTimeout(b,g))),c=!0,l=!1,p,m=()=>p??=(async()=>{let g=new AbortController,b,O=new Promise((A,N)=>{b=setTimeout(()=>{g.abort(),N(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,g.signal),O])}finally{clearTimeout(b)}})(),f,w=new Promise((g,b)=>{f=()=>{c&&m().catch(()=>{}),b(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",f,{once:!0})});w.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 g=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),w]);if(g.status!=="PENDING"&&(c=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(g.status==="DELIVERED"&&g.sealedMasterKey){let b=(await nr(g.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(b))throw new Error("invalid_master_key_material");return b}if(g.status==="EXPIRED")throw new qe(s.sessionId);await ir(d,a,e)}throw new Fe(s.sessionId)}catch(g){if(c&&(!l||e?.aborted))try{await m()}catch(b){if(e?.aborted)throw new ze(b)}throw g}finally{f&&e?.removeEventListener("abort",f)}}};async function ir(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 Ge(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||Pt(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}if(sr(e,r.applicationId)){let i=await r.source?.resolve();return i||Pt(r,()=>r.api.masterKeyAcquisition(),void 0,t,n)}return Pt(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,n)}}}function sr(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Pt(r,e,t,n,i){if((await e()).relayAvailable)return new Q({...r.relay,api:ar(r.api,t)}).resolve(n,i)}function ar(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 ie(r){return`${r.system}:${r.contextId}`}function we(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var te=class extends Error{constructor(t){super(`master_key_required:${ie(t)}`);this.ref=t;this.name="MasterKeyRequired"}},wt=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(ie(e),t),this}async resolve(e){return this.sources.get(ie(e))?.resolve()}};var Se=class{keys=new Map;async store(e,t){let n=ie(e),i=t.slice();this.keys.get(n)?.fill(0),this.keys.set(n,i)}async load(e){return this.keys.get(ie(e))?.slice()}async remove(e){let t=ie(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var Ee=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 Be=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},h=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var Ve=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var $e=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],Et={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","ipSource","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"]},xt=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],S=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},U=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function ue(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new U("plan_material_field_unknown");if(St(r.dataShards,"data_shards_invalid"),St(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&St(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new U("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new U("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new U("material_operation_invalid")}function St(r,e){if(!Array.isArray(r))throw new U(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new U(e);if(t.data!==void 0&&typeof t.data!="string")throw new U(e)}}function se(r){if(pe(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!cr(r.idempotencyKey))throw new S("idempotency_key_invalid");if(!r.name?.trim())throw new S("plan_name_required");if(!r.assets.length)throw new S("assets_required");let e=new Set;for(let t of r.assets){if(pe(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 S("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!$e.includes(t.type))throw new S("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new S("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 S("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new S("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new S("asset_field_names_invalid");if(or(t.matchOrigins),!t.isBinary){let s=Et[t.type];if(!s||i.some(a=>!s.includes(a)))throw new S("asset_field_name_not_canonical")}}if(!r.participants.length)throw new S("participants_required");for(let t of r.participants){if(pe(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Qt(t.routingEmail))throw new S("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new S("participant_relationships_invalid")}dr(r)}function or(r){if(r===void 0)return;if(!r.length)throw new S("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new S("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new S("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof S?n:new S("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new S("asset_match_origins_duplicated")}function dr(r){let e=r.policy;if(e&&pe(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new S("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){pe(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new S("authentication_mode_invalid")}if(e.moderation){pe(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new S("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new S("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new S("approval_mode_invalid")}let t=e.dms;if(!t)return;pe(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!Qt(t.subjectEmail))throw new S("dms_subject_invalid");if(!r.participants.some(s=>jt(s.routingEmail)===jt(t.subjectEmail)))throw new S("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 S("dms_countdown_invalid")}function cr(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 Qt(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function jt(r){return r.normalize("NFC").trim().toLowerCase()}function pe(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new S(t)}var xe=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)}},Ae=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),se(e),He(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={}){se(t);let a=await this.checkpoints.load(e);if(!a)throw new Re("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await Yt(t))throw new Re("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;He(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:s.signal});He(s.signal),s.onProgress?.("GENERATING_SHARES");let c=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});He(s.signal),ue(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 Yt(e),serverStage:t.stage})}},Re=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Yt(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 He(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Xt(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new Be(n.stage);return r.authorizeRevealAction(e,t)}function lr(r){let e=r?.status;return e===400||e===401||e===403}async function Jt(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(s){if(!lr(s))throw s}return r.releaseRevealMaterial(e,t)}var At={reason:500,commitSha:64,workflow:200,pipeline:300,target:200,image:300,version:100};function ae(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("operation_context_invalid");let e=r;for(let n of Object.keys(e))if(!Object.hasOwn(At,n))throw new Error("operation_context_invalid");let t={};for(let n of Object.keys(At)){if(!Object.hasOwn(e,n))continue;let i=e[n];if(typeof i!="string"||!i.trim()||i.length>At[n]||/[\x00-\x1f\x7f-\x9f]/.test(i)||n==="commitSha"&&(i.length<7||!/^[0-9a-fA-F]+$/.test(i)))throw new Error("operation_context_invalid");t[n]=i.trim()}return t}function pr(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"?mr(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":ur.has(r.stage)?"ENDED":"CONTINUING"}var ur=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function mr(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 Rt=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},M=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Qe(r,e,t={},n=!1){let i=t.operationContext===void 0?void 0:ae(t.operationContext);if(i!==void 0&&!n)throw new Error("operation_context_automation_only");if(t.signal?.aborted)throw x();let s=await r.getPlan(e),a=await r.getActivePlanReveal(e);if(a)throw a.planId!==e||a.mode!==(t.mode??"DIRECT")||a.protectedCopy!==void 0&&a.protectedCopy!==(t.protectedCopy??!1)?Object.assign(new Error("merge_process_already_active"),{code:"merge_process_already_active"}):Zt(a.id);if(t.signal?.aborted)throw x();let o=()=>r.prepareReveal(e,t.signal,async p=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(p)});if(n||await o(),t.signal?.aborted)throw x();let d=t.idempotencyKey??crypto.randomUUID(),c;try{c=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:d,...t.protectedCopy?{protectedCopy:!0}:{},...i!==void 0?{operationContext:i}:{}})}catch(p){if(p?.code!=="merge_process_already_active")throw p;let m=await r.getActivePlanReveal(e);throw!m||m.planId!==e||m.mode!==(t.mode??"DIRECT")||m.protectedCopy!==void 0&&m.protectedCopy!==(t.protectedCopy??!1)?p:Zt(m.id)}if(c.protectedCopy!==void 0&&c.protectedCopy!==(t.protectedCopy??!1))throw await r.closeReveal(c.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let l;try{if(t.signal?.aborted)throw x();let p=await hr(r,c,t);if(t.signal?.aborted||(n&&await o(),t.signal?.aborted)||(oe(t,"RELEASING_MATERIAL",p),t.signal?.aborted))throw x();let m=await r.releaseRevealMaterial(p.id,p.materialVersion??"1");if(t.signal?.aborted||(p.mode==="GOVERNED"&&await r.markRevealSharesCollected(p.id),t.signal?.aborted))throw x();let f;try{f=await br(r,p,Pr(m),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(oe(t,"RECONSTRUCTING",p),t.signal?.aborted))throw x();try{l=await r.reconstructPlanMaterial(f)}catch(g){throw t.signal?.aborted?x():(await r.reportRevealReconstruction(p.id,{status:"FAILED",errorCode:fr(g)}),g)}if(t.signal?.aborted)throw x();let w=await r.reportRevealReconstruction(p.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(oe(t,"OPEN",w),t.signal?.aborted))throw x();return new Ct(r,w,s,l,t.signal)}catch(p){throw l?.fill(0),await nn(r,c.id,t.signal?.aborted?"CANCELED":"ERROR"),p}}function Zt(r){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:r})}var gr=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function hr(r,e,t){let n=await ne(()=>r.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw x();if(t.onSession?.(n),t.onProgress?.({phase:pr(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(gr.has(n.stage))throw new _t(n.stage);await Tt(t.pollIntervalMs??1500,t.signal),n=await ne(()=>r.getReveal(e.id,t.signal),t.signal)}}var _t=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function oe(r,e,t){r.onProgress?.({phase:e,session:t})}function Tt(r,e){return e?.aborted?Promise.reject(x()):new Promise((t,n)=>{let i=setTimeout(a,Math.max(0,r)),s=()=>{clearTimeout(i),n(x())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var Ct=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 Rt;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 M("asset_selector_invalid");if(!this.client.assetDecoder)throw new M("asset_decoder_required");let n=e.map(({selector:s,options:a={}})=>{let o=Ir(s),d=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!d)throw new M("asset_not_found");if(d.isBinary)throw new M("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new M("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 M("asset_value_invalid");return{selector:a.selector,value:yr(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",en(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new M("asset_selector_invalid");if(!this.client.assetDecoder)throw new M("asset_decoder_required");let n=this.plan.assets.find(a=>a.code===e||a.id===e);if(!n)throw new M("asset_not_found");if(!n.isBinary)throw new M("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 M("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",en(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=nn(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 Ir(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new M("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new M("asset_selector_invalid");return{asset:r.asset,field:r.field}}function yr(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new M("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new M("asset_value_invalid");if(!(e in n)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?Et[t]:void 0)?.includes(e))return"";throw new M("asset_value_invalid")}return n[e]}function en(r){if(r instanceof M)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 fr(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function br(r,e,t,n){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await ne(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!n.proDevice)throw new We;let c=await ne(()=>r.getRevealCustodianClaimable(e.id,n.signal),n.signal);if(tn(c,i.id,e.planId),!c.shares.includes(i.data))throw new Z;oe(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:l}=await ne(()=>n.proDevice.write(c,n.signal),n.signal);if(n.signal?.aborted)throw x();if(!l?.trim())throw new Z;if(await r.claimRevealCustodianShare(e.id,c.id,l),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,c.id),n.signal?.aborted))throw x();return{...t,shares:t.shares.filter(p=>p!==i).concat(c.shares.map((p,m)=>({id:`${c.id}:${m}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:p})))}}if(d!=="SK_MOBILE")throw new Z;if(n.signal?.aborted)throw x();return await r.distributeRevealCustodianShare(e.id),oe(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await ne(()=>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),oe(n,"WAITING_FOR_CUSTODIAN_CLAIM",d),await Tt(n.pollIntervalMs??1500,n.signal),s=await ne(()=>r.getRevealCustodianAccess(e.id,n.signal),n.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!n.proDevice)throw new We;if(!s.shareId||!s.deviceId)throw new Z;oe(n,"CONNECTING_SAFEKEY_PRO",e);let d=await ne(()=>n.proDevice.read({shareId:s.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw x();if(tn(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new Z;if(await r.collectRevealCustodianShare(e.id,s.shareId),n.signal?.aborted)throw x();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 Z;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(n.onSession?.(a),oe(n,"WAITING_FOR_CUSTODIAN",a),n.signal?.aborted)throw x();await r.requestRevealCustodianRelease(e.id);let o=await vr(r,e,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 tn(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 Z}async function ne(r,e){if(e?.aborted)throw x();if(!e)return r();let t,n=new Promise((i,s)=>{t=()=>s(x()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw x();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function vr(r,e,t){let n=Date.parse(e.expiresAt),i=Number.isFinite(n)?Math.min(n,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new je;let s=await ne(()=>r.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new je;if(s&&s.status!=="PENDING"){let a=s;if(a.shares?.length)return a;throw new Z}await Tt(t.pollIntervalMs??1500,t.signal)}}var Z=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},We=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},je=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Pr(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function nn(r,e,t){if(t!=="CANCELED"){try{await r.closeReveal(e,t)}catch(a){if(!wr(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 wr(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function x(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var me=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 Se,this.state=t.state??new Ee,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??xr(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 h;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new h;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new h;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new h;return this.api.listMemberLogs(e,t)}listOrganizationMembers(e){if(!this.api)throw new h;return this.api.listOrganizationMembers(e)}listOrganizationAuditTrail(e){if(!this.api)throw new h;return this.api.listOrganizationAuditTrail(e)}getOrganizationInsights(e){if(!this.api)throw new h;return this.api.getOrganizationInsights(e)}getPlanResponsibilities(e){if(!this.api)throw new h;return this.api.getPlanResponsibilities(e)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return se(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new h;return ue(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new h;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new xe){if(this.requireApplication(),!this.api)throw new h;return new Ae(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 te({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 te(e);return await this.keyVault.store(e,Sr(s)),s}async prepareReveal(e,t,n){if(!this.api)throw new h;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 h;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new Ve;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 te({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=we(e);if(!i)throw new te({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,n)}initializeGovernedReveal(e,t){if(!this.api)throw new h;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new h;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new h;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,n){if(!this.api)throw new h;return this.api.createRevealFileAccess(e,t,n)}cancelRevealFileAccess(e,t,n){if(!this.api)throw new h;return this.api.cancelRevealFileAccess(e,t,n)}getActivePlanReveal(e){if(!this.api)throw new h;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new h;return this.api.getReveal(e,t)}openReveal(e,t){return Qe(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 h;return Jt(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new h;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new h;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new h;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new h;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new h;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new h;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new h;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,n){if(!this.api)throw new h;return this.api.closeReveal(e,t,n)}abortPlanAccess(e,t){if(!this.api)throw new h;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new h;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new h;return Xt(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new h;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new h;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new h;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new h;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new h;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new h;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 h;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 Ot;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new te({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},Ot=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Sr(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 xr(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 Ge({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return Ge({...e,organizationId:r.organizationId})}var Ar=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Rr=["DIRECT","GOVERNED"],sn=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],_r=["ACTIVE","REVOKED"],Cr=["SK_MOBILE"],Tr=["ACTIVE","INACTIVE"],Or=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function an(r){let e=D(r);return{items:$(e.items).map(cn),nextCursor:e.nextCursor===null?null:y(e.nextCursor,"nextCursor")}}function on(r){let e=D(r);return{total:Y(e.total,"total"),items:$(e.items).map(t=>{let n=D(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:y(n.id,"log.id"),planId:y(n.planId,"log.planId"),tenantId:y(n.tenantId,"log.tenantId"),event:y(n.event,"log.event"),occurredOn:y(n.occurredOn,"log.occurredOn"),status:re(n.status),title:y(n.title,"log.title"),details:$(n.details).map(i=>{let s=D(i);return{label:y(s.label,"log.detail.label"),value:y(s.value,"log.detail.value")}})}})}}function dn(r){let e=D(r);return{total:Y(e.total,"total"),items:$(e.items).map(t=>{let n=D(t);if("eventData"in n)throw new Error("invalid_elements_response");let i=y(n.source,"log.source");if(i!=="MEMBER"&&i!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:y(n.id,"log.id"),memberId:y(n.memberId,"log.memberId"),source:i,event:y(n.event,"log.event"),occurredOn:y(n.occurredOn,"log.occurredOn"),status:re(n.status)}})}}function Ye(r){let e=D(r),t=cn(e),n=D(e.source),i=y(n.kind,"source.kind");return{...t,assets:$(e.assets).map(s=>{let a=D(s);return{id:y(a.id,"asset.id"),code:re(a.code),type:B(y(a.type,"asset.type"),$e),name:y(a.name,"asset.name"),isBinary:Mr(a.isBinary,"asset.isBinary"),fieldNames:$(a.fieldNames).map(o=>y(o,"asset.fieldNames")),fileName:re(a.fileName),mimeType:re(a.mimeType),size:a.size===void 0||a.size===null?void 0:Y(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:$(a.matchOrigins).map(o=>y(o,"asset.matchOrigins"))}}),participants:$(e.participants).map(s=>{let a=D(s);return{id:y(a.id,"participant.id"),displayName:y(a.displayName,"participant.displayName"),relationships:$(a.relationships).map(o=>B(y(o,"relationship"),sn)),lifecycle:B(y(a.lifecycle,"participant.lifecycle"),_r)}}),revealPolicy:(()=>{let s=D(e.revealPolicy);return{masterKeyRelease:B(y(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:B(y(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=D(e.dms);return{subjectEmail:y(s.subjectEmail,"dms.subjectEmail"),countdownDays:Y(s.countdownDays,"dms.countdownDays"),countdownHours:Y(s.countdownHours,"dms.countdownHours"),countdownMinutes:Y(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:B(y(n.system,"source.system"),["INHERITI_BUSINESS"]),status:B(y(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function _e(r){let e=D(r);return{operationId:y(e.operationId,"operationId"),stage:B(y(e.stage,"stage"),xt),outcome:B(y(e.outcome,"outcome"),Or),planId:re(e.planId),lastErrorCode:re(e.lastErrorCode),participants:e.participants===void 0?void 0:$(e.participants).map(t=>{let n=D(t);return{clientParticipantRef:y(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:y(n.planParticipantId,"planParticipantId"),relationships:$(n.relationships).map(i=>kr(y(i,"relationship"),sn))}})}}function cn(r){let e=D(r),t=D(e.assetSummary),n=D(e.governance),i=D(e.participantSummary);return{id:y(e.id,"id"),name:y(e.name,"name"),description:re(e.description),status:B(y(e.status,"status"),Ar),createdAt:y(e.createdAt,"createdAt"),configuredAt:re(e.configuredAt),assetSummary:{count:Y(t.count,"assetSummary.count"),types:$(t.types).map(s=>B(y(s,"assetType"),$e)),names:rn(t.names).map(s=>y(s,"assetSummary.names"))},governance:{mode:B(y(n.mode,"governance.mode"),Rr),minimumApprovals:Y(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:Y(i.owners,"owners"),mergers:Y(i.mergers,"mergers"),moderators:Y(i.moderators,"moderators")},authentication:rn(e.authentication).map(s=>{let a=D(s);return{id:B(y(a.id,"authentication.id"),Cr),status:B(y(a.status,"authentication.status"),Tr)}})}}function B(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function kr(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function D(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function rn(r){return r==null?[]:$(r)}function $(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function y(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function re(r){return r==null?void 0:y(r,"optional")}function Y(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function Mr(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}function H(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function ge(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function _(r){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function kt(r){return r==null?void 0:_(r)}function K(r){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function Dr(r){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}function ln(r){let e=H(r);return{total:K(e.total),items:ge(e.items).map(t=>{let n=H(t);return{id:_(n.id),displayName:_(n.displayName),role:_(n.role),status:_(n.status)}})}}function pn(r){let e=H(r);return{total:K(e.total),shownCount:K(e.shownCount),totalCount:K(e.totalCount),nextCursor:e.nextCursor==null?null:_(e.nextCursor),hasMore:Dr(e.hasMore),items:ge(e.items).map(t=>{let n=H(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:_(n.id),occurredOn:_(n.occurredOn),actorName:_(n.actorName),actorRole:_(n.actorRole),category:_(n.category),action:_(n.action),subject:_(n.subject),status:_(n.status),sourceEvent:_(n.sourceEvent),planId:kt(n.planId),planName:kt(n.planName),responsibleMemberName:kt(n.responsibleMemberName)}})}}function un(r){let e=H(r),t=H(e.stats),n=H(e.planAccessResults);return{stats:{totalPlans:K(t.totalPlans),plansCreatedThisMonth:K(t.plansCreatedThisMonth),activeMembers:K(t.activeMembers),totalSeats:t.totalSeats==null?null:K(t.totalSeats),accessRequests30d:K(t.accessRequests30d),accessRequestsPrevious30d:K(t.accessRequestsPrevious30d),pendingApprovals:K(t.pendingApprovals)},plansOverTime:ge(e.plansOverTime).map(i=>{let s=H(i);return{month:_(s.month),count:K(s.count)}}),planTypes:ge(e.planTypes).map(i=>{let s=H(i);return{type:_(s.type),count:K(s.count)}}),accessModerationActivity:ge(e.accessModerationActivity).map(i=>{let s=H(i);return{week:_(s.week),requests:K(s.requests),approvals:K(s.approvals)}}),planAccessResults:{success:K(n.success),aborted:K(n.aborted),expired:K(n.expired)}}}function mn(r){let e=H(r);return{planId:_(e.planId),participants:ge(e.participants).map(t=>{let n=H(t);return{id:_(n.id),displayName:_(n.displayName),relationships:ge(n.relationships).map(i=>_(i)),lifecycle:_(n.lifecycle)}})}}function Xe(r,e){if(Object.keys(r).some(t=>!e.includes(t)))throw new Error("organization_query_field_unknown")}var be=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function gn(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 Nr(r,e){if(!e){if(r.length===0)throw new be("organization_required");if(r.length>1)throw new be("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new be("organization_access_denied");return e}function Kr(r){let e=E(r);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:P(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:P(e.participantRevision,1),createdAt:z(e.createdAt),...hn(e)}}function hn(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=E(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:u(t.memberId),...t.read!==void 0?{read:t.read}:{},...t.readAt!==void 0?{readAt:t.readAt===null?null:z(t.readAt)}:{},...Array.isArray(t.secrets)?{secrets:t.secrets.map(n=>{let i=E(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:P(i.position,0),status:i.status,...i.revealedAt!==void 0?{revealedAt:i.revealedAt===null?null:z(i.revealedAt)}:{}}})}:{}}})}}function In(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(Kr),total:P(e.total,0),limit:P(e.limit,1),offset:P(e.offset,0),unreadCount:P(e.unreadCount,0),readThroughSequence:P(e.readThroughSequence,0)}}function yn(r){let e=E(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:u(e.parentId),sequence:P(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:P(e.participantRevision,1),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(t=>{let n=E(t);return{unitId:u(n.unitId),position:P(n.position,0),commitment:u(n.commitment),status:u(n.status)}})}}function Mt(r){let e=E(r);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:u(e.parentId),sequence:P(e.sequence,1),status:e.status}}function fn(r){let e=E(r);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:u(e.conversationId),parentId:u(e.parentId),participantRevision:P(e.participantRevision,1),recipients:e.recipients.map(Dt)}}function bn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(t);return{parentId:u(n.parentId),sequence:P(n.sequence,1),senderMemberId:u(n.senderMemberId),senderDeviceId:u(n.senderDeviceId),participantRevision:P(n.participantRevision,1),createdAt:z(n.createdAt),...hn(n)}}),total:P(e.total,0),limit:P(e.limit,1),offset:P(e.offset,0),unreadCount:P(e.unreadCount,0),readThroughSequence:P(e.readThroughSequence,0)}}function vn(r){return{readThroughSequence:P(E(r).readThroughSequence,0)}}function Pn(r){return{clearedThroughSequence:P(E(r).clearedThroughSequence,0)}}function wn(r){let e=E(r);return{parentId:u(e.parentId),sequence:P(e.sequence,1),senderMemberId:u(e.senderMemberId),senderDeviceId:u(e.senderDeviceId),participantRevision:P(e.participantRevision,1),canonicalManifest:u(e.canonicalManifest),frame:u(e.frame),signature:u(e.signature),wrappedContentKey:u(e.wrappedContentKey),senderSigningPublicKey:u(e.senderSigningPublicKey)}}function E(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_inbox_response");return r}function u(r){if(typeof r!="string"||!r)throw new Error("invalid_inbox_response");return r}function z(r){let e=u(r);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function P(r,e){if(!Number.isSafeInteger(r)||r<e)throw new Error("invalid_inbox_response");return r}function Dt(r){let e=E(r);return{memberId:u(e.memberId),deviceId:u(e.deviceId),deviceVersion:P(e.deviceVersion,1),encryptionPublicKey:u(e.encryptionPublicKey),encryptionKeyFingerprint:u(e.encryptionKeyFingerprint),signingPublicKey:u(e.signingPublicKey),signingKeyFingerprint:u(e.signingKeyFingerprint)}}function ve(r){let e=E(r);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:u(e.id),tenantId:u(e.tenantId),memberId:u(e.memberId),version:e.version,encryptionPublicKey:u(e.encryptionPublicKey),encryptionKeyFingerprint:u(e.encryptionKeyFingerprint),signingPublicKey:u(e.signingPublicKey),signingKeyFingerprint:u(e.signingKeyFingerprint),status:e.status,createdAt:z(e.createdAt),updatedAt:z(e.updatedAt)}}function Je(r){let e=E(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:u(e.id),tenantId:u(e.tenantId),creatorMemberId:u(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(u),participantRevision:e.participantRevision,status:e.status,createdAt:z(e.createdAt),updatedAt:z(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=E(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:u(n.senderMemberId),createdAt:z(n.createdAt)}}return t}function Sn(r){let e=E(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(Je),total:e.total,limit:e.limit,offset:e.offset}}function En(r){let e=E(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=Dt(t);return{memberId:n.memberId,name:u(E(t).name),deviceId:n.deviceId,deviceVersion:n.deviceVersion,encryptionPublicKey:n.encryptionPublicKey,encryptionKeyFingerprint:n.encryptionKeyFingerprint,signingPublicKey:n.signingPublicKey,signingKeyFingerprint:n.signingKeyFingerprint}}),limit:P(e.limit,1),offset:P(e.offset,0),nextOffset:e.nextOffset===null?null:P(e.nextOffset,0)}}function xn(r){let e=E(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=E(t);if(typeof n.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:u(n.memberId),name:u(n.name),ready:n.ready,...n.profilePicture===void 0?{}:{profilePicture:{url:u(E(n.profilePicture).url)}}}}),limit:P(e.limit,1),offset:P(e.offset,0),nextOffset:e.nextOffset===null?null:P(e.nextOffset,0)}}function An(r){let e=E(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:u(e.conversationId),messageId:u(e.messageId),participantRevision:P(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(Dt),shareLayers:e.shareLayers.map(t=>{let n=E(t),i=u(n.id),s=u(n.dataShareId),a=u(n.keyShareId),o=u(n.type);if(o==="INHERITI_HSM")throw new Error("invalid_inbox_response");return o==="INHERITI_CHAIN"?{id:i,type:o,contractAddress:u(n.contractAddress),dataShareId:s,keyShareId:a}:{id:i,type:o,dataShareId:s,keyShareId:a}})}}function Ze(r){let e=E(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:u(e.messageId),status:e.status}}function Rn(r){let e=E(r);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(t=>{let n=E(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:u(n.id),status:n.status,senderMemberId:u(n.senderMemberId),senderDeviceId:u(n.senderDeviceId),createdAt:z(n.createdAt),updatedAt:z(n.updatedAt),expiresAt:z(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=E(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:u(a.memberId),status:a.status,...a.consumedAt!==void 0?{consumedAt:a.consumedAt===null?null:z(a.consumedAt)}:{}}})),i}),total:P(e.total,0),limit:P(e.limit,1),offset:P(e.offset,0)}}function _n(r){let e=E(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:u(e.leaseId),leaseExpiresAt:z(e.leaseExpiresAt),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),tenantWrappedShareKey:u(e.tenantWrappedShareKey),wrappedContentKey:u(e.wrappedContentKey),shares:e.shares.map(t=>{let n=E(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:P(n.index,0),shareId:u(n.shareId),layerId:u(n.layerId),ciphertext:u(n.ciphertext)}})}}function Cn(r){let e=E(r);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:u(e.leaseId),leaseExpiresAt:z(e.leaseExpiresAt),senderSigningPublicKey:u(e.senderSigningPublicKey),senderSigningKeyFingerprint:u(e.senderSigningKeyFingerprint),senderDeviceVersion:P(e.senderDeviceVersion,1),canonicalManifest:u(e.canonicalManifest),signature:u(e.signature),tenantWrappedShareKey:u(e.tenantWrappedShareKey),wrappedContentKey:u(e.wrappedContentKey),shares:e.shares.map(t=>{let n=E(t);if(n.kind!=="DATA"&&n.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:n.kind,index:P(n.index,0),shareId:u(n.shareId),layerId:u(n.layerId)}})}}function et(r){return typeof r=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(r)&&Number.isFinite(Date.parse(r))}function he(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 Ie(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var V=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}},ye=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;getFileAccess(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,t)}requestFileAccessOpening(e,t){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings`,"POST",t)}readFileAccessOpening(e,t,n,i){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}`,"GET",void 0,void 0,{"x-client-key-hash":n},i)}confirmFileAccessDelivery(e,t,n){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(t)}/confirm-delivery`,void 0,{"x-client-key-hash":n})}createInboxFileAccess(e,t,n,i){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses`,"POST",n,void 0,void 0,i)}createRevealFileAccess(e,t,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",t,void 0,void 0,n)}cancelRevealFileAccess(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",n)}cancelInboxFileAccess(e,t,n,i){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}/file-accesses/${encodeURIComponent(n)}`,void 0,void 0,"DELETE",i)}async getOwnFileAccessIdentityKey(e){let t=await this.request("v1/inbox/devices/me/identity-key","GET",void 0,void 0,void 0,e);if(t===null)return null;if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid_file_access_identity_key");let n=t;if(typeof n.publicKey!="string"||!n.publicKey||typeof n.fingerprint!="string"||!n.fingerprint||n.status!=="ACTIVE"&&n.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:n.publicKey,fingerprint:n.fingerprint,status:n.status}}async getOwnInboxDevice(e){let t=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return t===null?null:ve(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:ve(n)}async registerInboxDevice(e){return ve(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return ve(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return ve(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return Je(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,t){return Je(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 Sn(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 En(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 xn(await this.request(`v1/inbox/members${i}`,"GET",void 0,void 0,void 0,t))}async getInboxSendPreparation(e,t){return An(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,t))}async getNormalInboxSendPreparation(e,t){return fn(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 Ze(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",n))}async publishNormalInboxMessage(e,t){return Mt(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",t))}async publishInboxParent(e,t){return Mt(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 In(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 yn(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 Pn(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 bn(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 wn(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 vn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(t)}/read`,"POST",{deviceId:n}))}async stageInboxFile(e,t,n){return Ze(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 tt(o,s);if(!d.ok||d.result?.shareId!==n||d.result.status!=="STORED")throw new V(o.status,he(d),Ie(d),o.headers.get("x-request-id")??void 0)}async publishInboxFile(e,t,n){return Ze(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 Cn(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 p=c.body.getReader(),m=[],f=0;try{for(;;){a?.throwIfAborted();let b=await p.read();if(b.done)break;if(f+=b.value.length,f>14*1024*1024)throw new Error("invalid_inbox_share_size");m.push(b.value)}}catch(b){throw await p.cancel().catch(()=>{}),b}let w=new Uint8Array(f),g=0;for(let b of m)w.set(b,g),g+=b.length;return w}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 Rn(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,n))}async openInboxMessage(e,t,n){return _n(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(gn)}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 an(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Ye(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 on(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.q&&n.set("q",t.q),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 dn(await this.request(`v1/members/${encodeURIComponent(e)}/logs${i}`,"GET"))}async listOrganizationMembers(e={}){if(this.requireOrganizationSelection(),Xe(e,["limit","offset"]),e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>100))throw new Error("organization_query_limit_invalid");if(e.offset!==void 0&&(!Number.isSafeInteger(e.offset)||e.offset<0))throw new Error("organization_query_offset_invalid");let t=new URLSearchParams;return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),ln(await this.request(`v1/organization/members${t.size?`?${t}`:""}`,"GET"))}async listOrganizationAuditTrail(e){if(this.requireOrganizationSelection(),Xe(e,["from","to","limit","cursor","category","memberId","responsibleMemberId"]),!et(e.from)||!et(e.to)||Date.parse(e.from)>Date.parse(e.to))throw new Error("organization_query_date_invalid");if(e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>500))throw new Error("organization_query_limit_invalid");if(e.cursor!==void 0&&!/^[1-9]\d*$/.test(e.cursor))throw new Error("organization_query_cursor_invalid");let t=new URLSearchParams({from:e.from,to:e.to});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor!==void 0&&t.set("cursor",e.cursor),e.category!==void 0&&t.set("category",e.category),e.memberId!==void 0&&t.set("memberId",e.memberId),e.responsibleMemberId!==void 0&&t.set("responsibleMemberId",e.responsibleMemberId),pn(await this.request(`v1/organization/audit-trail?${t}`,"GET"))}async getOrganizationInsights(e={}){if(this.requireOrganizationSelection(),Xe(e,["from","to"]),e.from===void 0!=(e.to===void 0)||e.from!==void 0&&(!et(e.from)||!et(e.to)||Date.parse(e.from)>Date.parse(e.to)))throw new Error("organization_query_date_invalid");let t=new URLSearchParams;return e.from!==void 0&&e.to!==void 0&&(t.set("from",e.from),t.set("to",e.to)),un(await this.request(`v1/organization/insights${t.size?`?${t}`:""}`,"GET"))}async getPlanResponsibilities(e){if(this.requireOrganizationSelection(),!e)throw new Error("plan_id_required");return mn(await this.request(`v1/plans/${encodeURIComponent(e)}/responsibilities`,"GET"))}async startPlanCreation(e){se(e);let{idempotencyKey:t,...n}=e;return _e(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return _e(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return ue(t),_e(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return _e(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){if(t.operationContext!==void 0)throw new Error("operation_context_automation_only");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[f,w]of Object.entries(s??{}))d.set(f,w);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 p=await this.transport(new URL(e,c),l);a?.throwIfAborted();let m=await tt(p,a);if(a?.throwIfAborted(),!p.ok)throw new V(p.status,he(m),Ie(m),p.headers.get("x-request-id")??void 0);if(!m.ok||m.result===void 0)throw new V(p.status,he(m),Ie(m),p.headers.get("x-request-id")??void 0);return m.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 tt(d,i);throw new V(d.status,he(c),Ie(c),d.headers.get("x-request-id")??void 0)}return d}async requestWithoutResult(e,t,n,i="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let a=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});a&&o.set("authorization",`Bearer ${a}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId);for(let[p,m]of Object.entries(n??{}))o.set(p,m);t&&o.set("content-type","application/json");let d=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,d),{method:i,headers:o,body:t?JSON.stringify(t):void 0,signal:s}),l=await tt(c,s);if(s?.throwIfAborted(),!c.ok||!l.ok)throw new V(c.status,he(l),Ie(l),c.headers.get("x-request-id")??void 0)}requireOrganizationSelection(){if(!this.business?.organizationId)throw new V(400,"organization_selection_required")}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new V(400,"organization_selection_required")}};async function tt(r,e){try{return await r.json()}catch(t){if(e?.throwIfAborted(),t instanceof Error&&t.name==="AbortError")throw t;return{ok:!1}}}import{createNodeSsdpV2Processor as Vr}from"@safetech/inheriti-core-sdk/node";async function Nt(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=Lr(r),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,a);return Fr(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 Lr(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 Fr(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var Ce=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await Tn("plan_key_unwrap_failed",()=>Nt(e.planKey,t)),i=await crypto.subtle.importKey("raw",Kt(n),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await Tn("plan_share_decryption_failed",()=>Br(o.data,i));Gr(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 nt("plan_share_reconstruction_failed",zr(o))}}},nt=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},qr=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 zr(r){let e=r instanceof Error?r.message:void 0;if(e)return qr.has(e)?e:void 0}async function Tn(r,e){try{return await e()}catch{throw new nt(r)}}function Gr(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function Br(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=Kt(r.slice(0,t)),i=Kt(r.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(s)}function Kt(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 fe=class extends Ce{constructor(e){super(()=>Vr(e))}};var Te=class{constructor(e,t,n){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=n}firstRelayStates=new Map;async startReveal(e,t){let n=t.operationContext===void 0?void 0:ae(t.operationContext);return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey,...n===void 0?{}:{operationContext:n}},!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 Ye(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 V(c.status,l&&he(l),l&&Ie(l));return l?.result}};var C={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 de=class extends Error{constructor(t,n){super(n??`plan_request_failed_${t}`);this.status=t;this.code=n}},Oe=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",On(n))}configure(e,t,n){return this.request(e,`integrations/v1/plans/${encodeURIComponent(t)}/configure`,"POST",On(n))}async startRelaySession(e,t,n){if(t.system!=="INHERITI_BUSINESS"||t.contextId!==e)throw new Error(C.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(C.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(C.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(C.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 de(c.status,l.error);return l.result}};function On(r){return{protectionProtocol:r.protectionProtocol,operation:"FINALIZE",dataShards:r.dataShards,backupShards:r.backupShards,encryptedKey:r.encryptedKey,assetsMetadata:r.assetsMetadata,custodianPair:r.custodianShard}}var Me=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){ke(e.signal),Hr(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return ke(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){ke(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(ke(e.signal),!i.custodianPair)throw new U("custodian_share_required");let s=Ut(i.keyShards),a=await this.sealer.encryptShares(s,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(Ut(i.dataShards),a.symmetricKeyBase64),d=await this.sealer.encryptShares(Ut(i.backupShards),a.symmetricKeyBase64),c=await this.sealCustodianPair(i.custodianPair,a.symmetricKeyBase64);return ke(e.signal),{protectionProtocol:i.protocol,validatorShares:Lt(a.encryptedShares),dataShards:Lt(o.encryptedShares),backupShards:Lt(d.encryptedShares),encryptedKey:a.encryptedKey,assetsMetadata:$r(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:Ft(n.encryptedShares[0]),dataShard:Ft(n.encryptedShares[1])}}};function Ut(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function Lt(r){return r.map(Ft)}function Ft(r){return{id:r.id,data:r.encryptedData}}function $r(r,e){let t={};for(let n of r){let i=e.assets.find(s=>s.clientAssetRef===n.id);if(!i)throw new U("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 Hr(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new U("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new U("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new U("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 U("plan_secrets_declaration_mismatch")}}function ke(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function kn(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(C.invalidShares);let{assets:d,plan:c}=e;c.policy={custodian:n.withCustodian?"FORCE":"BYPASS"};let l=r.masterKeySource??new Q({api:{startRelaySession:f=>i.startRelaySession(r.organizationId,t.masterKeyAcquisition,f),readRelaySession:f=>i.readRelaySession(r.organizationId,f)}}),p=new Me(s,l);a?.("encrypting");let m=await p.encrypt({planId:r.planId,declaration:c,secrets:{assets:d,totalShares:r.totalShares,threshold:o}});return a?.("generating_shares"),p.generateShares({planId:r.planId,declaration:c,encrypted:m})}import{PlanAssetDeclaration as Wr}from"@safetech/inheriti-core-sdk/node";function Mn(r){let e=qt({planId:r.planId,title:r.title,assets:[r.asset]});return{asset:e.assets[0],plan:e.plan}}function qt(r){if(!r.assets.length)throw new S("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 S("binary_asset_metadata_invalid")}if(!Number.isSafeInteger(o)||!o)throw new S("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 Nn(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 Dn(new Uint8Array(await i.arrayBuffer())):i]))})));return Dn(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 Dn(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 De=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(C.invalidDeclaration);if(e.audience&&!e.audience.teamId?.trim())throw new Error(C.invalidDeclaration);if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new Error(C.invalidShares);let n=await Nn(e),i=this.flights.get(e.planId);if(i){if(i.fingerprint!==n)throw new Error(C.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=qt({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(C.reconciliationRequired);let a=await this.statusOrMissing(e.organizationId,e.planId);if(rt(a))return this.material.delete(e.planId),{planId:e.planId,status:"READY"};if(a&&!s)throw new Error(C.reconciliationRequired);if(!a&&s)throw new Error(C.reconciliationRequired);let o=await this.port.createContext(e.organizationId);if(!o.memberId||o.storage.activeDataStorageLayerCount!==e.totalShares)throw new Error(C.storageChanged);if(o.masterKeyAcquisition.system!=="INHERITI_BUSINESS"||o.masterKeyAcquisition.contextId!==e.organizationId)throw new Error(C.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 kn(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(!rt(await this.statusOrMissing(e.organizationId,e.planId)))throw l}n?.("verifying");let c=await this.port.status(e.organizationId,e.planId);return rt(c)&&this.material.delete(e.planId),{planId:e.planId,status:rt(c)?"READY":"PENDING"}}abandon(e){if(this.flights.has(e))throw new Error(C.reconciliationRequired);this.material.delete(e)}async statusOrMissing(e,t){try{return await this.port.status(e,t)}catch(n){if(n instanceof de&&n.status===404)return;throw n}}};function rt(r){return r?.status==="PROTECTED"||r?.status==="CONFIGURED"}var it=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(C.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(C.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(C.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(C.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)}),p={};try{p=await l.json()}catch{}if(!l.ok||p.ok!==!0){let m=Array.isArray(p.validationErrors)?p.validationErrors.join("; "):void 0;throw new de(l.status,m||p.error)}return p.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 st=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(p=>p.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 Q({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=g=>{g!==o&&(o=g,i?.(g))},c=g=>{if(g.processId!==e.editId||g.planId&&g.planId!==e.planId)return;switch(g.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 b=this.approvalError(g);if(b?.startsWith("edit_authentication_")&&d("pending_auth"),b?.startsWith("edit_moderation_")&&d("pending_moderation"),!o||!g.moderatorParticipants||g.requiredModeratorApprovals===void 0||!g.approvalProcess)return;let O=g.moderatorParticipants.map(A=>A.memberId??A.userId);O.some(A=>typeof A!="string"||!A)||new Set(O).size!==O.length||i?.(o,{requiredApprovals:g.requiredModeratorApprovals,approvedModerators:g.approvalProcess.approvedModerators,moderators:g.moderatorParticipants.map((A,N)=>{let R=O[N],J=A.flows.filter(Pe=>Pe.status==="PENDING"&&Pe.expiresAt&&Number.isFinite(Pe.expiresAt.getTime())).map(Pe=>Pe.expiresAt.getTime());return{id:R,displayName:a.get(R)||"Moderator",status:A.status,expiresAt:J.length?new Date(Math.min(...J)).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 p=await s.getView(e.editId);if(p?.processId!==e.editId||p.planId&&p.planId!==e.planId)throw new Error("edit_merge_not_ready");c(p),this.assertApprovalOutcome(e.planId,p);let m=p?.status;if(m!=="READY_TO_REVEAL"&&m!=="REVEALED")throw new Error("edit_merge_not_ready");d("revealing");let f=null,w={onRevealed:g=>{f=g},onViewUpdate:c,onRevealStepUpdate:(g,b)=>{if(b==="IN_PROCESS")switch(g){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&&(w.onCustodianShareRequired=async(g,b)=>{switch(b.mode){case"distribute":{this.assertNotAborted(e.signal),d("configuring_custodian_share");let O=await e.selectCustodianDevice?.()??"SK_MOBILE";if(this.assertNotAborted(e.signal),O==="SK_MOBILE")return s.distributeCustodianShareViaMobile(b.planId);if(O!=="SK_PRO")throw new Error("custodian_share_unavailable");if(!e.proDevice)throw new Error("safekey_pro_local_device_required");let A=e.proDevice;try{this.assertNotAborted(e.signal);let N=await s.getCustodianShareData(g);this.assertShare(N,b.planId),d("connecting_safekey_pro");let{deviceId:R}=await A.write(N,e.signal);if(this.assertNotAborted(e.signal),!R?.trim())throw new Error("custodian_share_unavailable");await s.recordCustodianShareClaim(b.planId,N.id,R,"SK_PRO"),this.assertNotAborted(e.signal),await s.markCustodianShareAsCollected(g,N.id);return}finally{A.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 O=e.proDevice;try{if(this.assertNotAborted(e.signal),!b.shareId||!b.deviceId)throw new Error("custodian_share_unavailable");d("connecting_safekey_pro");let A=await O.read({shareId:b.shareId,planId:b.planId},e.signal);if(this.assertNotAborted(e.signal),this.assertShare(A,b.planId,b.shareId),A.deviceId!==b.deviceId)throw new Error("custodian_share_unavailable");return{keyShares:A.shares}}finally{O.clearPin?.()}}default:throw new Error("unsupported_custodian_share_action")}}),m==="REVEALED"?await s.resumeReveal(e.editId,w,t):await s.openRevealWindow(e.editId,{timeoutMinutes:10},w,t),this.assertNotAborted(e.signal),!f)throw new Error("edit_assets_unavailable");return f}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 jr=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))),at=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(jr(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 ot=class{constructor(e,t,n){this.port=e;this.coreSdk=t;this.assetAccess=new st(e,t,n),this.reconfiguration=new at(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,p)=>p===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=Mn({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 Kn({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 p=Qr(l,d.searchParams,t,n),m=new Headers(o?.headers);m.set("x-organization-id",e),m.set("x-elements-environment",i);let f=c.pathname.endsWith("/integrations/")?`v1/${p}`:`integrations/v1/${p}`;return s(new URL(f,c),Object.assign({},o,{headers:m}))}}function Qr(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 Yr}from"@safetech/inheriti-core-sdk/node";function Un(r){return{async openReveal(e,t={}){let n=t.operationContext===void 0?void 0:ae(t.operationContext);if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let i=await r.api.planKeyReference(e),s=we(i);if(!i.masterKeyWrapped||!s||i.planId!==e)throw new Error("automation_plan_key_reference_invalid");let a=new Q({api:{startRelaySession:d=>r.api.startMasterKeyRelaySession(crypto.randomUUID(),e,d),readRelaySession:(d,c)=>r.api.readMasterKeyRelaySession(d,c),cancelRelaySession:(d,c)=>r.api.cancelMasterKeyRelaySession(d,c)}}),o=new me(void 0,{api:r.api,reconstructor:r.reconstructor,assetDecoder:r.assetDecoder,masterKeys:{resolve:(d,c,l)=>{if(d.system!==s.system||d.contextId!==s.contextId)throw new Error("automation_plan_key_reference_mismatch");return a.resolve(c,l)}}});return Qe(o,e,{...t,...n===void 0?{}:{operationContext:n}},!0)}}}function Xr(r){let e=new Te(r.apiUrl,r.getBearerToken,r.transport??globalThis.fetch.bind(globalThis));return{supportsOperationContext:!0,...Un({api:e,reconstructor:new fe(r.workerUrl),assetDecoder:Yr}),getPlan:t=>e.getPlan(t)}}import{generateInheritiFileKey as dt,sealInheritiFile as ct,readInheritiFileHeader as zt,openInheritiFile as Gt,InheritiFileInvalid as Jr,MAX_INHERITI_FILE_BYTES as Bt}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as lt,openInheritiFileKey as Vt}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";async function Zr(r){let{reveal:e,api:t,signal:n}=r;if(e.session.protectedCopy!==!0)throw new Error("protected_reveal_required");let i=await t.getOwnFileAccessIdentityKey(n);if(!i||i.status!=="ACTIVE")throw new Error("file_access_identity_unavailable");let s=Date.parse(e.session.expiresAt);if(!Number.isFinite(s)||s<=Date.now())throw new Error("reveal_expired");let a=r.openLimit??1;if(!Number.isSafeInteger(a)||a<1||a>4294967295)throw new Error("invalid_open_limit");await e.exportAsset(r.selector,async o=>{if(!(o.bytes instanceof Uint8Array)||o.bytes.length<1||o.bytes.length>Bt-1024*1024)throw new Error("unsupported_protected_asset");let d=dt(),c,l=!1,p=!1;try{n?.throwIfAborted();let m=await lt(d,i.publicKey);l=!0;let f=await t.createRevealFileAccess(e.session.id,{copyId:r.copyId,envelopeId:r.envelopeId,assetId:o.id,identityKeyFingerprint:i.fingerprint,sealedFileKey:m,openLimit:a},n);if(f.copyId!==r.copyId||f.status!=="PENDING")throw new Error("file_access_create_invalid");let w=await t.getFileAccess(r.copyId,n);for(;w.status==="PENDING";){if(n?.throwIfAborted(),Date.now()>=s)throw new Error("reveal_expired");await new Promise((b,O)=>{let A=()=>{clearTimeout(N),O(n?.reason)},N=setTimeout(()=>{n?.removeEventListener("abort",A),b()},Math.min(500,Math.max(1,s-Date.now())));n?.addEventListener("abort",A,{once:!0})}),w=await t.getFileAccess(r.copyId,n)}if(w.status!=="READY"||w.origin!=="REVEAL"||w.copyId!==r.copyId||w.allowedUses!==a||!w.recipient||!w.deployment||w.expiresAt!==null&&(!Number.isFinite(Date.parse(w.expiresAt))||Date.parse(w.expiresAt)>s||Date.parse(w.expiresAt)<=Date.now()))throw new Error("file_access_binding_invalid");let g=await ct({plaintext:o.bytes,fileKey:d,mimeType:o.mimeType,binding:w});g.fileKey.fill(0),c=g.fileBytes,n?.throwIfAborted(),await r.save({fileName:o.fileName,fileBytes:c}),p=!0}catch(m){if(l&&!p)try{await t.cancelRevealFileAccess(e.session.id,r.copyId)}catch(f){throw new AggregateError([m,f],"protected_asset_export_and_cleanup_failed",{cause:m})}throw m}finally{d.fill(0),c?.fill(0)}})}import{DataAssetDefinitionService as Vo}from"@safetech/inheriti-core-sdk/node";function Ln(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var pt=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Ln(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Ln(new Uint8Array(t))}},ut=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 Ne=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},G=class extends Ne{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},v=class extends Ne{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function mt(r){if(r instanceof Ne)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:L(n,"issuer"),authorizationEndpoint:L(n,"authorization_endpoint"),tokenEndpoint:L(n,"token_endpoint"),deviceAuthorizationEndpoint:ee(n,"device_authorization_endpoint"),endSessionEndpoint:ee(n,"end_session_endpoint"),revocationEndpoint:ee(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:L(t,"device_code"),userCode:L(t,"user_code"),verificationUri:L(t,"verification_uri"),verificationUriComplete:ee(t,"verification_uri_complete"),expiresInSeconds:qn(t,"expires_in"),intervalSeconds:$t(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 revoke(e){let t=await this.http(new URL(e.endpoint),{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.clientId,token:e.refreshToken,token_type_hint:"refresh_token"}),signal:e.signal});if(!t.ok)throw new v(`oauth_http_${t.status}`)}async exchangeBusinessSession(e){return this.businessSession(e.apiUrl,"exchange",{providerAccessToken:e.providerAccessToken})}async refreshBusinessSession(e){return this.businessSession(e.apiUrl,"refresh",{refreshToken:e.refreshToken})}async revokeBusinessSession(e){await this.businessRequest(e.apiUrl,"revoke",{refreshToken:e.refreshToken},e.signal)}async businessSession(e,t,n){let i=await this.businessRequest(e,t,n);return{accessToken:L(i,"accessToken"),refreshToken:L(i,"refreshToken"),accessExpiresAt:L(i,"accessExpiresAt"),sessionExpiresAt:L(i,"sessionExpiresAt"),familyId:L(i,"familyId"),environment:ti(i,"environment"),clientId:L(i,"clientId"),providerIssuer:L(i,"providerIssuer"),providerSubject:L(i,"providerSubject")}}async businessRequest(e,t,n,i){let s=e.endsWith("/")?e:`${e}/`,a=new URL(`operator-sessions/${t}`,s),o=await this.http(a,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},credentials:"omit",signal:i,body:JSON.stringify(n)}),d={};try{d=await o.json()}catch{}if(!o.ok)throw new v(`business_http_${o.status}`);if(d.ok!==!0||!ei(d.result))throw new v("invalid_business_response");return d.result}async token(e,t){let n=await this.form(e,t);return{accessToken:L(n,"access_token"),refreshToken:ee(n,"refresh_token"),idToken:ee(n,"id_token"),tokenType:L(n,"token_type"),expiresInSeconds:qn(n,"expires_in"),refreshExpiresInSeconds:$t(n,"refresh_expires_in"),scope:ee(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=ee(i,"error")??`oauth_http_${n.status}`;throw new v(s,ee(i,"error_description")??s)}return i}};function ei(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function ti(r,e){let t=L(r,e);if(t!=="TEST"&&t!=="LIVE")throw new v("invalid_business_response");return t}function L(r,e){let t=ee(r,e);if(!t)throw new v("invalid_oauth_response",`Missing ${e}`);return t}function ee(r,e){return typeof r[e]=="string"?r[e]:void 0}function qn(r,e){let t=$t(r,e);if(t===void 0)throw new v("invalid_oauth_response",`Missing ${e}`);return t}function $t(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var ni=600*1e3,gt=5,ri=5,zn=5e3,ii=new WeakMap,si=new WeakMap;async function Bn(r,e,t){let n=r.get(e),i,s=new Promise(a=>{i=a});r.set(e,s),n&&await n;try{return await t()}finally{r.get(e)===s&&r.delete(e),i()}}function ce(r,e){return Bn(ii,r,e)}var Gn=class{constructor(e){this.options=e;if(e.businessAuthority&&!e.businessApiUrl)throw new v("business_api_url_required");this.crypto=e.crypto??new pt,this.clock=e.clock??new ut}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(e){let t=await this.getDiscovery(),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(32),s=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(s),o=this.clock.now()+ni;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:n,nonce:i,codeVerifier:s,redirectUri:this.options.configuration.redirectUri,expiresAt:o});let d=new URL(t.authorizationEndpoint);return d.searchParams.set("response_type","code"),d.searchParams.set("client_id",this.options.configuration.clientId),d.searchParams.set("redirect_uri",this.options.configuration.redirectUri),d.searchParams.set("scope",this.options.configuration.scopes.join(" ")),d.searchParams.set("state",n),d.searchParams.set("nonce",i),d.searchParams.set("code_challenge",a),d.searchParams.set("code_challenge_method","S256"),e?.prompt&&d.searchParams.set("prompt",e.prompt),{authorizationUrl:d.toString(),expiresAt:o}}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 v("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new v("authorization_transaction_expired");let i=new URL(e),s=new URL(n.redirectUri);if(i.origin!==s.origin||i.pathname!==s.pathname)throw new v("redirect_uri_mismatch");if(i.searchParams.get("state")!==n.state)throw new v("state_mismatch");let a=i.searchParams.get("error");if(a)throw new v(a,i.searchParams.get("error_description")??a);let o=i.searchParams.get("code");if(!o)throw new v("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 ce(this.options.sessions,()=>this.options.sessions.save(l)),l}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new v("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(gt,t.intervalSeconds??gt),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 v("device_transaction_missing");let i=n,s=await this.getDiscovery(),a=Math.max(gt,i.intervalSeconds??gt),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 ce(this.options.sessions,()=>this.options.sessions.save(c)),await this.options.transactions.remove(t),c}catch(d){let c=mt(d);if(c==="authorization_pending"){o=this.clock.now()+a*1e3;continue}if(c==="slow_down"){a+=ri,o=this.clock.now()+a*1e3;continue}throw await this.options.transactions.remove(t),d}}throw await this.options.transactions.remove(t),new v("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e){if(this.isSafeIdBusinessMode()&&!this.isValidSafeIdBusinessSession(e))throw await this.clearIfUnchanged(e),new G;if(!this.options.businessApiUrl&&(e.kind==="business"||e.kind==="safeid-oidc-business"))throw await this.clearIfUnchanged(e),new G;if(this.options.businessApiUrl&&!this.isSafeIdBusinessMode()&&!this.isValidBusinessSession(e))throw await this.clearIfUnchanged(e),new G;return e.expiresAt>this.clock.now()?e.accessToken:(await this.refreshExpired(e)).accessToken}}refresh(){return this.refreshExpired()}refreshExpired(e){if(this.refreshFlight)return this.refreshFlight;let t=this.performRefresh(e).finally(()=>{this.refreshFlight===t&&(this.refreshFlight=void 0)});return this.refreshFlight=t,t}async clear(){let e;if(await ce(this.options.sessions,async()=>{try{e=await this.options.sessions.load()}finally{await this.options.sessions.clear()}}),this.isSafeIdBusinessMode()&&e&&this.isValidSafeIdBusinessSession(e)&&e.refreshToken){let i=new AbortController,s;try{await Promise.race([(async()=>{let a=await this.getDiscovery();a.revocationEndpoint&&this.options.transport.revoke&&await this.options.transport.revoke({endpoint:a.revocationEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken,signal:i.signal})})(),new Promise((a,o)=>{s=setTimeout(()=>{i.abort(),this.discovery=void 0,o(new v("provider_revoke_timeout"))},zn)})])}finally{s&&clearTimeout(s)}return}if(!this.options.businessApiUrl||!e||!this.isValidBusinessSession(e))return;let t=new AbortController,n;try{await Promise.race([this.options.transport.revokeBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:e.refreshToken,signal:t.signal}),new Promise((i,s)=>{n=setTimeout(()=>{t.abort(),s(new v("business_revoke_timeout"))},zn)})])}finally{n&&clearTimeout(n)}}async performRefresh(e){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.performProviderRefresh(e);let t=await this.options.sessions.load();if(!t||!this.isValidBusinessSession(t))throw t&&await this.clearIfUnchanged(t),new G;if(t.sessionExpiresAt<=this.clock.now())throw await this.clearIfCurrent(t),new G;let n;try{n=await this.options.transport.refreshBusinessSession({apiUrl:this.options.businessApiUrl,refreshToken:t.refreshToken})}catch(i){let s=mt(i);if(s==="business_http_409"){let a=await ce(this.options.sessions,async()=>{let o=await this.options.sessions.load();if(o&&this.isValidBusinessSession(o)&&o.refreshToken!==t.refreshToken&&o.familyId===t.familyId&&o.principal.subject===t.principal.subject)return o;o&&this.sameCredential(o,t)&&await this.options.sessions.clear()});if(a)return a;throw new G}throw s==="business_http_401"?(await this.clearIfCurrent(t),new G):i}try{let i=this.businessSession(n,t.principal,t);if(i.refreshToken===t.refreshToken)throw new v("refresh_token_rotation_missing");return await ce(this.options.sessions,async()=>{let s=await this.options.sessions.load();if(s&&this.isValidBusinessSession(s)&&s.familyId===t.familyId&&s.principal.subject===t.principal.subject&&s.refreshToken!==t.refreshToken)return s;if(!s||!this.sameCredential(s,t))throw new G;return await this.options.sessions.save(i),i})}catch(i){throw await this.clearIfCurrent(t),i}}sameCredential(e,t){return this.isValidBusinessSession(e)&&e.familyId===t.familyId&&e.refreshToken===t.refreshToken&&e.principal.subject===t.principal.subject}async clearIfUnchanged(e){await ce(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&t.kind===e.kind&&t.accessToken===e.accessToken&&t.refreshToken===e.refreshToken&&t.principal?.subject===e.principal?.subject&&await this.options.sessions.clear()})}async clearIfCurrent(e){await ce(this.options.sessions,async()=>{let t=await this.options.sessions.load();t&&this.sameCredential(t,e)&&await this.options.sessions.clear()})}async performProviderRefresh(e){return e??=await this.options.sessions.load(),Bn(si,this.options.sessions,async()=>{let t=await this.options.sessions.load();if(e&&t&&t.kind===e.kind&&t.refreshToken!==e.refreshToken&&t.expiresAt>this.clock.now()&&t.principal?.subject===e.principal?.subject&&t.principal?.sessionId===e.principal?.sessionId){if(this.isSafeIdBusinessMode()){if(this.isValidSafeIdBusinessSession(t))return t}else if(t.kind!=="business"&&t.kind!=="safeid-oidc-business")return t}return this.refreshProviderUnderLock()})}async refreshProviderUnderLock(){let e=await this.options.sessions.load();if(!e||(this.isSafeIdBusinessMode()?!this.isValidSafeIdBusinessSession(e):e.kind==="business"||e.kind==="safeid-oidc-business")||!e.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw e&&await this.clearIfUnchanged(e),new G;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=mt(n);throw i==="invalid_grant"||i==="invalid_client"||i==="unauthorized_client"||i==="registration_disabled"?(await this.clearIfUnchanged(e),new G):(this.isOfflineSession(e)||await this.clearIfUnchanged(e),n)}try{if(!t.refreshToken)throw new v("refresh_token_rotation_missing");let n=await this.acceptProviderTokens(t,void 0,e);return await ce(this.options.sessions,async()=>{let i=await this.options.sessions.load();if(!i||i.kind!==e.kind||i.refreshToken!==e.refreshToken||i.accessToken!==e.accessToken)throw new G;return await this.options.sessions.save(n),n})}catch(n){throw await this.clearIfUnchanged(e),n}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(F(e.issuer)!==F(this.options.configuration.issuer))throw new v("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}|${F(t)}|${n}|${i}|${this.options.businessApiUrl?this.isSafeIdBusinessMode()?"safeid-oidc":"business":"provider"}|${this.options.configuration.audience}`}async acceptTokens(e,t){if(!this.options.businessApiUrl||this.isSafeIdBusinessMode())return this.acceptProviderTokens(e,t);let n=await this.validateProviderTokens(e,t),i=await this.options.transport.exchangeBusinessSession({apiUrl:this.options.businessApiUrl,providerAccessToken:e.accessToken});return this.businessSession(i,n)}async validateProviderTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new v("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new v("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==n.subject||i.sessionId!==n.sessionId)throw new v("token_subject_mismatch")}return n}async acceptProviderTokens(e,t,n){let i=await this.validateProviderTokens(e,t);if(this.isSafeIdBusinessMode()&&!e.refreshToken)throw new G;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")),o={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};return this.isSafeIdBusinessMode()?{kind:"safeid-oidc-business",accessToken:o.accessToken,refreshToken:o.refreshToken,idToken:o.idToken,tokenType:o.tokenType,expiresAt:o.expiresAt,refreshExpiresAt:o.refreshExpiresAt,offlineAccessGranted:o.offlineAccessGranted,principal:o.principal,businessApiUrl:this.options.businessApiUrl,audience:this.options.configuration.audience,clientId:this.options.configuration.clientId,issuer:F(this.options.configuration.issuer),environment:this.options.configuration.environment}:o}isOfflineSession(e){return e.offlineAccessGranted===!0||e.offlineAccessGranted===void 0&&e.refreshExpiresAt===void 0&&this.options.configuration.scopes.includes("offline_access")}isSafeIdBusinessMode(){return this.options.businessAuthority==="safeid-oidc"}isValidSafeIdBusinessSession(e){let t=e,n=t.principal;return t.kind==="safeid-oidc-business"&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&(t.refreshExpiresAt===void 0||Number.isFinite(t.refreshExpiresAt))&&typeof t.issuer=="string"&&typeof t.businessApiUrl=="string"&&typeof t.audience=="string"&&typeof t.clientId=="string"&&(t.environment==="TEST"||t.environment==="LIVE")&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&typeof n.authorizedParty=="string"&&(n.environment==="TEST"||n.environment==="LIVE")&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&t.businessApiUrl===this.options.businessApiUrl&&e.audience===this.options.configuration.audience&&e.clientId===this.options.configuration.clientId&&F(t.issuer)===F(this.options.configuration.issuer)&&e.environment===this.options.configuration.environment&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment&&F(n.issuer)===F(this.options.configuration.issuer)&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)}businessSession(e,t,n){if(F(e.providerIssuer)!==F(t.issuer)||e.providerSubject!==t.subject||e.clientId!==this.options.configuration.clientId||e.environment!==this.options.configuration.environment||n&&e.familyId!==n.familyId)throw new v("business_identity_mismatch");let i=Date.parse(e.accessExpiresAt),s=Date.parse(e.sessionExpiresAt);if(!Number.isFinite(i)||!Number.isFinite(s)||i<=this.clock.now()||s<=this.clock.now()||i>s)throw new v("invalid_business_expiry");return{kind:"business",familyId:e.familyId,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenType:"Bearer",expiresAt:i,sessionExpiresAt:s,principal:{issuer:t.issuer,audience:t.audience,authorizedParty:t.authorizedParty,environment:t.environment,subject:t.subject,sessionId:t.sessionId,tokenId:t.tokenId,scopes:t.scopes,nonce:t.nonce}}}isValidBusinessSession(e){let t=e,n=t.principal;return t.kind==="business"&&typeof t.familyId=="string"&&t.familyId.length>0&&typeof t.accessToken=="string"&&t.accessToken.length>0&&typeof t.refreshToken=="string"&&t.refreshToken.length>0&&t.tokenType==="Bearer"&&Number.isFinite(t.expiresAt)&&Number.isFinite(t.sessionExpiresAt)&&typeof n=="object"&&n!==null&&typeof n.issuer=="string"&&F(n.issuer)===F(this.options.configuration.issuer)&&typeof n.subject=="string"&&n.subject.length>0&&(typeof n.audience=="string"||Array.isArray(n.audience)&&n.audience.every(i=>typeof i=="string"))&&(typeof n.audience=="string"?[n.audience]:n.audience).includes(this.options.configuration.audience)&&n.authorizedParty===this.options.configuration.clientId&&n.environment===this.options.configuration.environment}assertPrincipal(e,t,n){let i=this.options.configuration,s=typeof e.audience=="string"?[e.audience]:e.audience;if(F(e.issuer)!==F(i.issuer))throw new v("issuer_mismatch");if(!s.includes(i.audience))throw new v("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new v("client_mismatch");if(e.environment!==i.environment)throw new v("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new v("required_claim_missing");if(n&&e.nonce!==t)throw new v("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(F(e.issuer)!==F(n.issuer))throw new v("issuer_mismatch");if(!i.includes(n.clientId))throw new v("client_mismatch");if(e.authorizedParty!==n.clientId)throw new v("client_mismatch");if(!e.subject||!e.sessionId)throw new v("required_claim_missing");if(e.nonce!==t)throw new v("nonce_mismatch")}};function F(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 Yo,RawMasterKeySource as Xo,deriveMasterKey as Jo,generateHexSeed as Zo,computePassphraseVerifier as ed}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as nd}from"@safetech/inheriti-core-sdk/node";function Ao(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:Ht({apiUrl:r.apiUrl,getBearerToken:r.getBearerToken,transport:t,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners}),i=new ye(r.apiUrl,r.environment,r.getBearerToken,t,r.business?{organizationId:r.organizationId}:void 0);return new me(n,{keyVault:r.keyVault,state:r.state,api:i,reconstructor:new fe(r.workerUrl),masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:ai})}function Ro(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=Ht({apiUrl:new URL(r.apiUrl).origin,getBearerToken:r.getBearerToken,transport:e,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners});return new De(new Oe(r.apiUrl,r.environment,r.getBearerToken,e),t)}function _o(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=Ht({apiUrl:t,getBearerToken:r.getBearerToken,transport:Kn({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 ot(new it(r.apiUrl,r.environment,r.getBearerToken,e),n,r.editRecoveryStore)}import{createHash as oi}from"node:crypto";import{generateRSAOAEPKeyPair as di}from"@safetech/inheriti-core-sdk/crypto";async function $n(r){let e=zt(r.fileBytes);if(!/^[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(e.copyId))throw new Error("invalid_startup_file");if(r.signal?.aborted)throw new Error("opening_cancelled");let t=await r.api.getFileAccess(e.copyId,r.signal);if(e.deployment!==t.deployment||e.origin!==t.origin||e.copyId!==t.copyId||e.recipient!==t.recipient||e.expiresAt!==t.expiresAt||e.allowedUses!==t.allowedUses)throw new Error("file_binding_mismatch");return{header:e,access:t}}async function ci(r){let{api:e,sessionId:t,signal:n}=r;if(!/^[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(t))throw new Error("invalid_opening_session");let i=Uint8Array.from(r.fileBytes),s,a,o=()=>{if(n?.aborted)throw new Error("opening_cancelled")};try{let{access:d}=await $n({fileBytes:i,api:e,signal:n});if(d.status!=="READY"||d.expiresAt&&Date.parse(d.expiresAt)<=Date.now())throw new Error("file_access_unavailable");if(r.delivery==="REVEAL"&&d.origin!=="REVEAL")throw new Error("file_access_unavailable");o();let{publicKeyBase64:c,privateKey:l}=await di(),p=oi("sha256").update(c).digest("hex");o();let m=await e.requestFileAccessOpening(d.copyId,{sessionId:t,clientPublicKey:c,...r.delivery==="REVEAL"?{delivery:"REVEAL"}:{}});r.delivery==="REVEAL"&&r.onPairingCode?.(p.slice(0,12));let f=Math.min(Date.parse(m.expiresAt),Date.now()+3e5);if(!Number.isFinite(f))throw new Error("file_opening_expired");let w;for(;!n?.aborted&&Date.now()<f;){let O=await e.readFileAccessOpening(d.copyId,t,p,n);if(O.status==="READY"&&O.encryptedFileKey){w=O.encryptedFileKey;break}if(O.status==="EXPIRED"||O.status==="DELIVERY_CONFIRMED")throw new Error("file_opening_expired");o(),await new Promise(A=>{let N=()=>{clearTimeout(R),n?.removeEventListener("abort",N),A()},R=setTimeout(N,1e3);n?.addEventListener("abort",N,{once:!0})})}if(o(),!w)throw new Error("file_opening_expired");s=await Vt(w,l),o(),await e.confirmFileAccessDelivery(d.copyId,t,p);let g=await Gt(i,s,d);a=g.plaintext,o();let b={plaintext:a,header:g.header};return a=void 0,b}finally{i.fill(0),s?.fill(0),a?.fill(0)}}import{createHash as li,webcrypto as pi}from"node:crypto";import{canonicalInboxManifest as ui,decodeInboxManifest as mi,decodeInboxContentFrame as gi,decodeInboxText as hi,decryptInboxShare as Ii,encodeInboxContentFrame as Wt,encodeInboxText as yi,encryptInboxShare as Hn,inboxProtectedUnitCommitment as fi,inboxTextMetadataDigest as Wn,openInboxContent as bi,sealInboxContent as vi,signInboxFrame as Pi,unwrapInboxContentKey as wi,unwrapInboxShareKey as Si,verifyInboxFrame as jn,wrapInboxContentKey as Ei,wrapInboxShareKey as xi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as Ai}from"@safetech/inheriti-core-sdk/workers/inbox.node";var X=pi,k=X,T=r=>{if(!/^[0-9a-fA-F]{64}$/.test(r))throw new Error("invalid_inbox_key");return Buffer.from(r,"hex")},I=r=>{let e=Buffer.from(r,"base64");if(!r||e.toString("base64")!==r)throw new Error("invalid_inbox_base64");return Uint8Array.from(e)},W=(r,e)=>r.length===e.length&&r.every((t,n)=>t===e[n]),ht=async r=>new Uint8Array(await k.subtle.digest("SHA-256",Uint8Array.from(r))),Ke=r=>li("sha256").update(r).digest("hex"),le=class{constructor(e,t=new Ai){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=ui(i),a=await ht(s),{contentKey:o,frame:d}=await vi(yi(e.text),a,k),c=await this.signFrame(i,d,e.identity.signingPrivateKey,n.signingPublicKey),{shareKey:l,shares:p}=await this.protectShares(t,d,a),m=await this.wrapRecipientKeys(t,o,a),f=await xi(l,T(e.tenantKeyHex),a,i.tenantId,i.messageId,k);return{frame:Buffer.from(Wt(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(f).toString("base64"),recipients:m,shares:p}}}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&&!W(t,await fi(a,Wt(c),I(n.signature),k)))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 V&&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||Ke(I(n.signingPublicKey))!==n.signingKeyFingerprint||Ke(I(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:T(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(s=>({memberId:s.memberId,deviceId:s.deviceId,encryptionKeyFingerprint:T(s.encryptionKeyFingerprint)})),expiresAtEpochMs:i,metadataDigest:await Wn(k)}}async signFrame(e,t,n,i){let s=await k.subtle.importKey("pkcs8",I(n),"Ed25519",!1,["sign"]),a=await Pi(e,t,s,k),o=await k.subtle.importKey("spki",I(i),"Ed25519",!1,["verify"]);if(!await jn(e,t,a,o,k))throw new Error("inbox_identity_mismatch");return a}async protectShares(e,t,n){let i=await this.worker.split(Wt(t),{threshold:e.threshold,total:e.total,messageId:e.messageId,manifestDigest:n}),s=k.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 Hn(i.dataShares[o],s,n,e.messageId,k)).toString("base64")}),a.push({kind:"KEY",index:o,shareId:d.keyShareId,layerId:d.id,ciphertext:Buffer.from(await Hn(i.keyShares[o],s,n,e.messageId,k)).toString("base64")})}return{shareKey:s,shares:a}}async wrapRecipientKeys(e,t,n){return Promise.all(e.recipients.map(async i=>{let s=I(i.encryptionPublicKey);if(Ke(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await k.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 Ei(t,a,n,k)).toString("base64")}}))}async verifyOpening(e,t,n){let i=I(t.canonicalManifest),s=mi(i);if(s.tenantId!==e.identity.tenantId||s.conversationId!==e.conversationId||s.messageId!==e.messageId||s.expiresAtEpochMs<=Date.now()||!W(s.metadataDigest,n??await Wn(k)))throw new Error("inbox_manifest_mismatch");let a=s.recipients.find(d=>d.memberId===e.identity.memberId&&d.deviceId===e.identity.deviceId);if(!a||!W(a.encryptionKeyFingerprint,T(Ke(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let o=I(t.senderSigningPublicKey);if(t.senderSigningKeyFingerprint!==Ke(o)||!W(s.senderSigningKeyFingerprint,T(t.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return{manifest:s,manifestDigest:await ht(i),senderPublicDer:o}}async recoverFrame(e,t,n,i){let s=await Si(I(e.tenantWrappedShareKey),T(i),n,t.tenantId,t.messageId,k),a=[],o=[],d=new Set;for(let l of e.shares){let p=`${l.kind}:${l.index}`;if(d.has(p))throw new Error("duplicate_inbox_share");d.add(p);let m=await Ii(I(l.ciphertext),s,n,t.messageId,l.kind==="DATA"?"data":"key",l.index,k);(l.kind==="DATA"?a:o).push(m)}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 gi(c)}async decryptText(e,t,n,i,s,a){return hi(await this.decryptContent(e,t,n,i,s,a))}async decryptContent(e,t,n,i,s,a){let o=await k.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await jn(n,t,I(e.signature),o,k))throw new Error("inbox_signature_invalid");let d=await k.subtle.importKey("pkcs8",I(a),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await wi(I(e.wrappedContentKey),d,i,k);return bi(t,c,i,k)}};import{canonicalInboxManifest as Ri,decodeInboxContentFrame as _i,decodeInboxFile as Ci,decryptInboxShare as Ti,encodeInboxContentFrame as Oi,encodeInboxFile as ki,encryptInboxShare as Qn,inboxFileMetadataDigest as Yn,sealInboxContent as Mi,unwrapInboxShareKey as Di,wrapInboxShareKey as Ni}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var It=class extends le{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=Ri(s),o=await ht(a),d=ki(t.file),c;try{c=await Mi(d,o,X)}finally{d.fill(0)}let{contentKey:l,frame:p}=c,m=await this.signFrame(s,p,t.identity.signingPrivateKey,i.signingPublicKey);t.signal?.throwIfAborted();let f=await this.worker.split(Oi(p),{threshold:n.threshold,total:n.total,messageId:n.messageId,manifestDigest:o},t.signal,R=>t.onProgress?.(0,n.total*2,R.stage));t.signal?.throwIfAborted();let w=X.getRandomValues(new Uint8Array(32)),g=[];for(let R=0;R<n.total;R++){let J=n.shareLayers[R];g.push({reference:{kind:"DATA",index:R,shareId:J.dataShareId,layerId:J.id},bytes:await Qn(f.dataShares[R],w,o,n.messageId,X)}),g.push({reference:{kind:"KEY",index:R,shareId:J.keyShareId,layerId:J.id},bytes:await Qn(f.keyShares[R],w,o,n.messageId,X)})}let b=await this.wrapRecipientKeys(n,l,o),O=await Ni(w,T(t.tenantKeyHex),o,s.tenantId,s.messageId,X);t.signal?.throwIfAborted();let A=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(m).toString("base64"),tenantWrappedShareKey:Buffer.from(O).toString("base64"),recipients:b,shares:g.map(R=>R.reference)},t.signal);if(A.messageId!==n.messageId||A.status!=="PREPARING")throw new Error("invalid_inbox_stage");for(let R=0;R<g.length;R++){t.signal?.throwIfAborted();let J=g[R];await this.fileApi.uploadInboxFileShare(t.conversationId,n.messageId,J.reference.shareId,J.bytes,t.signal),t.onProgress?.(R+1,g.length,"UPLOADING")}t.signal?.throwIfAborted();let N=await this.fileApi.publishInboxFile(t.conversationId,n.messageId,t.signal);if(N.messageId!==n.messageId||N.status!=="AVAILABLE")throw new Error("invalid_inbox_publish");return N}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 Yn(X)),l=await this.recoverFileFrame(t,n,o,d);s=await this.decryptContent(n,l,o,d,c,t.identity.encryptionPrivateKey),i=Ci(s),t.signal?.throwIfAborted(),await t.save(i,{leaseId:n.leaseId,leaseExpiresAt:n.leaseExpiresAt}),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:T(i.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(a=>({memberId:a.memberId,deviceId:a.deviceId,encryptionKeyFingerprint:T(a.encryptionKeyFingerprint)})),expiresAtEpochMs:s,metadataDigest:await Yn(X)}}async recoverFileFrame(t,n,i,s){let a=await Di(I(n.tenantWrappedShareKey),T(t.tenantKeyHex),s,i.tenantId,i.messageId,X),o=[],d=[],c=new Set;for(let p=0;p<n.shares.length;p++){t.signal?.throwIfAborted();let m=n.shares[p],f=`${m.kind}:${m.index}`;if(c.has(f))throw new Error("duplicate_inbox_share");c.add(f);let w=await this.fileApi.downloadInboxFileShare(t.conversationId,t.messageId,m.shareId,t.identity.deviceId,n.leaseId,t.signal),g=await Ti(w,a,s,i.messageId,m.kind==="DATA"?"data":"key",m.index,X);(m.kind==="DATA"?o:d).push(g),t.onProgress?.(p+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,p=>t.onProgress?.(n.shares.length,n.shares.length,p.stage));return t.signal?.throwIfAborted(),_i(l)}};import{createHash as Jn,webcrypto as Ki}from"node:crypto";import{canonicalInboxParentManifest as Ui,decodeInboxParentManifest as Li,encodeInboxParentNormalFrame as Fi,decodeInboxParentNormalFrame as qi,sealInboxParentNormalBody as zi,openInboxParentNormalBody as Gi,wrapInboxParentNormalKey as Bi,unwrapInboxParentNormalKey as Vi,signInboxParentNormalFrame as $i,verifyInboxParentNormalFrame as Xn,encodeInboxText as Hi,decodeInboxText as Wi}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var j=Ki,Ue=r=>Jn("sha256").update(r).digest("hex"),yt=r=>Buffer.from(r).toString("base64"),ft=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 Jn("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||Ue(I(n.signingPublicKey))!==n.signingKeyFingerprint||Ue(I(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:T(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(i=>({memberId:i.memberId,deviceId:i.deviceId,encryptionKeyFingerprint:T(i.encryptionKeyFingerprint)})),protectedUnits:[]}}async createSubmission(e,t,n,i){let s=Ui(i),{contentKey:a,frame:o}=await zi(Hi(e.text),i,j),d=await j.subtle.importKey("pkcs8",I(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),c=await $i(i,o,d,j),l=await j.subtle.importKey("spki",I(n.signingPublicKey),"Ed25519",!1,["verify"]);if(!await Xn(i,o,c,l,j))throw new Error("inbox_identity_mismatch");let p=await Promise.all(t.recipients.map(m=>this.wrapRecipientKey(m,a,i)));return{parentId:i.parentId,idempotencyKey:i.parentId,senderDeviceId:n.deviceId,participantRevision:t.participantRevision,canonicalManifest:yt(s),frame:yt(Fi(o)),signature:yt(c),recipients:p}}async wrapRecipientKey(e,t,n){let i=I(e.encryptionPublicKey);if(Ue(i)!==e.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await j.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:yt(await Bi(t,s,n,j))}}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=Li(I(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(p=>p.memberId===e.identity.memberId&&p.deviceId===e.identity.deviceId);if(!i||!W(i.encryptionKeyFingerprint,T(Ue(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let s=I(t.senderSigningPublicKey);if(!W(n.senderSigningKeyFingerprint,T(Ue(s))))throw new Error("inbox_sender_key_mismatch");let a=qi(I(t.frame)),o=await j.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Xn(n,a,I(t.signature),o,j))throw new Error("inbox_signature_invalid");let d=await j.subtle.importKey("pkcs8",I(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),c=await Vi(I(t.wrappedContentKey),d,n,j),l=Wi(await Gi(a,c,n,j));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 tr,webcrypto as ji}from"node:crypto";import{canonicalInboxParentManifest as Qi,decodeInboxParentManifest as Yi,decodeInboxManifest as Xi,encodeInboxParentNormalFrame as Ji,decodeInboxParentNormalFrame as Zi,sealInboxParentNormalBody as es,openInboxParentNormalBody as ts,wrapInboxParentNormalKey as ns,unwrapInboxParentNormalKey as rs,signInboxParentNormalFrame as is,verifyInboxParentNormalFrame as Zn,signInboxProtectedParent as ss,verifyInboxProtectedParent as er,inboxProtectedUnitCommitment as as,encodeInboxText as os,decodeInboxText as ds}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var q=ji,bt=r=>Buffer.from(r).toString("base64"),Le=r=>tr("sha256").update(r).digest("hex"),vt=class{constructor(e,t){this.api=e;this.child=t??new le(e)}pending=new Map;child;async send(e){let t=tr("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(f=>"protectedText"in f).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(f=>"text"in f))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:p,recipients:m}=await this.signAndWrap(e,i,s,c);return{parentId:a,idempotencyKey:a,senderDeviceId:s.deviceId,mode:n,participantRevision:i.participantRevision,canonicalManifest:bt(Qi(c)),signature:bt(p),frame:l,recipients:m,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=Xi(I(c.submission.canonicalManifest));this.validateChildSnapshot(l,e,t,n);let p=await as(l,I(c.frame),I(c.submission.signature),q);i.push({position:o,frame:c.frame,child:c.submission}),s.push({unitId:c.submission.messageId,position:o,commitment:p});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&&W(s.encryptionKeyFingerprint,T(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:T(n.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(o=>({memberId:o.memberId,deviceId:o.deviceId,encryptionKeyFingerprint:T(o.encryptionKeyFingerprint)})),protectedUnits:a}}async signAndWrap(e,t,n,i){let s=await q.subtle.importKey("pkcs8",I(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),a=await q.subtle.importKey("spki",I(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 ss(e,t,q);if(!await er(e,i,n,q))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 es(os(JSON.stringify(s)),t,q),o=await is(t,a.frame,n,q);if(!await Zn(t,a.frame,o,i,q))throw new Error("inbox_identity_mismatch");return{frame:bt(Ji(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=I(i.encryptionPublicKey);if(Le(s)!==i.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let a=await q.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:bt(await ns(t,a,n,q))}}))}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||Le(I(n.signingPublicKey))!==n.signingKeyFingerprint||Le(I(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=Yi(I(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||!W(n.commitment,T(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||!W(n.encryptionKeyFingerprint,T(Le(I(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch")}async senderKey(e,t){let n=I(e.senderSigningPublicKey);if(Le(n)!==e.senderSigningKeyFingerprint||!W(t.senderSigningKeyFingerprint,T(e.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return q.subtle.importKey("spki",n,"Ed25519",!1,["verify"])}async openProtectedParent(e,t,n){if(e.frame!==null||e.wrappedContentKey!==null||!await er(t,I(e.signature),n,q))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=Zi(I(t.frame));if(!await Zn(n,s,I(t.signature),i,q))throw new Error("inbox_signature_invalid");let a=await q.subtle.importKey("pkcs8",I(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),o=await rs(I(t.wrappedContentKey),a,n,q),d=JSON.parse(ds(await ts(s,o,n,q)));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{be as BusinessOrganizationSelectionError,Me as CorePlanMaterialBuilder,Vo as DataAssetDefinitionService,V as ElementsApiRequestFailed,me as ElementsClient,Re as GuidedCreateRecoveryError,Ae as GuidedPlanCreator,Te as HttpAutomationRevealApiPort,ye as HttpElementsApiPort,Fn as HttpOperatorAuthTransport,it as HttpPlanEditPort,Oe as HttpQuickPlanPort,Jr as InheritiFileInvalid,S as InvalidPlanDeclaration,U as InvalidPlanMaterial,Bt as MAX_INHERITI_FILE_BYTES,ze as MasterKeyRelayCancellationFailed,qe as MasterKeyRelayExpired,Fe as MasterKeyRelayTimedOut,te as MasterKeyRequired,xe as MemoryGuidedCreateCheckpointStore,Se as MemoryKeyVault,Ee as MemoryStatePort,It as NodeInboxFile,ft as NodeInboxNormal,vt as NodeInboxParent,le as NodeInboxText,v as OAuthProtocolError,Gn as OperatorAuthClient,Ne as OperatorAuthError,G as OperatorReauthenticationRequired,Vn as OperatorSessionController,xt as PLAN_CREATION_SERVER_STAGES,Yo as PassphraseMasterKeySource,nd as PlanAssetDeclaration,de as PlanRequestFailed,De as QuickPlanCreator,ot as QuickPlanEditor,Xo as RawMasterKeySource,Q as RelayMasterKeySource,wt as StaticMasterKeyResolver,ut as SystemOAuthClock,pt as WebOAuthCrypto,ed as computePassphraseVerifier,Ge as createMasterKeyResolver,Xr as createNodeAutomationRevealClient,Ao as createNodeElementsClient,Ro as createNodeQuickPlanCreator,_o as createNodeQuickPlanEditor,ai as decodeAssetContainer,Jo as deriveMasterKey,Zr as exportProtectedRevealAsset,Zo as generateHexSeed,dt as generateInheritiFileKey,$n as inspectInheritiFileAccess,we as masterKeyRefFor,ie as masterKeyRefKey,mt as oauthErrorCode,Gt as openInheritiFile,ci as openInheritiFileAccess,Vt as openInheritiFileKey,zt as readInheritiFileHeader,ct as sealInheritiFile,lt as sealInheritiFileKey,Nr as selectBusinessOrganization,Nt as unwrapDekWithMasterKey,ae as validateOperationContext,se as validatePlanCreationInput,ue as validatePlanCreationMaterial};
|