@safetech/inheriti-client-sdk 1.17.9 → 1.17.11

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/node.js CHANGED
@@ -1 +1 @@
1
- import{createNodeSharedConfigurationSdk as qt,decodeAssetContainer as Bt}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Je,generateRSAOAEPKeyPair as et}from"@safetech/inheriti-core-sdk/crypto";var j=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},Y=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},M=class{constructor(e){this.options=e}async resolve(){let{publicKeyBase64:e,privateKey:t}=await et(),n=await this.options.api.startRelaySession(e),a=this.options.pollIntervalMs??2e3,i=Date.now()+(this.options.timeoutMs??600*1e3),s=this.options.sleep??(o=>new Promise(c=>setTimeout(c,o)));for(;Date.now()<i;){let o=await this.options.api.readRelaySession(n.sessionId);if(o.status==="DELIVERED"&&o.sealedMasterKey){let c=(await Je(o.sealedMasterKey,t)).trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(c))throw new Error("invalid_master_key_material");return c}if(o.status==="EXPIRED")throw new Y(n.sessionId);await s(a)}throw new j(n.sessionId)}};function X(r){return{resolve:async e=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let t=await r.source?.resolve();return t||se(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId})}if(tt(e,r.applicationId)){let t=await r.source?.resolve();return t||se(r,()=>r.api.masterKeyAcquisition())}return se(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId})}}}function tt(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function se(r,e,t){if((await e()).relayAvailable)return new M({...r.relay,api:rt(r.api,t)}).resolve()}function rt(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:t=>r.readMasterKeyRelaySession(t)}}function S(r){return`${r.system}:${r.contextId}`}function le(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var E=class extends Error{constructor(t){super(`master_key_required:${S(t)}`);this.ref=t;this.name="MasterKeyRequired"}},oe=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(S(e),t),this}async resolve(e){return this.sources.get(S(e))?.resolve()}};var b=class{keys=new Map;async store(e,t){this.keys.set(S(e),t.slice())}async load(e){return this.keys.get(S(e))?.slice()}async remove(e){this.keys.delete(S(e))}};var K=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 Q=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},d=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var Z=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var J=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],nt={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},de=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],u=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},g=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function T(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new g("plan_material_field_unknown");if(ce(r.dataShards,"data_shards_invalid"),ce(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&ce(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new g("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new g("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new g("material_operation_invalid")}function ce(r,e){if(!Array.isArray(r))throw new g(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new g(e);if(t.data!==void 0&&typeof t.data!="string")throw new g(e)}}function w(r){if(C(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!st(r.idempotencyKey))throw new u("idempotency_key_invalid");if(!r.name?.trim())throw new u("plan_name_required");if(!r.assets.length)throw new u("assets_required");let e=new Set;for(let t of r.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),!J.includes(t.type))throw new u("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new u("asset_binary_representation_invalid");let a=t.fieldNames??[];if(t.isBinary&&(a.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new u("binary_asset_metadata_invalid");if(!t.isBinary&&(!a.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new u("structured_asset_metadata_invalid");if(new Set(a).size!==a.length||a.some(i=>!i.trim()))throw new u("asset_field_names_invalid");if(at(t.matchOrigins),!t.isBinary){let i=nt[t.type];if(!i||a.some(s=>!i.includes(s)))throw new u("asset_field_name_not_canonical")}}if(!r.participants.length)throw new u("participants_required");for(let t of r.participants){if(C(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Oe(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")}it(r)}function at(r){if(r===void 0)return;if(!r.length)throw new u("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new u("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new u("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof u?n:new u("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new u("asset_match_origins_duplicated")}function it(r){let e=r.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 i=e.authentication.mode;if(i!==void 0&&i!=="EXCLUSIVE"&&i!=="ALL_REQUIRED")throw new u("authentication_mode_invalid")}if(e.moderation){C(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let i=r.participants.filter(c=>c.relationships.includes("MODERATOR"));if(i.length===0)throw new u("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>i.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 n=t.countdownHours??0,a=t.countdownMinutes??0;if(!Oe(t.subjectEmail))throw new u("dms_subject_invalid");if(!r.participants.some(i=>Te(i.routingEmail)===Te(t.subjectEmail)))throw new u("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(a)||t.countdownDays<0||n<0||n>23||a<0||a>59||t.countdownDays+n+a===0)throw new u("dms_countdown_invalid")}function st(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function Oe(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Te(r){return r.normalize("NFC").trim().toLowerCase()}function C(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new u(t)}var U=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)}},L=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),w(e),ee(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,a,i={}){w(t);let s=await this.checkpoints.load(e);if(!s)throw new G("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await De(t))throw new G("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(i.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;ee(i.signal),i.onProgress?.("ENCRYPTING");let c=await a.encrypt({planId:o.planId,declaration:t,secrets:n,signal:i.signal});ee(i.signal),i.onProgress?.("GENERATING_SHARES");let m=await a.generateShares({planId:o.planId,declaration:t,encrypted:c,signal:i.signal});ee(i.signal),T(m);let h=await this.api.supplyPlanCreationMaterial(e,m);return i.onProgress?.(h.stage),h.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,h),h}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await De(e),serverStage:t.stage})}},G=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function De(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,a)=>n.clientAssetRef.localeCompare(a.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,a)=>n.clientParticipantRef.localeCompare(a.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function ee(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function xe(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new Q(n.stage);return r.authorizeRevealAction(e,t)}function ot(r){let e=r?.status;return e===400||e===401||e===403}async function ke(r,e,t,n){let a=await r.getReveal(e);try{await n(a.planId)}catch(i){if(!ot(i))throw i}return r.releaseRevealMaterial(e,t)}function lt(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?dt(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":ct.has(r.stage)?"ENDED":"CONTINUING"}var ct=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function dt(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var pe=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},y=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Me(r,e,t={}){if(t.signal?.aborted)throw ye();let n=await r.getPlan(e);t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await r.prepareReveal(e);let a=t.idempotencyKey??crypto.randomUUID(),i=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a}),s;try{let o=await ut(r,i,t);x(t,"RELEASING_MATERIAL",o);let c=await r.releaseRevealMaterial(o.id,o.materialVersion??"1");o.mode==="GOVERNED"&&await r.markRevealSharesCollected(o.id);let m=await gt(r,o,Rt(c),t);x(t,"RECONSTRUCTING",o);try{s=await r.reconstructPlanMaterial(m)}catch($){throw await r.reportRevealReconstruction(o.id,{status:"FAILED",errorCode:yt($)}),$}let h=await r.reportRevealReconstruction(o.id,{status:"SUCCEEDED"});return x(t,"OPEN",h),new me(r,h,n,s,t.signal)}catch(o){throw s?.fill(0),await vt(r,i.id,t.signal?.aborted?"CANCELED":"ERROR"),o}}var pt=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function ut(r,e,t){let n=await r.getReveal(e.id);for(;;){if(t.onSession?.(n),t.onProgress?.({phase:lt(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(pt.has(n.stage))throw new ue(n.stage);await ge(t.pollIntervalMs??1500,t.signal),n=await r.getReveal(e.id)}}var ue=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function x(r,e,t){r.onProgress?.({phase:e,session:t})}function ge(r,e){return e?.aborted?Promise.reject(ye()):new Promise((t,n)=>{let a=setTimeout(s,Math.max(0,r)),i=()=>{clearTimeout(a),n(ye())};function s(){e?.removeEventListener("abort",i),t()}e?.addEventListener("abort",i,{once:!0})})}var me=class{constructor(e,t,n,a,i){this.client=e;this.session=t;this.plan=n;this.plaintext=a;let s=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(s,2147483647)),this.abortListener=i?()=>{this.close("CANCELED")}:void 0,i&&this.abortListener&&i.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new pe;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([a])=>{n=a?.value}),n}async consumeFields(e,t){if(e.length===0)throw new y("asset_selector_invalid");if(!this.client.assetDecoder)throw new y("asset_decoder_required");let n=e.map(({selector:i,options:s={}})=>{let o=mt(i),c=this.plan.assets.find(m=>(m.code??m.id)===o.asset);if(!c)throw new y("asset_not_found");if(c.isBinary)throw new y("action_not_allowed");if(!c.fieldNames.includes(o.field))throw new y("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:c,field:o.field,options:s}}),a=[];try{for(let s of n)a.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:s.options.idempotencyKey??crypto.randomUUID(),assetId:s.asset.id,fieldName:s.field,action:s.options.action??"VIEW_FIELD",...s.options.destination===void 0?{}:{destination:s.options.destination},...s.options.origin===void 0?{}:{origin:s.options.origin}}));let i=n.map(s=>{let o=this.client.assetDecoder(this.material).find(c=>c.id===s.asset.id||c.id===s.assetCode);if(!o)throw new y("asset_value_invalid");return{selector:s.selector,value:ht(o.data,s.field)}});await t(i)}catch(i){throw await Promise.all(a.map(s=>this.reportAction(s.id,"FAILED",Ne(i)))),i}await Promise.all(a.map(i=>this.reportAction(i.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new y("asset_selector_invalid");if(!this.client.assetDecoder)throw new y("asset_decoder_required");let n=this.plan.assets.find(s=>s.code===e||s.id===e);if(!n)throw new y("asset_not_found");if(!n.isBinary)throw new y("action_not_allowed");let a=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),i;try{let s=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!s||!(s.data instanceof Uint8Array))throw new y("asset_value_invalid");i=s.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:i})}catch(s){throw await this.reportAction(a.id,"FAILED",Ne(s)),s}finally{i?.fill(0)}await this.reportAction(a.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=this.client.closeReveal(this.session.id,e).then(()=>{}).catch(t=>{if(!be(t))throw t}),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function mt(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new y("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new y("asset_selector_invalid");return{asset:r.asset,field:r.field}}function ht(r,e){let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new y("asset_value_invalid")}if(!t||typeof t!="object"||Array.isArray(t)||!(e in t))throw new y("asset_value_invalid");return t[e]}function Ne(r){if(r instanceof y)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function yt(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function gt(r,e,t,n){if(t.shares.some(o=>o.shareType==="CUSTODIAN_KEY_SHARD"))return await r.distributeRevealCustodianShare(e.id),x(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t;let a=await r.getRevealCustodianAccess(e.id);for(;a.status==="PENDING"||a.status==="DISTRIBUTED";){let o={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(o),x(n,"WAITING_FOR_CUSTODIAN_CLAIM",o),await ge(n.pollIntervalMs??1500,n.signal),a=await r.getRevealCustodianAccess(e.id)}if(a.status!=="CLAIMED"||a.deviceType!=="SK_MOBILE")throw new te;let i={...e,stage:"WAITING_FOR_CUSTODIAN"};n.onSession?.(i),x(n,"WAITING_FOR_CUSTODIAN",i),await r.requestRevealCustodianRelease(e.id);let s=await ft(r,e.id,n);return Object.assign({},t,{shares:t.shares.concat(s.shares.map((o,c)=>({id:`${s.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:o})))})}async function ft(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let a=await r.getRevealCustodianShare(e);if(a&&a.status!=="PENDING"){let i=a;if(i.shares?.length)return i;throw new te}if(Date.now()>=n)throw new he;await ge(t.pollIntervalMs??1500,t.signal)}}var te=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},he=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function Rt(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function vt(r,e,t){try{await r.closeReveal(e,t)}catch(n){if(!be(n))throw n}}function be(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function ye(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var z=class{constructor(e,t={}){this.coreSdk=e;if(t.applicationId!==void 0&&t.organizationId!==void 0)throw new Error("application_and_business_context_conflict");if(t.organizationId!==void 0&&!t.organizationId.trim())throw new Error("organization_id_required");this.keyVault=t.keyVault??new b,this.state=t.state??new K,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Pt(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 d;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new d;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new d;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new d;return w(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new d;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new d;return T(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new d;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new U){if(this.requireApplication(),!this.api)throw new d;return new L(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()},n=await this.keyVault.load(t);if(n)return Ue(n);let a=await this.masterKeys?.resolve(t);if(!a)throw new E(t);return await this.keyVault.store(t,Ke(a)),a}async prepareReveal(e){if(!this.api)throw new d;let t=await this.api.planKeyReference(e);if(!t.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(t)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new d;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new Z;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){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 E({system:"INHERITI_BUSINESS",contextId:this.organizationId});let t=le(e);if(!t)throw new E({system:"INHERITI_ELEMENTS",contextId:e.planId});let n=await this.keyVault.load(t);if(n)return Ue(n);let a=await this.masterKeys?.resolve(t);if(!a)throw new E(t);return await this.keyVault.store(t,Ke(a)),a}initializeGovernedReveal(e,t){if(!this.api)throw new d;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new d;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new d;return this.api.startReveal(e,t)}getReveal(e){if(!this.api)throw new d;return this.api.getReveal(e)}openReveal(e,t){return Me(this,e,t)}async withReveal(e,t,n){let a=await this.openReveal(e,t);try{let i=await n(a);return await a.close("COMPLETED"),i}catch(i){throw await a.close(t.signal?.aborted?"CANCELED":"ERROR"),i}}async releaseRevealMaterial(e,t){if(!this.api)throw new d;return ke(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new d;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new d;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new d;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e){if(!this.api)throw new d;return this.api.getRevealCustodianAccess(e)}getRevealCustodianShare(e){if(!this.api)throw new d;return this.api.getRevealCustodianShare(e)}reportRevealReconstruction(e,t){if(!this.api)throw new d;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t){if(!this.api)throw new d;return this.api.closeReveal(e,t)}abortPlanAccess(e){if(!this.api)throw new d;return this.api.abortPlanAccess(e)}async authorizeRevealAction(e,t){if(!this.api)throw new d;return xe(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new d;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new d;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new d;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new d;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new d;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new d;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),a=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let i=n.validatorShares.map(m=>Object.assign({},m,{shareType:"VALIDATOR_SHARD"})),s=a.dataShards.map(m=>Object.assign({},m,{shareType:"DATA_SHARD"})),o=a.backupShards.map(m=>Object.assign({},m,{shareType:"BACKUP_SHARD"})),c=a.keyShards.map(m=>Object.assign({},m,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:a.dek||n.dek,shares:i.concat(s,o,c),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new d;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new fe;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new E({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 Ke(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Ue(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Pt(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return X({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return X({...e,organizationId:r.organizationId})}var It=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Et=["DIRECT","GOVERNED"],Ge=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],St=["ACTIVE","REVOKED"],wt=["SK_MOBILE"],At=["ACTIVE","INACTIVE"],_t=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function ze(r){let e=f(r);return{items:v(e.items).map(Be),nextCursor:e.nextCursor===null?null:l(e.nextCursor,"nextCursor")}}function Ve(r){let e=f(r);return{total:P(e.total,"total"),items:v(e.items).map(t=>{let n=f(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:l(n.id,"log.id"),planId:l(n.planId,"log.planId"),tenantId:l(n.tenantId,"log.tenantId"),event:l(n.event,"log.event"),occurredOn:l(n.occurredOn,"log.occurredOn"),status:A(n.status),title:l(n.title,"log.title"),details:v(n.details).map(a=>{let i=f(a);return{label:l(i.label,"log.detail.label"),value:l(i.value,"log.detail.value")}})}})}}function qe(r){let e=f(r),t=Be(e),n=f(e.source),a=l(n.kind,"source.kind");return{...t,assets:v(e.assets).map(i=>{let s=f(i);return{id:l(s.id,"asset.id"),code:A(s.code),type:R(l(s.type,"asset.type"),J),name:l(s.name,"asset.name"),isBinary:Tt(s.isBinary,"asset.isBinary"),fieldNames:v(s.fieldNames).map(o=>l(o,"asset.fieldNames")),fileName:A(s.fileName),mimeType:A(s.mimeType),size:s.size===void 0||s.size===null?void 0:P(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:v(s.matchOrigins).map(o=>l(o,"asset.matchOrigins"))}}),participants:v(e.participants).map(i=>{let s=f(i);return{id:l(s.id,"participant.id"),displayName:l(s.displayName,"participant.displayName"),relationships:v(s.relationships).map(o=>R(l(o,"relationship"),Ge)),lifecycle:R(l(s.lifecycle,"participant.lifecycle"),St)}}),revealPolicy:(()=>{let i=f(e.revealPolicy);return{masterKeyRelease:R(l(i.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:R(l(i.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let i=f(e.dms);return{subjectEmail:l(i.subjectEmail,"dms.subjectEmail"),countdownDays:P(i.countdownDays,"dms.countdownDays"),countdownHours:P(i.countdownHours,"dms.countdownHours"),countdownMinutes:P(i.countdownMinutes,"dms.countdownMinutes")}})(),source:a==="NATIVE"?{kind:"NATIVE"}:a==="BRIDGED"?{kind:"BRIDGED",system:R(l(n.system,"source.system"),["INHERITI_BUSINESS"]),status:R(l(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:a}}}function V(r){let e=f(r);return{operationId:l(e.operationId,"operationId"),stage:R(l(e.stage,"stage"),de),outcome:R(l(e.outcome,"outcome"),_t),planId:A(e.planId),lastErrorCode:A(e.lastErrorCode),participants:e.participants===void 0?void 0:v(e.participants).map(t=>{let n=f(t);return{clientParticipantRef:l(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:l(n.planParticipantId,"planParticipantId"),relationships:v(n.relationships).map(a=>Ct(l(a,"relationship"),Ge))}})}}function Be(r){let e=f(r),t=f(e.assetSummary),n=f(e.governance),a=f(e.participantSummary);return{id:l(e.id,"id"),name:l(e.name,"name"),description:A(e.description),status:R(l(e.status,"status"),It),createdAt:l(e.createdAt,"createdAt"),configuredAt:A(e.configuredAt),assetSummary:{count:P(t.count,"assetSummary.count"),types:v(t.types).map(i=>R(l(i,"assetType"),J)),names:Le(t.names).map(i=>l(i,"assetSummary.names"))},governance:{mode:R(l(n.mode,"governance.mode"),Et),minimumApprovals:P(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:P(a.owners,"owners"),mergers:P(a.mergers,"mergers"),moderators:P(a.moderators,"moderators")},authentication:Le(e.authentication).map(i=>{let s=f(i);return{id:R(l(s.id,"authentication.id"),wt),status:R(l(s.status,"authentication.status"),At)}})}}function R(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function Ct(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function f(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Le(r){return r==null?[]:v(r)}function v(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function l(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function A(r){return r==null?void 0:l(r,"optional")}function P(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function Tt(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var k=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function Fe(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function Ot(r,e){if(!e){if(r.length===0)throw new k("organization_required");if(r.length>1)throw new k("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new k("organization_access_denied");return e}function Re(r){return typeof r.error=="string"?r.error||void 0:r.error?.code??r.name??r.message}function ve(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var O=class extends Error{constructor(t,n,a){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=a;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},N=class{constructor(e,t,n,a,i){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=a;this.business=i?Object.freeze({...i}):void 0}business;listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(Fe)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let a of e.status??[])t.append("status",a);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return ze(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return qe(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let a=n.size?`?${n}`:"";return Ve(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${a}`,"GET"))}async startPlanCreation(e){w(e);let{idempotencyKey:t,...n}=e;return V(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return V(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return T(t),V(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return V(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET")}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",a,void 0,{"idempotency-key":n})}getReveal(e){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET")}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET")}getRevealCustodianShare(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET")}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t})}abortPlanAccess(e){return this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",a,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:a,...i}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",i,void 0,{"idempotency-key":a})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,a,i){this.requireBusinessSelection(e);let s=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});s&&o.set("authorization",`Bearer ${s}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&o.set("x-organization-id",this.business.organizationId),a?.requestId&&o.set("x-elements-step-up-request",a.requestId);for(let[$,Ze]of Object.entries(i??{}))o.set($,Ze);n&&o.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,m=await this.transport(new URL(e,c),{method:t,headers:o,body:n?JSON.stringify(n):void 0}),h=await He(m);if(!m.ok)throw new O(m.status,Re(h),ve(h));if(!h.ok||h.result===void 0)throw new O(m.status,Re(h),ve(h));return h.result}async requestWithoutResult(e){this.requireBusinessSelection(e);let t=await this.getBearerToken(),n=new Headers({"x-elements-environment":this.environment});t&&n.set("authorization",`Bearer ${t}`),this.business?.organizationId&&n.set("x-organization-id",this.business.organizationId);let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,i=await this.transport(new URL(e,a),{method:"POST",headers:n}),s=await He(i);if(!i.ok||!s.ok)throw new O(i.status,Re(s),ve(s))}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new O(400,"organization_selection_required")}};async function He(r){try{return await r.json()}catch{return{ok:!1}}}import{createNodeSsdpV2Processor as Ut}from"@safetech/inheriti-core-sdk/node";async function Pe(r,e){if(!e)throw new Error("master_key_required");let t=Dt(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),a=xt(r),i=a.slice(0,12),s=a.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},n,s);return kt(new Uint8Array(o))}function Dt(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function xt(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function kt(r){let e="";for(let t of r)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 n=await We("plan_key_unwrap_failed",()=>Pe(e.planKey,t)),a=await crypto.subtle.importKey("raw",Ie(n),{name:"AES-GCM"},!1,["decrypt"]),i=[],s=[];for(let o of e.shares){let c=await We("plan_share_decryption_failed",()=>Kt(o.data,a));bt(o.shareType)?s.push(c):i.push(c)}try{return await this.processor().reconstruct(i,{planId:e.planId,threshold:e.mergeThreshold,keyShares:s}).result}catch(o){throw new re("plan_share_reconstruction_failed",Mt(o))}}},re=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},Nt=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 Mt(r){let e=r instanceof Error?r.message:void 0;if(e)return Nt.has(e)?e:void 0}async function We(r,e){try{return await e()}catch{throw new re(r)}}function bt(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function Kt(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=Ie(r.slice(0,t)),a=Ie(r.slice(t+1)),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,a);return new TextDecoder().decode(i)}function Ie(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let a=0;a<e.length;a+=1)n[a]=e.charCodeAt(a);return t}var B=class extends q{constructor(e){super(()=>Ut(e))}};var we=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){F(e.signal),Gt(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return F(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){F(e.signal);let t=e.encrypted.totalShares+1,n=e.encrypted.threshold+1,a=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(F(e.signal),!a.custodianPair)throw new g("custodian_share_required");let i=Ee(a.keyShards),s=await this.sealer.encryptShares(i,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(Ee(a.dataShards),s.symmetricKeyBase64),c=await this.sealer.encryptShares(Ee(a.backupShards),s.symmetricKeyBase64),m=await this.sealCustodianPair(a.custodianPair,s.symmetricKeyBase64);return F(e.signal),{protectionProtocol:a.protocol,validatorShares:Se(s.encryptedShares),dataShards:Se(o.encryptedShares),backupShards:Se(c.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:Lt(e.encrypted.assets,e.declaration),custodianShard:m,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:Ae(n.encryptedShares[0]),dataShard:Ae(n.encryptedShares[1])}}};function Ee(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function Se(r){return r.map(Ae)}function Ae(r){return{id:r.id,data:r.encryptedData}}function Lt(r,e){let t={};for(let n of r){let a=e.assets.find(i=>i.clientAssetRef===n.id);if(!a)throw new g("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...a.fieldNames??[]],isBinary:a.isBinary,...a.fileName===void 0?{}:{fileName:a.fileName},...a.mimeType===void 0?{}:{mimeType:a.mimeType},...a.size===void 0?{}:{size:a.size}}}return t}function Gt(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new g("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new g("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new g("plan_secrets_declaration_mismatch");let t=new Map(r.assets.map(n=>[n.clientAssetRef,n]));for(let n of e.assets){let a=t.get(n.id);if(!a||a.type!==n.type)throw new g("plan_secrets_declaration_mismatch")}}function F(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}import{PassphraseMasterKeySource as pn,RawMasterKeySource as un,deriveMasterKey as mn,generateHexSeed as hn,computePassphraseVerifier as yn}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as fn}from"@safetech/inheriti-core-sdk/node";function $e(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var ne=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),$e(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return $e(new Uint8Array(t))}},ae=class{now(){return Date.now()}sleep(e,t){return new Promise((n,a)=>{if(t?.aborted)return a(t.reason??new DOMException("Aborted","AbortError"));let i=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(i),a(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var H=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},W=class extends H{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},p=class extends H{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function _e(r){if(r instanceof H)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var je=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:_(n,"issuer"),authorizationEndpoint:_(n,"authorization_endpoint"),tokenEndpoint:_(n,"token_endpoint"),deviceAuthorizationEndpoint:I(n,"device_authorization_endpoint"),endSessionEndpoint:I(n,"end_session_endpoint"),revocationEndpoint:I(n,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:_(t,"device_code"),userCode:_(t,"user_code"),verificationUri:_(t,"verification_uri"),verificationUriComplete:I(t,"verification_uri_complete"),expiresInSeconds:Ye(t,"expires_in"),intervalSeconds:Ce(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async token(e,t){let n=await this.form(e,t);return{accessToken:_(n,"access_token"),refreshToken:I(n,"refresh_token"),idToken:I(n,"id_token"),tokenType:_(n,"token_type"),expiresInSeconds:Ye(n,"expires_in"),refreshExpiresInSeconds:Ce(n,"refresh_expires_in"),scope:I(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),a={};try{a=await n.json()}catch{}if(!n.ok){let i=I(a,"error")??`oauth_http_${n.status}`;throw new p(i,I(a,"error_description")??i)}return a}};function _(r,e){let t=I(r,e);if(!t)throw new p("invalid_oauth_response",`Missing ${e}`);return t}function I(r,e){return typeof r[e]=="string"?r[e]:void 0}function Ye(r,e){let t=Ce(r,e);if(t===void 0)throw new p("invalid_oauth_response",`Missing ${e}`);return t}function Ce(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var zt=600*1e3,ie=5,Vt=5,Xe=class{constructor(e){this.options=e;this.crypto=e.crypto??new ne,this.clock=e.clock??new ae}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),a=this.crypto.randomUrlSafe(64),i=await this.crypto.sha256UrlSafe(a),s=this.clock.now()+zt;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:a,redirectUri:this.options.configuration.redirectUri,expiresAt:s});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",n),o.searchParams.set("code_challenge",i),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:s}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new p("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new p("authorization_transaction_expired");let a=new URL(e),i=new URL(n.redirectUri);if(a.origin!==i.origin||a.pathname!==i.pathname)throw new p("redirect_uri_mismatch");let s=a.searchParams.get("error");if(s)throw new p(s,a.searchParams.get("error_description")??s);if(a.searchParams.get("state")!==n.state)throw new p("state_mismatch");let o=a.searchParams.get("code");if(!o)throw new p("authorization_code_missing");let c=await this.getDiscovery(),m=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:c.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),h=await this.acceptTokens(m,n.nonce);return await this.options.sessions.save(h),h}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new p("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(ie,t.intervalSeconds??ie),a=this.clock.now(),i={...t,kind:"device-code",intervalSeconds:n,expiresAt:a+t.expiresInSeconds*1e3,nextPollAt:a+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),i),i}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new p("device_transaction_missing");let a=n,i=await this.getDiscovery(),s=Math.max(ie,a.intervalSeconds??ie),o=Math.max(a.nextPollAt,this.clock.now());for(;this.clock.now()<a.expiresAt&&!(o>=a.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let c=await this.options.transport.pollDeviceToken({tokenEndpoint:i.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:a.deviceCode});a.consumed=!0,await this.options.transactions.save(t,a);let m=await this.acceptTokens(c);return await this.options.sessions.save(m),await this.options.transactions.remove(t),m}catch(c){let m=_e(c);if(m==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(m==="slow_down"){s+=Vt,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),c}}throw await this.options.transactions.remove(t),new p("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new W;try{let t=await this.getDiscovery(),n=await this.options.transport.refresh({tokenEndpoint:t.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken});if(!n.refreshToken)throw new p("refresh_token_rotation_missing");let a=await this.acceptTokens(n);return await this.options.sessions.save(a),a}catch(t){await this.options.sessions.clear();let n=_e(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new W:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(D(e.issuer)!==D(this.options.configuration.issuer))throw new p("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:a}=this.options.configuration;return`${e}|${D(t)}|${n}|${a}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new p("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new p("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==n.subject||i.sessionId!==n.sessionId)throw new p("token_subject_mismatch")}let a=this.clock.now();return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:a+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0?void 0:a+e.refreshExpiresInSeconds*1e3,principal:n}}assertPrincipal(e,t,n){let a=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(D(e.issuer)!==D(a.issuer))throw new p("issuer_mismatch");if(!i.includes(a.audience))throw new p("audience_mismatch");if(e.authorizedParty!==a.clientId)throw new p("client_mismatch");if(e.environment!==a.environment)throw new p("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new p("required_claim_missing");if(n&&e.nonce!==t)throw new p("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(D(e.issuer)!==D(n.issuer))throw new p("issuer_mismatch");if(!a.includes(n.clientId))throw new p("client_mismatch");if(e.authorizedParty!==n.clientId)throw new p("client_mismatch");if(!e.subject||!e.sessionId)throw new p("required_claim_missing");if(e.nonce!==t)throw new p("nonce_mismatch")}};function D(r){return r.replace(/\/+$/u,"")}var Qe=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};function Xr(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=(i,s)=>{let o=new Headers(s?.headers);return o.set("x-elements-environment",r.environment),e(i,Object.assign({},s,{headers:o}))},n=r.business?void 0:qt({apiUrl:r.apiUrl,getBearerToken:r.getBearerToken,transport:t,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners}),a=new N(r.apiUrl,r.environment,r.getBearerToken,t,r.business?{organizationId:r.organizationId}:void 0);return new z(n,{keyVault:r.keyVault,state:r.state,api:a,reconstructor:new B(r.workerUrl),masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:Bt})}export{k as BusinessOrganizationSelectionError,we as CorePlanMaterialBuilder,O as ElementsApiRequestFailed,z as ElementsClient,G as GuidedCreateRecoveryError,L as GuidedPlanCreator,N as HttpElementsApiPort,je as HttpOperatorAuthTransport,u as InvalidPlanDeclaration,g as InvalidPlanMaterial,Y as MasterKeyRelayExpired,j as MasterKeyRelayTimedOut,E as MasterKeyRequired,U as MemoryGuidedCreateCheckpointStore,b as MemoryKeyVault,K as MemoryStatePort,p as OAuthProtocolError,Xe as OperatorAuthClient,H as OperatorAuthError,W as OperatorReauthenticationRequired,Qe as OperatorSessionController,de as PLAN_CREATION_SERVER_STAGES,pn as PassphraseMasterKeySource,fn as PlanAssetDeclaration,un as RawMasterKeySource,M as RelayMasterKeySource,oe as StaticMasterKeyResolver,ae as SystemOAuthClock,ne as WebOAuthCrypto,yn as computePassphraseVerifier,X as createMasterKeyResolver,Xr as createNodeElementsClient,Bt as decodeAssetContainer,mn as deriveMasterKey,hn as generateHexSeed,le as masterKeyRefFor,S as masterKeyRefKey,_e as oauthErrorCode,Ot as selectBusinessOrganization,Pe as unwrapDekWithMasterKey,w as validatePlanCreationInput,T as validatePlanCreationMaterial};
1
+ import{createNodeSharedConfigurationSdk as Wt,decodeAssetContainer as $t}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as nt,generateRSAOAEPKeyPair as at}from"@safetech/inheriti-core-sdk/crypto";var Z=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},J=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},L=class{constructor(e){this.options=e}async resolve(){let{publicKeyBase64:e,privateKey:t}=await at(),n=await this.options.api.startRelaySession(e),a=this.options.pollIntervalMs??2e3,i=Date.now()+(this.options.timeoutMs??600*1e3),s=this.options.sleep??(o=>new Promise(l=>setTimeout(l,o)));for(;Date.now()<i;){let o=await this.options.api.readRelaySession(n.sessionId);if(o.status==="DELIVERED"&&o.sealedMasterKey){let l=(await nt(o.sealedMasterKey,t)).trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(l))throw new Error("invalid_master_key_material");return l}if(o.status==="EXPIRED")throw new J(n.sessionId);await s(a)}throw new Z(n.sessionId)}};function ee(r){return{resolve:async e=>{if(r.organizationId!==void 0){if(e.system!=="INHERITI_BUSINESS"||e.contextId!==r.organizationId)return;let t=await r.source?.resolve();return t||pe(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId})}if(it(e,r.applicationId)){let t=await r.source?.resolve();return t||pe(r,()=>r.api.masterKeyAcquisition())}return pe(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId})}}}function it(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function pe(r,e,t){if((await e()).relayAvailable)return new L({...r.relay,api:st(r.api,t)}).resolve()}function st(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:t=>r.readMasterKeyRelaySession(t)}}function A(r){return`${r.system}:${r.contextId}`}function me(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var _=class extends Error{constructor(t){super(`master_key_required:${A(t)}`);this.ref=t;this.name="MasterKeyRequired"}},ue=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(A(e),t),this}async resolve(e){return this.sources.get(A(e))?.resolve()}};var G=class{keys=new Map;async store(e,t){this.keys.set(A(e),t.slice())}async load(e){return this.keys.get(A(e))?.slice()}async remove(e){this.keys.delete(A(e))}};var z=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 te=class extends Error{constructor(t){super("reveal_actions_not_open");this.stage=t;this.name="RevealActionsNotOpen"}code="reveal_actions_not_open"},p=class extends Error{constructor(){super("elements_api_port_required"),this.name="ElementsApiPortRequired"}};var re=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var ne=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],ot={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},ye=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],m=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},g=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function k(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new g("plan_material_field_unknown");if(he(r.dataShards,"data_shards_invalid"),he(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&he(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new g("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new g("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new g("material_operation_invalid")}function he(r,e){if(!Array.isArray(r))throw new g(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new g(e);if(t.data!==void 0&&typeof t.data!="string")throw new g(e)}}function C(r){if(x(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!ct(r.idempotencyKey))throw new m("idempotency_key_invalid");if(!r.name?.trim())throw new m("plan_name_required");if(!r.assets.length)throw new m("assets_required");let e=new Set;for(let t of r.assets){if(x(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new m("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!ne.includes(t.type))throw new m("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new m("asset_binary_representation_invalid");let a=t.fieldNames??[];if(t.isBinary&&(a.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new m("binary_asset_metadata_invalid");if(!t.isBinary&&(!a.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new m("structured_asset_metadata_invalid");if(new Set(a).size!==a.length||a.some(i=>!i.trim()))throw new m("asset_field_names_invalid");if(lt(t.matchOrigins),!t.isBinary){let i=ot[t.type];if(!i||a.some(s=>!i.includes(s)))throw new m("asset_field_name_not_canonical")}}if(!r.participants.length)throw new m("participants_required");for(let t of r.participants){if(x(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Me(t.routingEmail))throw new m("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new m("participant_relationships_invalid")}dt(r)}function lt(r){if(r===void 0)return;if(!r.length)throw new m("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new m("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new m("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof m?n:new m("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new m("asset_match_origins_duplicated")}function dt(r){let e=r.policy;if(e&&x(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new m("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){x(e.authentication,["mode"],"plan_authentication_field_unknown");let i=e.authentication.mode;if(i!==void 0&&i!=="EXCLUSIVE"&&i!=="ALL_REQUIRED")throw new m("authentication_mode_invalid")}if(e.moderation){x(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let i=r.participants.filter(l=>l.relationships.includes("MODERATOR"));if(i.length===0)throw new m("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>i.length))throw new m("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new m("approval_mode_invalid")}let t=e.dms;if(!t)return;x(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,a=t.countdownMinutes??0;if(!Me(t.subjectEmail))throw new m("dms_subject_invalid");if(!r.participants.some(i=>ke(i.routingEmail)===ke(t.subjectEmail)))throw new m("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(a)||t.countdownDays<0||n<0||n>23||a<0||a>59||t.countdownDays+n+a===0)throw new m("dms_countdown_invalid")}function ct(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(r)}function Me(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function ke(r){return r.normalize("NFC").trim().toLowerCase()}function x(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new m(t)}var V=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)}},q=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),C(e),ae(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,a,i={}){C(t);let s=await this.checkpoints.load(e);if(!s)throw new B("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await be(t))throw new B("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(i.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;ae(i.signal),i.onProgress?.("ENCRYPTING");let l=await a.encrypt({planId:o.planId,declaration:t,secrets:n,signal:i.signal});ae(i.signal),i.onProgress?.("GENERATING_SHARES");let d=await a.generateShares({planId:o.planId,declaration:t,encrypted:l,signal:i.signal});ae(i.signal),k(d);let h=await this.api.supplyPlanCreationMaterial(e,d);return i.onProgress?.(h.stage),h.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,h),h}async cancel(e){let t=await this.api.cancelPlanCreation(e);return t.outcome==="CANCELED"&&await this.checkpoints.remove(e),t}async saveCheckpoint(e,t){await this.checkpoints.save({idempotencyKey:e.idempotencyKey,operationId:t.operationId,declarationHash:await be(e),serverStage:t.stage})}},B=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function be(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,a)=>n.clientAssetRef.localeCompare(a.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,a)=>n.clientParticipantRef.localeCompare(a.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function ae(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Ke(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new te(n.stage);return r.authorizeRevealAction(e,t)}function pt(r){let e=r?.status;return e===400||e===401||e===403}async function Ue(r,e,t,n){let a=await r.getReveal(e);try{await n(a.planId)}catch(i){if(!pt(i))throw i}return r.releaseRevealMaterial(e,t)}function ut(r){return r.closedReason==="DMS_RESET"?"STOPPED_BY_DMS":r.stage==="STARTING"?"STARTING":r.stage==="WAITING_FOR_DMS"?"WAITING_FOR_DMS":r.stage==="WAITING_FOR_CUSTODIAN"?"WAITING_FOR_CUSTODIAN":r.stage==="WAITING_FOR_CUSTODIAN_CLAIM"?"WAITING_FOR_CUSTODIAN_CLAIM":r.stage==="WAITING_FOR_PARTICIPANTS"?ht(r):r.stage==="DENIED"?"DENIED":r.stage==="EXPIRED"?"EXPIRED":r.stage==="PARTICIPANT_REVOKED"?"PARTICIPANT_REVOKED":r.stage==="RECONCILIATION_REQUIRED"?"RECONCILIATION_REQUIRED":r.stage==="AUTHORIZED"||r.stage==="MATERIAL_AUTHORIZED"?"RELEASING_MATERIAL":r.stage==="MATERIAL_RELEASED"||r.stage==="RECONSTRUCTED"?"RECONSTRUCTING":r.stage==="ACTIONS_OPEN"?"OPEN":mt.has(r.stage)?"ENDED":"CONTINUING"}var mt=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function ht(r){return r.governanceGate==="DMS"?"WAITING_FOR_DMS":r.governanceGate==="MODERATION"?"WAITING_FOR_MODERATION":r.governanceGate==="AUTHENTICATION"||r.requiredModerators===void 0?"WAITING_FOR_AUTHENTICATION":"WAITING_FOR_MODERATION"}var fe=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},y=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function Ge(r,e,t={}){if(t.signal?.aborted)throw P();let n=await r.getPlan(e);t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await r.prepareReveal(e);let a=t.idempotencyKey??crypto.randomUUID(),i=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a}),s;try{let o=await gt(r,i,t);T(t,"RELEASING_MATERIAL",o);let l=await r.releaseRevealMaterial(o.id,o.materialVersion??"1");o.mode==="GOVERNED"&&await r.markRevealSharesCollected(o.id);let d=await Pt(r,o,St(l),t);T(t,"RECONSTRUCTING",o);try{s=await r.reconstructPlanMaterial(d)}catch(S){throw await r.reportRevealReconstruction(o.id,{status:"FAILED",errorCode:Rt(S)}),S}let h=await r.reportRevealReconstruction(o.id,{status:"SUCCEEDED"});return T(t,"OPEN",h),new Re(r,h,n,s,t.signal)}catch(o){throw s?.fill(0),await wt(r,i.id,t.signal?.aborted?"CANCELED":"ERROR"),o}}var yt=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function gt(r,e,t){let n=await r.getReveal(e.id);for(;;){if(t.onSession?.(n),t.onProgress?.({phase:ut(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(yt.has(n.stage))throw new ve(n.stage);await Ie(t.pollIntervalMs??1500,t.signal),n=await r.getReveal(e.id)}}var ve=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function T(r,e,t){r.onProgress?.({phase:e,session:t})}function Ie(r,e){return e?.aborted?Promise.reject(P()):new Promise((t,n)=>{let a=setTimeout(s,Math.max(0,r)),i=()=>{clearTimeout(a),n(P())};function s(){e?.removeEventListener("abort",i),t()}e?.addEventListener("abort",i,{once:!0})})}var Re=class{constructor(e,t,n,a,i){this.client=e;this.session=t;this.plan=n;this.plaintext=a;let s=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(s,2147483647)),this.abortListener=i?()=>{this.close("CANCELED")}:void 0,i&&this.abortListener&&i.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new fe;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([a])=>{n=a?.value}),n}async consumeFields(e,t){if(e.length===0)throw new y("asset_selector_invalid");if(!this.client.assetDecoder)throw new y("asset_decoder_required");let n=e.map(({selector:i,options:s={}})=>{let o=ft(i),l=this.plan.assets.find(d=>(d.code??d.id)===o.asset);if(!l)throw new y("asset_not_found");if(l.isBinary)throw new y("action_not_allowed");if(!l.fieldNames.includes(o.field))throw new y("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:l,field:o.field,options:s}}),a=[];try{for(let s of n)a.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:s.options.idempotencyKey??crypto.randomUUID(),assetId:s.asset.id,fieldName:s.field,action:s.options.action??"VIEW_FIELD",...s.options.destination===void 0?{}:{destination:s.options.destination},...s.options.origin===void 0?{}:{origin:s.options.origin}}));let i=n.map(s=>{let o=this.client.assetDecoder(this.material).find(l=>l.id===s.asset.id||l.id===s.assetCode);if(!o)throw new y("asset_value_invalid");return{selector:s.selector,value:vt(o.data,s.field,s.asset.type)}});await t(i)}catch(i){throw await Promise.all(a.map(s=>this.reportAction(s.id,"FAILED",Le(i)))),i}await Promise.all(a.map(i=>this.reportAction(i.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new y("asset_selector_invalid");if(!this.client.assetDecoder)throw new y("asset_decoder_required");let n=this.plan.assets.find(s=>s.code===e||s.id===e);if(!n)throw new y("asset_not_found");if(!n.isBinary)throw new y("action_not_allowed");let a=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),i;try{let s=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!s||!(s.data instanceof Uint8Array))throw new y("asset_value_invalid");i=s.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:i})}catch(s){throw await this.reportAction(a.id,"FAILED",Le(s)),s}finally{i?.fill(0)}await this.reportAction(a.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=this.client.closeReveal(this.session.id,e).then(()=>{}).catch(t=>{if(!ze(t))throw t}),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function ft(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new y("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new y("asset_selector_invalid");return{asset:r.asset,field:r.field}}function vt(r,e,t){let n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new y("asset_value_invalid")}if(!n||typeof n!="object"||Array.isArray(n))throw new y("asset_value_invalid");if(!(e in n)){if(t==="USER-PSWD"&&["appOrWebsite","email","username","password"].includes(e))return"";throw new y("asset_value_invalid")}return n[e]}function Le(r){if(r instanceof y)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function Rt(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function Pt(r,e,t,n){let a=t.shares.find(l=>l.shareType==="CUSTODIAN_KEY_SHARD");if(a){let l=await F(()=>n.selectCustodianDevice?.(),n.signal)??"SK_MOBILE";if(l==="SK_PRO"){if(!n.proDevice)throw new ie;let d=await F(()=>r.getRevealCustodianClaimable(e.id),n.signal);if(ge(d,a.id,e.planId),!d.shares.includes(a.data))throw new R;T(n,"CONNECTING_SAFEKEY_PRO",e);let{deviceId:h}=await F(()=>n.proDevice.write(d,n.signal),n.signal);if(n.signal?.aborted)throw P();if(!h?.trim())throw new R;let S=await F(()=>n.proDevice.read({shareId:d.id,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw P();if(ge(S,d.id,e.planId),S.deviceId!==h)throw new R;if(S.shares.length!==d.shares.length||S.shares.some((N,ce)=>N!==d.shares[ce]))throw new R;if(await r.claimRevealCustodianShare(e.id,d.id,h),n.signal?.aborted||(await r.collectRevealCustodianShare(e.id,d.id),n.signal?.aborted))throw P();return{...t,shares:t.shares.filter(N=>N!==a).concat(S.shares.map((N,ce)=>({id:`${S.id}:${ce}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:N})))}}if(l!=="SK_MOBILE")throw new R;return await r.distributeRevealCustodianShare(e.id),T(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t}let i=await r.getRevealCustodianAccess(e.id);for(;i.status==="PENDING"||i.status==="DISTRIBUTED";){let l={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(l),T(n,"WAITING_FOR_CUSTODIAN_CLAIM",l),await Ie(n.pollIntervalMs??1500,n.signal),i=await r.getRevealCustodianAccess(e.id)}if(i.status==="CLAIMED"&&i.deviceType==="SK_PRO"){if(!n.proDevice)throw new ie;if(!i.shareId||!i.deviceId)throw new R;T(n,"CONNECTING_SAFEKEY_PRO",e);let l=await F(()=>n.proDevice.read({shareId:i.shareId,planId:e.planId},n.signal),n.signal);if(n.signal?.aborted)throw P();if(ge(l,i.shareId,e.planId),l.deviceId!==i.deviceId)throw new R;if(await r.collectRevealCustodianShare(e.id,i.shareId),n.signal?.aborted)throw P();return{...t,shares:t.shares.concat(l.shares.map((d,h)=>({id:`${l.id}:${h}`,storageLayerId:"SK_PRO",shareType:"CUSTODIAN_KEY_SHARD",data:d})))}}if(i.status!=="CLAIMED"||i.deviceType!=="SK_MOBILE")throw new R;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};n.onSession?.(s),T(n,"WAITING_FOR_CUSTODIAN",s),await r.requestRevealCustodianRelease(e.id);let o=await It(r,e.id,n);return Object.assign({},t,{shares:t.shares.concat(o.shares.map((l,d)=>({id:`${o.id}:${d}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:l})))})}function ge(r,e,t){if(r?.id!==e||r.planId!==t||!Array.isArray(r.shares)||r.shares.length===0||r.shares.some(n=>typeof n!="string"||!n))throw new R}async function F(r,e){if(e?.aborted)throw P();if(!e)return r();let t,n=new Promise((a,i)=>{t=()=>i(P()),e.addEventListener("abort",t,{once:!0})});try{return await Promise.race([Promise.resolve().then(()=>{if(e.aborted)throw P();return r()}),n])}finally{t&&e.removeEventListener("abort",t)}}async function It(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let a=await r.getRevealCustodianShare(e);if(a&&a.status!=="PENDING"){let i=a;if(i.shares?.length)return i;throw new R}if(Date.now()>=n)throw new Pe;await Ie(t.pollIntervalMs??1500,t.signal)}}var R=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},ie=class extends Error{code="safekey_pro_local_device_required";constructor(){super("safekey_pro_local_device_required"),this.name="SafeKeyProLocalDeviceRequired"}},Pe=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function St(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function wt(r,e,t){try{await r.closeReveal(e,t)}catch(n){if(!ze(n))throw n}}function ze(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function P(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var H=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 G,this.state=t.state??new z,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??Et(t),this.applicationId=t.applicationId,this.organizationId=t.organizationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;organizationId;assetDecoder;listPlans(e){if(!this.api)throw new p;return this.api.listPlans(e)}getPlan(e){if(!this.api)throw new p;return this.api.getPlan(e)}listPlanLogs(e,t){if(!this.api)throw new p;return this.api.listPlanLogs(e,t)}startPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return C(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(this.requireApplication(),!this.api)throw new p;return k(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new p;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new V){if(this.requireApplication(),!this.api)throw new p;return new q(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()},n=await this.keyVault.load(t);if(n)return qe(n);let a=await this.masterKeys?.resolve(t);if(!a)throw new _(t);return await this.keyVault.store(t,Ve(a)),a}async prepareReveal(e){if(!this.api)throw new p;let t=await this.api.planKeyReference(e);if(!t.masterKeyWrapped)throw new Error("master_key_protection_required");return{masterKeyWrapped:!0,masterKeyHex:await this.resolveMasterKey(t)}}async revealPlan(e,t){await this.prepareReveal(e);let n=await this.collectPlanMaterial(e,t);return this.reconstructPlanMaterial(n)}collectPlanMaterial(e,t){if(!this.api)throw new p;return t?this.api.collectPlanMaterial(e,t):this.api.collectPlanMaterial(e)}async reconstructPlanMaterial(e){if(!this.reconstructor)throw new re;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){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");if(this.organizationId&&(e.sourceReference?.system!=="INHERITI_BUSINESS"||e.sourceReference.contextId!==this.organizationId))throw new _({system:"INHERITI_BUSINESS",contextId:this.organizationId});let t=me(e);if(!t)throw new _({system:"INHERITI_ELEMENTS",contextId:e.planId});let n=await this.keyVault.load(t);if(n)return qe(n);let a=await this.masterKeys?.resolve(t);if(!a)throw new _(t);return await this.keyVault.store(t,Ve(a)),a}initializeGovernedReveal(e,t){if(!this.api)throw new p;return t?this.api.initializeGovernedReveal(e,t):this.api.initializeGovernedReveal(e)}getGovernedReveal(e,t){if(!this.api)throw new p;return t?this.api.getGovernedReveal(e,t):this.api.getGovernedReveal(e)}startReveal(e,t){if(!this.api)throw new p;return this.api.startReveal(e,t)}getReveal(e){if(!this.api)throw new p;return this.api.getReveal(e)}openReveal(e,t){return Ge(this,e,t)}async withReveal(e,t,n){let a=await this.openReveal(e,t);try{let i=await n(a);return await a.close("COMPLETED"),i}catch(i){throw await a.close(t.signal?.aborted?"CANCELED":"ERROR"),i}}async releaseRevealMaterial(e,t){if(!this.api)throw new p;return Ue(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new p;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new p;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new p;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e){if(!this.api)throw new p;return this.api.getRevealCustodianAccess(e)}getRevealCustodianShare(e){if(!this.api)throw new p;return this.api.getRevealCustodianShare(e)}getRevealCustodianClaimable(e){if(!this.api)throw new p;return this.api.getRevealCustodianClaimable(e)}claimRevealCustodianShare(e,t,n){if(!this.api)throw new p;return this.api.claimRevealCustodianShare(e,t,n)}collectRevealCustodianShare(e,t){if(!this.api)throw new p;return this.api.collectRevealCustodianShare(e,t)}reportRevealReconstruction(e,t){if(!this.api)throw new p;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t){if(!this.api)throw new p;return this.api.closeReveal(e,t)}abortPlanAccess(e){if(!this.api)throw new p;return this.api.abortPlanAccess(e)}async authorizeRevealAction(e,t){if(!this.api)throw new p;return Ke(this.api,e,t)}reportRevealActionOutcome(e,t,n){if(!this.api)throw new p;return this.api.reportRevealActionOutcome(e,t,n)}getCustodianShare(e,t){if(!this.api)throw new p;return t?this.api.getCustodianShare(e,t):this.api.getCustodianShare(e)}releaseCustodianShare(e){if(!this.api)throw new p;return this.api.releaseCustodianShare(e)}exportPlanBridge(e,t){if(!this.api)throw new p;return this.api.exportPlanBridge(e,t)}importPlanBridge(e){if(!this.api)throw new p;return this.api.importPlanBridge(e)}async collectGovernedPlanMaterial(e,t){if(!this.api)throw new p;await this.resolveMasterKey({planId:e.planId,masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference});let n=t?await this.api.collectGovernedValidatorShares(e.processId,t):await this.api.collectGovernedValidatorShares(e.processId),a=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let i=n.validatorShares.map(d=>Object.assign({},d,{shareType:"VALIDATOR_SHARD"})),s=a.dataShards.map(d=>Object.assign({},d,{shareType:"DATA_SHARD"})),o=a.backupShards.map(d=>Object.assign({},d,{shareType:"BACKUP_SHARD"})),l=a.keyShards.map(d=>Object.assign({},d,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:a.dek||n.dek,shares:i.concat(s,o,l),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new p;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new Se;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new _({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},Se=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Ve(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function qe(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Et(r){if(!r.api)return;let e={api:r.api,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};if(r.applicationId)return ee({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return ee({...e,organizationId:r.organizationId})}var _t=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],At=["DIRECT","GOVERNED"],Fe=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],Ct=["ACTIVE","REVOKED"],Tt=["SK_MOBILE"],Ot=["ACTIVE","INACTIVE"],Dt=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function He(r){let e=f(r);return{items:I(e.items).map(je),nextCursor:e.nextCursor===null?null:c(e.nextCursor,"nextCursor")}}function We(r){let e=f(r);return{total:w(e.total,"total"),items:I(e.items).map(t=>{let n=f(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:c(n.id,"log.id"),planId:c(n.planId,"log.planId"),tenantId:c(n.tenantId,"log.tenantId"),event:c(n.event,"log.event"),occurredOn:c(n.occurredOn,"log.occurredOn"),status:O(n.status),title:c(n.title,"log.title"),details:I(n.details).map(a=>{let i=f(a);return{label:c(i.label,"log.detail.label"),value:c(i.value,"log.detail.value")}})}})}}function $e(r){let e=f(r),t=je(e),n=f(e.source),a=c(n.kind,"source.kind");return{...t,assets:I(e.assets).map(i=>{let s=f(i);return{id:c(s.id,"asset.id"),code:O(s.code),type:v(c(s.type,"asset.type"),ne),name:c(s.name,"asset.name"),isBinary:xt(s.isBinary,"asset.isBinary"),fieldNames:I(s.fieldNames).map(o=>c(o,"asset.fieldNames")),fileName:O(s.fileName),mimeType:O(s.mimeType),size:s.size===void 0||s.size===null?void 0:w(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:I(s.matchOrigins).map(o=>c(o,"asset.matchOrigins"))}}),participants:I(e.participants).map(i=>{let s=f(i);return{id:c(s.id,"participant.id"),displayName:c(s.displayName,"participant.displayName"),relationships:I(s.relationships).map(o=>v(c(o,"relationship"),Fe)),lifecycle:v(c(s.lifecycle,"participant.lifecycle"),Ct)}}),revealPolicy:(()=>{let i=f(e.revealPolicy);return{masterKeyRelease:v(c(i.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:v(c(i.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let i=f(e.dms);return{subjectEmail:c(i.subjectEmail,"dms.subjectEmail"),countdownDays:w(i.countdownDays,"dms.countdownDays"),countdownHours:w(i.countdownHours,"dms.countdownHours"),countdownMinutes:w(i.countdownMinutes,"dms.countdownMinutes")}})(),source:a==="NATIVE"?{kind:"NATIVE"}:a==="BRIDGED"?{kind:"BRIDGED",system:v(c(n.system,"source.system"),["INHERITI_BUSINESS"]),status:v(c(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:a}}}function W(r){let e=f(r);return{operationId:c(e.operationId,"operationId"),stage:v(c(e.stage,"stage"),ye),outcome:v(c(e.outcome,"outcome"),Dt),planId:O(e.planId),lastErrorCode:O(e.lastErrorCode),participants:e.participants===void 0?void 0:I(e.participants).map(t=>{let n=f(t);return{clientParticipantRef:c(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:c(n.planParticipantId,"planParticipantId"),relationships:I(n.relationships).map(a=>Nt(c(a,"relationship"),Fe))}})}}function je(r){let e=f(r),t=f(e.assetSummary),n=f(e.governance),a=f(e.participantSummary);return{id:c(e.id,"id"),name:c(e.name,"name"),description:O(e.description),status:v(c(e.status,"status"),_t),createdAt:c(e.createdAt,"createdAt"),configuredAt:O(e.configuredAt),assetSummary:{count:w(t.count,"assetSummary.count"),types:I(t.types).map(i=>v(c(i,"assetType"),ne)),names:Be(t.names).map(i=>c(i,"assetSummary.names"))},governance:{mode:v(c(n.mode,"governance.mode"),At),minimumApprovals:w(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:w(a.owners,"owners"),mergers:w(a.mergers,"mergers"),moderators:w(a.moderators,"moderators")},authentication:Be(e.authentication).map(i=>{let s=f(i);return{id:v(c(s.id,"authentication.id"),Tt),status:v(c(s.status,"authentication.status"),Ot)}})}}function v(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function Nt(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function f(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Be(r){return r==null?[]:I(r)}function I(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function c(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function O(r){return r==null?void 0:c(r,"optional")}function w(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function xt(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var K=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function Ye(r){if(!r||typeof r!="object"||!("items"in r)||!Array.isArray(r.items)||!r.items.every(e=>e&&typeof e=="object"&&"id"in e&&typeof e.id=="string"&&!!e.id&&"name"in e&&typeof e.name=="string"))throw new Error("business_organizations_invalid");return r.items.map(({id:e,name:t})=>({id:e,name:t}))}function kt(r,e){if(!e){if(r.length===0)throw new K("organization_required");if(r.length>1)throw new K("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new K("organization_access_denied");return e}function we(r){return typeof r.error=="string"?r.error||void 0:r.error?.code??r.name??r.message}function Ee(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var M=class extends Error{constructor(t,n,a){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=a;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},U=class{constructor(e,t,n,a,i){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=a;this.business=i?Object.freeze({...i}):void 0}business;listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(Ye)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let a of e.status??[])t.append("status",a);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return He(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return $e(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let a=n.size?`?${n}`:"";return We(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${a}`,"GET"))}async startPlanCreation(e){C(e);let{idempotencyKey:t,...n}=e;return W(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return W(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return k(t),W(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return W(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,t){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,"GET")}startMasterKeyRelaySession(e,t){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...t})}readMasterKeyRelaySession(e){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET")}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,t)}initializeGovernedReveal(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,t)}getGovernedReveal(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,t)}collectGovernedValidatorShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,t)}collectGovernedShares(e,t){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,t)}markGovernedSharesCollected(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-collected`)}markGovernedSharesReconstructed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares-reconstructed`)}markGovernedDataRevealed(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/data-revealed`)}closeGovernedReveal(e){return this.requestWithoutResult(`shared-plans/governed-reveal/${encodeURIComponent(e)}/close`)}startReveal(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",a,void 0,{"idempotency-key":n})}getReveal(e){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET")}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET")}getRevealCustodianShare(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET")}getRevealCustodianClaimable(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET")}claimRevealCustodianShare(e,t,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:t,deviceId:n})}collectRevealCustodianShare(e,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:t})}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t})}abortPlanAccess(e){return this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...a}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",a,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:a,...i}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",i,void 0,{"idempotency-key":a})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,a,i){this.requireBusinessSelection(e);let s=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});s&&o.set("authorization",`Bearer ${s}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&o.set("x-organization-id",this.business.organizationId),a?.requestId&&o.set("x-elements-step-up-request",a.requestId);for(let[S,N]of Object.entries(i??{}))o.set(S,N);n&&o.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,d=await this.transport(new URL(e,l),{method:t,headers:o,body:n?JSON.stringify(n):void 0}),h=await Xe(d);if(!d.ok)throw new M(d.status,we(h),Ee(h));if(!h.ok||h.result===void 0)throw new M(d.status,we(h),Ee(h));return h.result}async requestWithoutResult(e,t){this.requireBusinessSelection(e);let n=await this.getBearerToken(),a=new Headers({"x-elements-environment":this.environment});n&&a.set("authorization",`Bearer ${n}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId),t&&a.set("content-type","application/json");let i=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,s=await this.transport(new URL(e,i),{method:"POST",headers:a,body:t?JSON.stringify(t):void 0}),o=await Xe(s);if(!s.ok||!o.ok)throw new M(s.status,we(o),Ee(o))}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new M(400,"organization_selection_required")}};async function Xe(r){try{return await r.json()}catch{return{ok:!1}}}import{createNodeSsdpV2Processor as Vt}from"@safetech/inheriti-core-sdk/node";async function _e(r,e){if(!e)throw new Error("master_key_required");let t=Mt(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),a=bt(r),i=a.slice(0,12),s=a.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},n,s);return Kt(new Uint8Array(o))}function Mt(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function bt(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}function Kt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var $=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await Qe("plan_key_unwrap_failed",()=>_e(e.planKey,t)),a=await crypto.subtle.importKey("raw",Ae(n),{name:"AES-GCM"},!1,["decrypt"]),i=[],s=[];for(let o of e.shares){let l=await Qe("plan_share_decryption_failed",()=>zt(o.data,a));Gt(o.shareType)?s.push(l):i.push(l)}try{return await this.processor().reconstruct(i,{planId:e.planId,threshold:e.mergeThreshold,keyShares:s}).result}catch(o){throw new se("plan_share_reconstruction_failed",Lt(o))}}},se=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},Ut=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 Lt(r){let e=r instanceof Error?r.message:void 0;if(e)return Ut.has(e)?e:void 0}async function Qe(r,e){try{return await e()}catch{throw new se(r)}}function Gt(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function zt(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=Ae(r.slice(0,t)),a=Ae(r.slice(t+1)),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,a);return new TextDecoder().decode(i)}function Ae(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let a=0;a<e.length;a+=1)n[a]=e.charCodeAt(a);return t}var j=class extends ${constructor(e){super(()=>Vt(e))}};var Oe=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){Y(e.signal),Bt(e.declaration,e.secrets);let t=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return Y(e.signal),{data:t,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){Y(e.signal);let t=e.encrypted.totalShares+1,n=e.encrypted.threshold+1,a=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:!0,protocol:"SSDP_PLUS_V2",planId:e.planId});if(Y(e.signal),!a.custodianPair)throw new g("custodian_share_required");let i=Ce(a.keyShards),s=await this.sealer.encryptShares(i,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(Ce(a.dataShards),s.symmetricKeyBase64),l=await this.sealer.encryptShares(Ce(a.backupShards),s.symmetricKeyBase64),d=await this.sealCustodianPair(a.custodianPair,s.symmetricKeyBase64);return Y(e.signal),{protectionProtocol:a.protocol,validatorShares:Te(s.encryptedShares),dataShards:Te(o.encryptedShares),backupShards:Te(l.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:qt(e.encrypted.assets,e.declaration),custodianShard:d,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:De(n.encryptedShares[0]),dataShard:De(n.encryptedShares[1])}}};function Ce(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function Te(r){return r.map(De)}function De(r){return{id:r.id,data:r.encryptedData}}function qt(r,e){let t={};for(let n of r){let a=e.assets.find(i=>i.clientAssetRef===n.id);if(!a)throw new g("plan_secrets_declaration_mismatch");t[n.id]={type:n.type,meta:{name:n.meta.name,notes:n.meta.notes,...n.meta.code===void 0?{}:{code:n.meta.code},...n.meta.matchOrigins===void 0?{}:{matchOrigins:[...n.meta.matchOrigins]}},fieldNames:[...a.fieldNames??[]],isBinary:a.isBinary,...a.fileName===void 0?{}:{fileName:a.fileName},...a.mimeType===void 0?{}:{mimeType:a.mimeType},...a.size===void 0?{}:{size:a.size}}}return t}function Bt(r,e){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new g("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new g("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new g("plan_secrets_declaration_mismatch");let t=new Map(r.assets.map(n=>[n.clientAssetRef,n]));for(let n of e.assets){let a=t.get(n.id);if(!a||a.type!==n.type)throw new g("plan_secrets_declaration_mismatch")}}function Y(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}import{PassphraseMasterKeySource as yn,RawMasterKeySource as gn,deriveMasterKey as fn,generateHexSeed as vn,computePassphraseVerifier as Rn}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as In}from"@safetech/inheriti-core-sdk/node";function Ze(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var oe=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Ze(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Ze(new Uint8Array(t))}},le=class{now(){return Date.now()}sleep(e,t){return new Promise((n,a)=>{if(t?.aborted)return a(t.reason??new DOMException("Aborted","AbortError"));let i=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(i),a(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var X=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},Q=class extends X{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},u=class extends X{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Ne(r){if(r instanceof X)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var Je=class{constructor(e=globalThis.fetch.bind(globalThis)){this.http=e}async discover(e){let t=e.endsWith("/")?e:`${e}/`,n=await this.json(new URL(".well-known/openid-configuration",t),{method:"GET"});return{issuer:D(n,"issuer"),authorizationEndpoint:D(n,"authorization_endpoint"),tokenEndpoint:D(n,"token_endpoint"),deviceAuthorizationEndpoint:E(n,"device_authorization_endpoint"),endSessionEndpoint:E(n,"end_session_endpoint"),revocationEndpoint:E(n,"revocation_endpoint")}}async exchangeAuthorizationCode(e){return this.token(e.tokenEndpoint,{grant_type:"authorization_code",client_id:e.clientId,code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}async startDeviceAuthorization(e){let t=await this.form(e.endpoint,{client_id:e.clientId,scope:e.scopes.join(" ")});return{deviceCode:D(t,"device_code"),userCode:D(t,"user_code"),verificationUri:D(t,"verification_uri"),verificationUriComplete:E(t,"verification_uri_complete"),expiresInSeconds:et(t,"expires_in"),intervalSeconds:xe(t,"interval")}}pollDeviceToken(e){return this.token(e.tokenEndpoint,{grant_type:"urn:ietf:params:oauth:grant-type:device_code",client_id:e.clientId,device_code:e.deviceCode})}refresh(e){return this.token(e.tokenEndpoint,{grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken})}async token(e,t){let n=await this.form(e,t);return{accessToken:D(n,"access_token"),refreshToken:E(n,"refresh_token"),idToken:E(n,"id_token"),tokenType:D(n,"token_type"),expiresInSeconds:et(n,"expires_in"),refreshExpiresInSeconds:xe(n,"refresh_expires_in"),scope:E(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),a={};try{a=await n.json()}catch{}if(!n.ok){let i=E(a,"error")??`oauth_http_${n.status}`;throw new u(i,E(a,"error_description")??i)}return a}};function D(r,e){let t=E(r,e);if(!t)throw new u("invalid_oauth_response",`Missing ${e}`);return t}function E(r,e){return typeof r[e]=="string"?r[e]:void 0}function et(r,e){let t=xe(r,e);if(t===void 0)throw new u("invalid_oauth_response",`Missing ${e}`);return t}function xe(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Ft=600*1e3,de=5,Ht=5,tt=class{constructor(e){this.options=e;this.crypto=e.crypto??new oe,this.clock=e.clock??new le}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),a=this.crypto.randomUrlSafe(64),i=await this.crypto.sha256UrlSafe(a),s=this.clock.now()+Ft;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:a,redirectUri:this.options.configuration.redirectUri,expiresAt:s});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",n),o.searchParams.set("code_challenge",i),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:s}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new u("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new u("authorization_transaction_expired");let a=new URL(e),i=new URL(n.redirectUri);if(a.origin!==i.origin||a.pathname!==i.pathname)throw new u("redirect_uri_mismatch");let s=a.searchParams.get("error");if(s)throw new u(s,a.searchParams.get("error_description")??s);if(a.searchParams.get("state")!==n.state)throw new u("state_mismatch");let o=a.searchParams.get("code");if(!o)throw new u("authorization_code_missing");let l=await this.getDiscovery(),d=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:l.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),h=await this.acceptTokens(d,n.nonce);return await this.options.sessions.save(h),h}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new u("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(de,t.intervalSeconds??de),a=this.clock.now(),i={...t,kind:"device-code",intervalSeconds:n,expiresAt:a+t.expiresInSeconds*1e3,nextPollAt:a+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),i),i}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new u("device_transaction_missing");let a=n,i=await this.getDiscovery(),s=Math.max(de,a.intervalSeconds??de),o=Math.max(a.nextPollAt,this.clock.now());for(;this.clock.now()<a.expiresAt&&!(o>=a.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let l=await this.options.transport.pollDeviceToken({tokenEndpoint:i.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:a.deviceCode});a.consumed=!0,await this.options.transactions.save(t,a);let d=await this.acceptTokens(l);return await this.options.sessions.save(d),await this.options.transactions.remove(t),d}catch(l){let d=Ne(l);if(d==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(d==="slow_down"){s+=Ht,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),l}}throw await this.options.transactions.remove(t),new u("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new Q;try{let t=await this.getDiscovery(),n=await this.options.transport.refresh({tokenEndpoint:t.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken});if(!n.refreshToken)throw new u("refresh_token_rotation_missing");let a=await this.acceptTokens(n);return await this.options.sessions.save(a),a}catch(t){await this.options.sessions.clear();let n=Ne(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new Q:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(b(e.issuer)!==b(this.options.configuration.issuer))throw new u("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:a}=this.options.configuration;return`${e}|${b(t)}|${n}|${a}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new u("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new u("id_token_validation_required");let i=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(i,t),i.subject!==n.subject||i.sessionId!==n.sessionId)throw new u("token_subject_mismatch")}let a=this.clock.now();return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:a+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0?void 0:a+e.refreshExpiresInSeconds*1e3,principal:n}}assertPrincipal(e,t,n){let a=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(b(e.issuer)!==b(a.issuer))throw new u("issuer_mismatch");if(!i.includes(a.audience))throw new u("audience_mismatch");if(e.authorizedParty!==a.clientId)throw new u("client_mismatch");if(e.environment!==a.environment)throw new u("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new u("required_claim_missing");if(n&&e.nonce!==t)throw new u("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(b(e.issuer)!==b(n.issuer))throw new u("issuer_mismatch");if(!a.includes(n.clientId))throw new u("client_mismatch");if(e.authorizedParty!==n.clientId)throw new u("client_mismatch");if(!e.subject||!e.sessionId)throw new u("required_claim_missing");if(e.nonce!==t)throw new u("nonce_mismatch")}};function b(r){return r.replace(/\/+$/u,"")}var rt=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};function en(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=(i,s)=>{let o=new Headers(s?.headers);return o.set("x-elements-environment",r.environment),e(i,Object.assign({},s,{headers:o}))},n=r.business?void 0:Wt({apiUrl:r.apiUrl,getBearerToken:r.getBearerToken,transport:t,workerUrl:r.workerUrl,reconciliationConcurrency:r.reconciliationConcurrency,eventListeners:r.eventListeners}),a=new U(r.apiUrl,r.environment,r.getBearerToken,t,r.business?{organizationId:r.organizationId}:void 0);return new H(n,{keyVault:r.keyVault,state:r.state,api:a,reconstructor:new j(r.workerUrl),masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:$t})}export{K as BusinessOrganizationSelectionError,Oe as CorePlanMaterialBuilder,M as ElementsApiRequestFailed,H as ElementsClient,B as GuidedCreateRecoveryError,q as GuidedPlanCreator,U as HttpElementsApiPort,Je as HttpOperatorAuthTransport,m as InvalidPlanDeclaration,g as InvalidPlanMaterial,J as MasterKeyRelayExpired,Z as MasterKeyRelayTimedOut,_ as MasterKeyRequired,V as MemoryGuidedCreateCheckpointStore,G as MemoryKeyVault,z as MemoryStatePort,u as OAuthProtocolError,tt as OperatorAuthClient,X as OperatorAuthError,Q as OperatorReauthenticationRequired,rt as OperatorSessionController,ye as PLAN_CREATION_SERVER_STAGES,yn as PassphraseMasterKeySource,In as PlanAssetDeclaration,gn as RawMasterKeySource,L as RelayMasterKeySource,ue as StaticMasterKeyResolver,le as SystemOAuthClock,oe as WebOAuthCrypto,Rn as computePassphraseVerifier,ee as createMasterKeyResolver,en as createNodeElementsClient,$t as decodeAssetContainer,fn as deriveMasterKey,vn as generateHexSeed,me as masterKeyRefFor,A as masterKeyRefKey,Ne as oauthErrorCode,kt as selectBusinessOrganization,_e as unwrapDekWithMasterKey,C as validatePlanCreationInput,k as validatePlanCreationMaterial};
@@ -396,6 +396,9 @@ interface ElementsApiPort {
396
396
  requestRevealCustodianRelease(revealId: string): Promise<void>;
397
397
  getRevealCustodianAccess(revealId: string): Promise<CustodianShareAccess>;
398
398
  getRevealCustodianShare(revealId: string): Promise<CustodianShareResult>;
399
+ getRevealCustodianClaimable(revealId: string): Promise<ProCustodianShare>;
400
+ claimRevealCustodianShare(revealId: string, shareId: string, deviceId: string): Promise<void>;
401
+ collectRevealCustodianShare(revealId: string, shareId: string): Promise<void>;
399
402
  reportRevealReconstruction(revealId: string, input: RevealReconstructionInput): Promise<RevealSession>;
400
403
  closeReveal(revealId: string, reason: RevealCloseReason): Promise<RevealSession>;
401
404
  /**
@@ -591,6 +594,7 @@ interface CustodianShareAccess {
591
594
  status: 'PENDING' | 'DISTRIBUTED' | 'CLAIMED' | 'INVALID' | 'NOT_FOUND';
592
595
  deviceType: string;
593
596
  shareId: string;
597
+ deviceId?: string;
594
598
  distributedAt: string | null;
595
599
  }
596
600
  interface AuthorizeRevealActionInput {
@@ -629,6 +633,11 @@ type CustodianShareResult = {
629
633
  planId: string;
630
634
  isMergeAuthority: boolean;
631
635
  };
636
+ interface ProCustodianShare {
637
+ id: string;
638
+ planId: string;
639
+ shares: string[];
640
+ }
632
641
  declare class RevealActionsNotOpen extends Error {
633
642
  readonly stage: string;
634
643
  readonly code = "reveal_actions_not_open";
@@ -914,7 +923,7 @@ type RevealPhase =
914
923
  * one-shot material release. A host that derives its own key never sees this phase — it passes
915
924
  * through in a single call — so its presence means a person has to answer on SafeKey Mobile.
916
925
  */
917
- 'WAITING_FOR_MASTER_KEY' | 'STARTING' | 'WAITING_FOR_DMS' | 'WAITING_FOR_AUTHENTICATION' | 'WAITING_FOR_MODERATION' | 'RELEASING_MATERIAL' | 'WAITING_FOR_CUSTODIAN_CLAIM' | 'WAITING_FOR_CUSTODIAN' | 'CUSTODIAN_SHARE_DISTRIBUTED' | 'RECONSTRUCTING' | 'OPEN' | 'DENIED' | 'EXPIRED' | 'PARTICIPANT_REVOKED' | 'RECONCILIATION_REQUIRED' | 'STOPPED_BY_DMS' | 'ENDED'
926
+ 'WAITING_FOR_MASTER_KEY' | 'STARTING' | 'WAITING_FOR_DMS' | 'WAITING_FOR_AUTHENTICATION' | 'WAITING_FOR_MODERATION' | 'RELEASING_MATERIAL' | 'WAITING_FOR_CUSTODIAN_CLAIM' | 'WAITING_FOR_CUSTODIAN' | 'CONNECTING_SAFEKEY_PRO' | 'CUSTODIAN_SHARE_DISTRIBUTED' | 'RECONSTRUCTING' | 'OPEN' | 'DENIED' | 'EXPIRED' | 'PARTICIPANT_REVOKED' | 'RECONCILIATION_REQUIRED' | 'STOPPED_BY_DMS' | 'ENDED'
918
927
  /** A stage this build has not been taught to name. Stages are additive, so it is a wait. */
919
928
  | 'CONTINUING';
920
929
  interface RevealProgress {
@@ -935,6 +944,20 @@ interface OpenRevealOptions {
935
944
  pollIntervalMs?: number;
936
945
  /** How long to wait for a SafeKey Mobile custodian release before giving up. Default 2 minutes. */
937
946
  custodianTimeoutMs?: number;
947
+ /** Called only on first access. Omit for the existing SafeKey Mobile behavior. */
948
+ selectCustodianDevice?: () => 'SK_MOBILE' | 'SK_PRO' | Promise<'SK_MOBILE' | 'SK_PRO'>;
949
+ /** Local transport only; its read must come from the connected device. */
950
+ proDevice?: {
951
+ write(share: ProCustodianShare, signal?: AbortSignal): Promise<{
952
+ deviceId: string;
953
+ }>;
954
+ read(request: {
955
+ shareId: string;
956
+ planId: string;
957
+ }, signal?: AbortSignal): Promise<ProCustodianShare & {
958
+ deviceId: string;
959
+ }>;
960
+ };
938
961
  /** Every step of the reveal, named. Prefer this to `onSession`, which reports server stages only. */
939
962
  onProgress?: (progress: RevealProgress) => void;
940
963
  onSession?: (session: RevealSession) => void;
@@ -1126,6 +1149,9 @@ declare class ElementsClient {
1126
1149
  requestRevealCustodianRelease(revealId: string): Promise<void>;
1127
1150
  getRevealCustodianAccess(revealId: string): Promise<CustodianShareAccess>;
1128
1151
  getRevealCustodianShare(revealId: string): Promise<CustodianShareResult>;
1152
+ getRevealCustodianClaimable(revealId: string): Promise<ProCustodianShare>;
1153
+ claimRevealCustodianShare(revealId: string, shareId: string, deviceId: string): Promise<void>;
1154
+ collectRevealCustodianShare(revealId: string, shareId: string): Promise<void>;
1129
1155
  reportRevealReconstruction(revealId: string, input: RevealReconstructionInput): Promise<RevealSession>;
1130
1156
  closeReveal(revealId: string, reason: RevealCloseReason): Promise<RevealSession>;
1131
1157
  abortPlanAccess(planId: string): Promise<{
@@ -1227,6 +1253,9 @@ declare class HttpElementsApiPort implements ElementsApiPort {
1227
1253
  requestRevealCustodianRelease(revealId: string): Promise<void>;
1228
1254
  getRevealCustodianAccess(revealId: string): Promise<CustodianShareAccess>;
1229
1255
  getRevealCustodianShare(revealId: string): Promise<CustodianShareResult>;
1256
+ getRevealCustodianClaimable(revealId: string): Promise<ProCustodianShare>;
1257
+ claimRevealCustodianShare(revealId: string, shareId: string, deviceId: string): Promise<void>;
1258
+ collectRevealCustodianShare(revealId: string, shareId: string): Promise<void>;
1230
1259
  reportRevealReconstruction(revealId: string, input: RevealReconstructionInput): Promise<RevealSession>;
1231
1260
  closeReveal(revealId: string, reason: RevealCloseReason): Promise<RevealSession>;
1232
1261
  abortPlanAccess(planId: string): Promise<{
@@ -1533,4 +1562,4 @@ declare class OperatorSessionController {
1533
1562
  }
1534
1563
 
1535
1564
  export { BusinessOrganizationSelectionError, CANONICAL_PLAN_ASSET_TYPES, CANONICAL_STRUCTURED_ASSET_FIELDS, CorePlanMaterialBuilder, ElementsApiPortRequired, ElementsApiRequestFailed, ElementsClient, GuidedCreateRecoveryError, GuidedPlanCreator, HostProcessRuntimeEnvironment, HttpElementsApiPort, HttpOperatorAuthTransport, InheritiClientProvider, InvalidPlanDeclaration, InvalidPlanMaterial, LocalProcessReconciliationOwnership, MasterKeyRelayExpired, MasterKeyRelayTimedOut, MasterKeyRequired, MemoryGuidedCreateCheckpointStore, MemoryKeyVault, MemoryStatePort, OAuthProtocolError, OperatorAuthClient, OperatorAuthError, OperatorReauthenticationRequired, OperatorSessionController, PLAN_CREATION_SERVER_STAGES, PlanMaterialReconstructionFailed, PlanMaterialReconstructorRequired, PollingSharedPlanEventListener, RelayMasterKeySource, RevealActionsNotOpen, RevealFieldAccessError, RevealHandleClosed, StaticMasterKeyResolver, SystemOAuthClock, WebOAuthCrypto, createElementsClient, createMasterKeyResolver, getAvailableEnvs, masterKeyRefFor, masterKeyRefKey, oauthErrorCode, parseAssetFieldSelector, revealPhaseOf, selectBusinessOrganization, unwrapDekWithMasterKey, useClient, validatePlanCreationInput, validatePlanCreationMaterial };
1536
- export type { AssetFieldSelector, AuthorizationTransaction, AuthorizeRevealActionInput, BusinessOrganization, CanonicalPlanAssetType, CollectedPlanMaterial, CompatibleValue, ConsumedRevealField, CorePlanSecrets, CustodianShareResult, DeclaredMasterKeySource, DecodedPlanAsset, DeviceAuthorization, DeviceTransaction, ElementsApiPort, ElementsClientOptions, ElementsEnvironment, EncryptedPlanMaterial, EncryptedPlanShard, ExportPlanBridgeInput, GovernedRevealSession, GovernedRevealState, GovernedShare, GovernedSharesMaterial, GovernedValidatorMaterial, GuidedCreateCheckpoint, GuidedCreateCheckpointStore, GuidedCreateLocalStage, GuidedCreateOptions, InheritiClientProviderProps, IntegrationPlanAssetDeclaration, KeyVault, ListPlanLogsInput, ListPlansInput, MasterKeyAcquisition, MasterKeyAcquisitionOptions, MasterKeyRef, MasterKeyRelayContext, MasterKeyRelayPort, MasterKeyRelaySessionOpened, MasterKeyRelaySessionState, MasterKeyResolver, NativePlanParticipant, OAuthClock, OAuthCrypto, OAuthHttpTransport, OAuthTokenResponse, OAuthTransaction, OAuthTransactionStore, OidcDiscoveryDocument, OpenRevealOptions, OperatorAuthClientOptions, OperatorAuthConfiguration, OperatorAuthTransport, OperatorSession, OperatorSessionControlPort, OperatorSessionStore, OperatorSessionSummary, OperatorTokenValidator, PlanAssetContainerDecoder, PlanAssetSummary, PlanBridgeEnvelope, PlanCreationOutcome, PlanCreationProgress, PlanCreationServerStage, PlanDetail, PlanGovernanceMode, PlanGovernancePolicy, PlanLog, PlanLogPage, PlanMaterialBuilder, PlanMaterialReconstructor, PlanPage, PlanParticipantRelationship, PlanRevealProfile, PlanStatus, PlanSummary, RelayMasterKeySourceOptions, ReportRevealActionOutcomeInput, RevealAction, RevealActionDestination, RevealActionOutcome, RevealActionType, RevealCloseReason, RevealFieldConsumption, RevealFieldDestination, RevealFieldOptions, RevealHandle, RevealMode, RevealPhase, RevealProgress, RevealReconstructionInput, RevealSession, RevealStage, StartPlanCreationInput, StartRevealInput, StatePort, StepUpReadContext, ValidatedOperatorToken };
1565
+ export type { AssetFieldSelector, AuthorizationTransaction, AuthorizeRevealActionInput, BusinessOrganization, CanonicalPlanAssetType, CollectedPlanMaterial, CompatibleValue, ConsumedRevealField, CorePlanSecrets, CustodianShareResult, DeclaredMasterKeySource, DecodedPlanAsset, DeviceAuthorization, DeviceTransaction, ElementsApiPort, ElementsClientOptions, ElementsEnvironment, EncryptedPlanMaterial, EncryptedPlanShard, ExportPlanBridgeInput, GovernedRevealSession, GovernedRevealState, GovernedShare, GovernedSharesMaterial, GovernedValidatorMaterial, GuidedCreateCheckpoint, GuidedCreateCheckpointStore, GuidedCreateLocalStage, GuidedCreateOptions, InheritiClientProviderProps, IntegrationPlanAssetDeclaration, KeyVault, ListPlanLogsInput, ListPlansInput, MasterKeyAcquisition, MasterKeyAcquisitionOptions, MasterKeyRef, MasterKeyRelayContext, MasterKeyRelayPort, MasterKeyRelaySessionOpened, MasterKeyRelaySessionState, MasterKeyResolver, NativePlanParticipant, OAuthClock, OAuthCrypto, OAuthHttpTransport, OAuthTokenResponse, OAuthTransaction, OAuthTransactionStore, OidcDiscoveryDocument, OpenRevealOptions, OperatorAuthClientOptions, OperatorAuthConfiguration, OperatorAuthTransport, OperatorSession, OperatorSessionControlPort, OperatorSessionStore, OperatorSessionSummary, OperatorTokenValidator, PlanAssetContainerDecoder, PlanAssetSummary, PlanBridgeEnvelope, PlanCreationOutcome, PlanCreationProgress, PlanCreationServerStage, PlanDetail, PlanGovernanceMode, PlanGovernancePolicy, PlanLog, PlanLogPage, PlanMaterialBuilder, PlanMaterialReconstructor, PlanPage, PlanParticipantRelationship, PlanRevealProfile, PlanStatus, PlanSummary, ProCustodianShare, RelayMasterKeySourceOptions, ReportRevealActionOutcomeInput, RevealAction, RevealActionDestination, RevealActionOutcome, RevealActionType, RevealCloseReason, RevealFieldConsumption, RevealFieldDestination, RevealFieldOptions, RevealHandle, RevealMode, RevealPhase, RevealProgress, RevealReconstructionInput, RevealSession, RevealStage, StartPlanCreationInput, StartRevealInput, StatePort, StepUpReadContext, ValidatedOperatorToken };
@@ -97,6 +97,9 @@ export interface ElementsApiPort {
97
97
  requestRevealCustodianRelease(revealId: string): Promise<void>;
98
98
  getRevealCustodianAccess(revealId: string): Promise<CustodianShareAccess>;
99
99
  getRevealCustodianShare(revealId: string): Promise<CustodianShareResult>;
100
+ getRevealCustodianClaimable(revealId: string): Promise<ProCustodianShare>;
101
+ claimRevealCustodianShare(revealId: string, shareId: string, deviceId: string): Promise<void>;
102
+ collectRevealCustodianShare(revealId: string, shareId: string): Promise<void>;
100
103
  reportRevealReconstruction(revealId: string, input: RevealReconstructionInput): Promise<RevealSession>;
101
104
  closeReveal(revealId: string, reason: RevealCloseReason): Promise<RevealSession>;
102
105
  /**
@@ -292,6 +295,7 @@ export interface CustodianShareAccess {
292
295
  status: 'PENDING' | 'DISTRIBUTED' | 'CLAIMED' | 'INVALID' | 'NOT_FOUND';
293
296
  deviceType: string;
294
297
  shareId: string;
298
+ deviceId?: string;
295
299
  distributedAt: string | null;
296
300
  }
297
301
  export interface AuthorizeRevealActionInput {
@@ -330,6 +334,11 @@ export type CustodianShareResult = {
330
334
  planId: string;
331
335
  isMergeAuthority: boolean;
332
336
  };
337
+ export interface ProCustodianShare {
338
+ id: string;
339
+ planId: string;
340
+ shares: string[];
341
+ }
333
342
  export declare class RevealActionsNotOpen extends Error {
334
343
  readonly stage: string;
335
344
  readonly code = "reveal_actions_not_open";
@@ -171,6 +171,9 @@ export default class ElementsClient {
171
171
  requestRevealCustodianRelease(revealId: string): Promise<void>;
172
172
  getRevealCustodianAccess(revealId: string): Promise<import("./elements-api-port").CustodianShareAccess>;
173
173
  getRevealCustodianShare(revealId: string): Promise<CustodianShareResult>;
174
+ getRevealCustodianClaimable(revealId: string): Promise<import("./elements-api-port").ProCustodianShare>;
175
+ claimRevealCustodianShare(revealId: string, shareId: string, deviceId: string): Promise<void>;
176
+ collectRevealCustodianShare(revealId: string, shareId: string): Promise<void>;
174
177
  reportRevealReconstruction(revealId: string, input: RevealReconstructionInput): Promise<RevealSession>;
175
178
  closeReveal(revealId: string, reason: RevealCloseReason): Promise<RevealSession>;
176
179
  abortPlanAccess(planId: string): Promise<{
@@ -72,6 +72,9 @@ export default class HttpElementsApiPort implements ElementsApiPort {
72
72
  requestRevealCustodianRelease(revealId: string): Promise<void>;
73
73
  getRevealCustodianAccess(revealId: string): Promise<import('./elements-api-port').CustodianShareAccess>;
74
74
  getRevealCustodianShare(revealId: string): Promise<CustodianShareResult>;
75
+ getRevealCustodianClaimable(revealId: string): Promise<import('./elements-api-port').ProCustodianShare>;
76
+ claimRevealCustodianShare(revealId: string, shareId: string, deviceId: string): Promise<void>;
77
+ collectRevealCustodianShare(revealId: string, shareId: string): Promise<void>;
75
78
  reportRevealReconstruction(revealId: string, input: RevealReconstructionInput): Promise<RevealSession>;
76
79
  closeReveal(revealId: string, reason: RevealCloseReason): Promise<RevealSession>;
77
80
  abortPlanAccess(planId: string): Promise<{
@@ -5,7 +5,7 @@ export { MemoryKeyVault } from './key-vault';
5
5
  export type { KeyVault } from './key-vault';
6
6
  export { MemoryStatePort } from './state-port';
7
7
  export type { StatePort } from './state-port';
8
- export type { CollectedPlanMaterial, ElementsApiPort, StepUpReadContext } from './elements-api-port';
8
+ export type { CollectedPlanMaterial, ElementsApiPort, ProCustodianShare, StepUpReadContext } from './elements-api-port';
9
9
  export type { GovernedRevealSession, GovernedRevealState, GovernedShare, GovernedSharesMaterial, GovernedValidatorMaterial } from './elements-api-port';
10
10
  export type { AuthorizeRevealActionInput, CustodianShareResult, ReportRevealActionOutcomeInput, RevealAction, RevealActionDestination, RevealActionOutcome, RevealActionType, RevealCloseReason, RevealMode, RevealReconstructionInput, RevealSession, RevealStage, StartRevealInput } from './elements-api-port';
11
11
  export type { ExportPlanBridgeInput, PlanBridgeEnvelope, PlanRevealProfile } from './elements-api-port';
@@ -1,5 +1,5 @@
1
1
  import type ElementsClient from './elements-client';
2
- import type { RevealActionDestination, RevealActionType, RevealCloseReason, RevealMode, RevealSession } from './elements-api-port';
2
+ import type { ProCustodianShare, RevealActionDestination, RevealActionType, RevealCloseReason, RevealMode, RevealSession } from './elements-api-port';
3
3
  export type AssetFieldSelector = string | {
4
4
  asset: string;
5
5
  field: string;
@@ -44,7 +44,7 @@ export type RevealPhase =
44
44
  * one-shot material release. A host that derives its own key never sees this phase — it passes
45
45
  * through in a single call — so its presence means a person has to answer on SafeKey Mobile.
46
46
  */
47
- 'WAITING_FOR_MASTER_KEY' | 'STARTING' | 'WAITING_FOR_DMS' | 'WAITING_FOR_AUTHENTICATION' | 'WAITING_FOR_MODERATION' | 'RELEASING_MATERIAL' | 'WAITING_FOR_CUSTODIAN_CLAIM' | 'WAITING_FOR_CUSTODIAN' | 'CUSTODIAN_SHARE_DISTRIBUTED' | 'RECONSTRUCTING' | 'OPEN' | 'DENIED' | 'EXPIRED' | 'PARTICIPANT_REVOKED' | 'RECONCILIATION_REQUIRED' | 'STOPPED_BY_DMS' | 'ENDED'
47
+ 'WAITING_FOR_MASTER_KEY' | 'STARTING' | 'WAITING_FOR_DMS' | 'WAITING_FOR_AUTHENTICATION' | 'WAITING_FOR_MODERATION' | 'RELEASING_MATERIAL' | 'WAITING_FOR_CUSTODIAN_CLAIM' | 'WAITING_FOR_CUSTODIAN' | 'CONNECTING_SAFEKEY_PRO' | 'CUSTODIAN_SHARE_DISTRIBUTED' | 'RECONSTRUCTING' | 'OPEN' | 'DENIED' | 'EXPIRED' | 'PARTICIPANT_REVOKED' | 'RECONCILIATION_REQUIRED' | 'STOPPED_BY_DMS' | 'ENDED'
48
48
  /** A stage this build has not been taught to name. Stages are additive, so it is a wait. */
49
49
  | 'CONTINUING';
50
50
  export interface RevealProgress {
@@ -65,6 +65,20 @@ export interface OpenRevealOptions {
65
65
  pollIntervalMs?: number;
66
66
  /** How long to wait for a SafeKey Mobile custodian release before giving up. Default 2 minutes. */
67
67
  custodianTimeoutMs?: number;
68
+ /** Called only on first access. Omit for the existing SafeKey Mobile behavior. */
69
+ selectCustodianDevice?: () => 'SK_MOBILE' | 'SK_PRO' | Promise<'SK_MOBILE' | 'SK_PRO'>;
70
+ /** Local transport only; its read must come from the connected device. */
71
+ proDevice?: {
72
+ write(share: ProCustodianShare, signal?: AbortSignal): Promise<{
73
+ deviceId: string;
74
+ }>;
75
+ read(request: {
76
+ shareId: string;
77
+ planId: string;
78
+ }, signal?: AbortSignal): Promise<ProCustodianShare & {
79
+ deviceId: string;
80
+ }>;
81
+ };
68
82
  /** Every step of the reveal, named. Prefer this to `onSession`, which reports server stages only. */
69
83
  onProgress?: (progress: RevealProgress) => void;
70
84
  onSession?: (session: RevealSession) => void;
@@ -105,6 +119,10 @@ export declare class CustodianShareUnavailable extends Error {
105
119
  readonly code = "custodian_share_unavailable";
106
120
  constructor();
107
121
  }
122
+ export declare class SafeKeyProLocalDeviceRequired extends Error {
123
+ readonly code = "safekey_pro_local_device_required";
124
+ constructor();
125
+ }
108
126
  /** Nobody approved on the device in time. A person did not act; nothing is wrong with the reveal. */
109
127
  export declare class CustodianShareTimedOut extends Error {
110
128
  readonly code = "custodian_share_timed_out";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@safetech/inheriti-client-sdk",
3
- "version": "1.17.9",
3
+ "version": "1.17.11",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -42,7 +42,7 @@
42
42
  "license": "MIT",
43
43
  "dependencies": {
44
44
  "@safetech/safekey-sdk": "^1.0.0",
45
- "@safetech/inheriti-core-sdk": "4.0.28"
45
+ "@safetech/inheriti-core-sdk": "4.0.29"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@rollup/plugin-alias": "^5.1.1",