@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/automation.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decodeAssetContainer as Pt}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as ke,generateRSAOAEPKeyPair as Ke}from"@safetech/inheriti-core-sdk/crypto";var re=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ie=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},se=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},M=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:r,privateKey:i}=await Ke();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(r),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(y=>new Promise(R=>setTimeout(R,y))),l=!0,p=!1,f,h=()=>f??=(async()=>{let y=new AbortController,R,De=new Promise((bt,Ne)=>{R=setTimeout(()=>{y.abort(),Ne(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,y.signal),De])}finally{clearTimeout(R)}})(),x,N=new Promise((y,R)=>{x=()=>{l&&h().catch(()=>{}),R(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",x,{once:!0})});N.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),p=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let y=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),N]);if(y.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(y.status==="DELIVERED"&&y.sealedMasterKey){let R=(await ke(y.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(R))throw new Error("invalid_master_key_material");return R}if(y.status==="EXPIRED")throw new ie(s.sessionId);await Ue(d,a,e)}throw new re(s.sessionId)}catch(y){if(l&&(!p||e?.aborted))try{await h()}catch(R){if(e?.aborted)throw new se(R)}throw y}finally{x&&e?.removeEventListener("abort",x)}}};async function Ue(n,e,t){if(!t)return n(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((r,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),n(e).then(r,i).finally(()=>t.removeEventListener("abort",s))})}function oe(n){return{resolve:async(e,t,r)=>{if(n.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==n.organizationId)return;let i=await n.source?.resolve();return i||ae(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}if(Le(e,n.applicationId)){let i=await n.source?.resolve();return i||ae(n,()=>n.api.masterKeyAcquisition(),void 0,t,r)}return ae(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}}}function Le(n,e){return n.system==="INHERITI_ELEMENTS"&&n.contextId===e}async function ae(n,e,t,r,i){if((await e()).relayAvailable)return new M({...n.relay,api:qe(n.api,t)}).resolve(r,i)}function qe(n,e){return{startRelaySession:t=>e?n.startMasterKeyRelaySession(t,e):n.startMasterKeyRelaySession(t),readRelaySession:(t,r)=>n.readMasterKeyRelaySession(t,r),cancelRelaySession:(t,r)=>n.cancelMasterKeyRelaySession(t,r)}}function k(n){return`${n.system}:${n.contextId}`}function z(n){return n.sourceReference?{system:n.sourceReference.system,contextId:n.sourceReference.contextId}:n.tenantId?{system:"INHERITI_ELEMENTS",contextId:n.tenantId}:void 0}var S=class extends Error{constructor(t){super(`master_key_required:${k(t)}`);this.ref=t;this.name="MasterKeyRequired"}};var F=class{keys=new Map;async store(e,t){let r=k(e),i=t.slice();this.keys.get(r)?.fill(0),this.keys.set(r,i)}async load(e){return this.keys.get(k(e))?.slice()}async remove(e){let t=k(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var $=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 V=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},c=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var B=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var H=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],le={"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"]};var u=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},E=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function K(n){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(n).some(t=>!e.includes(t)))throw new E("plan_material_field_unknown");if(de(n.dataShards,"data_shards_invalid"),de(n.backupShards,"backup_shards_invalid"),n.validatorShares!==void 0&&de(n.validatorShares,"validator_shares_invalid"),n.validatorShares?.length&&!n.encryptedKey)throw new E("validator_shares_require_encrypted_key");if(n.protectionProtocol!==void 0&&n.protectionProtocol!=="SSDP_PLUS_V1"&&n.protectionProtocol!=="SSDP_PLUS_V2")throw new E("protection_protocol_invalid");if(n.operation!==void 0&&n.operation!=="DRAFT"&&n.operation!=="FINALIZE")throw new E("material_operation_invalid")}function de(n,e){if(!Array.isArray(n))throw new E(e);for(let t of n){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new E(e);if(t.data!==void 0&&typeof t.data!="string")throw new E(e)}}function D(n){if(C(n,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Fe(n.idempotencyKey))throw new u("idempotency_key_invalid");if(!n.name?.trim())throw new u("plan_name_required");if(!n.assets.length)throw new u("assets_required");let e=new Set;for(let t of n.assets){if(C(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 u("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!H.includes(t.type))throw new u("asset_type_invalid");let r=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==r)throw new u("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 u("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new u("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new u("asset_field_names_invalid");if(Ge(t.matchOrigins),!t.isBinary){let s=le[t.type];if(!s||i.some(a=>!s.includes(a)))throw new u("asset_field_name_not_canonical")}}if(!n.participants.length)throw new u("participants_required");for(let t of n.participants){if(C(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!ve(t.routingEmail))throw new u("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new u("participant_relationships_invalid")}ze(n)}function Ge(n){if(n===void 0)return;if(!n.length)throw new u("asset_match_origins_invalid");let e=n.map(t=>{if(typeof t!="string"||!t.trim())throw new u("asset_match_origin_invalid");try{let r=new URL(t);if(!["http:","https:"].includes(r.protocol)||r.origin!==t.trim())throw new u("asset_match_origin_invalid");return r.origin}catch(r){throw r instanceof u?r:new u("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new u("asset_match_origins_duplicated")}function ze(n){let e=n.policy;if(e&&C(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new u("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){C(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new u("authentication_mode_invalid")}if(e.moderation){C(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=n.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new u("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new u("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new u("approval_mode_invalid")}let t=e.dms;if(!t)return;C(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let r=t.countdownHours??0,i=t.countdownMinutes??0;if(!ve(t.subjectEmail))throw new u("dms_subject_invalid");if(!n.participants.some(s=>he(s.routingEmail)===he(t.subjectEmail)))throw new u("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(r)||!Number.isInteger(i)||t.countdownDays<0||r<0||r>23||i<0||i>59||t.countdownDays+r+i===0)throw new u("dms_countdown_invalid")}function Fe(n){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(n)}function ve(n){return typeof n=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(n.normalize("NFC").trim())}function he(n){return n.normalize("NFC").trim().toLowerCase()}function C(n,e,t){if(Object.keys(n).some(r=>!e.includes(r)))throw new u(t)}var j=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)}},Y=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),D(e),W(t.signal);let r=await this.api.startPlanCreation(e);return r.outcome==="COMPLETED"||r.outcome==="CANCELED"?await this.checkpoints.remove(r.operationId):await this.saveCheckpoint(e,r),t.onProgress?.(r.stage),r}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,r,i,s={}){D(t);let a=await this.checkpoints.load(e);if(!a)throw new X("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await Re(t))throw new X("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;W(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:r,signal:s.signal});W(s.signal),s.onProgress?.("GENERATING_SHARES");let l=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});W(s.signal),K(l);let p=await this.api.supplyPlanCreationMaterial(e,l);return s.onProgress?.(p.stage),p.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,p),p}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 Re(e),serverStage:t.stage})}},X=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Re(n){let e=JSON.stringify({name:n.name.normalize("NFC").trim(),description:n.description?.normalize("NFC").trim()??null,assets:n.assets.map(r=>({...r,fieldNames:[...r.fieldNames??[]]})).sort((r,i)=>r.clientAssetRef.localeCompare(i.clientAssetRef)),participants:n.participants.map(r=>({...r,routingEmail:r.routingEmail.normalize("NFC").trim(),relationships:[...r.relationships].sort()})).sort((r,i)=>r.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:n.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}function W(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function Pe(n,e,t){let r=await n.getReveal(e);if(r.stage!=="ACTIONS_OPEN")throw new V(r.stage);return n.authorizeRevealAction(e,t)}function $e(n){let e=n?.status;return e===400||e===401||e===403}async function be(n,e,t,r){let i=await n.getReveal(e);try{await r(i.planId)}catch(s){if(!$e(s))throw s}return n.releaseRevealMaterial(e,t)}var ce={reason:500,commitSha:64,workflow:200,pipeline:300,target:200,image:300,version:100};function T(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("operation_context_invalid");let e=n;for(let r of Object.keys(e))if(!Object.hasOwn(ce,r))throw new Error("operation_context_invalid");let t={};for(let r of Object.keys(ce)){if(!Object.hasOwn(e,r))continue;let i=e[r];if(typeof i!="string"||!i.trim()||i.length>ce[r]||/[\x00-\x1f\x7f-\x9f]/.test(i)||r==="commitSha"&&(i.length<7||!/^[0-9a-fA-F]+$/.test(i)))throw new Error("operation_context_invalid");t[r]=i.trim()}return t}function Ve(n){return n.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":n.stage==="STARTING"?"STARTING":n.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":n.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":n.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":n.stage==="WAITING_FOR_PARTICIPANTS"?He(n):n.stage==="DENIED"?"DENIED":n.stage==="EXPIRED"?"EXPIRED":n.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":n.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":n.stage==="MATERIAL_RELEASED"||n.stage==="RECONSTRUCTED"?"RECONSTRUCTING":n.stage==="ACTIONS_OPEN"?"OPEN":Be.has(n.stage)?"ENDED":"CONTINUING"}var Be=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function He(n){return n.governanceGate==="DMS"?"WAITING_FOR_DMS":n.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":n.governanceGate==="AUTHENTICATION"||n.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var ue=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},I=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function J(n,e,t={},r=!1){let i=t.operationContext===void 0?void 0:T(t.operationContext);if(i!==void 0&&!r)throw new Error("operation_context_automation_only");if(t.signal?.aborted)throw m();let s=await n.getPlan(e),a=await n.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"}):Ee(a.id);if(t.signal?.aborted)throw m();let o=()=>n.prepareReveal(e,t.signal,async f=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(f)});if(r||await o(),t.signal?.aborted)throw m();let d=t.idempotencyKey??crypto.randomUUID(),l;try{l=await n.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:d,...t.protectedCopy?{protectedCopy:!0}:{},...i!==void 0?{operationContext:i}:{}})}catch(f){if(f?.code!=="merge_process_already_active")throw f;let h=await n.getActivePlanReveal(e);throw!h||h.planId!==e||h.mode!==(t.mode??"DIRECT")||h.protectedCopy!==void 0&&h.protectedCopy!==(t.protectedCopy??!1)?f:Ee(h.id)}if(l.protectedCopy!==void 0&&l.protectedCopy!==(t.protectedCopy??!1))throw await n.closeReveal(l.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let p;try{if(t.signal?.aborted)throw m();let f=await je(n,l,t);if(t.signal?.aborted||(r&&await o(),t.signal?.aborted)||(_(t,"RELEASING_MATERIAL",f),t.signal?.aborted))throw m();let h=await n.releaseRevealMaterial(f.id,f.materialVersion??"1");if(t.signal?.aborted||(f.mode==="GOVERNED"&&await n.markRevealSharesCollected(f.id),t.signal?.aborted))throw m();let x;try{x=await Ze(n,f,et(h),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(_(t,"RECONSTRUCTING",f),t.signal?.aborted))throw m();try{p=await n.reconstructPlanMaterial(x)}catch(y){throw t.signal?.aborted?m():(await n.reportRevealReconstruction(f.id,{status:"FAILED",errorCode:Qe(y)}),y)}if(t.signal?.aborted)throw m();let N=await n.reportRevealReconstruction(f.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(_(t,"OPEN",N),t.signal?.aborted))throw m();return new me(n,N,s,p,t.signal)}catch(f){throw p?.fill(0),await Se(n,l.id,t.signal?.aborted?"CANCELED":"ERROR"),f}}function Ee(n){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:n})}var We=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function je(n,e,t){let r=await w(()=>n.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw m();if(t.onSession?.(r),t.onProgress?.({phase:Ve(r),session:r}),r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED")return r;if(We.has(r.stage))throw new pe(r.stage);await ge(t.pollIntervalMs??1500,t.signal),r=await w(()=>n.getReveal(e.id,t.signal),t.signal)}}var pe=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function _(n,e,t){n.onProgress?.({phase:e,session:t})}function ge(n,e){return e?.aborted?Promise.reject(m()):new Promise((t,r)=>{let i=setTimeout(a,Math.max(0,n)),s=()=>{clearTimeout(i),r(m())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var me=class{constructor(e,t,r,i,s){this.client=e;this.session=t;this.plan=r;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 ue;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let r;return await this.consumeFields([{selector:e,options:t}],([i])=>{r=i?.value}),r}async consumeFields(e,t){if(e.length===0)throw new I("asset_selector_invalid");if(!this.client.assetDecoder)throw new I("asset_decoder_required");let r=e.map(({selector:s,options:a={}})=>{let o=Ye(s),d=this.plan.assets.find(l=>(l.code??l.id)===o.asset);if(!d)throw new I("asset_not_found");if(d.isBinary)throw new I("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new I("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 r)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=r.map(a=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===a.asset.id||d.id===a.assetCode);if(!o)throw new I("asset_value_invalid");return{selector:a.selector,value:Xe(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",we(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new I("asset_selector_invalid");if(!this.client.assetDecoder)throw new I("asset_decoder_required");let r=this.plan.assets.find(a=>a.code===e||a.id===e);if(!r)throw new I("asset_not_found");if(!r.isBinary)throw new I("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:r.id,action:"EXPORT_ASSET"}),s;try{let a=this.client.assetDecoder(this.material).find(o=>o.id===r.id||o.id===r.code);if(!a||!(a.data instanceof Uint8Array))throw new I("asset_value_invalid");s=a.data.slice(),await t({id:r.id,fileName:r.fileName,mimeType:r.mimeType,bytes:s})}catch(a){throw await this.reportAction(i.id,"FAILED",we(a)),a}finally{s?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,r){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...r===void 0?{}:{errorCode:r}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=Se(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 Ye(n){if(typeof n=="string"){let e=n.lastIndexOf(".");if(e<=0||e===n.length-1)throw new I("asset_selector_invalid");n={asset:n.slice(0,e),field:n.slice(e+1)}}if(!n.asset?.trim()||!n.field?.trim())throw new I("asset_selector_invalid");return{asset:n.asset,field:n.field}}function Xe(n,e,t){let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new I("asset_value_invalid")}if(!r||typeof r!="object"||Array.isArray(r))throw new I("asset_value_invalid");if(!(e in r)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?le[t]:void 0)?.includes(e))return"";throw new I("asset_value_invalid")}return r[e]}function we(n){if(n instanceof I)return n.code;let e=n?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function Qe(n){let e=n?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Ze(n,e,t,r){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await w(()=>r.selectCustodianDevice?.(),r.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!r.proDevice)throw new Q;let l=await w(()=>n.getRevealCustodianClaimable(e.id,r.signal),r.signal);if(Ae(l,i.id,e.planId),!l.shares.includes(i.data))throw new b;_(r,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:p}=await w(()=>r.proDevice.write(l,r.signal),r.signal);if(r.signal?.aborted)throw m();if(!p?.trim())throw new b;if(await n.claimRevealCustodianShare(e.id,l.id,p),r.signal?.aborted||(await n.collectRevealCustodianShare(e.id,l.id),r.signal?.aborted))throw m();return{...t,shares:t.shares.filter(f=>f!==i).concat(l.shares.map((f,h)=>({id:`${l.id}:${h}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:f})))}}if(d!=="SK_MOBILE")throw new b;if(r.signal?.aborted)throw m();return await n.distributeRevealCustodianShare(e.id),_(r,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await w(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};r.onSession?.(d),_(r,"WAITING_FOR_CUSTODIAN_CLAIM",d),await ge(r.pollIntervalMs??1500,r.signal),s=await w(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!r.proDevice)throw new Q;if(!s.shareId||!s.deviceId)throw new b;_(r,"CONNECTING_SAFEKEY_PRO",e);let d=await w(()=>r.proDevice.read({shareId:s.shareId,planId:e.planId},r.signal),r.signal);if(r.signal?.aborted)throw m();if(Ae(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new b;if(await n.collectRevealCustodianShare(e.id,s.shareId),r.signal?.aborted)throw m();return{...t,shares:t.shares.concat(d.shares.map((l,p)=>({id:`${d.id}:${p}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:l})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new b;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(r.onSession?.(a),_(r,"WAITING_FOR_CUSTODIAN",a),r.signal?.aborted)throw m();await n.requestRevealCustodianRelease(e.id);let o=await Je(n,e,r);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,l)=>({id:`${o.id}:${l}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function Ae(n,e,t){if(n?.id!==e||n.planId!==t||!Array.isArray(n.shares)||n.shares.length===0||n.shares.some(r=>typeof r!="string"||!r))throw new b}async function w(n,e){if(e?.aborted)throw m();if(!e)return n();let t,r=new Promise((i,s)=>{t=()=>s(m()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw m();return n()}),r])}finally{t&&e.removeEventListener("abort",t)}}async function Je(n,e,t){let r=Date.parse(e.expiresAt),i=Number.isFinite(r)?Math.min(r,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new Z;let s=await w(()=>n.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new Z;if(s&&s.status!=="PENDING"){let a=s;if(a.shares?.length)return a;throw new b}await ge(t.pollIntervalMs??1500,t.signal)}}var b=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Q=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Z=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function et(n){return n&&typeof n=="object"&&"material"in n?n.material:n}async function Se(n,e,t){if(t!=="CANCELED"){try{await n.closeReveal(e,t)}catch(a){if(!tt(a))throw a}return}let r=new AbortController,i,s=new Promise((a,o)=>{i=setTimeout(()=>{r.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([n.closeReveal(e,t,r.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 tt(n){let e=n&&typeof n=="object"&&"code"in n?String(n.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function m(){let n=new Error("reveal_canceled");return n.name="AbortError",n}var U=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 F,this.state=t.state??new $,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??it(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 c;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new c;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new c;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new c;return this.api.listMemberLogs(e,t)}listOrganizationMembers(e){if(!this.api)throw new c;return this.api.listOrganizationMembers(e)}listOrganizationAuditTrail(e){if(!this.api)throw new c;return this.api.listOrganizationAuditTrail(e)}getOrganizationInsights(e){if(!this.api)throw new c;return this.api.getOrganizationInsights(e)}getPlanResponsibilities(e){if(!this.api)throw new c;return this.api.getPlanResponsibilities(e)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return D(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new c;return K(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new j){if(this.requireApplication(),!this.api)throw new c;return new Y(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),r=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",r)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new S({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,r){let i=await this.keyVault.load(e);if(i)return rt(i);let s=await this.masterKeys?.resolve(e,t,r);if(!s)throw new S(e);return await this.keyVault.store(e,nt(s)),s}async prepareReveal(e,t,r){if(!this.api)throw new c;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,r)}}async revealPlan(e,t){await this.prepareReveal(e);let r=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(r)}collectPlanMaterial(e,t){if(!this.api)throw new c;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new B;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,r){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 S({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=z(e);if(!i)throw new S({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,r)}initializeGovernedReveal(e,t){if(!this.api)throw new c;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new c;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new c;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,r){if(!this.api)throw new c;return this.api.createRevealFileAccess(e,t,r)}cancelRevealFileAccess(e,t,r){if(!this.api)throw new c;return this.api.cancelRevealFileAccess(e,t,r)}getActivePlanReveal(e){if(!this.api)throw new c;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new c;return this.api.getReveal(e,t)}openReveal(e,t){return J(this,e,t)}async withReveal(e,t,r){let i=await this.openReveal(e,t);try{let s=await r(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 c;return be(this.api,e,t,r=>this.prepareReveal(r))}markRevealSharesCollected(e){if(!this.api)throw new c;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new c;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new c;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,r){if(!this.api)throw new c;return this.api.claimRevealCustodianShare(e,t,r)}collectRevealCustodianShare(e,t){if(!this.api)throw new c;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new c;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,r){if(!this.api)throw new c;return this.api.closeReveal(e,t,r)}abortPlanAccess(e,t){if(!this.api)throw new c;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new c;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new c;return Pe(this.api,e,t)}reportRevealActionOutcome(e,t,r){if(!this.api)throw new c;return this.api.reportRevealActionOutcome(e,t,r)}getCustodianShare(e,t){if(!this.api)throw new c;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new c;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new c;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new c;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new c;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let r=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=r.validatorShares.map(l=>Object.assign({},l,{shareType:"VALIDATOR_SHARD"})),a=i.dataShards.map(l=>Object.assign({},l,{shareType:"DATA_SHARD"})),o=i.backupShards.map(l=>Object.assign({},l,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(l=>Object.assign({},l,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||r.dek,shares:s.concat(a,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let r=await this.reconstructPlanMaterial(t);if(!this.api)throw new c;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),r}useCase(e,t){if(!this.coreSdk)throw new fe;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new S({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},fe=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function nt(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function rt(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function it(n){if(!n.api)return;let e={api:n.api,...n.masterKey?.source?{source:n.masterKey.source}:{},...n.masterKey?.relay?{relay:n.masterKey.relay}:{}};if(n.applicationId)return oe({...e,applicationId:n.applicationId});if(n.organizationId!==void 0)return oe({...e,organizationId:n.organizationId})}function _e(n){return{async openReveal(e,t={}){let r=t.operationContext===void 0?void 0:T(t.operationContext);if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let i=await n.api.planKeyReference(e),s=z(i);if(!i.masterKeyWrapped||!s||i.planId!==e)throw new Error("automation_plan_key_reference_invalid");let a=new M({api:{startRelaySession:d=>n.api.startMasterKeyRelaySession(crypto.randomUUID(),e,d),readRelaySession:(d,l)=>n.api.readMasterKeyRelaySession(d,l),cancelRelaySession:(d,l)=>n.api.cancelMasterKeyRelaySession(d,l)}}),o=new U(void 0,{api:n.api,reconstructor:n.reconstructor,assetDecoder:n.assetDecoder,masterKeys:{resolve:(d,l,p)=>{if(d.system!==s.system||d.contextId!==s.contextId)throw new Error("automation_plan_key_reference_mismatch");return a.resolve(l,p)}}});return J(o,e,{...t,...r===void 0?{}:{operationContext:r}},!0)}}}var st=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],at=["DIRECT","GOVERNED"],ot=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],dt=["ACTIVE","REVOKED"],lt=["SK_MOBILE"],ct=["ACTIVE","INACTIVE"];function Ie(n){let e=P(n),t=ut(e),r=P(e.source),i=g(r.kind,"source.kind");return{...t,assets:O(e.assets).map(s=>{let a=P(s);return{id:g(a.id,"asset.id"),code:L(a.code),type:v(g(a.type,"asset.type"),H),name:g(a.name,"asset.name"),isBinary:pt(a.isBinary,"asset.isBinary"),fieldNames:O(a.fieldNames).map(o=>g(o,"asset.fieldNames")),fileName:L(a.fileName),mimeType:L(a.mimeType),size:a.size===void 0||a.size===null?void 0:A(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:O(a.matchOrigins).map(o=>g(o,"asset.matchOrigins"))}}),participants:O(e.participants).map(s=>{let a=P(s);return{id:g(a.id,"participant.id"),displayName:g(a.displayName,"participant.displayName"),relationships:O(a.relationships).map(o=>v(g(o,"relationship"),ot)),lifecycle:v(g(a.lifecycle,"participant.lifecycle"),dt)}}),revealPolicy:(()=>{let s=P(e.revealPolicy);return{masterKeyRelease:v(g(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:v(g(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=P(e.dms);return{subjectEmail:g(s.subjectEmail,"dms.subjectEmail"),countdownDays:A(s.countdownDays,"dms.countdownDays"),countdownHours:A(s.countdownHours,"dms.countdownHours"),countdownMinutes:A(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:v(g(r.system,"source.system"),["INHERITI_BUSINESS"]),status:v(g(r.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function ut(n){let e=P(n),t=P(e.assetSummary),r=P(e.governance),i=P(e.participantSummary);return{id:g(e.id,"id"),name:g(e.name,"name"),description:L(e.description),status:v(g(e.status,"status"),st),createdAt:g(e.createdAt,"createdAt"),configuredAt:L(e.configuredAt),assetSummary:{count:A(t.count,"assetSummary.count"),types:O(t.types).map(s=>v(g(s,"assetType"),H)),names:xe(t.names).map(s=>g(s,"assetSummary.names"))},governance:{mode:v(g(r.mode,"governance.mode"),at),minimumApprovals:A(r.minimumApprovals,"minimumApprovals")},participantSummary:{owners:A(i.owners,"owners"),mergers:A(i.mergers,"mergers"),moderators:A(i.moderators,"moderators")},authentication:xe(e.authentication).map(s=>{let a=P(s);return{id:v(g(a.id,"authentication.id"),lt),status:v(g(a.status,"authentication.status"),ct)}})}}function v(n,e){return e.includes(n)?n:{kind:"UNKNOWN",raw:n}}function P(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function xe(n){return n==null?[]:O(n)}function O(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function g(n,e){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function L(n){return n==null?void 0:g(n,"optional")}function A(n,e){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function pt(n,e){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}function Ce(n){return typeof n.error=="string"?/^[a-z][a-z0-9_]*$/.test(n.error)?n.error:typeof n.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(n.validationErrors)?n.validationErrors:n.error||void 0:n.error?.code??n.name??n.message}function Te(n){return typeof n.error=="object"&&n.error?.requestId?n.error.requestId:n.description}var ee=class extends Error{constructor(t,r,i,s){super(r??`elements_api_request_failed_${t}`);this.status=t;this.code=r;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}};var te=class{constructor(e,t,r){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=r}firstRelayStates=new Map;async startReveal(e,t){let r=t.operationContext===void 0?void 0:T(t.operationContext);return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey,...r===void 0?{}:{operationContext:r}},!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 Ie(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,r){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,r)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...s}=r;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,r){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:r},!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 r=this.firstRelayStates.get(e);return r?(this.firstRelayStates.delete(e),Promise.resolve(r)):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,r,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});r!==void 0&&d.set("content-type","application/json");let l=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:r===void 0?void 0:JSON.stringify(r),signal:a});a?.throwIfAborted();let p;try{p=await l.json()}catch{a?.throwIfAborted()}if(!l.ok||p&&p.ok===!1||i&&p?.result===void 0)throw new ee(l.status,p&&Ce(p),p&&Te(p));return p?.result}};import{createNodeSsdpV2Processor as Rt}from"@safetech/inheriti-core-sdk/node";async function Oe(n,e){if(!e)throw new Error("master_key_required");let t=mt(e),r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=gt(n),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},r,a);return ft(new Uint8Array(o))}function mt(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function gt(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function ft(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var q=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let r=await Me("plan_key_unwrap_failed",()=>Oe(e.planKey,t)),i=await crypto.subtle.importKey("raw",ye(r),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await Me("plan_share_decryption_failed",()=>vt(o.data,i));ht(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 ne("plan_share_reconstruction_failed",yt(o))}}},ne=class extends Error{constructor(t,r){super(t);this.code=t;this.reason=r;this.name="PlanMaterialReconstructionFailed"}},It=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 yt(n){let e=n instanceof Error?n.message:void 0;if(e)return It.has(e)?e:void 0}async function Me(n,e){try{return await e()}catch{throw new ne(n)}}function ht(n){return n==="VALIDATOR_SHARD"||n==="CUSTODIAN_KEY_SHARD"}async function vt(n,e){let t=n.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let r=ye(n.slice(0,t)),i=ye(n.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,i);return new TextDecoder().decode(s)}function ye(n){let e=atob(n),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let i=0;i<e.length;i+=1)r[i]=e.charCodeAt(i);return t}var G=class extends q{constructor(e){super(()=>Rt(e))}};function ar(n){let e=new te(n.apiUrl,n.getBearerToken,n.transport??globalThis.fetch.bind(globalThis));return{supportsOperationContext:!0,..._e({api:e,reconstructor:new G(n.workerUrl),assetDecoder:Pt}),getPlan:t=>e.getPlan(t)}}export{ar as createNodeAutomationRevealClient,T as validateOperationContext};
|
|
1
|
+
import{decodeAssetContainer as Rt}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as ke,generateRSAOAEPKeyPair as Ke}from"@safetech/inheriti-core-sdk/crypto";var re=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},ie=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},se=class extends Error{code="master_key_relay_cancellation_failed";constructor(e){super("master_key_relay_cancellation_failed",{cause:e}),this.name="MasterKeyRelayCancellationFailed"}},M=class{constructor(e){this.options=e}async resolve(e,t){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let{publicKeyBase64:r,privateKey:i}=await Ke();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let s=await this.options.api.startRelaySession(r),a=this.options.pollIntervalMs??2e3,o=Date.now()+(this.options.timeoutMs??600*1e3),d=this.options.sleep??(y=>new Promise(P=>setTimeout(P,y))),l=!0,p=!1,f,h=()=>f??=(async()=>{let y=new AbortController,P,De=new Promise((bt,Ne)=>{P=setTimeout(()=>{y.abort(),Ne(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,y.signal),De])}finally{clearTimeout(P)}})(),x,N=new Promise((y,P)=>{x=()=>{l&&h().catch(()=>{}),P(new DOMException("The operation was aborted","AbortError"))},e?.addEventListener("abort",x,{once:!0})});N.catch(()=>{});try{if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");for(await t?.(s),p=!0;Date.now()<o;){if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");let y=await Promise.race([this.options.api.readRelaySession(s.sessionId,e),N]);if(y.status!=="PENDING"&&(l=!1),e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(y.status==="DELIVERED"&&y.sealedMasterKey){let P=(await ke(y.sealedMasterKey,i)).trim().toLowerCase();if(e?.aborted)throw new DOMException("The operation was aborted","AbortError");if(!/^[0-9a-f]{64}$/.test(P))throw new Error("invalid_master_key_material");return P}if(y.status==="EXPIRED")throw new ie(s.sessionId);await Ue(d,a,e)}throw new re(s.sessionId)}catch(y){if(l&&(!p||e?.aborted))try{await h()}catch(P){if(e?.aborted)throw new se(P)}throw y}finally{x&&e?.removeEventListener("abort",x)}}};async function Ue(n,e,t){if(!t)return n(e);if(t.aborted)throw new DOMException("The operation was aborted","AbortError");await new Promise((r,i)=>{let s=()=>i(new DOMException("The operation was aborted","AbortError"));t.addEventListener("abort",s,{once:!0}),n(e).then(r,i).finally(()=>t.removeEventListener("abort",s))})}function oe(n){return{resolve:async(e,t,r)=>{if(n.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==n.organizationId)return;let i=await n.source?.resolve();return i||ae(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}if(Le(e,n.applicationId)){let i=await n.source?.resolve();return i||ae(n,()=>n.api.masterKeyAcquisition(),void 0,t,r)}return ae(n,()=>n.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId},t,r)}}}function Le(n,e){return n.system==="INHERITI_ELEMENTS"&&n.contextId===e}async function ae(n,e,t,r,i){if((await e()).relayAvailable)return new M({...n.relay,api:qe(n.api,t)}).resolve(r,i)}function qe(n,e){return{startRelaySession:t=>e?n.startMasterKeyRelaySession(t,e):n.startMasterKeyRelaySession(t),readRelaySession:(t,r)=>n.readMasterKeyRelaySession(t,r),cancelRelaySession:(t,r)=>n.cancelMasterKeyRelaySession(t,r)}}function k(n){return`${n.system}:${n.contextId}`}function z(n){return n.sourceReference?{system:n.sourceReference.system,contextId:n.sourceReference.contextId}:n.tenantId?{system:"INHERITI_ELEMENTS",contextId:n.tenantId}:void 0}var S=class extends Error{constructor(t){super(`master_key_required:${k(t)}`);this.ref=t;this.name="MasterKeyRequired"}};var F=class{keys=new Map;async store(e,t){let r=k(e),i=t.slice();this.keys.get(r)?.fill(0),this.keys.set(r,i)}async load(e){return this.keys.get(k(e))?.slice()}async remove(e){let t=k(e);this.keys.get(t)?.fill(0),this.keys.delete(t)}};var $=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 V=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},c=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var B=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var H=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],le={"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"]};var u=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},E=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function K(n){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(n).some(t=>!e.includes(t)))throw new E("plan_material_field_unknown");if(de(n.dataShards,"data_shards_invalid"),de(n.backupShards,"backup_shards_invalid"),n.validatorShares!==void 0&&de(n.validatorShares,"validator_shares_invalid"),n.validatorShares?.length&&!n.encryptedKey)throw new E("validator_shares_require_encrypted_key");if(n.protectionProtocol!==void 0&&n.protectionProtocol!=="SSDP_PLUS_V1"&&n.protectionProtocol!=="SSDP_PLUS_V2")throw new E("protection_protocol_invalid");if(n.operation!==void 0&&n.operation!=="DRAFT"&&n.operation!=="FINALIZE")throw new E("material_operation_invalid")}function de(n,e){if(!Array.isArray(n))throw new E(e);for(let t of n){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new E(e);if(t.data!==void 0&&typeof t.data!="string")throw new E(e)}}function D(n){if(C(n,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Fe(n.idempotencyKey))throw new u("idempotency_key_invalid");if(!n.name?.trim())throw new u("plan_name_required");if(!n.assets.length)throw new u("assets_required");let e=new Set;for(let t of n.assets){if(C(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 u("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!H.includes(t.type))throw new u("asset_type_invalid");let r=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==r)throw new u("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 u("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new u("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(s=>!s.trim()))throw new u("asset_field_names_invalid");if(Ge(t.matchOrigins),!t.isBinary){let s=le[t.type];if(!s||i.some(a=>!s.includes(a)))throw new u("asset_field_name_not_canonical")}}if(!n.participants.length)throw new u("participants_required");for(let t of n.participants){if(C(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!ve(t.routingEmail))throw new u("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new u("participant_relationships_invalid")}ze(n)}function Ge(n){if(n===void 0)return;if(!n.length)throw new u("asset_match_origins_invalid");let e=n.map(t=>{if(typeof t!="string"||!t.trim())throw new u("asset_match_origin_invalid");try{let r=new URL(t);if(!["http:","https:"].includes(r.protocol)||r.origin!==t.trim())throw new u("asset_match_origin_invalid");return r.origin}catch(r){throw r instanceof u?r:new u("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new u("asset_match_origins_duplicated")}function ze(n){let e=n.policy;if(e&&C(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new u("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){C(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new u("authentication_mode_invalid")}if(e.moderation){C(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=n.participants.filter(d=>d.relationships.includes("MODERATOR"));if(s.length===0)throw new u("moderation_requires_moderators");let a=e.moderation.minimumApprovals;if(a!==void 0&&(!Number.isInteger(a)||a<1||a>s.length))throw new u("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new u("approval_mode_invalid")}let t=e.dms;if(!t)return;C(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let r=t.countdownHours??0,i=t.countdownMinutes??0;if(!ve(t.subjectEmail))throw new u("dms_subject_invalid");if(!n.participants.some(s=>he(s.routingEmail)===he(t.subjectEmail)))throw new u("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(r)||!Number.isInteger(i)||t.countdownDays<0||r<0||r>23||i<0||i>59||t.countdownDays+r+i===0)throw new u("dms_countdown_invalid")}function Fe(n){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(n)}function ve(n){return typeof n=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(n.normalize("NFC").trim())}function he(n){return n.normalize("NFC").trim().toLowerCase()}function C(n,e,t){if(Object.keys(n).some(r=>!e.includes(r)))throw new u(t)}var j=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)}},Y=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),D(e),W(t.signal);let r=await this.api.startPlanCreation(e);return r.outcome==="COMPLETED"||r.outcome==="CANCELED"?await this.checkpoints.remove(r.operationId):await this.saveCheckpoint(e,r),t.onProgress?.(r.stage),r}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,r,i,s={}){D(t);let a=await this.checkpoints.load(e);if(!a)throw new X("creation_checkpoint_missing");if(a.idempotencyKey!==t.idempotencyKey||a.declarationHash!==await Pe(t))throw new X("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;W(s.signal),s.onProgress?.("ENCRYPTING");let d=await i.encrypt({planId:o.planId,declaration:t,secrets:r,signal:s.signal});W(s.signal),s.onProgress?.("GENERATING_SHARES");let l=await i.generateShares({planId:o.planId,declaration:t,encrypted:d,signal:s.signal});W(s.signal),K(l);let p=await this.api.supplyPlanCreationMaterial(e,l);return s.onProgress?.(p.stage),p.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,p),p}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 Pe(e),serverStage:t.stage})}},X=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Pe(n){let e=JSON.stringify({name:n.name.normalize("NFC").trim(),description:n.description?.normalize("NFC").trim()??null,assets:n.assets.map(r=>({...r,fieldNames:[...r.fieldNames??[]]})).sort((r,i)=>r.clientAssetRef.localeCompare(i.clientAssetRef)),participants:n.participants.map(r=>({...r,routingEmail:r.routingEmail.normalize("NFC").trim(),relationships:[...r.relationships].sort()})).sort((r,i)=>r.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:n.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(r=>r.toString(16).padStart(2,"0")).join("")}function W(n){if(n?.aborted)throw n.reason??new DOMException("Aborted","AbortError")}async function Re(n,e,t){let r=await n.getReveal(e);if(r.stage!=="ACTIONS_OPEN")throw new V(r.stage);return n.authorizeRevealAction(e,t)}function $e(n){let e=n?.status;return e===400||e===401||e===403}async function be(n,e,t,r){let i=await n.getReveal(e);try{await r(i.planId)}catch(s){if(!$e(s))throw s}return n.releaseRevealMaterial(e,t)}var ce={reason:500,commitSha:64,workflow:200,pipeline:300,target:200,image:300,version:100};function T(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("operation_context_invalid");let e=n;for(let r of Object.keys(e))if(!Object.hasOwn(ce,r))throw new Error("operation_context_invalid");let t={};for(let r of Object.keys(ce)){if(!Object.hasOwn(e,r))continue;let i=e[r];if(typeof i!="string"||!i.trim()||i.length>ce[r]||/[\x00-\x1f\x7f-\x9f]/.test(i)||r==="commitSha"&&(i.length<7||!/^[0-9a-fA-F]+$/.test(i)))throw new Error("operation_context_invalid");t[r]=i.trim()}return t}function Ve(n){return n.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":n.stage==="STARTING"?"STARTING":n.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":n.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":n.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":n.stage==="WAITING_FOR_PARTICIPANTS"?He(n):n.stage==="DENIED"?"DENIED":n.stage==="EXPIRED"?"EXPIRED":n.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":n.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":n.stage==="MATERIAL_RELEASED"||n.stage==="RECONSTRUCTED"?"RECONSTRUCTING":n.stage==="ACTIONS_OPEN"?"OPEN":Be.has(n.stage)?"ENDED":"CONTINUING"}var Be=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function He(n){return n.governanceGate==="DMS"?"WAITING_FOR_DMS":n.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":n.governanceGate==="AUTHENTICATION"||n.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var ue=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},I=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function J(n,e,t={},r=!1){let i=t.operationContext===void 0?void 0:T(t.operationContext);if(i!==void 0&&!r)throw new Error("operation_context_automation_only");if(t.signal?.aborted)throw m();let s=await n.getPlan(e),a=await n.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"}):Ee(a.id);if(t.signal?.aborted)throw m();let o=()=>n.prepareReveal(e,t.signal,async f=>{t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await t.onRelaySession?.(f)});if(r||await o(),t.signal?.aborted)throw m();let d=t.idempotencyKey??crypto.randomUUID(),l;try{l=await n.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:d,...t.protectedCopy?{protectedCopy:!0}:{},...i!==void 0?{operationContext:i}:{}})}catch(f){if(f?.code!=="merge_process_already_active")throw f;let h=await n.getActivePlanReveal(e);throw!h||h.planId!==e||h.mode!==(t.mode??"DIRECT")||h.protectedCopy!==void 0&&h.protectedCopy!==(t.protectedCopy??!1)?f:Ee(h.id)}if(l.protectedCopy!==void 0&&l.protectedCopy!==(t.protectedCopy??!1))throw await n.closeReveal(l.id,"ERROR",t.signal),Object.assign(new Error("reveal_protected_copy_mismatch"),{code:"reveal_protected_copy_mismatch"});let p;try{if(t.signal?.aborted)throw m();let f=await je(n,l,t);if(t.signal?.aborted||(r&&await o(),t.signal?.aborted)||(_(t,"RELEASING_MATERIAL",f),t.signal?.aborted))throw m();let h=await n.releaseRevealMaterial(f.id,f.materialVersion??"1");if(t.signal?.aborted||(f.mode==="GOVERNED"&&await n.markRevealSharesCollected(f.id),t.signal?.aborted))throw m();let x;try{x=await Ze(n,f,et(h),t)}finally{t.proDevice?.clearPin?.()}if(t.signal?.aborted||(_(t,"RECONSTRUCTING",f),t.signal?.aborted))throw m();try{p=await n.reconstructPlanMaterial(x)}catch(y){throw t.signal?.aborted?m():(await n.reportRevealReconstruction(f.id,{status:"FAILED",errorCode:Qe(y)}),y)}if(t.signal?.aborted)throw m();let N=await n.reportRevealReconstruction(f.id,{status:"SUCCEEDED"});if(t.signal?.aborted||(_(t,"OPEN",N),t.signal?.aborted))throw m();return new me(n,N,s,p,t.signal)}catch(f){throw p?.fill(0),await Se(n,l.id,t.signal?.aborted?"CANCELED":"ERROR"),f}}function Ee(n){return Object.assign(new Error("reveal_restart_required"),{code:"reveal_restart_required",revealId:n})}var We=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function je(n,e,t){let r=await w(()=>n.getReveal(e.id,t.signal),t.signal);for(;;){if(t.signal?.aborted)throw m();if(t.onSession?.(r),t.onProgress?.({phase:Ve(r),session:r}),r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED")return r;if(We.has(r.stage))throw new pe(r.stage);await ge(t.pollIntervalMs??1500,t.signal),r=await w(()=>n.getReveal(e.id,t.signal),t.signal)}}var pe=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function _(n,e,t){n.onProgress?.({phase:e,session:t})}function ge(n,e){return e?.aborted?Promise.reject(m()):new Promise((t,r)=>{let i=setTimeout(a,Math.max(0,n)),s=()=>{clearTimeout(i),r(m())};function a(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var me=class{constructor(e,t,r,i,s){this.client=e;this.session=t;this.plan=r;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 ue;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let r;return await this.consumeFields([{selector:e,options:t}],([i])=>{r=i?.value}),r}async consumeFields(e,t){if(e.length===0)throw new I("asset_selector_invalid");if(!this.client.assetDecoder)throw new I("asset_decoder_required");let r=e.map(({selector:s,options:a={}})=>{let o=Ye(s),d=this.plan.assets.find(l=>(l.code??l.id)===o.asset);if(!d)throw new I("asset_not_found");if(d.isBinary)throw new I("action_not_allowed");if(!d.fieldNames.includes(o.field))throw new I("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 r)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=r.map(a=>{let o=this.client.assetDecoder(this.material).find(d=>d.id===a.asset.id||d.id===a.assetCode);if(!o)throw new I("asset_value_invalid");return{selector:a.selector,value:Xe(o.data,a.field,a.asset.type)}});await t(s)}catch(s){throw await Promise.all(i.map(a=>this.reportAction(a.id,"FAILED",we(s)))),s}await Promise.all(i.map(s=>this.reportAction(s.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new I("asset_selector_invalid");if(!this.client.assetDecoder)throw new I("asset_decoder_required");let r=this.plan.assets.find(a=>a.code===e||a.id===e);if(!r)throw new I("asset_not_found");if(!r.isBinary)throw new I("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:r.id,action:"EXPORT_ASSET"}),s;try{let a=this.client.assetDecoder(this.material).find(o=>o.id===r.id||o.id===r.code);if(!a||!(a.data instanceof Uint8Array))throw new I("asset_value_invalid");s=a.data.slice(),await t({id:r.id,fileName:r.fileName,mimeType:r.mimeType,bytes:s})}catch(a){throw await this.reportAction(i.id,"FAILED",we(a)),a}finally{s?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,r){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...r===void 0?{}:{errorCode:r}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=Se(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 Ye(n){if(typeof n=="string"){let e=n.lastIndexOf(".");if(e<=0||e===n.length-1)throw new I("asset_selector_invalid");n={asset:n.slice(0,e),field:n.slice(e+1)}}if(!n.asset?.trim()||!n.field?.trim())throw new I("asset_selector_invalid");return{asset:n.asset,field:n.field}}function Xe(n,e,t){let r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{throw new I("asset_value_invalid")}if(!r||typeof r!="object"||Array.isArray(r))throw new I("asset_value_invalid");if(!(e in r)){if((typeof t=="string"&&t!=="PLAIN-TEXT"&&t!=="SEED-PHRASE"?le[t]:void 0)?.includes(e))return"";throw new I("asset_value_invalid")}return r[e]}function we(n){if(n instanceof I)return n.code;let e=n?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function Qe(n){let e=n?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Ze(n,e,t,r){let i=t.shares.find(d=>d.shareType==="CUSTODIAN_KEY_SHARD");if(i){let d=await w(()=>r.selectCustodianDevice?.(),r.signal)??"SK_MOBILE";if(d==="SK_PRO"){if(!r.proDevice)throw new Q;let l=await w(()=>n.getRevealCustodianClaimable(e.id,r.signal),r.signal);if(Ae(l,i.id,e.planId),!l.shares.includes(i.data))throw new b;_(r,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:p}=await w(()=>r.proDevice.write(l,r.signal),r.signal);if(r.signal?.aborted)throw m();if(!p?.trim())throw new b;if(await n.claimRevealCustodianShare(e.id,l.id,p),r.signal?.aborted||(await n.collectRevealCustodianShare(e.id,l.id),r.signal?.aborted))throw m();return{...t,shares:t.shares.filter(f=>f!==i).concat(l.shares.map((f,h)=>({id:`${l.id}:${h}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:f})))}}if(d!=="SK_MOBILE")throw new b;if(r.signal?.aborted)throw m();return await n.distributeRevealCustodianShare(e.id),_(r,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let s=await w(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let d={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};r.onSession?.(d),_(r,"WAITING_FOR_CUSTODIAN_CLAIM",d),await ge(r.pollIntervalMs??1500,r.signal),s=await w(()=>n.getRevealCustodianAccess(e.id,r.signal),r.signal)}if(s.status==="CLAIMED"&&s.deviceType==="SK_PRO"){if(!r.proDevice)throw new Q;if(!s.shareId||!s.deviceId)throw new b;_(r,"CONNECTING_SAFEKEY_PRO",e);let d=await w(()=>r.proDevice.read({shareId:s.shareId,planId:e.planId},r.signal),r.signal);if(r.signal?.aborted)throw m();if(Ae(d,s.shareId,e.planId),d.deviceId!==s.deviceId)throw new b;if(await n.collectRevealCustodianShare(e.id,s.shareId),r.signal?.aborted)throw m();return{...t,shares:t.shares.concat(d.shares.map((l,p)=>({id:`${d.id}:${p}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:l})))}}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new b;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};if(r.onSession?.(a),_(r,"WAITING_FOR_CUSTODIAN",a),r.signal?.aborted)throw m();await n.requestRevealCustodianRelease(e.id);let o=await Je(n,e,r);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((d,l)=>({id:`${o.id}:${l}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:d})))})}function Ae(n,e,t){if(n?.id!==e||n.planId!==t||!Array.isArray(n.shares)||n.shares.length===0||n.shares.some(r=>typeof r!="string"||!r))throw new b}async function w(n,e){if(e?.aborted)throw m();if(!e)return n();let t,r=new Promise((i,s)=>{t=()=>s(m()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw m();return n()}),r])}finally{t&&e.removeEventListener("abort",t)}}async function Je(n,e,t){let r=Date.parse(e.expiresAt),i=Number.isFinite(r)?Math.min(r,Date.now()+(t.custodianTimeoutMs??1/0)):Date.now()+(t.custodianTimeoutMs??12e4);for(;;){if(Date.now()>=i)throw new Z;let s=await w(()=>n.getRevealCustodianShare(e.id,t.signal),t.signal);if(Date.now()>=i)throw new Z;if(s&&s.status!=="PENDING"){let a=s;if(a.shares?.length)return a;throw new b}await ge(t.pollIntervalMs??1500,t.signal)}}var b=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},Q=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Z=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function et(n){return n&&typeof n=="object"&&"material"in n?n.material:n}async function Se(n,e,t){if(t!=="CANCELED"){try{await n.closeReveal(e,t)}catch(a){if(!tt(a))throw a}return}let r=new AbortController,i,s=new Promise((a,o)=>{i=setTimeout(()=>{r.abort(),o(new Error("reveal_cancellation_timed_out"))},5e3)});try{let a=await Promise.race([n.closeReveal(e,t,r.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 tt(n){let e=n&&typeof n=="object"&&"code"in n?String(n.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function m(){let n=new Error("reveal_canceled");return n.name="AbortError",n}var U=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 F,this.state=t.state??new $,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??it(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 c;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new c;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new c;return this.api.listPlanLogs(e,t)}listMemberLogs(e,t){if(!this.api)throw new c;return this.api.listMemberLogs(e,t)}listOrganizationMembers(e){if(!this.api)throw new c;return this.api.listOrganizationMembers(e)}listOrganizationAuditTrail(e){if(!this.api)throw new c;return this.api.listOrganizationAuditTrail(e)}getOrganizationInsights(e){if(!this.api)throw new c;return this.api.getOrganizationInsights(e)}getPlanResponsibilities(e){if(!this.api)throw new c;return this.api.getPlanResponsibilities(e)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return D(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new c;return K(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new c;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new j){if(this.requireApplication(),!this.api)throw new c;return new Y(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),r=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",r)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()};return this.resolveKey(t)}async organizationMasterKey(e,t){if(!this.organizationId)throw new S({system:"INHERITI_BUSINESS",contextId:"organization"});return this.resolveKey({system:"INHERITI_BUSINESS",contextId:this.organizationId},e,t)}async resolveKey(e,t,r){let i=await this.keyVault.load(e);if(i)return rt(i);let s=await this.masterKeys?.resolve(e,t,r);if(!s)throw new S(e);return await this.keyVault.store(e,nt(s)),s}async prepareReveal(e,t,r){if(!this.api)throw new c;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,r)}}async revealPlan(e,t){await this.prepareReveal(e);let r=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(r)}collectPlanMaterial(e,t){if(!this.api)throw new c;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new B;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,r){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 S({system:"INHERITI_BUSINESS",contextId:this.organizationId});let i=z(e);if(!i)throw new S({system:"INHERITI_ELEMENTS",contextId:e.planId});return this.resolveKey(i,t,r)}initializeGovernedReveal(e,t){if(!this.api)throw new c;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new c;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new c;return this.api.startReveal(e,t)}createRevealFileAccess(e,t,r){if(!this.api)throw new c;return this.api.createRevealFileAccess(e,t,r)}cancelRevealFileAccess(e,t,r){if(!this.api)throw new c;return this.api.cancelRevealFileAccess(e,t,r)}getActivePlanReveal(e){if(!this.api)throw new c;return this.organizationId?this.api.getActivePlanReveal(e):Promise.resolve(null)}getReveal(e,t){if(!this.api)throw new c;return this.api.getReveal(e,t)}openReveal(e,t){return J(this,e,t)}async withReveal(e,t,r){let i=await this.openReveal(e,t);try{let s=await r(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 c;return be(this.api,e,t,r=>this.prepareReveal(r))}markRevealSharesCollected(e){if(!this.api)throw new c;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new c;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new c;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianAccess(e,t)}getRevealCustodianShare(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianShare(e,t)}getRevealCustodianClaimable(e,t){if(!this.api)throw new c;return this.api.getRevealCustodianClaimable(e,t)}claimRevealCustodianShare(e,t,r){if(!this.api)throw new c;return this.api.claimRevealCustodianShare(e,t,r)}collectRevealCustodianShare(e,t){if(!this.api)throw new c;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new c;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t,r){if(!this.api)throw new c;return this.api.closeReveal(e,t,r)}abortPlanAccess(e,t){if(!this.api)throw new c;return this.api.abortPlanAccess(e,t)}cancelMasterKeyRelaySession(e,t){if(!this.api)throw new c;return this.api.cancelMasterKeyRelaySession(e,t)}async authorizeRevealAction(e,t){if(!this.api)throw new c;return Re(this.api,e,t)}reportRevealActionOutcome(e,t,r){if(!this.api)throw new c;return this.api.reportRevealActionOutcome(e,t,r)}getCustodianShare(e,t){if(!this.api)throw new c;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new c;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new c;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new c;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new c;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let r=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=r.validatorShares.map(l=>Object.assign({},l,{shareType:"VALIDATOR_SHARD"})),a=i.dataShards.map(l=>Object.assign({},l,{shareType:"DATA_SHARD"})),o=i.backupShards.map(l=>Object.assign({},l,{shareType:"BACKUP_SHARD"})),d=i.keyShards.map(l=>Object.assign({},l,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||r.dek,shares:s.concat(a,o,d),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let r=await this.reconstructPlanMaterial(t);if(!this.api)throw new c;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),r}useCase(e,t){if(!this.coreSdk)throw new fe;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new S({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},fe=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function nt(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function rt(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function it(n){if(!n.api)return;let e={api:n.api,...n.masterKey?.source?{source:n.masterKey.source}:{},...n.masterKey?.relay?{relay:n.masterKey.relay}:{}};if(n.applicationId)return oe({...e,applicationId:n.applicationId});if(n.organizationId!==void 0)return oe({...e,organizationId:n.organizationId})}function _e(n){return{async openReveal(e,t={}){let r=t.operationContext===void 0?void 0:T(t.operationContext);if("proDevice"in t||"selectCustodianDevice"in t)throw new Error("safekey_pro_local_device_required");let i=await n.api.planKeyReference(e),s=z(i);if(!i.masterKeyWrapped||!s||i.planId!==e)throw new Error("automation_plan_key_reference_invalid");let a=new M({api:{startRelaySession:d=>n.api.startMasterKeyRelaySession(crypto.randomUUID(),e,d),readRelaySession:(d,l)=>n.api.readMasterKeyRelaySession(d,l),cancelRelaySession:(d,l)=>n.api.cancelMasterKeyRelaySession(d,l)}}),o=new U(void 0,{api:n.api,reconstructor:n.reconstructor,assetDecoder:n.assetDecoder,masterKeys:{resolve:(d,l,p)=>{if(d.system!==s.system||d.contextId!==s.contextId)throw new Error("automation_plan_key_reference_mismatch");return a.resolve(l,p)}}});return J(o,e,{...t,...r===void 0?{}:{operationContext:r}},!0)}}}var st=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],at=["DIRECT","GOVERNED"],ot=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],dt=["ACTIVE","REVOKED"],lt=["SK_MOBILE"],ct=["ACTIVE","INACTIVE"];function Ie(n){let e=R(n),t=ut(e),r=R(e.source),i=g(r.kind,"source.kind");return{...t,assets:O(e.assets).map(s=>{let a=R(s);return{id:g(a.id,"asset.id"),code:L(a.code),type:v(g(a.type,"asset.type"),H),name:g(a.name,"asset.name"),isBinary:pt(a.isBinary,"asset.isBinary"),fieldNames:O(a.fieldNames).map(o=>g(o,"asset.fieldNames")),fileName:L(a.fileName),mimeType:L(a.mimeType),size:a.size===void 0||a.size===null?void 0:A(a.size,"asset.size"),matchOrigins:a.matchOrigins===void 0?void 0:O(a.matchOrigins).map(o=>g(o,"asset.matchOrigins"))}}),participants:O(e.participants).map(s=>{let a=R(s);return{id:g(a.id,"participant.id"),displayName:g(a.displayName,"participant.displayName"),relationships:O(a.relationships).map(o=>v(g(o,"relationship"),ot)),lifecycle:v(g(a.lifecycle,"participant.lifecycle"),dt)}}),revealPolicy:(()=>{let s=R(e.revealPolicy);return{masterKeyRelease:v(g(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:v(g(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=R(e.dms);return{subjectEmail:g(s.subjectEmail,"dms.subjectEmail"),countdownDays:A(s.countdownDays,"dms.countdownDays"),countdownHours:A(s.countdownHours,"dms.countdownHours"),countdownMinutes:A(s.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:v(g(r.system,"source.system"),["INHERITI_BUSINESS"]),status:v(g(r.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function ut(n){let e=R(n),t=R(e.assetSummary),r=R(e.governance),i=R(e.participantSummary);return{id:g(e.id,"id"),name:g(e.name,"name"),description:L(e.description),status:v(g(e.status,"status"),st),createdAt:g(e.createdAt,"createdAt"),configuredAt:L(e.configuredAt),assetSummary:{count:A(t.count,"assetSummary.count"),types:O(t.types).map(s=>v(g(s,"assetType"),H)),names:xe(t.names).map(s=>g(s,"assetSummary.names"))},governance:{mode:v(g(r.mode,"governance.mode"),at),minimumApprovals:A(r.minimumApprovals,"minimumApprovals")},participantSummary:{owners:A(i.owners,"owners"),mergers:A(i.mergers,"mergers"),moderators:A(i.moderators,"moderators")},authentication:xe(e.authentication).map(s=>{let a=R(s);return{id:v(g(a.id,"authentication.id"),lt),status:v(g(a.status,"authentication.status"),ct)}})}}function v(n,e){return e.includes(n)?n:{kind:"UNKNOWN",raw:n}}function R(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_elements_response");return n}function xe(n){return n==null?[]:O(n)}function O(n){if(!Array.isArray(n))throw new Error("invalid_elements_response");return n}function g(n,e){if(typeof n!="string"||!n)throw new Error("invalid_elements_response");return n}function L(n){return n==null?void 0:g(n,"optional")}function A(n,e){if(typeof n!="number"||!Number.isFinite(n))throw new Error("invalid_elements_response");return n}function pt(n,e){if(typeof n!="boolean")throw new Error("invalid_elements_response");return n}function Ce(n){return typeof n.error=="string"?/^[a-z][a-z0-9_]*$/.test(n.error)?n.error:typeof n.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(n.validationErrors)?n.validationErrors:n.error||void 0:n.error?.code??n.name??n.message}function Te(n){return typeof n.error=="object"&&n.error?.requestId?n.error.requestId:n.description}var ee=class extends Error{constructor(t,r,i,s){super(r??`elements_api_request_failed_${t}`);this.status=t;this.code=r;this.detail=i;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}};var te=class{constructor(e,t,r){this.apiUrl=e;this.getAutomationBearerToken=t;this.transport=r}firstRelayStates=new Map;async startReveal(e,t){let r=t.operationContext===void 0?void 0:T(t.operationContext);return await this.request("automation/reveals","POST",{planId:e,idempotencyKey:t.idempotencyKey,...r===void 0?{}:{operationContext:r}},!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 Ie(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,r){return this.request(`automation/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t},!0,void 0,r)}abortReveal(e){return this.request(`automation/reveals/${encodeURIComponent(e)}`,"DELETE",void 0,!1)}authorizeRevealAction(e,t){let{idempotencyKey:r,...i}=t;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions`,"POST",i,!0,{"idempotency-key":r})}reportRevealActionOutcome(e,t,r){let{idempotencyKey:i,...s}=r;return this.request(`automation/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,!0,{"idempotency-key":i})}async startMasterKeyRelaySession(e,t,r){await this.request("automation/master-key/relay-sessions","POST",{sessionId:e,planId:t,clientPublicKey:r},!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 r=this.firstRelayStates.get(e);return r?(this.firstRelayStates.delete(e),Promise.resolve(r)):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,r,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});r!==void 0&&d.set("content-type","application/json");let l=await this.transport(new URL(e,this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`),{method:t,headers:d,body:r===void 0?void 0:JSON.stringify(r),signal:a});a?.throwIfAborted();let p;try{p=await l.json()}catch{a?.throwIfAborted()}if(!l.ok||p&&p.ok===!1||i&&p?.result===void 0)throw new ee(l.status,p&&Ce(p),p&&Te(p));return p?.result}};import{createNodeSsdpV2Processor as Pt}from"@safetech/inheriti-core-sdk/node";async function Oe(n,e){if(!e)throw new Error("master_key_required");let t=mt(e),r=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=gt(n),s=i.slice(0,12),a=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},r,a);return ft(new Uint8Array(o))}function mt(n){let e=n.match(/.{2}/g);if(!e||e.length*2!==n.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function gt(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function ft(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var q=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let r=await Me("plan_key_unwrap_failed",()=>Oe(e.planKey,t)),i=await crypto.subtle.importKey("raw",ye(r),{name:"AES-GCM"},!1,["decrypt"]),s=[],a=[];for(let o of e.shares){let d=await Me("plan_share_decryption_failed",()=>vt(o.data,i));ht(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 ne("plan_share_reconstruction_failed",yt(o))}}},ne=class extends Error{constructor(t,r){super(t);this.code=t;this.reason=r;this.name="PlanMaterialReconstructionFailed"}},It=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 yt(n){let e=n instanceof Error?n.message:void 0;if(e)return It.has(e)?e:void 0}async function Me(n,e){try{return await e()}catch{throw new ne(n)}}function ht(n){return n==="VALIDATOR_SHARD"||n==="CUSTODIAN_KEY_SHARD"}async function vt(n,e){let t=n.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let r=ye(n.slice(0,t)),i=ye(n.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},e,i);return new TextDecoder().decode(s)}function ye(n){let e=atob(n),t=new ArrayBuffer(e.length),r=new Uint8Array(t);for(let i=0;i<e.length;i+=1)r[i]=e.charCodeAt(i);return t}var G=class extends q{constructor(e){super(()=>Pt(e))}};function ar(n){let e=new te(n.apiUrl,n.getBearerToken,n.transport??globalThis.fetch.bind(globalThis));return{supportsOperationContext:!0,..._e({api:e,reconstructor:new G(n.workerUrl),assetDecoder:Rt}),getPlan:t=>e.getPlan(t)}}export{ar as createNodeAutomationRevealClient,T as validateOperationContext};
|