@safetech/inheriti-client-sdk 1.17.6 → 1.17.7

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.d.ts CHANGED
@@ -5,7 +5,7 @@ import type { KeyVault } from './src/elements/key-vault';
5
5
  import type { MasterKeyResolver } from './src/elements/master-key';
6
6
  import type { ElementsClientOptions } from './src/elements/elements-client';
7
7
  import type { StatePort } from './src/elements/state-port';
8
- export interface NodeElementsClientOptions extends NodeSharedConfigurationSdkOptions {
8
+ export type NodeElementsClientOptions = NodeSharedConfigurationSdkOptions & {
9
9
  environment: 'TEST' | 'LIVE';
10
10
  keyVault?: KeyVault;
11
11
  state?: StatePort;
@@ -17,12 +17,20 @@ export interface NodeElementsClientOptions extends NodeSharedConfigurationSdkOpt
17
17
  masterKeys?: MasterKeyResolver;
18
18
  /** What custody this host holds locally. See `ElementsClientOptions['masterKey']`. */
19
19
  masterKey?: ElementsClientOptions['masterKey'];
20
- /** The Application this client acts for; needed to wrap keys of plans it creates. */
20
+ } & ({
21
21
  applicationId: string;
22
- }
22
+ business?: never;
23
+ organizationId?: never;
24
+ } | {
25
+ business: true;
26
+ organizationId?: string;
27
+ applicationId?: never;
28
+ });
23
29
  export declare function createNodeElementsClient(options: NodeElementsClientOptions): ElementsClient;
24
30
  export { ElementsClient };
25
31
  export { default as HttpElementsApiPort, ElementsApiRequestFailed } from './src/elements/http-elements-api-port';
32
+ export { selectBusinessOrganization, BusinessOrganizationSelectionError } from './src/business/organizations';
33
+ export type { BusinessOrganization } from './src/business/organizations';
26
34
  export type { StepUpReadContext } from './src/elements/elements-api-port';
27
35
  export { MemoryKeyVault } from './src/elements/key-vault';
28
36
  export type { KeyVault } from './src/elements/key-vault';
@@ -35,14 +43,14 @@ export { RelayMasterKeySource, MasterKeyRelayExpired, MasterKeyRelayTimedOut } f
35
43
  export { createMasterKeyResolver } from './src/elements/master-key-acquisition';
36
44
  export type { MasterKeySource } from '@safetech/inheriti-core-sdk';
37
45
  export type { DeclaredMasterKeySource, MasterKeyAcquisitionOptions } from './src/elements/master-key-acquisition';
38
- export type { MasterKeyAcquisition, MasterKeyRelaySessionOpened, MasterKeyRelaySessionState } from './src/elements/elements-api-port';
46
+ export type { MasterKeyAcquisition, MasterKeyRelayContext, MasterKeyRelaySessionOpened, MasterKeyRelaySessionState } from './src/elements/elements-api-port';
39
47
  export type { MasterKeyRelayPort } from './src/elements/relay-master-key-source';
40
48
  export { GuidedPlanCreator, GuidedCreateRecoveryError, MemoryGuidedCreateCheckpointStore } from './src/elements/guided-plan-creator';
41
49
  export type { GuidedCreateCheckpointStore, GuidedCreateOptions, PlanMaterialBuilder } from './src/elements/guided-plan-creator';
42
50
  export { CorePlanMaterialBuilder } from './src/elements/core-plan-material-builder';
43
51
  export type { CorePlanSecrets } from './src/elements/core-plan-material-builder';
44
52
  export { InvalidPlanDeclaration, InvalidPlanMaterial, PLAN_CREATION_SERVER_STAGES, validatePlanCreationInput, validatePlanCreationMaterial } from './src/elements/plan-operations';
45
- export type { EncryptedPlanMaterial, EncryptedPlanShard, GuidedCreateCheckpoint, GuidedCreateLocalStage, ListPlansInput, PlanCreationOutcome, PlanCreationProgress, PlanCreationServerStage, PlanDetail, PlanPage, StartPlanCreationInput, } from './src/elements/plan-operations';
53
+ export type { EncryptedPlanMaterial, EncryptedPlanShard, GuidedCreateCheckpoint, GuidedCreateLocalStage, ListPlansInput, PlanCreationOutcome, PlanCreationProgress, PlanCreationServerStage, PlanDetail, ListPlanLogsInput, PlanLog, PlanLogPage, PlanPage, StartPlanCreationInput, } from './src/elements/plan-operations';
46
54
  export { PassphraseMasterKeySource, RawMasterKeySource, deriveMasterKey, generateHexSeed, computePassphraseVerifier } from '@safetech/inheriti-core-sdk/node';
47
55
  export { PlanAssetDeclaration } from '@safetech/inheriti-core-sdk/node';
48
56
  export type { PlanAssetDeclarationEntry, PlanAssetDeclarationInput } from '@safetech/inheriti-core-sdk/node';
package/dist/node.js CHANGED
@@ -1 +1 @@
1
- import{createNodeSharedConfigurationSdk as Mt,decodeAssetContainer as xt}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as $e,generateRSAOAEPKeyPair as je}from"@safetech/inheriti-core-sdk/crypto";var W=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},$=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},k=class{constructor(e){this.options=e}async resolve(){let{publicKeyBase64:e,privateKey:t}=await je(),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 $e(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 $(n.sessionId);await s(a)}throw new W(n.sessionId)}};function re(r){return{resolve:async e=>{if(Ye(e,r.applicationId)){let t=await r.source?.resolve();return t||we(r,()=>r.api.masterKeyAcquisition())}return we(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId))}}}function Ye(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function we(r,e){if((await e()).relayAvailable)return new k({...r.relay,api:Qe(r.api)}).resolve()}function Qe(r){return{startRelaySession:e=>r.startMasterKeyRelaySession(e),readRelaySession:e=>r.readMasterKeyRelaySession(e)}}function S(r){return`${r.system}:${r.contextId}`}function ae(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var I=class extends Error{constructor(t){super(`master_key_required:${S(t)}`);this.ref=t;this.name="MasterKeyRequired"}},ne=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 M=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 x=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 j=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 Y=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var Q=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],Xe={"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"]},se=["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"}},y=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function _(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new y("plan_material_field_unknown");if(ie(r.dataShards,"data_shards_invalid"),ie(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&ie(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new y("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new y("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new y("material_operation_invalid")}function ie(r,e){if(!Array.isArray(r))throw new y(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new y(e);if(t.data!==void 0&&typeof t.data!="string")throw new y(e)}}function w(r){if(C(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!et(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(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 m("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!Q.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(Ze(t.matchOrigins),!t.isBinary){let i=Xe[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(C(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Ce(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")}Je(r)}function Ze(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 Je(r){let e=r.policy;if(e&&C(e,["authentication","moderation","dms","masterKeyRelease","custodian"],"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"){C(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){C(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;C(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,a=t.countdownMinutes??0;if(!Ce(t.subjectEmail))throw new m("dms_subject_invalid");if(!r.participants.some(i=>Ae(i.routingEmail)===Ae(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 et(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 Ce(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Ae(r){return r.normalize("NFC").trim().toLowerCase()}function C(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new m(t)}var b=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)}},K=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),w(e),X(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 U("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await _e(t))throw new U("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;X(i.signal),i.onProgress?.("ENCRYPTING");let l=await a.encrypt({planId:o.planId,declaration:t,secrets:n,signal:i.signal});X(i.signal),i.onProgress?.("GENERATING_SHARES");let c=await a.generateShares({planId:o.planId,declaration:t,encrypted:l,signal:i.signal});X(i.signal),_(c);let h=await this.api.supplyPlanCreationMaterial(e,c);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 _e(e),serverStage:t.stage})}},U=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function _e(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 X(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Te(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new j(n.stage);return r.authorizeRevealAction(e,t)}function tt(r){let e=r?.status;return e===400||e===401||e===403}async function Oe(r,e,t,n){let a=await r.getReveal(e);try{await n(a.planId)}catch(i){if(!tt(i))throw i}return r.releaseRevealMaterial(e,t)}function rt(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"?at(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":nt.has(r.stage)?"ENDED":"CONTINUING"}var nt=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function at(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 oe=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},R=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function De(r,e,t={}){if(t.signal?.aborted)throw pe();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 st(r,i,t);L(t,"RELEASING_MATERIAL",o);let l=await r.releaseRevealMaterial(o.id,o.materialVersion??"1");o.mode==="GOVERNED"&&await r.markRevealSharesCollected(o.id);let c=await dt(r,o,n,ut(l),t);L(t,"RECONSTRUCTING",o),s=await r.reconstructPlanMaterial(c);let h=await r.reportRevealReconstruction(o.id,{status:"SUCCEEDED"});return L(t,"OPEN",h),new ce(r,h,n,s,t.signal)}catch(o){throw s?.fill(0),await mt(r,i.id,t.signal?.aborted?"CANCELED":"ERROR"),o}}var it=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function st(r,e,t){let n=await r.getReveal(e.id);for(;;){if(t.onSession?.(n),t.onProgress?.({phase:rt(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(it.has(n.stage))throw new le(n.stage);await ue(t.pollIntervalMs??1500,t.signal),n=await r.getReveal(e.id)}}var le=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function L(r,e,t){r.onProgress?.({phase:e,session:t})}function ue(r,e){return e?.aborted?Promise.reject(pe()):new Promise((t,n)=>{let a=setTimeout(s,Math.max(0,r)),i=()=>{clearTimeout(a),n(pe())};function s(){e?.removeEventListener("abort",i),t()}e?.addEventListener("abort",i,{once:!0})})}var ce=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 oe;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 R("asset_selector_invalid");if(!this.client.assetDecoder)throw new R("asset_decoder_required");let n=e.map(({selector:i,options:s={}})=>{let o=ot(i),l=this.plan.assets.find(c=>(c.code??c.id)===o.asset);if(!l)throw new R("asset_not_found");if(l.isBinary)throw new R("action_not_allowed");if(!l.fieldNames.includes(o.field))throw new R("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 R("asset_value_invalid");return{selector:s.selector,value:lt(o.data,s.field)}});await t(i)}catch(i){throw await Promise.all(a.map(s=>this.reportAction(s.id,"FAILED",ct(i)))),i}await Promise.all(a.map(i=>this.reportAction(i.id,"SUCCEEDED")))}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=this.client.closeReveal(this.session.id,e).then(()=>{}).catch(t=>{if(!Ne(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 ot(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new R("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new R("asset_selector_invalid");return{asset:r.asset,field:r.field}}function lt(r,e){let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new R("asset_value_invalid")}if(!t||typeof t!="object"||Array.isArray(t)||!(e in t))throw new R("asset_value_invalid");return t[e]}function ct(r){if(r instanceof R)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"}async function dt(r,e,t,n,a){if(t.revealPolicy?.custodian!=="FORCE"||n.shares.some(l=>l.shareType==="CUSTODIAN_KEY_SHARD"))return n;let i=await r.getRevealCustodianAccess(e.id);for(;i.status==="PENDING"||i.status==="DISTRIBUTED";){let l={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};a.onSession?.(l),L(a,"WAITING_FOR_CUSTODIAN_CLAIM",l),await ue(a.pollIntervalMs??1500,a.signal),i=await r.getRevealCustodianAccess(e.id)}if(i.status!=="CLAIMED"||i.deviceType!=="SK_MOBILE")throw new Z;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};a.onSession?.(s),L(a,"WAITING_FOR_CUSTODIAN",s),await r.requestRevealCustodianRelease(e.id);let o=await pt(r,e.id,a);return Object.assign({},n,{shares:n.shares.concat(o.shares.map((l,c)=>({id:`${o.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:l})))})}async function pt(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 Z}if(Date.now()>=n)throw new de;await ue(t.pollIntervalMs??1500,t.signal)}}var Z=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},de=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function ut(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function mt(r,e,t){try{await r.closeReveal(e,t)}catch(n){if(!Ne(n))throw n}}function Ne(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function pe(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var G=class{constructor(e,t={}){this.coreSdk=e;this.keyVault=t.keyVault??new M,this.state=t.state??new x,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??ht(t),this.applicationId=t.applicationId,this.assetDecoder=t.assetDecoder}keyVault;state;api;reconstructor;masterKeys;applicationId;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)}startPlanCreation(e){if(!this.api)throw new d;return w(e),this.api.startPlanCreation(e)}getPlanCreation(e){if(!this.api)throw new d;return this.api.getPlanCreation(e)}supplyPlanCreationMaterial(e,t){if(!this.api)throw new d;return _(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(!this.api)throw new d;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new b){if(!this.api)throw new d;return new K(this.api,e)}createPlan(e){return 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(){if(!this.applicationId)throw new I({system:"INHERITI_ELEMENTS",contextId:"application"});let e={system:"INHERITI_ELEMENTS",contextId:this.applicationId},t=await this.keyVault.load(e);if(t)return Me(t);let n=await this.masterKeys?.resolve(e);if(!n)throw new I(e);return await this.keyVault.store(e,ke(n)),n}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 Y;return this.reconstructor.reconstruct(e,await this.resolveMasterKey(e))}async forgetMasterKey(e){let t=e??(this.applicationId?{system:"INHERITI_ELEMENTS",contextId:this.applicationId}:void 0);t&&await this.keyVault.remove(t)}async resolveMasterKey(e){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let t=ae(e);if(!t)throw new I({system:"INHERITI_ELEMENTS",contextId:e.planId});let n=await this.keyVault.load(t);if(n)return Me(n);let a=await this.masterKeys?.resolve(t);if(!a)throw new I(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 De(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 Oe(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new d;return this.api.markRevealSharesCollected(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 Te(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(c=>Object.assign({},c,{shareType:"VALIDATOR_SHARD"})),s=a.dataShards.map(c=>Object.assign({},c,{shareType:"DATA_SHARD"})),o=a.backupShards.map(c=>Object.assign({},c,{shareType:"BACKUP_SHARD"})),l=a.keyShards.map(c=>Object.assign({},c,{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 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 me;return this.coreSdk.getService(e).execute(t)}},me=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 Me(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function ht(r){if(!r.api||!r.applicationId)return;let e={api:r.api,applicationId:r.applicationId,...r.masterKey?.source?{source:r.masterKey.source}:{},...r.masterKey?.relay?{relay:r.masterKey.relay}:{}};return re(e)}var yt=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],ft=["DIRECT","GOVERNED"],be=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],gt=["ACTIVE","REVOKED"],Rt=["SK_MOBILE"],Pt=["ACTIVE","INACTIVE"],vt=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Ke(r){let e=g(r);return{items:P(e.items).map(Le),nextCursor:e.nextCursor===null?null:p(e.nextCursor,"nextCursor")}}function Ue(r){let e=g(r),t=Le(e),n=g(e.source),a=p(n.kind,"source.kind");return{...t,assets:P(e.assets).map(i=>{let s=g(i);return{id:p(s.id,"asset.id"),code:T(s.code),type:f(p(s.type,"asset.type"),Q),name:p(s.name,"asset.name"),isBinary:St(s.isBinary,"asset.isBinary"),fieldNames:P(s.fieldNames).map(o=>p(o,"asset.fieldNames")),fileName:T(s.fileName),mimeType:T(s.mimeType),size:s.size===void 0||s.size===null?void 0:E(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:P(s.matchOrigins).map(o=>p(o,"asset.matchOrigins"))}}),participants:P(e.participants).map(i=>{let s=g(i);return{id:p(s.id,"participant.id"),displayName:p(s.displayName,"participant.displayName"),relationships:P(s.relationships).map(o=>f(p(o,"relationship"),be)),lifecycle:f(p(s.lifecycle,"participant.lifecycle"),gt)}}),revealPolicy:(()=>{let i=g(e.revealPolicy);return{masterKeyRelease:f(p(i.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:f(p(i.custodian,"custodian"),["FORCE","BYPASS"])}})(),dms:e.dms===void 0?void 0:(()=>{let i=g(e.dms);return{subjectEmail:p(i.subjectEmail,"dms.subjectEmail"),countdownDays:E(i.countdownDays,"dms.countdownDays"),countdownHours:E(i.countdownHours,"dms.countdownHours"),countdownMinutes:E(i.countdownMinutes,"dms.countdownMinutes")}})(),source:a==="NATIVE"?{kind:"NATIVE"}:a==="BRIDGED"?{kind:"BRIDGED",system:f(p(n.system,"source.system"),["INHERITI_BUSINESS"]),status:f(p(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:a}}}function V(r){let e=g(r);return{operationId:p(e.operationId,"operationId"),stage:f(p(e.stage,"stage"),se),outcome:f(p(e.outcome,"outcome"),vt),planId:T(e.planId),lastErrorCode:T(e.lastErrorCode),participants:e.participants===void 0?void 0:P(e.participants).map(t=>{let n=g(t);return{clientParticipantRef:p(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:p(n.planParticipantId,"planParticipantId"),relationships:P(n.relationships).map(a=>Et(p(a,"relationship"),be))}})}}function Le(r){let e=g(r),t=g(e.assetSummary),n=g(e.governance),a=g(e.participantSummary);return{id:p(e.id,"id"),name:p(e.name,"name"),description:T(e.description),status:f(p(e.status,"status"),yt),createdAt:p(e.createdAt,"createdAt"),configuredAt:T(e.configuredAt),assetSummary:{count:E(t.count,"assetSummary.count"),types:P(t.types).map(i=>f(p(i,"assetType"),Q)),names:xe(t.names).map(i=>p(i,"assetSummary.names"))},governance:{mode:f(p(n.mode,"governance.mode"),ft),minimumApprovals:E(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:E(a.owners,"owners"),mergers:E(a.mergers,"mergers"),moderators:E(a.moderators,"moderators")},authentication:xe(e.authentication).map(i=>{let s=g(i);return{id:f(p(s.id,"authentication.id"),Rt),status:f(p(s.status,"authentication.status"),Pt)}})}}function f(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function Et(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function g(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function xe(r){return r==null?[]:P(r)}function P(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function p(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function T(r){return r==null?void 0:p(r,"optional")}function E(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function St(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}function he(r){return typeof r.error=="string"?r.error||void 0:r.error?.code??r.name??r.message}function ye(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var D=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){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=a}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 Ke(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Ue(await this.request(`v1/plans/${encodeURIComponent(e)}`,"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),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){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e})}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`)}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){let s=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});s&&o.set("authorization",`Bearer ${s}`),a?.requestId&&o.set("x-elements-step-up-request",a.requestId);for(let[He,We]of Object.entries(i??{}))o.set(He,We);n&&o.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,l),{method:t,headers:o,body:n?JSON.stringify(n):void 0}),h=await Ge(c);if(!c.ok)throw new D(c.status,he(h),ye(h));if(!h.ok||h.result===void 0)throw new D(c.status,he(h),ye(h));return h.result}async requestWithoutResult(e){let t=await this.getBearerToken(),n=new Headers({"x-elements-environment":this.environment});t&&n.set("authorization",`Bearer ${t}`);let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,i=await this.transport(new URL(e,a),{method:"POST",headers:n}),s=await Ge(i);if(!i.ok||!s.ok)throw new D(i.status,he(s),ye(s))}};async function Ge(r){try{return await r.json()}catch{return{ok:!1}}}import{createConfiguredSsdpV2Processor as Tt}from"@safetech/inheriti-core-sdk/node";async function fe(r,e){if(!e)throw new Error("master_key_required");let t=It(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),a=wt(r),i=a.slice(0,12),s=a.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},n,s);return At(new Uint8Array(o))}function It(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 wt(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 At(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 fe(e.planKey,t),a=await crypto.subtle.importKey("raw",ge(n),{name:"AES-GCM"},!1,["decrypt"]),i=[],s=[];for(let o of e.shares){let l=await _t(o.data,a);Ct(o.shareType)?s.push(l):i.push(l)}return this.processor().reconstruct(i,{planId:e.planId,threshold:e.mergeThreshold,keyShares:s}).result}};function Ct(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function _t(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=ge(r.slice(0,t)),a=ge(r.slice(t+1)),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,a);return new TextDecoder().decode(i)}function ge(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 F=class extends q{constructor(){super(Tt)}};var ve=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){let t=e.declaration.policy?.custodian==="FORCE";B(e.signal),Dt(e.declaration,e.secrets,t);let n=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return B(e.signal),{data:n,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,withCustodian:t,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){B(e.signal);let t=e.encrypted.totalShares+(e.encrypted.withCustodian?1:0),n=e.encrypted.threshold+(e.encrypted.withCustodian?1:0),a=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:e.encrypted.withCustodian,protocol:"SSDP_PLUS_V2",planId:e.planId});B(e.signal);let i=Re(a.keyShards),s=await this.sealer.encryptShares(i,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(Re(a.dataShards),s.symmetricKeyBase64),l=await this.sealer.encryptShares(Re(a.backupShards),s.symmetricKeyBase64),c=a.custodianPair?await this.sealCustodianPair(a.custodianPair,s.symmetricKeyBase64):void 0;return B(e.signal),{protectionProtocol:a.protocol,validatorShares:Pe(s.encryptedShares),dataShards:Pe(o.encryptedShares),backupShards:Pe(l.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:Ot(e.encrypted.assets,e.declaration),custodianShard:c,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:Ee(n.encryptedShares[0]),dataShard:Ee(n.encryptedShares[1])}}};function Re(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function Pe(r){return r.map(Ee)}function Ee(r){return{id:r.id,data:r.encryptedData}}function Ot(r,e){let t={};for(let n of r){let a=e.assets.find(i=>i.clientAssetRef===n.id);if(!a)throw new y("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 Dt(r,e,t){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new y("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new y("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new y("plan_secrets_declaration_mismatch");let n=new Map(r.assets.map(a=>[a.clientAssetRef,a]));for(let a of e.assets){let i=n.get(a.id);if(!i||i.type!==a.type)throw new y("plan_secrets_declaration_mismatch")}}function B(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}import{PassphraseMasterKeySource as Zr,RawMasterKeySource as Jr,deriveMasterKey as en,generateHexSeed as tn,computePassphraseVerifier as rn}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as an}from"@safetech/inheriti-core-sdk/node";function Ve(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var J=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Ve(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Ve(new Uint8Array(t))}},ee=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 z=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},H=class extends z{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},u=class extends z{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function Se(r){if(r instanceof z)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var qe=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:A(n,"issuer"),authorizationEndpoint:A(n,"authorization_endpoint"),tokenEndpoint:A(n,"token_endpoint"),deviceAuthorizationEndpoint:v(n,"device_authorization_endpoint"),endSessionEndpoint:v(n,"end_session_endpoint"),revocationEndpoint:v(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:A(t,"device_code"),userCode:A(t,"user_code"),verificationUri:A(t,"verification_uri"),verificationUriComplete:v(t,"verification_uri_complete"),expiresInSeconds:Fe(t,"expires_in"),intervalSeconds:Ie(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:A(n,"access_token"),refreshToken:v(n,"refresh_token"),idToken:v(n,"id_token"),tokenType:A(n,"token_type"),expiresInSeconds:Fe(n,"expires_in"),refreshExpiresInSeconds:Ie(n,"refresh_expires_in"),scope:v(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=v(a,"error")??`oauth_http_${n.status}`;throw new u(i,v(a,"error_description")??i)}return a}};function A(r,e){let t=v(r,e);if(!t)throw new u("invalid_oauth_response",`Missing ${e}`);return t}function v(r,e){return typeof r[e]=="string"?r[e]:void 0}function Fe(r,e){let t=Ie(r,e);if(t===void 0)throw new u("invalid_oauth_response",`Missing ${e}`);return t}function Ie(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Nt=600*1e3,te=5,kt=5,Be=class{constructor(e){this.options=e;this.crypto=e.crypto??new J,this.clock=e.clock??new ee}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()+Nt;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(),c=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:l.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),h=await this.acceptTokens(c,n.nonce);return await this.options.sessions.save(h),h}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new u("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(te,t.intervalSeconds??te),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(te,a.intervalSeconds??te),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 c=await this.acceptTokens(l);return await this.options.sessions.save(c),await this.options.transactions.remove(t),c}catch(l){let c=Se(l);if(c==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(c==="slow_down"){s+=kt,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 H;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=Se(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new H:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(O(e.issuer)!==O(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}|${O(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(O(e.issuer)!==O(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(O(e.issuer)!==O(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 O(r){return r.replace(/\/+$/u,"")}var ze=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 Gr(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=Mt({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);return new G(n,{keyVault:r.keyVault,state:r.state,api:a,reconstructor:new F,masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,assetDecoder:xt})}export{ve as CorePlanMaterialBuilder,D as ElementsApiRequestFailed,G as ElementsClient,U as GuidedCreateRecoveryError,K as GuidedPlanCreator,N as HttpElementsApiPort,qe as HttpOperatorAuthTransport,m as InvalidPlanDeclaration,y as InvalidPlanMaterial,$ as MasterKeyRelayExpired,W as MasterKeyRelayTimedOut,I as MasterKeyRequired,b as MemoryGuidedCreateCheckpointStore,M as MemoryKeyVault,x as MemoryStatePort,u as OAuthProtocolError,Be as OperatorAuthClient,z as OperatorAuthError,H as OperatorReauthenticationRequired,ze as OperatorSessionController,se as PLAN_CREATION_SERVER_STAGES,Zr as PassphraseMasterKeySource,an as PlanAssetDeclaration,Jr as RawMasterKeySource,k as RelayMasterKeySource,ne as StaticMasterKeyResolver,ee as SystemOAuthClock,J as WebOAuthCrypto,rn as computePassphraseVerifier,re as createMasterKeyResolver,Gr as createNodeElementsClient,xt as decodeAssetContainer,en as deriveMasterKey,tn as generateHexSeed,ae as masterKeyRefFor,S as masterKeyRefKey,Se as oauthErrorCode,fe as unwrapDekWithMasterKey,w as validatePlanCreationInput,_ as validatePlanCreationMaterial};
1
+ import{createNodeSharedConfigurationSdk as Ut,decodeAssetContainer as Lt}from"@safetech/inheriti-core-sdk/node";import{decryptRSAOAEP as Qe,generateRSAOAEPKeyPair as Ze}from"@safetech/inheriti-core-sdk/crypto";var $=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"}},M=class{constructor(e){this.options=e}async resolve(){let{publicKeyBase64:e,privateKey:t}=await Ze(),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 Qe(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 $(n.sessionId)}};function Y(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||ae(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId})}if(Je(e,r.applicationId)){let t=await r.source?.resolve();return t||ae(r,()=>r.api.masterKeyAcquisition())}return ae(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId})}}}function Je(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function ae(r,e,t){if((await e()).relayAvailable)return new M({...r.relay,api:et(r.api,t)}).resolve()}function et(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 se(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"}},ie=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 k=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 b=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 X=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 Q=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var Z=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],tt={"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"]},le=["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"}},f=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 f("plan_material_field_unknown");if(oe(r.dataShards,"data_shards_invalid"),oe(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&oe(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new f("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new f("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new f("material_operation_invalid")}function oe(r,e){if(!Array.isArray(r))throw new f(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new f(e);if(t.data!==void 0&&typeof t.data!="string")throw new f(e)}}function w(r){if(_(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!at(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(_(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),!Z.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(rt(t.matchOrigins),!t.isBinary){let i=tt[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(_(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!_e(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")}nt(r)}function rt(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 nt(r){let e=r.policy;if(e&&_(e,["authentication","moderation","dms","masterKeyRelease","custodian"],"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"){_(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){_(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;_(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,a=t.countdownMinutes??0;if(!_e(t.subjectEmail))throw new m("dms_subject_invalid");if(!r.participants.some(i=>Ce(i.routingEmail)===Ce(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 at(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 _e(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Ce(r){return r.normalize("NFC").trim().toLowerCase()}function _(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new m(t)}var K=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)}},U=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),w(e),J(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 L("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await Te(t))throw new L("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;J(i.signal),i.onProgress?.("ENCRYPTING");let l=await a.encrypt({planId:o.planId,declaration:t,secrets:n,signal:i.signal});J(i.signal),i.onProgress?.("GENERATING_SHARES");let p=await a.generateShares({planId:o.planId,declaration:t,encrypted:l,signal:i.signal});J(i.signal),T(p);let h=await this.api.supplyPlanCreationMaterial(e,p);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 Te(e),serverStage:t.stage})}},L=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Te(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 J(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function Oe(r,e,t){let n=await r.getReveal(e);if(n.stage!=="ACTIONS_OPEN")throw new X(n.stage);return r.authorizeRevealAction(e,t)}function it(r){let e=r?.status;return e===400||e===401||e===403}async function De(r,e,t,n){let a=await r.getReveal(e);try{await n(a.planId)}catch(i){if(!it(i))throw i}return r.releaseRevealMaterial(e,t)}function st(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"?lt(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":ot.has(r.stage)?"ENDED":"CONTINUING"}var ot=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function lt(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 ce=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 Ne(r,e,t={}){if(t.signal?.aborted)throw me();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 dt(r,i,t);G(t,"RELEASING_MATERIAL",o);let l=await r.releaseRevealMaterial(o.id,o.materialVersion??"1");o.mode==="GOVERNED"&&await r.markRevealSharesCollected(o.id);let p=await mt(r,o,n,yt(l),t);G(t,"RECONSTRUCTING",o),s=await r.reconstructPlanMaterial(p);let h=await r.reportRevealReconstruction(o.id,{status:"SUCCEEDED"});return G(t,"OPEN",h),new pe(r,h,n,s,t.signal)}catch(o){throw s?.fill(0),await gt(r,i.id,t.signal?.aborted?"CANCELED":"ERROR"),o}}var ct=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function dt(r,e,t){let n=await r.getReveal(e.id);for(;;){if(t.onSession?.(n),t.onProgress?.({phase:st(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(ct.has(n.stage))throw new de(n.stage);await he(t.pollIntervalMs??1500,t.signal),n=await r.getReveal(e.id)}}var de=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function G(r,e,t){r.onProgress?.({phase:e,session:t})}function he(r,e){return e?.aborted?Promise.reject(me()):new Promise((t,n)=>{let a=setTimeout(s,Math.max(0,r)),i=()=>{clearTimeout(a),n(me())};function s(){e?.removeEventListener("abort",i),t()}e?.addEventListener("abort",i,{once:!0})})}var pe=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 ce;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=pt(i),l=this.plan.assets.find(p=>(p.code??p.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:ut(o.data,s.field)}});await t(i)}catch(i){throw await Promise.all(a.map(s=>this.reportAction(s.id,"FAILED",xe(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",xe(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(!Me(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 pt(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 ut(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 xe(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"}async function mt(r,e,t,n,a){if(t.revealPolicy?.custodian!=="FORCE"||n.shares.some(l=>l.shareType==="CUSTODIAN_KEY_SHARD"))return n;let i=await r.getRevealCustodianAccess(e.id);for(;i.status==="PENDING"||i.status==="DISTRIBUTED";){let l={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};a.onSession?.(l),G(a,"WAITING_FOR_CUSTODIAN_CLAIM",l),await he(a.pollIntervalMs??1500,a.signal),i=await r.getRevealCustodianAccess(e.id)}if(i.status!=="CLAIMED"||i.deviceType!=="SK_MOBILE")throw new ee;let s={...e,stage:"WAITING_FOR_CUSTODIAN"};a.onSession?.(s),G(a,"WAITING_FOR_CUSTODIAN",s),await r.requestRevealCustodianRelease(e.id);let o=await ht(r,e.id,a);return Object.assign({},n,{shares:n.shares.concat(o.shares.map((l,p)=>({id:`${o.id}:${p}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:l})))})}async function ht(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 ee}if(Date.now()>=n)throw new ue;await he(t.pollIntervalMs??1500,t.signal)}}var ee=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},ue=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function yt(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function gt(r,e,t){try{await r.closeReveal(e,t)}catch(n){if(!Me(n))throw n}}function Me(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function me(){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 k,this.state=t.state??new b,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??ft(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 K){if(this.requireApplication(),!this.api)throw new d;return new U(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 be(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 Q;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=se(e);if(!t)throw new E({system:"INHERITI_ELEMENTS",contextId:e.planId});let n=await this.keyVault.load(t);if(n)return be(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 Ne(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 De(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new d;return this.api.markRevealSharesCollected(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 Oe(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(p=>Object.assign({},p,{shareType:"VALIDATOR_SHARD"})),s=a.dataShards.map(p=>Object.assign({},p,{shareType:"DATA_SHARD"})),o=a.backupShards.map(p=>Object.assign({},p,{shareType:"BACKUP_SHARD"})),l=a.keyShards.map(p=>Object.assign({},p,{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 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 ye;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new E({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},ye=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 be(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function ft(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 Y({...e,applicationId:r.applicationId});if(r.organizationId!==void 0)return Y({...e,organizationId:r.organizationId})}var Rt=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Pt=["DIRECT","GOVERNED"],Ue=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],vt=["ACTIVE","REVOKED"],It=["SK_MOBILE"],Et=["ACTIVE","INACTIVE"],St=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Le(r){let e=g(r);return{items:P(e.items).map(Ve),nextCursor:e.nextCursor===null?null:c(e.nextCursor,"nextCursor")}}function Ge(r){let e=g(r);return{total:v(e.total,"total"),items:P(e.items).map(t=>{let n=g(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:A(n.status),title:c(n.title,"log.title"),details:P(n.details).map(a=>{let i=g(a);return{label:c(i.label,"log.detail.label"),value:c(i.value,"log.detail.value")}})}})}}function ze(r){let e=g(r),t=Ve(e),n=g(e.source),a=c(n.kind,"source.kind");return{...t,assets:P(e.assets).map(i=>{let s=g(i);return{id:c(s.id,"asset.id"),code:A(s.code),type:R(c(s.type,"asset.type"),Z),name:c(s.name,"asset.name"),isBinary:At(s.isBinary,"asset.isBinary"),fieldNames:P(s.fieldNames).map(o=>c(o,"asset.fieldNames")),fileName:A(s.fileName),mimeType:A(s.mimeType),size:s.size===void 0||s.size===null?void 0:v(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:P(s.matchOrigins).map(o=>c(o,"asset.matchOrigins"))}}),participants:P(e.participants).map(i=>{let s=g(i);return{id:c(s.id,"participant.id"),displayName:c(s.displayName,"participant.displayName"),relationships:P(s.relationships).map(o=>R(c(o,"relationship"),Ue)),lifecycle:R(c(s.lifecycle,"participant.lifecycle"),vt)}}),revealPolicy:(()=>{let i=g(e.revealPolicy);return{masterKeyRelease:R(c(i.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:R(c(i.custodian,"custodian"),["FORCE","BYPASS"])}})(),dms:e.dms===void 0?void 0:(()=>{let i=g(e.dms);return{subjectEmail:c(i.subjectEmail,"dms.subjectEmail"),countdownDays:v(i.countdownDays,"dms.countdownDays"),countdownHours:v(i.countdownHours,"dms.countdownHours"),countdownMinutes:v(i.countdownMinutes,"dms.countdownMinutes")}})(),source:a==="NATIVE"?{kind:"NATIVE"}:a==="BRIDGED"?{kind:"BRIDGED",system:R(c(n.system,"source.system"),["INHERITI_BUSINESS"]),status:R(c(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:a}}}function V(r){let e=g(r);return{operationId:c(e.operationId,"operationId"),stage:R(c(e.stage,"stage"),le),outcome:R(c(e.outcome,"outcome"),St),planId:A(e.planId),lastErrorCode:A(e.lastErrorCode),participants:e.participants===void 0?void 0:P(e.participants).map(t=>{let n=g(t);return{clientParticipantRef:c(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:c(n.planParticipantId,"planParticipantId"),relationships:P(n.relationships).map(a=>wt(c(a,"relationship"),Ue))}})}}function Ve(r){let e=g(r),t=g(e.assetSummary),n=g(e.governance),a=g(e.participantSummary);return{id:c(e.id,"id"),name:c(e.name,"name"),description:A(e.description),status:R(c(e.status,"status"),Rt),createdAt:c(e.createdAt,"createdAt"),configuredAt:A(e.configuredAt),assetSummary:{count:v(t.count,"assetSummary.count"),types:P(t.types).map(i=>R(c(i,"assetType"),Z)),names:Ke(t.names).map(i=>c(i,"assetSummary.names"))},governance:{mode:R(c(n.mode,"governance.mode"),Pt),minimumApprovals:v(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:v(a.owners,"owners"),mergers:v(a.mergers,"mergers"),moderators:v(a.moderators,"moderators")},authentication:Ke(e.authentication).map(i=>{let s=g(i);return{id:R(c(s.id,"authentication.id"),It),status:R(c(s.status,"authentication.status"),Et)}})}}function R(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function wt(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function g(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function Ke(r){return r==null?[]:P(r)}function P(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 A(r){return r==null?void 0:c(r,"optional")}function v(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function At(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var x=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function qe(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 Ct(r,e){if(!e){if(r.length===0)throw new x("organization_required");if(r.length>1)throw new x("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new x("organization_access_denied");return e}function ge(r){return typeof r.error=="string"?r.error||void 0:r.error?.code??r.name??r.message}function fe(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(qe)}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 Le(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return ze(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let a=n.size?`?${n}`:"";return Ge(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`)}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"&&o.set("x-organization-id",this.business.organizationId),a?.requestId&&o.set("x-elements-step-up-request",a.requestId);for(let[Ye,Xe]of Object.entries(i??{}))o.set(Ye,Xe);n&&o.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,p=await this.transport(new URL(e,l),{method:t,headers:o,body:n?JSON.stringify(n):void 0}),h=await Be(p);if(!p.ok)throw new O(p.status,ge(h),fe(h));if(!h.ok||h.result===void 0)throw new O(p.status,ge(h),fe(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 Be(i);if(!i.ok||!s.ok)throw new O(i.status,ge(s),fe(s))}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!this.business.organizationId)throw new O(400,"organization_selection_required")}};async function Be(r){try{return await r.json()}catch{return{ok:!1}}}import{createConfiguredSsdpV2Processor as Nt}from"@safetech/inheriti-core-sdk/node";async function Re(r,e){if(!e)throw new Error("master_key_required");let t=_t(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),a=Tt(r),i=a.slice(0,12),s=a.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},n,s);return Ot(new Uint8Array(o))}function _t(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Tt(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 Ot(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 Re(e.planKey,t),a=await crypto.subtle.importKey("raw",Pe(n),{name:"AES-GCM"},!1,["decrypt"]),i=[],s=[];for(let o of e.shares){let l=await xt(o.data,a);Dt(o.shareType)?s.push(l):i.push(l)}return this.processor().reconstruct(i,{planId:e.planId,threshold:e.mergeThreshold,keyShares:s}).result}};function Dt(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function xt(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=Pe(r.slice(0,t)),a=Pe(r.slice(t+1)),i=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,a);return new TextDecoder().decode(i)}function Pe(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(){super(Nt)}};var Ee=class{constructor(e,t){this.masterKeySource=t;this.generator=e.getService("SharedPlanSharesGenerator"),this.sealer=e.getService("ShareEncryptionService")}generator;sealer;async encrypt(e){let t=e.declaration.policy?.custodian==="FORCE";F(e.signal),kt(e.declaration,e.secrets,t);let n=await this.generator.prepare(e.secrets.assets,"SSDP_PLUS_V2");return F(e.signal),{data:n,assets:e.secrets.assets,totalShares:e.secrets.totalShares,threshold:e.secrets.threshold,withCustodian:t,masterKey:await this.masterKeySource.resolve()}}async generateShares(e){F(e.signal);let t=e.encrypted.totalShares+(e.encrypted.withCustodian?1:0),n=e.encrypted.threshold+(e.encrypted.withCustodian?1:0),a=await this.generator.generate(e.encrypted.data,{total:t,threshold:n,withCustodian:e.encrypted.withCustodian,protocol:"SSDP_PLUS_V2",planId:e.planId});F(e.signal);let i=ve(a.keyShards),s=await this.sealer.encryptShares(i,void 0,e.encrypted.masterKey),o=await this.sealer.encryptShares(ve(a.dataShards),s.symmetricKeyBase64),l=await this.sealer.encryptShares(ve(a.backupShards),s.symmetricKeyBase64),p=a.custodianPair?await this.sealCustodianPair(a.custodianPair,s.symmetricKeyBase64):void 0;return F(e.signal),{protectionProtocol:a.protocol,validatorShares:Ie(s.encryptedShares),dataShards:Ie(o.encryptedShares),backupShards:Ie(l.encryptedShares),encryptedKey:s.encryptedKey,assetsMetadata:Mt(e.encrypted.assets,e.declaration),custodianShard:p,operation:"FINALIZE"}}async sealCustodianPair(e,t){let n=await this.sealer.encryptShares([e.keyShard,e.dataShard],t);return{keyShard:Se(n.encryptedShares[0]),dataShard:Se(n.encryptedShares[1])}}};function ve(r){return r.map(e=>({id:crypto.randomUUID(),data:e}))}function Ie(r){return r.map(Se)}function Se(r){return{id:r.id,data:r.encryptedData}}function Mt(r,e){let t={};for(let n of r){let a=e.assets.find(i=>i.clientAssetRef===n.id);if(!a)throw new f("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 kt(r,e,t){if(!Number.isInteger(e.totalShares)||e.totalShares<1)throw new f("total_shares_invalid");if(!Number.isInteger(e.threshold)||e.threshold<1||e.threshold>e.totalShares)throw new f("share_threshold_invalid");if(e.assets.length!==r.assets.length)throw new f("plan_secrets_declaration_mismatch");let n=new Map(r.assets.map(a=>[a.clientAssetRef,a]));for(let a of e.assets){let i=n.get(a.id);if(!i||i.type!==a.type)throw new f("plan_secrets_declaration_mismatch")}}function F(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}import{PassphraseMasterKeySource as sn,RawMasterKeySource as on,deriveMasterKey as ln,generateHexSeed as cn,computePassphraseVerifier as dn}from"@safetech/inheriti-core-sdk/node";import{PlanAssetDeclaration as un}from"@safetech/inheriti-core-sdk/node";function Fe(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var te=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),Fe(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Fe(new Uint8Array(t))}},re=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"}},u=class extends H{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function we(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 He=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:C(n,"issuer"),authorizationEndpoint:C(n,"authorization_endpoint"),tokenEndpoint:C(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:C(t,"device_code"),userCode:C(t,"user_code"),verificationUri:C(t,"verification_uri"),verificationUriComplete:I(t,"verification_uri_complete"),expiresInSeconds:We(t,"expires_in"),intervalSeconds:Ae(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:C(n,"access_token"),refreshToken:I(n,"refresh_token"),idToken:I(n,"id_token"),tokenType:C(n,"token_type"),expiresInSeconds:We(n,"expires_in"),refreshExpiresInSeconds:Ae(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 u(i,I(a,"error_description")??i)}return a}};function C(r,e){let t=I(r,e);if(!t)throw new u("invalid_oauth_response",`Missing ${e}`);return t}function I(r,e){return typeof r[e]=="string"?r[e]:void 0}function We(r,e){let t=Ae(r,e);if(t===void 0)throw new u("invalid_oauth_response",`Missing ${e}`);return t}function Ae(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var bt=600*1e3,ne=5,Kt=5,$e=class{constructor(e){this.options=e;this.crypto=e.crypto??new te,this.clock=e.clock??new re}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()+bt;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(),p=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(p,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(ne,t.intervalSeconds??ne),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(ne,a.intervalSeconds??ne),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 p=await this.acceptTokens(l);return await this.options.sessions.save(p),await this.options.transactions.remove(t),p}catch(l){let p=we(l);if(p==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(p==="slow_down"){s+=Kt,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 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 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=we(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 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}|${D(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(D(e.issuer)!==D(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(D(e.issuer)!==D(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 D(r){return r.replace(/\/+$/u,"")}var je=class{constructor(e,t){this.control=e;this.local=t}list(){return this.control.list()}async revoke(e){await this.control.revoke(e),(await this.local.load())?.principal.sessionId===e&&await this.local.clear()}async logout(){let e=await this.local.load();if(e)try{await this.control.logout(e.principal.sessionId)}finally{await this.local.clear()}}};function Hr(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=(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:Ut({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,masterKeys:r.masterKeys,masterKey:r.masterKey,applicationId:r.applicationId,organizationId:r.organizationId,assetDecoder:Lt})}export{x as BusinessOrganizationSelectionError,Ee as CorePlanMaterialBuilder,O as ElementsApiRequestFailed,z as ElementsClient,L as GuidedCreateRecoveryError,U as GuidedPlanCreator,N as HttpElementsApiPort,He as HttpOperatorAuthTransport,m as InvalidPlanDeclaration,f as InvalidPlanMaterial,j as MasterKeyRelayExpired,$ as MasterKeyRelayTimedOut,E as MasterKeyRequired,K as MemoryGuidedCreateCheckpointStore,k as MemoryKeyVault,b as MemoryStatePort,u as OAuthProtocolError,$e as OperatorAuthClient,H as OperatorAuthError,W as OperatorReauthenticationRequired,je as OperatorSessionController,le as PLAN_CREATION_SERVER_STAGES,sn as PassphraseMasterKeySource,un as PlanAssetDeclaration,on as RawMasterKeySource,M as RelayMasterKeySource,ie as StaticMasterKeyResolver,re as SystemOAuthClock,te as WebOAuthCrypto,dn as computePassphraseVerifier,Y as createMasterKeyResolver,Hr as createNodeElementsClient,Lt as decodeAssetContainer,ln as deriveMasterKey,cn as generateHexSeed,se as masterKeyRefFor,S as masterKeyRefKey,we as oauthErrorCode,Ct as selectBusinessOrganization,Re as unwrapDekWithMasterKey,w as validatePlanCreationInput,T as validatePlanCreationMaterial};
@@ -105,6 +105,27 @@ interface PlanPage {
105
105
  items: PlanSummary[];
106
106
  nextCursor: string | null;
107
107
  }
108
+ interface ListPlanLogsInput {
109
+ limit?: number;
110
+ offset?: number;
111
+ }
112
+ interface PlanLog {
113
+ id: string;
114
+ planId: string;
115
+ tenantId: string;
116
+ event: string;
117
+ occurredOn: string;
118
+ status?: string;
119
+ title: string;
120
+ details: Array<{
121
+ label: string;
122
+ value: string;
123
+ }>;
124
+ }
125
+ interface PlanLogPage {
126
+ items: PlanLog[];
127
+ total: number;
128
+ }
108
129
  interface ListPlansInput {
109
130
  cursor?: string;
110
131
  limit?: number;
@@ -328,6 +349,10 @@ interface MasterKeyRelaySessionOpened {
328
349
  sessionId: string;
329
350
  expiresAt: string | Date;
330
351
  }
352
+ interface MasterKeyRelayContext {
353
+ system: string;
354
+ contextId: string;
355
+ }
331
356
  interface MasterKeyRelaySessionState {
332
357
  status: 'PENDING' | 'DELIVERED' | 'EXPIRED';
333
358
  sealedMasterKey?: string;
@@ -341,10 +366,11 @@ interface ElementsApiPort {
341
366
  * Asks the device holding the key to release it to this host. Creating the session *is* the
342
367
  * SafeKey request; there is no separate "notify" step.
343
368
  */
344
- startMasterKeyRelaySession(clientPublicKey: string): Promise<MasterKeyRelaySessionOpened>;
369
+ startMasterKeyRelaySession(clientPublicKey: string, context?: MasterKeyRelayContext): Promise<MasterKeyRelaySessionOpened>;
345
370
  readMasterKeyRelaySession(sessionId: string): Promise<MasterKeyRelaySessionState>;
346
371
  listPlans(input?: ListPlansInput): Promise<PlanPage>;
347
372
  getPlan(planId: string): Promise<PlanDetail>;
373
+ listPlanLogs(planId: string, input?: ListPlanLogsInput): Promise<PlanLogPage>;
348
374
  startPlanCreation(input: StartPlanCreationInput): Promise<PlanCreationProgress>;
349
375
  getPlanCreation(operationId: string): Promise<PlanCreationProgress>;
350
376
  supplyPlanCreationMaterial(operationId: string, material: EncryptedPlanMaterial): Promise<PlanCreationProgress>;
@@ -516,8 +542,8 @@ type RevealMode = 'DIRECT' | 'GOVERNED';
516
542
  /** Reveal stages are additive. Hosts must treat unknown non-terminal values as waiting. */
517
543
  type RevealStage = 'STARTING' | 'WAITING_FOR_DMS' | 'WAITING_FOR_PARTICIPANTS' | 'AUTHORIZED' | 'MATERIAL_AUTHORIZED' | 'MATERIAL_RELEASED' | 'RECONSTRUCTED' | 'ACTIONS_OPEN' | 'CLOSING' | 'CLOSED' | 'DENIED' | 'PARTICIPANT_REVOKED' | 'RECONCILIATION_REQUIRED' | 'EXPIRED' | 'CANCELED' | 'FAILED' | 'WAITING_FOR_CUSTODIAN_CLAIM' | 'WAITING_FOR_CUSTODIAN';
518
544
  type RevealCloseReason = 'COMPLETED' | 'CANCELED' | 'DMS_RESET' | 'ERROR';
519
- type RevealActionType = 'VIEW_FIELD' | 'COPY_FIELD' | 'USE_FIELD' | 'EXPORT_ASSET' | 'AUTOFILL_FIELD' | 'INSERT_FIELD';
520
- type RevealActionDestination = 'STDIN' | 'ENVIRONMENT' | 'FILE_DESCRIPTOR' | 'LOCAL_SOCKET' | 'TEMPORARY_FILE';
545
+ type RevealActionType = 'VIEW_FIELD' | 'COPY_FIELD' | 'USE_FIELD' | 'EXPORT_ASSET' | 'AUTOFILL_FIELD' | 'INSERT_FIELD' | 'DELIVER_FIELD';
546
+ type RevealActionDestination = 'STDIN' | 'ENVIRONMENT' | 'FILE_DESCRIPTOR' | 'LOCAL_SOCKET' | 'TEMPORARY_FILE' | 'LOCAL_BROWSER';
521
547
  type RevealActionOutcome = 'SUCCEEDED' | 'FAILED' | 'CANCELED';
522
548
  interface StartRevealInput {
523
549
  mode: RevealMode;
@@ -530,6 +556,7 @@ interface RevealReconstructionInput {
530
556
  interface RevealSession {
531
557
  id: string;
532
558
  idempotencyKey: string;
559
+ /** Standalone Application ID; embedded Business currently fills this wire alias with the integration client ID. */
533
560
  applicationId: string;
534
561
  environment: 'TEST' | 'LIVE';
535
562
  planId: string;
@@ -716,10 +743,8 @@ declare class RelayMasterKeySource implements MasterKeySource {
716
743
  interface DeclaredMasterKeySource {
717
744
  resolve(): Promise<string | undefined>;
718
745
  }
719
- interface MasterKeyAcquisitionOptions {
746
+ type MasterKeyAcquisitionOptions = {
720
747
  api: ElementsApiPort;
721
- /** The Application this host acts for. A ref naming any other context is foreign. */
722
- applicationId: string;
723
748
  /**
724
749
  * What this host can produce on its own: a passphrase-derived key, or key material it already
725
750
  * holds. Absent means the host has no custody of its own and must be given the key.
@@ -732,7 +757,13 @@ interface MasterKeyAcquisitionOptions {
732
757
  source?: DeclaredMasterKeySource;
733
758
  /** Passed through to the relay, for hosts that want a different wait or poll interval. */
734
759
  relay?: Omit<RelayMasterKeySourceOptions, 'api'>;
735
- }
760
+ } & ({
761
+ applicationId: string;
762
+ organizationId?: never;
763
+ } | {
764
+ organizationId: string;
765
+ applicationId?: never;
766
+ });
736
767
  /**
737
768
  * Decides how this host obtains the key that opens a plan, and does it.
738
769
  *
@@ -859,6 +890,12 @@ interface ConsumedRevealField {
859
890
  value: unknown;
860
891
  }
861
892
  type RevealFieldDestination = (fields: readonly ConsumedRevealField[]) => void | Promise<void>;
893
+ type RevealAssetDestination = (asset: {
894
+ id: string;
895
+ fileName?: string;
896
+ mimeType?: string;
897
+ bytes: Uint8Array;
898
+ }) => void | Promise<void>;
862
899
  /**
863
900
  * Where a reveal has got to, in the order a reveal runs.
864
901
  *
@@ -911,6 +948,7 @@ interface RevealHandle {
911
948
  field<TValue = unknown>(selector: AssetFieldSelector, options?: RevealFieldOptions): Promise<TValue>;
912
949
  /** Authorize, decode and deliver fields without returning their plaintext to the caller. */
913
950
  consumeFields(fields: readonly RevealFieldConsumption[], destination: RevealFieldDestination): Promise<void>;
951
+ exportAsset(selector: string, destination: RevealAssetDestination): Promise<void>;
914
952
  close(reason?: RevealCloseReason): Promise<void>;
915
953
  [Symbol.asyncDispose](): Promise<void>;
916
954
  }
@@ -965,7 +1003,9 @@ interface ElementsClientOptions {
965
1003
  relay?: MasterKeyAcquisitionOptions['relay'];
966
1004
  };
967
1005
  /** The Application this client acts for; needed to wrap keys of plans it creates. */
968
- applicationId: string;
1006
+ applicationId?: string;
1007
+ /** The selected Business organization for this client instance. */
1008
+ organizationId?: string;
969
1009
  assetDecoder: PlanAssetContainerDecoder;
970
1010
  }
971
1011
  declare class ElementsClient {
@@ -980,15 +1020,18 @@ declare class ElementsClient {
980
1020
  masterKeys?: MasterKeyResolver;
981
1021
  masterKey?: ElementsClientOptions['masterKey'];
982
1022
  applicationId?: string;
1023
+ organizationId?: string;
983
1024
  assetDecoder?: PlanAssetContainerDecoder;
984
1025
  });
985
1026
  private readonly api?;
986
1027
  private readonly reconstructor?;
987
1028
  private readonly masterKeys?;
988
1029
  private readonly applicationId?;
1030
+ private readonly organizationId?;
989
1031
  readonly assetDecoder?: PlanAssetContainerDecoder;
990
1032
  listPlans(input?: ListPlansInput): Promise<PlanPage>;
991
1033
  getPlan(planId: string): Promise<PlanDetail>;
1034
+ listPlanLogs(planId: string, input?: ListPlanLogsInput): Promise<PlanLogPage>;
992
1035
  startPlanCreation(input: StartPlanCreationInput): Promise<PlanCreationProgress>;
993
1036
  getPlanCreation(operationId: string): Promise<PlanCreationProgress>;
994
1037
  supplyPlanCreationMaterial(operationId: string, material: EncryptedPlanMaterial): Promise<PlanCreationProgress>;
@@ -1098,9 +1141,21 @@ declare class ElementsClient {
1098
1141
  collectGovernedPlanMaterial(session: GovernedRevealSession, stepUp?: StepUpReadContext): Promise<CollectedPlanMaterial>;
1099
1142
  reconstructGovernedPlanMaterial(session: GovernedRevealSession, material: CollectedPlanMaterial): Promise<Uint8Array>;
1100
1143
  private useCase;
1144
+ private requireApplication;
1101
1145
  }
1102
1146
  declare function createElementsClient(options: ElementsClientOptions): ElementsClient;
1103
1147
 
1148
+ interface BusinessOrganization {
1149
+ id: string;
1150
+ name: string;
1151
+ }
1152
+ declare class BusinessOrganizationSelectionError extends Error {
1153
+ readonly code: 'organization_required' | 'organization_selection_required' | 'organization_access_denied';
1154
+ constructor(code: 'organization_required' | 'organization_selection_required' | 'organization_access_denied');
1155
+ }
1156
+ /** A sole eligible organization can be selected automatically; several require a choice. */
1157
+ declare function selectBusinessOrganization(items: readonly BusinessOrganization[], selectedId?: string): string;
1158
+
1104
1159
  declare class ElementsApiRequestFailed extends Error {
1105
1160
  readonly status: number;
1106
1161
  readonly code?: string | undefined;
@@ -1113,9 +1168,14 @@ declare class HttpElementsApiPort implements ElementsApiPort {
1113
1168
  private readonly environment;
1114
1169
  private readonly getBearerToken;
1115
1170
  private readonly transport;
1116
- constructor(apiUrl: string, environment: 'TEST' | 'LIVE', getBearerToken: BearerTokenResolver, transport: HttpTransport);
1171
+ constructor(apiUrl: string, environment: 'TEST' | 'LIVE', getBearerToken: BearerTokenResolver, transport: HttpTransport, business?: {
1172
+ readonly organizationId?: string;
1173
+ });
1174
+ private readonly business?;
1175
+ listBusinessOrganizations(): Promise<BusinessOrganization[]>;
1117
1176
  listPlans(input?: ListPlansInput): Promise<PlanPage>;
1118
1177
  getPlan(planId: string): Promise<PlanDetail>;
1178
+ listPlanLogs(planId: string, input?: ListPlanLogsInput): Promise<PlanLogPage>;
1119
1179
  startPlanCreation(input: StartPlanCreationInput): Promise<PlanCreationProgress>;
1120
1180
  getPlanCreation(operationId: string): Promise<PlanCreationProgress>;
1121
1181
  supplyPlanCreationMaterial(operationId: string, material: EncryptedPlanMaterial): Promise<PlanCreationProgress>;
@@ -1130,7 +1190,7 @@ declare class HttpElementsApiPort implements ElementsApiPort {
1130
1190
  */
1131
1191
  masterKeyAcquisition(): Promise<MasterKeyAcquisition>;
1132
1192
  foreignMasterKeyAcquisition(system: string, contextId: string): Promise<MasterKeyAcquisition>;
1133
- startMasterKeyRelaySession(clientPublicKey: string): Promise<MasterKeyRelaySessionOpened>;
1193
+ startMasterKeyRelaySession(clientPublicKey: string, context?: MasterKeyRelayContext): Promise<MasterKeyRelaySessionOpened>;
1134
1194
  readMasterKeyRelaySession(sessionId: string): Promise<MasterKeyRelaySessionState>;
1135
1195
  planKeyReference(planId: string): Promise<PlanKeyReference>;
1136
1196
  collectPlanMaterial(planId: string, stepUp?: StepUpReadContext): Promise<CollectedPlanMaterial>;
@@ -1164,6 +1224,7 @@ declare class HttpElementsApiPort implements ElementsApiPort {
1164
1224
  }>;
1165
1225
  private request;
1166
1226
  private requestWithoutResult;
1227
+ private requireBusinessSelection;
1167
1228
  }
1168
1229
 
1169
1230
  /**
@@ -1449,5 +1510,5 @@ declare class OperatorSessionController {
1449
1510
  logout(): Promise<void>;
1450
1511
  }
1451
1512
 
1452
- export { 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, PlanMaterialReconstructorRequired, PollingSharedPlanEventListener, RelayMasterKeySource, RevealActionsNotOpen, RevealFieldAccessError, RevealHandleClosed, StaticMasterKeyResolver, SystemOAuthClock, WebOAuthCrypto, createElementsClient, createMasterKeyResolver, getAvailableEnvs, masterKeyRefFor, masterKeyRefKey, oauthErrorCode, parseAssetFieldSelector, revealPhaseOf, unwrapDekWithMasterKey, useClient, validatePlanCreationInput, validatePlanCreationMaterial };
1453
- export type { AssetFieldSelector, AuthorizationTransaction, AuthorizeRevealActionInput, 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, ListPlansInput, MasterKeyAcquisition, MasterKeyAcquisitionOptions, MasterKeyRef, 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, 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 };
1513
+ 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, PlanMaterialReconstructorRequired, PollingSharedPlanEventListener, RelayMasterKeySource, RevealActionsNotOpen, RevealFieldAccessError, RevealHandleClosed, StaticMasterKeyResolver, SystemOAuthClock, WebOAuthCrypto, createElementsClient, createMasterKeyResolver, getAvailableEnvs, masterKeyRefFor, masterKeyRefKey, oauthErrorCode, parseAssetFieldSelector, revealPhaseOf, selectBusinessOrganization, unwrapDekWithMasterKey, useClient, validatePlanCreationInput, validatePlanCreationMaterial };
1514
+ 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 };
@@ -0,0 +1,11 @@
1
+ export interface BusinessOrganization {
2
+ id: string;
3
+ name: string;
4
+ }
5
+ export declare class BusinessOrganizationSelectionError extends Error {
6
+ readonly code: 'organization_required' | 'organization_selection_required' | 'organization_access_denied';
7
+ constructor(code: 'organization_required' | 'organization_selection_required' | 'organization_access_denied');
8
+ }
9
+ export declare function decodeBusinessOrganizations(value: unknown): BusinessOrganization[];
10
+ /** A sole eligible organization can be selected automatically; several require a choice. */
11
+ export declare function selectBusinessOrganization(items: readonly BusinessOrganization[], selectedId?: string): string;
@@ -48,6 +48,10 @@ export interface MasterKeyRelaySessionOpened {
48
48
  sessionId: string;
49
49
  expiresAt: string | Date;
50
50
  }
51
+ export interface MasterKeyRelayContext {
52
+ system: string;
53
+ contextId: string;
54
+ }
51
55
  export interface MasterKeyRelaySessionState {
52
56
  status: 'PENDING' | 'DELIVERED' | 'EXPIRED';
53
57
  sealedMasterKey?: string;
@@ -61,10 +65,11 @@ export interface ElementsApiPort {
61
65
  * Asks the device holding the key to release it to this host. Creating the session *is* the
62
66
  * SafeKey request; there is no separate "notify" step.
63
67
  */
64
- startMasterKeyRelaySession(clientPublicKey: string): Promise<MasterKeyRelaySessionOpened>;
68
+ startMasterKeyRelaySession(clientPublicKey: string, context?: MasterKeyRelayContext): Promise<MasterKeyRelaySessionOpened>;
65
69
  readMasterKeyRelaySession(sessionId: string): Promise<MasterKeyRelaySessionState>;
66
70
  listPlans(input?: import('./plan-operations').ListPlansInput): Promise<import('./plan-operations').PlanPage>;
67
71
  getPlan(planId: string): Promise<import('./plan-operations').PlanDetail>;
72
+ listPlanLogs(planId: string, input?: import('./plan-operations').ListPlanLogsInput): Promise<import('./plan-operations').PlanLogPage>;
68
73
  startPlanCreation(input: import('./plan-operations').StartPlanCreationInput): Promise<import('./plan-operations').PlanCreationProgress>;
69
74
  getPlanCreation(operationId: string): Promise<import('./plan-operations').PlanCreationProgress>;
70
75
  supplyPlanCreationMaterial(operationId: string, material: import('./plan-operations').EncryptedPlanMaterial): Promise<import('./plan-operations').PlanCreationProgress>;
@@ -236,8 +241,8 @@ export type RevealMode = 'DIRECT' | 'GOVERNED';
236
241
  /** Reveal stages are additive. Hosts must treat unknown non-terminal values as waiting. */
237
242
  export type RevealStage = 'STARTING' | 'WAITING_FOR_DMS' | 'WAITING_FOR_PARTICIPANTS' | 'AUTHORIZED' | 'MATERIAL_AUTHORIZED' | 'MATERIAL_RELEASED' | 'RECONSTRUCTED' | 'ACTIONS_OPEN' | 'CLOSING' | 'CLOSED' | 'DENIED' | 'PARTICIPANT_REVOKED' | 'RECONCILIATION_REQUIRED' | 'EXPIRED' | 'CANCELED' | 'FAILED' | 'WAITING_FOR_CUSTODIAN_CLAIM' | 'WAITING_FOR_CUSTODIAN';
238
243
  export type RevealCloseReason = 'COMPLETED' | 'CANCELED' | 'DMS_RESET' | 'ERROR';
239
- export type RevealActionType = 'VIEW_FIELD' | 'COPY_FIELD' | 'USE_FIELD' | 'EXPORT_ASSET' | 'AUTOFILL_FIELD' | 'INSERT_FIELD';
240
- export type RevealActionDestination = 'STDIN' | 'ENVIRONMENT' | 'FILE_DESCRIPTOR' | 'LOCAL_SOCKET' | 'TEMPORARY_FILE';
244
+ export type RevealActionType = 'VIEW_FIELD' | 'COPY_FIELD' | 'USE_FIELD' | 'EXPORT_ASSET' | 'AUTOFILL_FIELD' | 'INSERT_FIELD' | 'DELIVER_FIELD';
245
+ export type RevealActionDestination = 'STDIN' | 'ENVIRONMENT' | 'FILE_DESCRIPTOR' | 'LOCAL_SOCKET' | 'TEMPORARY_FILE' | 'LOCAL_BROWSER';
241
246
  export type RevealActionOutcome = 'SUCCEEDED' | 'FAILED' | 'CANCELED';
242
247
  export interface StartRevealInput {
243
248
  mode: RevealMode;
@@ -250,6 +255,7 @@ export interface RevealReconstructionInput {
250
255
  export interface RevealSession {
251
256
  id: string;
252
257
  idempotencyKey: string;
258
+ /** Standalone Application ID; embedded Business currently fills this wire alias with the integration client ID. */
253
259
  applicationId: string;
254
260
  environment: 'TEST' | 'LIVE';
255
261
  planId: string;