@safetech/inheriti-client-sdk 1.17.6 → 1.17.8
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/README.md +17 -1
- package/dist/browser.d.ts +14 -6
- package/dist/browser.js +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/inheriti-client-sdk.umd.js +53 -75
- package/dist/node.d.ts +13 -5
- package/dist/node.js +1 -1
- package/dist/sdk-types.d.ts +87 -20
- package/dist/src/business/organizations.d.ts +11 -0
- package/dist/src/elements/core-plan-material-builder.d.ts +0 -3
- package/dist/src/elements/elements-api-port.d.ts +12 -4
- package/dist/src/elements/elements-client.d.ts +9 -2
- package/dist/src/elements/http-elements-api-port.d.ts +12 -4
- package/dist/src/elements/index.d.ts +2 -1
- package/dist/src/elements/master-key-acquisition.d.ts +8 -4
- package/dist/src/elements/node-plan-material-reconstructor.d.ts +1 -1
- package/dist/src/elements/plan-operation-codec.d.ts +2 -1
- package/dist/src/elements/plan-operations.d.ts +22 -3
- package/dist/src/elements/scoped-reveal.d.ts +8 -1
- package/dist/src/elements/ssdp-v2-plan-material-reconstructor.d.ts +7 -0
- package/dist/test.d.ts +184 -1
- package/package.json +3 -8
- package/docs/docs.json +0 -18331
- package/docs/elements-shared-mode.md +0 -28
- package/docs/operator-auth.md +0 -76
- package/docs/plan-operations.md +0 -41
- package/index.ts +0 -10
- package/node.ts +0 -74
package/README.md
CHANGED
|
@@ -20,7 +20,7 @@ This SDK abstracts and simplifies communication with the Inheriti® platform by
|
|
|
20
20
|
- ✅ Modular and composable architecture
|
|
21
21
|
- ✅ Compatible with browser and server environments
|
|
22
22
|
|
|
23
|
-
##
|
|
23
|
+
## Operator authentication
|
|
24
24
|
|
|
25
25
|
New integrations should use the host-neutral `OperatorAuthClient` for OIDC authorization code/PKCE or device
|
|
26
26
|
authorization. Hosts retain control of secure storage and platform UI; the SDK validates protocol state and
|
|
@@ -29,3 +29,19 @@ boundaries, and migration guidance for the existing `connect` API.
|
|
|
29
29
|
|
|
30
30
|
The typed list, detail, and resumable creation facade is documented in
|
|
31
31
|
[Application plan operations](docs/plan-operations.md).
|
|
32
|
+
|
|
33
|
+
## Embedded Business context
|
|
34
|
+
|
|
35
|
+
For a Business integration, create the Node or browser client with `business: true` and no
|
|
36
|
+
`applicationId`. Call `listBusinessOrganizations()` through its HTTP port, or use the private
|
|
37
|
+
`@safetech/inheriti-elements-core` facade's `listOrganizations()`. Select the only eligible
|
|
38
|
+
organization with `selectBusinessOrganization(items)`, or pass an explicit ID when several are
|
|
39
|
+
available. Create a new client with `organizationId` for plan and reveal calls; create another
|
|
40
|
+
client when the selected organization changes. The selected ID is sent as `x-organization-id` on
|
|
41
|
+
embedded requests, while discovery has no organization header. A client without a selection
|
|
42
|
+
rejects plan calls before sending them.
|
|
43
|
+
|
|
44
|
+
Business key acquisition uses the plan's `INHERITI_BUSINESS:<organizationId>` source reference.
|
|
45
|
+
The legacy `RevealSession.applicationId` response field currently contains the integration client
|
|
46
|
+
ID for Business; it is not the organization ID and should not be passed as an SDK `applicationId`.
|
|
47
|
+
Plan creation and `applicationMasterKey()` still require a real standalone Elements Application ID.
|
package/dist/browser.d.ts
CHANGED
|
@@ -24,12 +24,10 @@ import type { MasterKeyResolver } from './src/elements/master-key';
|
|
|
24
24
|
import type { ElementsClientOptions } from './src/elements/elements-client';
|
|
25
25
|
import type { PlanMaterialReconstructor } from './src/elements/plan-material-reconstructor';
|
|
26
26
|
import type { StatePort } from './src/elements/state-port';
|
|
27
|
-
export
|
|
27
|
+
export type BrowserElementsClientOptions = {
|
|
28
28
|
apiUrl: string;
|
|
29
29
|
environment: 'TEST' | 'LIVE';
|
|
30
30
|
getBearerToken: () => Promise<string | null>;
|
|
31
|
-
/** The Application this client acts for; the reveal path resolves its key under this id. */
|
|
32
|
-
applicationId: string;
|
|
33
31
|
/**
|
|
34
32
|
* Resolves master keys per plan reference. A host that composes its own custody passes this;
|
|
35
33
|
* one that only declares what it holds passes `masterKey` instead and lets the client compose
|
|
@@ -44,7 +42,15 @@ export interface BrowserElementsClientOptions {
|
|
|
44
42
|
/** Overrides reconstruction wholesale; otherwise a `BrowserPlanMaterialReconstructor` is built. */
|
|
45
43
|
reconstructor?: PlanMaterialReconstructor;
|
|
46
44
|
reconstruction?: BrowserPlanMaterialReconstructorOptions;
|
|
47
|
-
}
|
|
45
|
+
} & ({
|
|
46
|
+
applicationId: string;
|
|
47
|
+
business?: never;
|
|
48
|
+
organizationId?: never;
|
|
49
|
+
} | {
|
|
50
|
+
business: true;
|
|
51
|
+
organizationId?: string;
|
|
52
|
+
applicationId?: never;
|
|
53
|
+
});
|
|
48
54
|
/**
|
|
49
55
|
* A reveal-capable Elements client for a bundled browser host.
|
|
50
56
|
*
|
|
@@ -67,7 +73,7 @@ export { RelayMasterKeySource, MasterKeyRelayExpired, MasterKeyRelayTimedOut } f
|
|
|
67
73
|
export { createMasterKeyResolver } from './src/elements/master-key-acquisition';
|
|
68
74
|
export type { MasterKeySource } from '@safetech/inheriti-core-sdk';
|
|
69
75
|
export type { DeclaredMasterKeySource, MasterKeyAcquisitionOptions } from './src/elements/master-key-acquisition';
|
|
70
|
-
export type { MasterKeyAcquisition, MasterKeyRelaySessionOpened, MasterKeyRelaySessionState } from './src/elements/elements-api-port';
|
|
76
|
+
export type { MasterKeyAcquisition, MasterKeyRelayContext, MasterKeyRelaySessionOpened, MasterKeyRelaySessionState } from './src/elements/elements-api-port';
|
|
71
77
|
export type { MasterKeyRelayPort } from './src/elements/relay-master-key-source';
|
|
72
78
|
export { PassphraseMasterKeySource, RawMasterKeySource, computePassphraseVerifier, deriveMasterKey, generateHexSeed } from '@safetech/inheriti-core-sdk/crypto';
|
|
73
79
|
export type { MasterKeySource } from '@safetech/inheriti-core-sdk/crypto';
|
|
@@ -79,6 +85,8 @@ export { openScopedReveal, revealPhaseOf, RevealAuthorizationEnded, RevealFieldA
|
|
|
79
85
|
export type { AssetFieldSelector, OpenRevealOptions, RevealFieldOptions, RevealHandle, RevealPhase, RevealProgress } from './src/elements/scoped-reveal';
|
|
80
86
|
export type { CollectedPlanMaterial, GovernedRevealSession, GovernedRevealState, PlanKeyReference } from './src/elements/elements-api-port';
|
|
81
87
|
export { default as HttpElementsApiPort, ElementsApiRequestFailed } from './src/elements/http-elements-api-port';
|
|
88
|
+
export { selectBusinessOrganization, BusinessOrganizationSelectionError } from './src/business/organizations';
|
|
89
|
+
export type { BusinessOrganization } from './src/business/organizations';
|
|
82
90
|
export { SystemOAuthClock, WebOAuthCrypto } from './src/operator-auth/defaults';
|
|
83
91
|
export { HttpOperatorAuthTransport } from './src/operator-auth/http-operator-auth-transport';
|
|
84
92
|
export { OperatorAuthClient } from './src/operator-auth/operator-auth-client';
|
|
@@ -88,4 +96,4 @@ export type * from './src/operator-auth/ports';
|
|
|
88
96
|
export type * from './src/operator-auth/types';
|
|
89
97
|
export type { ElementsApiPort, StepUpReadContext } from './src/elements/elements-api-port';
|
|
90
98
|
export type { RevealAction, RevealActionDestination, RevealActionOutcome, RevealActionType, RevealCloseReason, RevealMode, RevealSession, RevealStage, } from './src/elements/elements-api-port';
|
|
91
|
-
export type { ListPlansInput, PlanDetail, PlanPage, PlanSummary } from './src/elements/plan-operations';
|
|
99
|
+
export type { ListPlanLogsInput, ListPlansInput, PlanDetail, PlanLog, PlanLogPage, PlanPage, PlanSummary } from './src/elements/plan-operations';
|
package/dist/browser.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decodeAssetContainer as Tt}from"@safetech/inheriti-core-sdk/core/protocols/ssdp+";import{decryptRSAOAEP as ze,generateRSAOAEPKeyPair as He}from"@safetech/inheriti-core-sdk/crypto";var H=class extends Error{constructor(t){super("master_key_relay_timed_out");this.sessionId=t;this.name="MasterKeyRelayTimedOut"}},W=class extends Error{constructor(t){super("master_key_relay_expired");this.sessionId=t;this.name="MasterKeyRelayExpired"}},x=class{constructor(e){this.options=e}async resolve(){let{publicKeyBase64:e,privateKey:t}=await He(),n=await this.options.api.startRelaySession(e),a=this.options.pollIntervalMs??2e3,s=Date.now()+(this.options.timeoutMs??600*1e3),i=this.options.sleep??(o=>new Promise(l=>setTimeout(l,o)));for(;Date.now()<s;){let o=await this.options.api.readRelaySession(n.sessionId);if(o.status==="DELIVERED"&&o.sealedMasterKey){let l=(await ze(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 W(n.sessionId);await i(a)}throw new H(n.sessionId)}};function se(r){return{resolve:async e=>{if(We(e,r.applicationId)){let t=await r.source?.resolve();return t||Ie(r,()=>r.api.masterKeyAcquisition())}return Ie(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId))}}}function We(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function Ie(r,e){if((await e()).relayAvailable)return new x({...r.relay,api:$e(r.api)}).resolve()}function $e(r){return{startRelaySession:e=>r.startMasterKeyRelaySession(e),readRelaySession:e=>r.readMasterKeyRelaySession(e)}}function I(r){return`${r.system}:${r.contextId}`}function oe(r){return r.sourceReference?{system:r.sourceReference.system,contextId:r.sourceReference.contextId}:r.tenantId?{system:"INHERITI_ELEMENTS",contextId:r.tenantId}:void 0}var A=class extends Error{constructor(t){super(`master_key_required:${I(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(I(e),t),this}async resolve(e){return this.sources.get(I(e))?.resolve()}};var b=class{keys=new Map;async store(e,t){this.keys.set(I(e),t.slice())}async load(e){return this.keys.get(I(e))?.slice()}async remove(e){this.keys.delete(I(e))}};var K=class{values=new Map;async set(e,t){this.values.set(e,t)}async get(e){return this.values.get(e)}async remove(e){this.values.delete(e)}};var $=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 U=class extends Error{constructor(){super("plan_material_reconstructor_required"),this.name="PlanMaterialReconstructorRequired"}};var j=["PLAIN-TEXT","USER-PSWD","RECOVERY-CODE","PIN-CODE","API-KEY","PRIVATE-KEY","SEED-PHRASE","PAYMENT-DEBIT-CARD","PAYMENT-CREDIT-CARD","DOCUMENT","IMAGE","VIDEO"],je={"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"]},we=["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"}},P=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function O(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new P("plan_material_field_unknown");if(le(r.dataShards,"data_shards_invalid"),le(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&le(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new P("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new P("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new P("material_operation_invalid")}function le(r,e){if(!Array.isArray(r))throw new P(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new P(e);if(t.data!==void 0&&typeof t.data!="string")throw new P(e)}}function C(r){if(S(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Xe(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(S(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),!j.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(s=>!s.trim()))throw new m("asset_field_names_invalid");if(Ye(t.matchOrigins),!t.isBinary){let s=je[t.type];if(!s||a.some(i=>!s.includes(i)))throw new m("asset_field_name_not_canonical")}}if(!r.participants.length)throw new m("participants_required");for(let t of r.participants){if(S(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Se(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")}Qe(r)}function Ye(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 Qe(r){let e=r.policy;if(e&&S(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"){S(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new m("authentication_mode_invalid")}if(e.moderation){S(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=r.participants.filter(l=>l.relationships.includes("MODERATOR"));if(s.length===0)throw new m("moderation_requires_moderators");let i=e.moderation.minimumApprovals;if(i!==void 0&&(!Number.isInteger(i)||i<1||i>s.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;S(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,a=t.countdownMinutes??0;if(!Se(t.subjectEmail))throw new m("dms_subject_invalid");if(!r.participants.some(s=>Ae(s.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 Xe(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 Se(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function Ae(r){return r.normalize("NFC").trim().toLowerCase()}function S(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new m(t)}var Q=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)}},X=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),C(e),Y(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,s={}){C(t);let i=await this.checkpoints.load(e);if(!i)throw new Z("creation_checkpoint_missing");if(i.idempotencyKey!==t.idempotencyKey||i.declarationHash!==await Ce(t))throw new Z("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(s.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;Y(s.signal),s.onProgress?.("ENCRYPTING");let l=await a.encrypt({planId:o.planId,declaration:t,secrets:n,signal:s.signal});Y(s.signal),s.onProgress?.("GENERATING_SHARES");let u=await a.generateShares({planId:o.planId,declaration:t,encrypted:l,signal:s.signal});Y(s.signal),O(u);let h=await this.api.supplyPlanCreationMaterial(e,u);return s.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 Ce(e),serverStage:t.stage})}},Z=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Ce(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 Y(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 $(n.stage);return r.authorizeRevealAction(e,t)}function Ze(r){let e=r?.status;return e===400||e===401||e===403}async function _e(r,e,t,n){let a=await r.getReveal(e);try{await n(a.planId)}catch(s){if(!Ze(s))throw s}return r.releaseRevealMaterial(e,t)}function Oe(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"?et(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":Je.has(r.stage)?"ENDED":"CONTINUING"}var Je=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function et(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 J=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 ue(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(),s=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:a}),i;try{let o=await rt(r,s,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 u=await st(r,o,n,ot(l),t);L(t,"RECONSTRUCTING",o),i=await r.reconstructPlanMaterial(u);let h=await r.reportRevealReconstruction(o.id,{status:"SUCCEEDED"});return L(t,"OPEN",h),new ce(r,h,n,i,t.signal)}catch(o){throw i?.fill(0),await lt(r,s.id,t.signal?.aborted?"CANCELED":"ERROR"),o}}var tt=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function rt(r,e,t){let n=await r.getReveal(e.id);for(;;){if(t.onSession?.(n),t.onProgress?.({phase:Oe(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(tt.has(n.stage))throw new ee(n.stage);await me(t.pollIntervalMs??1500,t.signal),n=await r.getReveal(e.id)}}var ee=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 me(r,e){return e?.aborted?Promise.reject(pe()):new Promise((t,n)=>{let a=setTimeout(i,Math.max(0,r)),s=()=>{clearTimeout(a),n(pe())};function i(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}var ce=class{constructor(e,t,n,a,s){this.client=e;this.session=t;this.plan=n;this.plaintext=a;let i=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(i,2147483647)),this.abortListener=s?()=>{this.close("CANCELED")}:void 0,s&&this.abortListener&&s.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new J;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:s,options:i={}})=>{let o=De(s),l=this.plan.assets.find(u=>(u.code??u.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:i}}),a=[];try{for(let i of n)a.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:i.options.idempotencyKey??crypto.randomUUID(),assetId:i.asset.id,fieldName:i.field,action:i.options.action??"VIEW_FIELD",...i.options.destination===void 0?{}:{destination:i.options.destination},...i.options.origin===void 0?{}:{origin:i.options.origin}}));let s=n.map(i=>{let o=this.client.assetDecoder(this.material).find(l=>l.id===i.asset.id||l.id===i.assetCode);if(!o)throw new y("asset_value_invalid");return{selector:i.selector,value:nt(o.data,i.field)}});await t(s)}catch(s){throw await Promise.all(a.map(i=>this.reportAction(i.id,"FAILED",at(s)))),s}await Promise.all(a.map(s=>this.reportAction(s.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(!ke(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 De(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 nt(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 at(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 st(r,e,t,n,a){if(t.revealPolicy?.custodian!=="FORCE"||n.shares.some(l=>l.shareType==="CUSTODIAN_KEY_SHARD"))return n;let s=await r.getRevealCustodianAccess(e.id);for(;s.status==="PENDING"||s.status==="DISTRIBUTED";){let l={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};a.onSession?.(l),L(a,"WAITING_FOR_CUSTODIAN_CLAIM",l),await me(a.pollIntervalMs??1500,a.signal),s=await r.getRevealCustodianAccess(e.id)}if(s.status!=="CLAIMED"||s.deviceType!=="SK_MOBILE")throw new te;let i={...e,stage:"WAITING_FOR_CUSTODIAN"};a.onSession?.(i),L(a,"WAITING_FOR_CUSTODIAN",i),await r.requestRevealCustodianRelease(e.id);let o=await it(r,e.id,a);return Object.assign({},n,{shares:n.shares.concat(o.shares.map((l,u)=>({id:`${o.id}:${u}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:l})))})}async function it(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let a=await r.getRevealCustodianShare(e);if(a&&a.status!=="PENDING"){let s=a;if(s.shares?.length)return s;throw new te}if(Date.now()>=n)throw new de;await me(t.pollIntervalMs??1500,t.signal)}}var te=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 ot(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function lt(r,e,t){try{await r.closeReveal(e,t)}catch(n){if(!ke(n))throw n}}function ke(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 b,this.state=t.state??new K,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??ct(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 C(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 O(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(!this.api)throw new d;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new Q){if(!this.api)throw new d;return new X(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 A({system:"INHERITI_ELEMENTS",contextId:"application"});let e={system:"INHERITI_ELEMENTS",contextId:this.applicationId},t=await this.keyVault.load(e);if(t)return Ne(t);let n=await this.masterKeys?.resolve(e);if(!n)throw new A(e);return await this.keyVault.store(e,Me(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 U;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=oe(e);if(!t)throw new A({system:"INHERITI_ELEMENTS",contextId:e.planId});let n=await this.keyVault.load(t);if(n)return Ne(n);let a=await this.masterKeys?.resolve(t);if(!a)throw new A(t);return await this.keyVault.store(t,Me(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 ue(this,e,t)}async withReveal(e,t,n){let a=await this.openReveal(e,t);try{let s=await n(a);return await a.close("COMPLETED"),s}catch(s){throw await a.close(t.signal?.aborted?"CANCELED":"ERROR"),s}}async releaseRevealMaterial(e,t){if(!this.api)throw new d;return _e(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 s=n.validatorShares.map(u=>Object.assign({},u,{shareType:"VALIDATOR_SHARD"})),i=a.dataShards.map(u=>Object.assign({},u,{shareType:"DATA_SHARD"})),o=a.backupShards.map(u=>Object.assign({},u,{shareType:"BACKUP_SHARD"})),l=a.keyShards.map(u=>Object.assign({},u,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:a.dek||n.dek,shares:s.concat(i,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 re;return this.coreSdk.getService(e).execute(t)}},re=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Me(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 Ne(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function ct(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 se(e)}import{createBrowserSsdpV2WorkerFactory as yt,createSsdpV2Processor as ft}from"@safetech/inheriti-core-sdk/workers/ssdp-v2";async function he(r,e){if(!e)throw new Error("master_key_required");let t=dt(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),a=pt(r),s=a.slice(0,12),i=a.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,i);return ut(new Uint8Array(o))}function dt(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function pt(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 ut(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var V=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await he(e.planKey,t),a=await crypto.subtle.importKey("raw",ye(n),{name:"AES-GCM"},!1,["decrypt"]),s=[],i=[];for(let o of e.shares){let l=await ht(o.data,a);mt(o.shareType)?i.push(l):s.push(l)}return this.processor().reconstruct(s,{planId:e.planId,threshold:e.mergeThreshold,keyShares:i}).result}};function mt(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function ht(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=ye(r.slice(0,t)),a=ye(r.slice(t+1)),s=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,a);return new TextDecoder().decode(s)}function ye(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 V{constructor(e={}){let t=e.processor??ft(e.workerUrl!==void 0&&typeof Worker<"u"?{workerFactory:yt(e.workerUrl),allowMainThreadFallback:!0}:{allowMainThreadFallback:!0});super(()=>t)}};var Rt=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],gt=["DIRECT","GOVERNED"],be=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],vt=["ACTIVE","REVOKED"],Pt=["SK_MOBILE"],Et=["ACTIVE","INACTIVE"],It=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Ke(r){let e=R(r);return{items:g(e.items).map(Le),nextCursor:e.nextCursor===null?null:p(e.nextCursor,"nextCursor")}}function Ue(r){let e=R(r),t=Le(e),n=R(e.source),a=p(n.kind,"source.kind");return{...t,assets:g(e.assets).map(s=>{let i=R(s);return{id:p(i.id,"asset.id"),code:T(i.code),type:f(p(i.type,"asset.type"),j),name:p(i.name,"asset.name"),isBinary:wt(i.isBinary,"asset.isBinary"),fieldNames:g(i.fieldNames).map(o=>p(o,"asset.fieldNames")),fileName:T(i.fileName),mimeType:T(i.mimeType),size:i.size===void 0||i.size===null?void 0:E(i.size,"asset.size"),matchOrigins:i.matchOrigins===void 0?void 0:g(i.matchOrigins).map(o=>p(o,"asset.matchOrigins"))}}),participants:g(e.participants).map(s=>{let i=R(s);return{id:p(i.id,"participant.id"),displayName:p(i.displayName,"participant.displayName"),relationships:g(i.relationships).map(o=>f(p(o,"relationship"),be)),lifecycle:f(p(i.lifecycle,"participant.lifecycle"),vt)}}),revealPolicy:(()=>{let s=R(e.revealPolicy);return{masterKeyRelease:f(p(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:f(p(s.custodian,"custodian"),["FORCE","BYPASS"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=R(e.dms);return{subjectEmail:p(s.subjectEmail,"dms.subjectEmail"),countdownDays:E(s.countdownDays,"dms.countdownDays"),countdownHours:E(s.countdownHours,"dms.countdownHours"),countdownMinutes:E(s.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 q(r){let e=R(r);return{operationId:p(e.operationId,"operationId"),stage:f(p(e.stage,"stage"),we),outcome:f(p(e.outcome,"outcome"),It),planId:T(e.planId),lastErrorCode:T(e.lastErrorCode),participants:e.participants===void 0?void 0:g(e.participants).map(t=>{let n=R(t);return{clientParticipantRef:p(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:p(n.planParticipantId,"planParticipantId"),relationships:g(n.relationships).map(a=>At(p(a,"relationship"),be))}})}}function Le(r){let e=R(r),t=R(e.assetSummary),n=R(e.governance),a=R(e.participantSummary);return{id:p(e.id,"id"),name:p(e.name,"name"),description:T(e.description),status:f(p(e.status,"status"),Rt),createdAt:p(e.createdAt,"createdAt"),configuredAt:T(e.configuredAt),assetSummary:{count:E(t.count,"assetSummary.count"),types:g(t.types).map(s=>f(p(s,"assetType"),j)),names:xe(t.names).map(s=>p(s,"assetSummary.names"))},governance:{mode:f(p(n.mode,"governance.mode"),gt),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(s=>{let i=R(s);return{id:f(p(i.id,"authentication.id"),Pt),status:f(p(i.status,"authentication.status"),Et)}})}}function f(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function At(r,e){if(!e.includes(r))throw new Error("invalid_elements_response");return r}function R(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("invalid_elements_response");return r}function xe(r){return r==null?[]:g(r)}function g(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 wt(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}function fe(r){return typeof r.error=="string"?r.error||void 0:r.error?.code??r.name??r.message}function Re(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}},k=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){C(e);let{idempotencyKey:t,...n}=e;return q(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return q(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return O(t),q(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return q(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,...s}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",s,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,s){let i=await this.getBearerToken(),o=new Headers({"x-elements-environment":this.environment});i&&o.set("authorization",`Bearer ${i}`),a?.requestId&&o.set("x-elements-step-up-request",a.requestId);for(let[qe,Be]of Object.entries(s??{}))o.set(qe,Be);n&&o.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,u=await this.transport(new URL(e,l),{method:t,headers:o,body:n?JSON.stringify(n):void 0}),h=await Ge(u);if(!u.ok)throw new D(u.status,fe(h),Re(h));if(!h.ok||h.result===void 0)throw new D(u.status,fe(h),Re(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}/`,s=await this.transport(new URL(e,a),{method:"POST",headers:n}),i=await Ge(s);if(!s.ok||!i.ok)throw new D(s.status,fe(i),Re(i))}};async function Ge(r){try{return await r.json()}catch{return{ok:!1}}}import{PassphraseMasterKeySource as Nr,RawMasterKeySource as xr,computePassphraseVerifier as br,deriveMasterKey as Kr,generateHexSeed as Ur}from"@safetech/inheriti-core-sdk/crypto";function Ve(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var B=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))}},z=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 s=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(s),a(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var M=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},N=class extends M{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},c=class extends M{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function ne(r){if(r instanceof M)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var ge=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:w(n,"issuer"),authorizationEndpoint:w(n,"authorization_endpoint"),tokenEndpoint:w(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:w(t,"device_code"),userCode:w(t,"user_code"),verificationUri:w(t,"verification_uri"),verificationUriComplete:v(t,"verification_uri_complete"),expiresInSeconds:Fe(t,"expires_in"),intervalSeconds:ve(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:w(n,"access_token"),refreshToken:v(n,"refresh_token"),idToken:v(n,"id_token"),tokenType:w(n,"token_type"),expiresInSeconds:Fe(n,"expires_in"),refreshExpiresInSeconds:ve(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 s=v(a,"error")??`oauth_http_${n.status}`;throw new c(s,v(a,"error_description")??s)}return a}};function w(r,e){let t=v(r,e);if(!t)throw new c("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=ve(r,e);if(t===void 0)throw new c("invalid_oauth_response",`Missing ${e}`);return t}function ve(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var St=600*1e3,ae=5,Ct=5,Pe=class{constructor(e){this.options=e;this.crypto=e.crypto??new B,this.clock=e.clock??new z}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),s=await this.crypto.sha256UrlSafe(a),i=this.clock.now()+St;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:a,redirectUri:this.options.configuration.redirectUri,expiresAt:i});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",n),o.searchParams.set("code_challenge",s),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:i}}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 c("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new c("authorization_transaction_expired");let a=new URL(e),s=new URL(n.redirectUri);if(a.origin!==s.origin||a.pathname!==s.pathname)throw new c("redirect_uri_mismatch");let i=a.searchParams.get("error");if(i)throw new c(i,a.searchParams.get("error_description")??i);if(a.searchParams.get("state")!==n.state)throw new c("state_mismatch");let o=a.searchParams.get("code");if(!o)throw new c("authorization_code_missing");let l=await this.getDiscovery(),u=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(u,n.nonce);return await this.options.sessions.save(h),h}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new c("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(ae,t.intervalSeconds??ae),a=this.clock.now(),s={...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"),s),s}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new c("device_transaction_missing");let a=n,s=await this.getDiscovery(),i=Math.max(ae,a.intervalSeconds??ae),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:s.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:a.deviceCode});a.consumed=!0,await this.options.transactions.save(t,a);let u=await this.acceptTokens(l);return await this.options.sessions.save(u),await this.options.transactions.remove(t),u}catch(l){let u=ne(l);if(u==="authorization_pending"){o=this.clock.now()+i*1e3;continue}if(u==="slow_down"){i+=Ct,o=this.clock.now()+i*1e3;continue}throw await this.options.transactions.remove(t),l}}throw await this.options.transactions.remove(t),new c("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 N;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 c("refresh_token_rotation_missing");let a=await this.acceptTokens(n);return await this.options.sessions.save(a),a}catch(t){await this.options.sessions.clear();let n=ne(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new N:t}}async getDiscovery(){this.discovery??=this.options.transport.discover(this.options.configuration.issuer);try{let e=await this.discovery;if(_(e.issuer)!==_(this.options.configuration.issuer))throw new c("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}|${_(t)}|${n}|${a}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new c("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 c("id_token_validation_required");let s=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(s,t),s.subject!==n.subject||s.sessionId!==n.sessionId)throw new c("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,s=typeof e.audience=="string"?[e.audience]:e.audience;if(_(e.issuer)!==_(a.issuer))throw new c("issuer_mismatch");if(!s.includes(a.audience))throw new c("audience_mismatch");if(e.authorizedParty!==a.clientId)throw new c("client_mismatch");if(e.environment!==a.environment)throw new c("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new c("required_claim_missing");if(n&&e.nonce!==t)throw new c("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(_(e.issuer)!==_(n.issuer))throw new c("issuer_mismatch");if(!a.includes(n.clientId))throw new c("client_mismatch");if(e.authorizedParty!==n.clientId)throw new c("client_mismatch");if(!e.subject||!e.sessionId)throw new c("required_claim_missing");if(e.nonce!==t)throw new c("nonce_mismatch")}};function _(r){return r.replace(/\/+$/u,"")}var Ee=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 wr(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=new k(r.apiUrl,r.environment,r.getBearerToken,e);return new G(void 0,{api:t,applicationId:r.applicationId,masterKeys:r.masterKeys,masterKey:r.masterKey,assetDecoder:Tt,reconstructor:r.reconstructor??new F(r.reconstruction??{}),...r.keyVault===void 0?{}:{keyVault:r.keyVault},...r.state===void 0?{}:{state:r.state}})}export{F as BrowserPlanMaterialReconstructor,re as CoreSdkContainerRequired,D as ElementsApiRequestFailed,G as ElementsClient,k as HttpElementsApiPort,ge as HttpOperatorAuthTransport,W as MasterKeyRelayExpired,H as MasterKeyRelayTimedOut,A as MasterKeyRequired,b as MemoryKeyVault,K as MemoryStatePort,c as OAuthProtocolError,Pe as OperatorAuthClient,M as OperatorAuthError,N as OperatorReauthenticationRequired,Ee as OperatorSessionController,Nr as PassphraseMasterKeySource,U as PlanMaterialReconstructorRequired,xr as RawMasterKeySource,x as RelayMasterKeySource,ee as RevealAuthorizationEnded,y as RevealFieldAccessError,J as RevealHandleClosed,ie as StaticMasterKeyResolver,z as SystemOAuthClock,B as WebOAuthCrypto,br as computePassphraseVerifier,wr as createBrowserElementsClient,se as createMasterKeyResolver,Tt as decodeAssetContainer,Kr as deriveMasterKey,Ur as generateHexSeed,oe as masterKeyRefFor,I as masterKeyRefKey,ne as oauthErrorCode,ue as openScopedReveal,De as parseAssetFieldSelector,Oe as revealPhaseOf,he as unwrapDekWithMasterKey};
|
|
1
|
+
import{decodeAssetContainer as Kt}from"@safetech/inheriti-core-sdk/core/protocols/ssdp+";import{decryptRSAOAEP as Xe,generateRSAOAEPKeyPair as Qe}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"}},K=class{constructor(e){this.options=e}async resolve(){let{publicKeyBase64:e,privateKey:t}=await Qe(),n=await this.options.api.startRelaySession(e),i=this.options.pollIntervalMs??2e3,a=Date.now()+(this.options.timeoutMs??600*1e3),s=this.options.sleep??(o=>new Promise(c=>setTimeout(c,o)));for(;Date.now()<a;){let o=await this.options.api.readRelaySession(n.sessionId);if(o.status==="DELIVERED"&&o.sealedMasterKey){let c=(await Xe(o.sealedMasterKey,t)).trim().toLowerCase();if(!/^[0-9a-f]{64}$/.test(c))throw new Error("invalid_master_key_material");return c}if(o.status==="EXPIRED")throw new j(n.sessionId);await s(i)}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||ce(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId})}if(Ze(e,r.applicationId)){let t=await r.source?.resolve();return t||ce(r,()=>r.api.masterKeyAcquisition())}return ce(r,()=>r.api.foreignMasterKeyAcquisition(e.system,e.contextId),{system:e.system,contextId:e.contextId})}}}function Ze(r,e){return r.system==="INHERITI_ELEMENTS"&&r.contextId===e}async function ce(r,e,t){if((await e()).relayAvailable)return new K({...r.relay,api:Je(r.api,t)}).resolve()}function Je(r,e){return{startRelaySession:t=>e?r.startMasterKeyRelaySession(t,e):r.startMasterKeyRelaySession(t),readRelaySession:t=>r.readMasterKeyRelaySession(t)}}function w(r){return`${r.system}:${r.contextId}`}function pe(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:${w(t)}`);this.ref=t;this.name="MasterKeyRequired"}},de=class{sources=new Map;constructor(e=[]){for(let t of e)this.register(t.ref,t.source)}register(e,t){return this.sources.set(w(e),t),this}async resolve(e){return this.sources.get(w(e))?.resolve()}};var U=class{keys=new Map;async store(e,t){this.keys.set(w(e),t.slice())}async load(e){return this.keys.get(w(e))?.slice()}async remove(e){this.keys.delete(w(e))}};var L=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 G=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"],et={"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"]},Ce=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],u=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanDeclaration"}},E=class extends Error{constructor(t){super(t);this.code=t;this.name="InvalidPlanMaterial"}};function D(r){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(r).some(t=>!e.includes(t)))throw new E("plan_material_field_unknown");if(ue(r.dataShards,"data_shards_invalid"),ue(r.backupShards,"backup_shards_invalid"),r.validatorShares!==void 0&&ue(r.validatorShares,"validator_shares_invalid"),r.validatorShares?.length&&!r.encryptedKey)throw new E("validator_shares_require_encrypted_key");if(r.protectionProtocol!==void 0&&r.protectionProtocol!=="SSDP_PLUS_V1"&&r.protectionProtocol!=="SSDP_PLUS_V2")throw new E("protection_protocol_invalid");if(r.operation!==void 0&&r.operation!=="DRAFT"&&r.operation!=="FINALIZE")throw new E("material_operation_invalid")}function ue(r,e){if(!Array.isArray(r))throw new E(e);for(let t of r){if(typeof t!="object"||t===null||typeof t.id!="string"||!t.id)throw new E(e);if(t.data!==void 0&&typeof t.data!="string")throw new E(e)}}function C(r){if(_(r,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!nt(r.idempotencyKey))throw new u("idempotency_key_invalid");if(!r.name?.trim())throw new u("plan_name_required");if(!r.assets.length)throw new u("assets_required");let e=new Set;for(let t of r.assets){if(_(t,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!t.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(t.clientAssetRef)||e.has(t.clientAssetRef))throw new u("client_asset_ref_invalid");if(e.add(t.clientAssetRef),!Q.includes(t.type))throw new u("asset_type_invalid");let n=t.type==="DOCUMENT"||t.type==="IMAGE"||t.type==="VIDEO";if(t.isBinary!==n)throw new u("asset_binary_representation_invalid");let i=t.fieldNames??[];if(t.isBinary&&(i.length||!t.fileName||!t.mimeType||!Number.isSafeInteger(t.size)||t.size<0))throw new u("binary_asset_metadata_invalid");if(!t.isBinary&&(!i.length||t.fileName!==void 0||t.mimeType!==void 0||t.size!==void 0))throw new u("structured_asset_metadata_invalid");if(new Set(i).size!==i.length||i.some(a=>!a.trim()))throw new u("asset_field_names_invalid");if(tt(t.matchOrigins),!t.isBinary){let a=et[t.type];if(!a||i.some(s=>!a.includes(s)))throw new u("asset_field_name_not_canonical")}}if(!r.participants.length)throw new u("participants_required");for(let t of r.participants){if(_(t,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!t.clientParticipantRef?.trim()||!t.displayName?.trim()||!Te(t.routingEmail))throw new u("participant_invalid");if(!t.relationships.length||t.relationships.includes("ALLOW")&&t.relationships.includes("DENY"))throw new u("participant_relationships_invalid")}rt(r)}function tt(r){if(r===void 0)return;if(!r.length)throw new u("asset_match_origins_invalid");let e=r.map(t=>{if(typeof t!="string"||!t.trim())throw new u("asset_match_origin_invalid");try{let n=new URL(t);if(!["http:","https:"].includes(n.protocol)||n.origin!==t.trim())throw new u("asset_match_origin_invalid");return n.origin}catch(n){throw n instanceof u?n:new u("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new u("asset_match_origins_duplicated")}function rt(r){let e=r.policy;if(e&&_(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new u("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){_(e.authentication,["mode"],"plan_authentication_field_unknown");let a=e.authentication.mode;if(a!==void 0&&a!=="EXCLUSIVE"&&a!=="ALL_REQUIRED")throw new u("authentication_mode_invalid")}if(e.moderation){_(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let a=r.participants.filter(c=>c.relationships.includes("MODERATOR"));if(a.length===0)throw new u("moderation_requires_moderators");let s=e.moderation.minimumApprovals;if(s!==void 0&&(!Number.isInteger(s)||s<1||s>a.length))throw new u("minimum_approvals_invalid");let o=e.moderation.approvalMode;if(o!==void 0&&o!=="THRESHOLD"&&o!=="UNANIMOUS")throw new u("approval_mode_invalid")}let t=e.dms;if(!t)return;_(t,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let n=t.countdownHours??0,i=t.countdownMinutes??0;if(!Te(t.subjectEmail))throw new u("dms_subject_invalid");if(!r.participants.some(a=>_e(a.routingEmail)===_e(t.subjectEmail)))throw new u("dms_subject_not_participant");if(!Number.isInteger(t.countdownDays)||!Number.isInteger(n)||!Number.isInteger(i)||t.countdownDays<0||n<0||n>23||i<0||i>59||t.countdownDays+n+i===0)throw new u("dms_countdown_invalid")}function nt(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 Te(r){return typeof r=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(r.normalize("NFC").trim())}function _e(r){return r.normalize("NFC").trim().toLowerCase()}function _(r,e,t){if(Object.keys(r).some(n=>!e.includes(n)))throw new u(t)}var J=class{checkpoints=new Map;async load(e){return this.checkpoints.get(e)}async save(e){this.checkpoints.set(e.operationId,e)}async remove(e){this.checkpoints.delete(e)}},ee=class{constructor(e,t){this.api=e;this.checkpoints=t}async start(e,t={}){t.onProgress?.("VALIDATING_ASSETS"),C(e),Z(t.signal);let n=await this.api.startPlanCreation(e);return n.outcome==="COMPLETED"||n.outcome==="CANCELED"?await this.checkpoints.remove(n.operationId):await this.saveCheckpoint(e,n),t.onProgress?.(n.stage),n}async status(e){return this.api.getPlanCreation(e)}async resume(e,t,n,i,a={}){C(t);let s=await this.checkpoints.load(e);if(!s)throw new te("creation_checkpoint_missing");if(s.idempotencyKey!==t.idempotencyKey||s.declarationHash!==await Oe(t))throw new te("creation_declaration_mismatch");let o=await this.api.getPlanCreation(e);if(a.onProgress?.(o.stage),o.outcome==="COMPLETED"||o.outcome==="CANCELED")return await this.checkpoints.remove(e),o;if(o.stage!=="AWAITING_ENCRYPTED_MATERIAL"||!o.planId)return o;Z(a.signal),a.onProgress?.("ENCRYPTING");let c=await i.encrypt({planId:o.planId,declaration:t,secrets:n,signal:a.signal});Z(a.signal),a.onProgress?.("GENERATING_SHARES");let m=await i.generateShares({planId:o.planId,declaration:t,encrypted:c,signal:a.signal});Z(a.signal),D(m);let y=await this.api.supplyPlanCreationMaterial(e,m);return a.onProgress?.(y.stage),y.outcome==="COMPLETED"?await this.checkpoints.remove(e):await this.saveCheckpoint(t,y),y}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 Oe(e),serverStage:t.stage})}},te=class extends Error{constructor(t){super(t);this.code=t;this.name="GuidedCreateRecoveryError"}};async function Oe(r){let e=JSON.stringify({name:r.name.normalize("NFC").trim(),description:r.description?.normalize("NFC").trim()??null,assets:r.assets.map(n=>({...n,fieldNames:[...n.fieldNames??[]]})).sort((n,i)=>n.clientAssetRef.localeCompare(i.clientAssetRef)),participants:r.participants.map(n=>({...n,routingEmail:n.routingEmail.normalize("NFC").trim(),relationships:[...n.relationships].sort()})).sort((n,i)=>n.clientParticipantRef.localeCompare(i.clientParticipantRef)),policy:r.policy??null}),t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function Z(r){if(r?.aborted)throw r.reason??new DOMException("Aborted","AbortError")}async function De(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 xe(r,e,t,n){let i=await r.getReveal(e);try{await n(i.planId)}catch(a){if(!it(a))throw a}return r.releaseRevealMaterial(e,t)}function Me(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"?st(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":at.has(r.stage)?"ENDED":"CONTINUING"}var at=new Set(["CANCELED","FAILED","CLOSING","CLOSED"]);function st(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 re=class extends Error{code="reveal_handle_closed";constructor(){super("reveal_handle_closed"),this.name="RevealHandleClosed"}},h=class extends Error{constructor(t){super(t);this.code=t;this.name="RevealFieldAccessError"}};async function ge(r,e,t={}){if(t.signal?.aborted)throw ye();let n=await r.getPlan(e);t.onProgress?.({phase:"WAITING_FOR_MASTER_KEY"}),await r.prepareReveal(e);let i=t.idempotencyKey??crypto.randomUUID(),a=await r.startReveal(e,{mode:t.mode??"DIRECT",idempotencyKey:i}),s;try{let o=await lt(r,a,t);x(t,"RELEASING_MATERIAL",o);let c=await r.releaseRevealMaterial(o.id,o.materialVersion??"1");o.mode==="GOVERNED"&&await r.markRevealSharesCollected(o.id);let m=await pt(r,o,mt(c),t);x(t,"RECONSTRUCTING",o);try{s=await r.reconstructPlanMaterial(m)}catch(W){throw await r.reportRevealReconstruction(o.id,{status:"FAILED",errorCode:dt(W)}),W}let y=await r.reportRevealReconstruction(o.id,{status:"SUCCEEDED"});return x(t,"OPEN",y),new me(r,y,n,s,t.signal)}catch(o){throw s?.fill(0),await ht(r,a.id,t.signal?.aborted?"CANCELED":"ERROR"),o}}var ot=new Set(["DENIED","PARTICIPANT_REVOKED","RECONCILIATION_REQUIRED","EXPIRED","CANCELED","FAILED","CLOSED"]);async function lt(r,e,t){let n=await r.getReveal(e.id);for(;;){if(t.onSession?.(n),t.onProgress?.({phase:Me(n),session:n}),n.stage==="AUTHORIZED"||n.stage==="MATERIAL_AUTHORIZED")return n;if(ot.has(n.stage))throw new ne(n.stage);await fe(t.pollIntervalMs??1500,t.signal),n=await r.getReveal(e.id)}}var ne=class extends Error{constructor(t){super(`reveal_authorization_ended:${t}`);this.stage=t;this.name="RevealAuthorizationEnded"}code="reveal_authorization_ended"};function x(r,e,t){r.onProgress?.({phase:e,session:t})}function fe(r,e){return e?.aborted?Promise.reject(ye()):new Promise((t,n)=>{let i=setTimeout(s,Math.max(0,r)),a=()=>{clearTimeout(i),n(ye())};function s(){e?.removeEventListener("abort",a),t()}e?.addEventListener("abort",a,{once:!0})})}var me=class{constructor(e,t,n,i,a){this.client=e;this.session=t;this.plan=n;this.plaintext=i;let s=Math.max(0,new Date(t.expiresAt).getTime()-Date.now());this.expiryTimer=setTimeout(()=>this.wipe(),Math.min(s,2147483647)),this.abortListener=a?()=>{this.close("CANCELED")}:void 0,a&&this.abortListener&&a.addEventListener("abort",this.abortListener,{once:!0})}plaintext;closePromise;expiryTimer;abortListener;get material(){if(!this.plaintext)throw new re;return this.plaintext}get closed(){return this.plaintext===void 0}async field(e,t={}){let n;return await this.consumeFields([{selector:e,options:t}],([i])=>{n=i?.value}),n}async consumeFields(e,t){if(e.length===0)throw new h("asset_selector_invalid");if(!this.client.assetDecoder)throw new h("asset_decoder_required");let n=e.map(({selector:a,options:s={}})=>{let o=Ne(a),c=this.plan.assets.find(m=>(m.code??m.id)===o.asset);if(!c)throw new h("asset_not_found");if(c.isBinary)throw new h("action_not_allowed");if(!c.fieldNames.includes(o.field))throw new h("asset_field_not_found");return{selector:`${o.asset}.${o.field}`,assetCode:o.asset,asset:c,field:o.field,options:s}}),i=[];try{for(let s of n)i.push(await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:s.options.idempotencyKey??crypto.randomUUID(),assetId:s.asset.id,fieldName:s.field,action:s.options.action??"VIEW_FIELD",...s.options.destination===void 0?{}:{destination:s.options.destination},...s.options.origin===void 0?{}:{origin:s.options.origin}}));let a=n.map(s=>{let o=this.client.assetDecoder(this.material).find(c=>c.id===s.asset.id||c.id===s.assetCode);if(!o)throw new h("asset_value_invalid");return{selector:s.selector,value:ct(o.data,s.field)}});await t(a)}catch(a){throw await Promise.all(i.map(s=>this.reportAction(s.id,"FAILED",ke(a)))),a}await Promise.all(i.map(a=>this.reportAction(a.id,"SUCCEEDED")))}async exportAsset(e,t){if(!e?.trim())throw new h("asset_selector_invalid");if(!this.client.assetDecoder)throw new h("asset_decoder_required");let n=this.plan.assets.find(s=>s.code===e||s.id===e);if(!n)throw new h("asset_not_found");if(!n.isBinary)throw new h("action_not_allowed");let i=await this.client.authorizeRevealAction(this.session.id,{idempotencyKey:crypto.randomUUID(),assetId:n.id,action:"EXPORT_ASSET"}),a;try{let s=this.client.assetDecoder(this.material).find(o=>o.id===n.id||o.id===n.code);if(!s||!(s.data instanceof Uint8Array))throw new h("asset_value_invalid");a=s.data.slice(),await t({id:n.id,fileName:n.fileName,mimeType:n.mimeType,bytes:a})}catch(s){throw await this.reportAction(i.id,"FAILED",ke(s)),s}finally{a?.fill(0)}await this.reportAction(i.id,"SUCCEEDED")}reportAction(e,t,n){return this.client.reportRevealActionOutcome(this.session.id,e,{idempotencyKey:crypto.randomUUID(),outcome:t,reportedAt:new Date().toISOString(),...n===void 0?{}:{errorCode:n}})}close(e="COMPLETED"){return this.closePromise?this.closePromise:(this.wipe(),this.closePromise=this.client.closeReveal(this.session.id,e).then(()=>{}).catch(t=>{if(!be(t))throw t}),this.closePromise)}[Symbol.asyncDispose](){return this.close("COMPLETED")}wipe(){this.plaintext&&(this.plaintext.fill(0),this.plaintext=void 0,clearTimeout(this.expiryTimer))}};function Ne(r){if(typeof r=="string"){let e=r.lastIndexOf(".");if(e<=0||e===r.length-1)throw new h("asset_selector_invalid");r={asset:r.slice(0,e),field:r.slice(e+1)}}if(!r.asset?.trim()||!r.field?.trim())throw new h("asset_selector_invalid");return{asset:r.asset,field:r.field}}function ct(r,e){let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new h("asset_value_invalid")}if(!t||typeof t!="object"||Array.isArray(t)||!(e in t))throw new h("asset_value_invalid");return t[e]}function ke(r){if(r instanceof h)return r.code;let e=r?.code;return typeof e=="string"&&/^[a-z][a-z0-9_]{2,63}$/u.test(e)?e:"host_field_access_failed"}function dt(r){let e=r?.code;return typeof e=="string"&&/^plan_[a-z0-9_]{3,59}$/u.test(e)?e:"plan_reconstruction_failed"}async function pt(r,e,t,n){if(t.shares.some(o=>o.shareType==="CUSTODIAN_KEY_SHARD"))return await r.distributeRevealCustodianShare(e.id),x(n,"CUSTODIAN_SHARE_DISTRIBUTED",e),t;let i=await r.getRevealCustodianAccess(e.id);for(;i.status==="PENDING"||i.status==="DISTRIBUTED";){let o={...e,stage:"WAITING_FOR_CUSTODIAN_CLAIM"};n.onSession?.(o),x(n,"WAITING_FOR_CUSTODIAN_CLAIM",o),await fe(n.pollIntervalMs??1500,n.signal),i=await r.getRevealCustodianAccess(e.id)}if(i.status!=="CLAIMED"||i.deviceType!=="SK_MOBILE")throw new ie;let a={...e,stage:"WAITING_FOR_CUSTODIAN"};n.onSession?.(a),x(n,"WAITING_FOR_CUSTODIAN",a),await r.requestRevealCustodianRelease(e.id);let s=await ut(r,e.id,n);return Object.assign({},t,{shares:t.shares.concat(s.shares.map((o,c)=>({id:`${s.id}:${c}`,storageLayerId:"SK_MOBILE",shareType:"CUSTODIAN_KEY_SHARD",data:o})))})}async function ut(r,e,t){let n=Date.now()+(t.custodianTimeoutMs??12e4);for(;;){let i=await r.getRevealCustodianShare(e);if(i&&i.status!=="PENDING"){let a=i;if(a.shares?.length)return a;throw new ie}if(Date.now()>=n)throw new he;await fe(t.pollIntervalMs??1500,t.signal)}}var ie=class extends Error{code="custodian_share_unavailable";constructor(){super("custodian_share_unavailable"),this.name="CustodianShareUnavailable"}},he=class extends Error{code="custodian_share_timed_out";constructor(){super("custodian_share_timed_out"),this.name="CustodianShareTimedOut"}};function mt(r){return r&&typeof r=="object"&&"material"in r?r.material:r}async function ht(r,e,t){try{await r.closeReveal(e,t)}catch(n){if(!be(n))throw n}}function be(r){let e=r&&typeof r=="object"&&"code"in r?String(r.code):"";return e==="reveal_expired"||e==="reveal_stage_conflict"}function ye(){let r=new Error("reveal_canceled");return r.name="AbortError",r}var z=class{constructor(e,t={}){this.coreSdk=e;if(t.applicationId!==void 0&&t.organizationId!==void 0)throw new Error("application_and_business_context_conflict");if(t.organizationId!==void 0&&!t.organizationId.trim())throw new Error("organization_id_required");this.keyVault=t.keyVault??new U,this.state=t.state??new L,this.api=t.api,this.reconstructor=t.reconstructor,this.masterKeys=t.masterKeys??yt(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 C(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 D(t),this.api.supplyPlanCreationMaterial(e,t)}cancelPlanCreation(e){if(this.requireApplication(),!this.api)throw new d;return this.api.cancelPlanCreation(e)}guidedPlanCreator(e=new J){if(this.requireApplication(),!this.api)throw new d;return new ee(this.api,e)}createPlan(e){return this.requireApplication(),this.useCase("CreateSharedProtectionPlanUseCase",e)}async configurePlan(e){let t=await this.applicationMasterKey(),n=Object.assign({},e,{masterKey:t});return this.useCase("ConfigureSharedProtectionPlanUseCase",n)}async applicationMasterKey(){let t={system:"INHERITI_ELEMENTS",contextId:this.requireApplication()},n=await this.keyVault.load(t);if(n)return Ue(n);let i=await this.masterKeys?.resolve(t);if(!i)throw new I(t);return await this.keyVault.store(t,Ke(i)),i}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 G;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 I({system:"INHERITI_BUSINESS",contextId:this.organizationId});let t=pe(e);if(!t)throw new I({system:"INHERITI_ELEMENTS",contextId:e.planId});let n=await this.keyVault.load(t);if(n)return Ue(n);let i=await this.masterKeys?.resolve(t);if(!i)throw new I(t);return await this.keyVault.store(t,Ke(i)),i}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 ge(this,e,t)}async withReveal(e,t,n){let i=await this.openReveal(e,t);try{let a=await n(i);return await i.close("COMPLETED"),a}catch(a){throw await i.close(t.signal?.aborted?"CANCELED":"ERROR"),a}}async releaseRevealMaterial(e,t){if(!this.api)throw new d;return xe(this.api,e,t,n=>this.prepareReveal(n))}markRevealSharesCollected(e){if(!this.api)throw new d;return this.api.markRevealSharesCollected(e)}distributeRevealCustodianShare(e){if(!this.api)throw new d;return this.api.distributeRevealCustodianShare(e)}requestRevealCustodianRelease(e){if(!this.api)throw new d;return this.api.requestRevealCustodianRelease(e)}getRevealCustodianAccess(e){if(!this.api)throw new d;return this.api.getRevealCustodianAccess(e)}getRevealCustodianShare(e){if(!this.api)throw new d;return this.api.getRevealCustodianShare(e)}reportRevealReconstruction(e,t){if(!this.api)throw new d;return this.api.reportRevealReconstruction(e,t)}closeReveal(e,t){if(!this.api)throw new d;return this.api.closeReveal(e,t)}abortPlanAccess(e){if(!this.api)throw new d;return this.api.abortPlanAccess(e)}async authorizeRevealAction(e,t){if(!this.api)throw new d;return De(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),i=t?await this.api.collectGovernedShares(e.processId,t):await this.api.collectGovernedShares(e.processId);await this.api.markGovernedSharesCollected(e.processId);let a=n.validatorShares.map(m=>Object.assign({},m,{shareType:"VALIDATOR_SHARD"})),s=i.dataShards.map(m=>Object.assign({},m,{shareType:"DATA_SHARD"})),o=i.backupShards.map(m=>Object.assign({},m,{shareType:"BACKUP_SHARD"})),c=i.keyShards.map(m=>Object.assign({},m,{shareType:"CUSTODIAN_KEY_SHARD"}));return{planId:e.planId,mergeThreshold:e.mergeThreshold,planKey:i.dek||n.dek,shares:a.concat(s,o,c),verifiedStorageLayerTypes:[],masterKeyWrapped:e.masterKeyWrapped,tenantId:e.tenantId,sourceReference:e.sourceReference}}async reconstructGovernedPlanMaterial(e,t){let n=await this.reconstructPlanMaterial(t);if(!this.api)throw new d;return await this.api.markGovernedSharesReconstructed(e.processId),await this.api.markGovernedDataRevealed(e.processId),await this.api.closeGovernedReveal(e.processId),n}useCase(e,t){if(!this.coreSdk)throw new ae;return this.coreSdk.getService(e).execute(t)}requireApplication(){if(!this.applicationId)throw new I({system:"INHERITI_ELEMENTS",contextId:"application"});return this.applicationId}},ae=class extends Error{code="core_sdk_container_required";constructor(){super("core_sdk_container_required"),this.name="CoreSdkContainerRequired"}};function Ke(r){let e=r.match(/.{2}/g);if(!e||e.length*2!==r.length)throw new Error("invalid_master_key_material");return new Uint8Array(e.map(t=>parseInt(t,16)))}function Ue(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function yt(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})}import{createBrowserSsdpV2WorkerFactory as wt,createSsdpV2Processor as At}from"@safetech/inheriti-core-sdk/workers/ssdp-v2";async function Re(r,e){if(!e)throw new Error("master_key_required");let t=gt(e),n=await crypto.subtle.importKey("raw",t,{name:"AES-GCM"},!1,["decrypt"]),i=ft(r),a=i.slice(0,12),s=i.slice(12),o=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},n,s);return Rt(new Uint8Array(o))}function gt(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 ft(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 Rt(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}var V=class{constructor(e){this.processor=e}async reconstruct(e,t){if(!e.masterKeyWrapped)throw new Error("master_key_protection_required");let n=await Le("plan_key_unwrap_failed",()=>Re(e.planKey,t)),i=await crypto.subtle.importKey("raw",ve(n),{name:"AES-GCM"},!1,["decrypt"]),a=[],s=[];for(let o of e.shares){let c=await Le("plan_share_decryption_failed",()=>Et(o.data,i));It(o.shareType)?s.push(c):a.push(c)}try{return await this.processor().reconstruct(a,{planId:e.planId,threshold:e.mergeThreshold,keyShares:s}).result}catch(o){throw new se("plan_share_reconstruction_failed",Pt(o))}}},se=class extends Error{constructor(t,n){super(t);this.code=t;this.reason=n;this.name="PlanMaterialReconstructionFailed"}},vt=new Set(["insufficient_valid_data_shards","insufficient_valid_key_shards","mixed_share_sets","threshold_metadata_mismatch","duplicate_data_shard","duplicate_key_shard","plan_binding_mismatch","ciphertext_digest_mismatch","v2_authentication_failed","shard_kind_mismatch","envelope_truncated","invalid_envelope_magic","unsupported_envelope_version","invalid_shard_kind","unsupported_v2_suite","invalid_envelope_length","crc32c_mismatch","invalid_envelope_metadata","invalid_envelope_threshold","invalid_data_shard_length","invalid_base64url","insufficient_shards","insufficient_key_shards","conflicting_key_shards","duplicate_shard","invalid_shard_index","invalid_key_shard_index","invalid_shard_length","invalid_key_length","plaintext_length_mismatch","ssdp_v2_worker_failed","ssdp_v2_worker_not_configured","unexpected_ssdp_v2_worker_response"]);function Pt(r){let e=r instanceof Error?r.message:void 0;if(e)return vt.has(e)?e:void 0}async function Le(r,e){try{return await e()}catch{throw new se(r)}}function It(r){return r==="VALIDATOR_SHARD"||r==="CUSTODIAN_KEY_SHARD"}async function Et(r,e){let t=r.indexOf(":");if(t<1)throw new Error("invalid_encrypted_plan_share");let n=ve(r.slice(0,t)),i=ve(r.slice(t+1)),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},e,i);return new TextDecoder().decode(a)}function ve(r){let e=atob(r),t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let i=0;i<e.length;i+=1)n[i]=e.charCodeAt(i);return t}var q=class extends V{constructor(e={}){let t=e.processor??At(e.workerUrl!==void 0&&typeof Worker<"u"?{workerFactory:wt(e.workerUrl),allowMainThreadFallback:!0}:{allowMainThreadFallback:!0});super(()=>t)}};var St=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],_t=["DIRECT","GOVERNED"],ze=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],Ct=["ACTIVE","REVOKED"],Tt=["SK_MOBILE"],Ot=["ACTIVE","INACTIVE"],Dt=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Ve(r){let e=g(r);return{items:R(e.items).map(Be),nextCursor:e.nextCursor===null?null:l(e.nextCursor,"nextCursor")}}function qe(r){let e=g(r);return{total:v(e.total,"total"),items:R(e.items).map(t=>{let n=g(t);if("eventData"in n)throw new Error("invalid_elements_response");return{id:l(n.id,"log.id"),planId:l(n.planId,"log.planId"),tenantId:l(n.tenantId,"log.tenantId"),event:l(n.event,"log.event"),occurredOn:l(n.occurredOn,"log.occurredOn"),status:A(n.status),title:l(n.title,"log.title"),details:R(n.details).map(i=>{let a=g(i);return{label:l(a.label,"log.detail.label"),value:l(a.value,"log.detail.value")}})}})}}function Fe(r){let e=g(r),t=Be(e),n=g(e.source),i=l(n.kind,"source.kind");return{...t,assets:R(e.assets).map(a=>{let s=g(a);return{id:l(s.id,"asset.id"),code:A(s.code),type:f(l(s.type,"asset.type"),Q),name:l(s.name,"asset.name"),isBinary:kt(s.isBinary,"asset.isBinary"),fieldNames:R(s.fieldNames).map(o=>l(o,"asset.fieldNames")),fileName:A(s.fileName),mimeType:A(s.mimeType),size:s.size===void 0||s.size===null?void 0:v(s.size,"asset.size"),matchOrigins:s.matchOrigins===void 0?void 0:R(s.matchOrigins).map(o=>l(o,"asset.matchOrigins"))}}),participants:R(e.participants).map(a=>{let s=g(a);return{id:l(s.id,"participant.id"),displayName:l(s.displayName,"participant.displayName"),relationships:R(s.relationships).map(o=>f(l(o,"relationship"),ze)),lifecycle:f(l(s.lifecycle,"participant.lifecycle"),Ct)}}),revealPolicy:(()=>{let a=g(e.revealPolicy);return{masterKeyRelease:f(l(a.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:f(l(a.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let a=g(e.dms);return{subjectEmail:l(a.subjectEmail,"dms.subjectEmail"),countdownDays:v(a.countdownDays,"dms.countdownDays"),countdownHours:v(a.countdownHours,"dms.countdownHours"),countdownMinutes:v(a.countdownMinutes,"dms.countdownMinutes")}})(),source:i==="NATIVE"?{kind:"NATIVE"}:i==="BRIDGED"?{kind:"BRIDGED",system:f(l(n.system,"source.system"),["INHERITI_BUSINESS"]),status:f(l(n.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:i}}}function F(r){let e=g(r);return{operationId:l(e.operationId,"operationId"),stage:f(l(e.stage,"stage"),Ce),outcome:f(l(e.outcome,"outcome"),Dt),planId:A(e.planId),lastErrorCode:A(e.lastErrorCode),participants:e.participants===void 0?void 0:R(e.participants).map(t=>{let n=g(t);return{clientParticipantRef:l(n.clientParticipantRef,"clientParticipantRef"),planParticipantId:l(n.planParticipantId,"planParticipantId"),relationships:R(n.relationships).map(i=>xt(l(i,"relationship"),ze))}})}}function Be(r){let e=g(r),t=g(e.assetSummary),n=g(e.governance),i=g(e.participantSummary);return{id:l(e.id,"id"),name:l(e.name,"name"),description:A(e.description),status:f(l(e.status,"status"),St),createdAt:l(e.createdAt,"createdAt"),configuredAt:A(e.configuredAt),assetSummary:{count:v(t.count,"assetSummary.count"),types:R(t.types).map(a=>f(l(a,"assetType"),Q)),names:Ge(t.names).map(a=>l(a,"assetSummary.names"))},governance:{mode:f(l(n.mode,"governance.mode"),_t),minimumApprovals:v(n.minimumApprovals,"minimumApprovals")},participantSummary:{owners:v(i.owners,"owners"),mergers:v(i.mergers,"mergers"),moderators:v(i.moderators,"moderators")},authentication:Ge(e.authentication).map(a=>{let s=g(a);return{id:f(l(s.id,"authentication.id"),Tt),status:f(l(s.status,"authentication.status"),Ot)}})}}function f(r,e){return e.includes(r)?r:{kind:"UNKNOWN",raw:r}}function xt(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 Ge(r){return r==null?[]:R(r)}function R(r){if(!Array.isArray(r))throw new Error("invalid_elements_response");return r}function l(r,e){if(typeof r!="string"||!r)throw new Error("invalid_elements_response");return r}function A(r){return r==null?void 0:l(r,"optional")}function v(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("invalid_elements_response");return r}function kt(r,e){if(typeof r!="boolean")throw new Error("invalid_elements_response");return r}var k=class extends Error{constructor(t){super(t);this.code=t;this.name="BusinessOrganizationSelectionError"}};function He(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 Mt(r,e){if(!e){if(r.length===0)throw new k("organization_required");if(r.length>1)throw new k("organization_selection_required");return r[0].id}if(!r.some(({id:t})=>t===e))throw new k("organization_access_denied");return e}function Pe(r){return typeof r.error=="string"?r.error||void 0:r.error?.code??r.name??r.message}function Ie(r){return typeof r.error=="object"&&r.error?.requestId?r.error.requestId:r.description}var T=class extends Error{constructor(t,n,i){super(n??`elements_api_request_failed_${t}`);this.status=t;this.code=n;this.detail=i;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},M=class{constructor(e,t,n,i,a){this.apiUrl=e;this.environment=t;this.getBearerToken=n;this.transport=i;this.business=a?Object.freeze({...a}):void 0}business;listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(He)}async listPlans(e={}){let t=new URLSearchParams;e.cursor&&t.set("cursor",e.cursor),e.limit!==void 0&&t.set("limit",String(e.limit));for(let i of e.status??[])t.append("status",i);e.assetType&&t.set("assetType",e.assetType),e.namePrefix&&t.set("namePrefix",e.namePrefix);let n=t.size?`?${t}`:"";return Ve(await this.request(`v1/plans${n}`,"GET"))}async getPlan(e){return Fe(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,t={}){let n=new URLSearchParams;t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset));let i=n.size?`?${n}`:"";return qe(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${i}`,"GET"))}async startPlanCreation(e){C(e);let{idempotencyKey:t,...n}=e;return F(await this.request("v1/plan-creations","POST",n,void 0,{"idempotency-key":t}))}async getPlanCreation(e){return F(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,t){return D(t),F(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",t))}async cancelPlanCreation(e){return F(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,...i}=t;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",i,void 0,{"idempotency-key":n})}getReveal(e){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET")}releaseRevealMaterial(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:t})}markRevealSharesCollected(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/shares-collected`)}distributeRevealCustodianShare(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/distribute`)}requestRevealCustodianRelease(e){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/release`)}getRevealCustodianAccess(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET")}getRevealCustodianShare(e){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET")}reportRevealReconstruction(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",t)}closeReveal(e,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:t})}abortPlanAccess(e){return this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"DELETE")}authorizeRevealAction(e,t){let{idempotencyKey:n,...i}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",i,void 0,{"idempotency-key":n})}reportRevealActionOutcome(e,t,n){let{idempotencyKey:i,...a}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(t)}/outcome`,"PUT",a,void 0,{"idempotency-key":i})}getCustodianShare(e,t){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,t)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,t){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",t)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,t,n,i,a){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),i?.requestId&&o.set("x-elements-step-up-request",i.requestId);for(let[W,Ye]of Object.entries(a??{}))o.set(W,Ye);n&&o.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,m=await this.transport(new URL(e,c),{method:t,headers:o,body:n?JSON.stringify(n):void 0}),y=await We(m);if(!m.ok)throw new T(m.status,Pe(y),Ie(y));if(!y.ok||y.result===void 0)throw new T(m.status,Pe(y),Ie(y));return y.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 i=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,a=await this.transport(new URL(e,i),{method:"POST",headers:n}),s=await We(a);if(!a.ok||!s.ok)throw new T(a.status,Pe(s),Ie(s))}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!this.business.organizationId)throw new T(400,"organization_selection_required")}};async function We(r){try{return await r.json()}catch{return{ok:!1}}}import{PassphraseMasterKeySource as Br,RawMasterKeySource as Hr,computePassphraseVerifier as Wr,deriveMasterKey as $r,generateHexSeed as jr}from"@safetech/inheriti-core-sdk/crypto";function $e(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/u,"")}var B=class{randomUrlSafe(e){let t=new Uint8Array(e);return globalThis.crypto.getRandomValues(t),$e(t)}async sha256UrlSafe(e){let t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return $e(new Uint8Array(t))}},H=class{now(){return Date.now()}sleep(e,t){return new Promise((n,i)=>{if(t?.aborted)return i(t.reason??new DOMException("Aborted","AbortError"));let a=setTimeout(n,e);t?.addEventListener("abort",()=>{clearTimeout(a),i(t.reason??new DOMException("Aborted","AbortError"))},{once:!0})})}};var N=class extends Error{constructor(t,n=t){super(n);this.code=t;this.name="OperatorAuthError"}},b=class extends N{constructor(e="The operator must authenticate again"){super("reauthentication_required",e),this.name="OperatorReauthenticationRequired"}},p=class extends N{constructor(e,t=e){super(e,t),this.name="OAuthProtocolError"}};function oe(r){if(r instanceof N)return r.code;if(typeof r!="object"||r===null)return;let e=r.code??r.error;return typeof e=="string"?e:void 0}var Ee=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:S(n,"issuer"),authorizationEndpoint:S(n,"authorization_endpoint"),tokenEndpoint:S(n,"token_endpoint"),deviceAuthorizationEndpoint:P(n,"device_authorization_endpoint"),endSessionEndpoint:P(n,"end_session_endpoint"),revocationEndpoint:P(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:S(t,"device_code"),userCode:S(t,"user_code"),verificationUri:S(t,"verification_uri"),verificationUriComplete:P(t,"verification_uri_complete"),expiresInSeconds:je(t,"expires_in"),intervalSeconds:we(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:S(n,"access_token"),refreshToken:P(n,"refresh_token"),idToken:P(n,"id_token"),tokenType:S(n,"token_type"),expiresInSeconds:je(n,"expires_in"),refreshExpiresInSeconds:we(n,"refresh_expires_in"),scope:P(n,"scope")}}form(e,t){return this.json(e,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",accept:"application/json"},body:new URLSearchParams(t)})}async json(e,t){let n=await this.http(e instanceof URL?e:new URL(e),t),i={};try{i=await n.json()}catch{}if(!n.ok){let a=P(i,"error")??`oauth_http_${n.status}`;throw new p(a,P(i,"error_description")??a)}return i}};function S(r,e){let t=P(r,e);if(!t)throw new p("invalid_oauth_response",`Missing ${e}`);return t}function P(r,e){return typeof r[e]=="string"?r[e]:void 0}function je(r,e){let t=we(r,e);if(t===void 0)throw new p("invalid_oauth_response",`Missing ${e}`);return t}function we(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}var Nt=600*1e3,le=5,bt=5,Ae=class{constructor(e){this.options=e;this.crypto=e.crypto??new B,this.clock=e.clock??new H}crypto;clock;discovery;refreshFlight;async beginAuthorizationCode(){let e=await this.getDiscovery(),t=this.crypto.randomUrlSafe(32),n=this.crypto.randomUrlSafe(32),i=this.crypto.randomUrlSafe(64),a=await this.crypto.sha256UrlSafe(i),s=this.clock.now()+Nt;await this.options.transactions.save(this.transactionKey("authorization-code"),{kind:"authorization-code",state:t,nonce:n,codeVerifier:i,redirectUri:this.options.configuration.redirectUri,expiresAt:s});let o=new URL(e.authorizationEndpoint);return o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.options.configuration.clientId),o.searchParams.set("redirect_uri",this.options.configuration.redirectUri),o.searchParams.set("scope",this.options.configuration.scopes.join(" ")),o.searchParams.set("state",t),o.searchParams.set("nonce",n),o.searchParams.set("code_challenge",a),o.searchParams.set("code_challenge_method","S256"),{authorizationUrl:o.toString(),expiresAt:s}}async completeAuthorizationCode(e){let t=this.transactionKey("authorization-code"),n=await this.options.transactions.load(t);if(await this.options.transactions.remove(t),!n||n.kind!=="authorization-code")throw new p("authorization_transaction_missing");if(n.expiresAt<=this.clock.now())throw new p("authorization_transaction_expired");let i=new URL(e),a=new URL(n.redirectUri);if(i.origin!==a.origin||i.pathname!==a.pathname)throw new p("redirect_uri_mismatch");let s=i.searchParams.get("error");if(s)throw new p(s,i.searchParams.get("error_description")??s);if(i.searchParams.get("state")!==n.state)throw new p("state_mismatch");let o=i.searchParams.get("code");if(!o)throw new p("authorization_code_missing");let c=await this.getDiscovery(),m=await this.options.transport.exchangeAuthorizationCode({tokenEndpoint:c.tokenEndpoint,clientId:this.options.configuration.clientId,code:o,codeVerifier:n.codeVerifier,redirectUri:n.redirectUri}),y=await this.acceptTokens(m,n.nonce);return await this.options.sessions.save(y),y}async beginDeviceAuthorization(){let e=await this.getDiscovery();if(!e.deviceAuthorizationEndpoint)throw new p("device_authorization_unsupported");let t=await this.options.transport.startDeviceAuthorization({endpoint:e.deviceAuthorizationEndpoint,clientId:this.options.configuration.clientId,scopes:this.options.configuration.scopes}),n=Math.max(le,t.intervalSeconds??le),i=this.clock.now(),a={...t,kind:"device-code",intervalSeconds:n,expiresAt:i+t.expiresInSeconds*1e3,nextPollAt:i+n*1e3,consumed:!1};return await this.options.transactions.save(this.transactionKey("device-code"),a),a}async pollDeviceAuthorization(e){let t=this.transactionKey("device-code"),n=await this.options.transactions.load(t);if(!n||n.kind!=="device-code"||n.consumed)throw new p("device_transaction_missing");let i=n,a=await this.getDiscovery(),s=Math.max(le,i.intervalSeconds??le),o=Math.max(i.nextPollAt,this.clock.now());for(;this.clock.now()<i.expiresAt&&!(o>=i.expiresAt);){await this.clock.sleep(Math.max(0,o-this.clock.now()),e);try{let c=await this.options.transport.pollDeviceToken({tokenEndpoint:a.tokenEndpoint,clientId:this.options.configuration.clientId,deviceCode:i.deviceCode});i.consumed=!0,await this.options.transactions.save(t,i);let m=await this.acceptTokens(c);return await this.options.sessions.save(m),await this.options.transactions.remove(t),m}catch(c){let m=oe(c);if(m==="authorization_pending"){o=this.clock.now()+s*1e3;continue}if(m==="slow_down"){s+=bt,o=this.clock.now()+s*1e3;continue}throw await this.options.transactions.remove(t),c}}throw await this.options.transactions.remove(t),new p("expired_token","The device authorization expired")}async getAccessToken(){let e=await this.options.sessions.load();if(e)return e.expiresAt>this.clock.now()?e.accessToken:(await this.refresh()).accessToken}refresh(){if(this.refreshFlight)return this.refreshFlight;let e=this.performRefresh().finally(()=>{this.refreshFlight===e&&(this.refreshFlight=void 0)});return this.refreshFlight=e,e}async clear(){await this.options.sessions.clear()}async performRefresh(){let e=await this.options.sessions.load();if(!e?.refreshToken||e.refreshExpiresAt!==void 0&&e.refreshExpiresAt<=this.clock.now())throw await this.options.sessions.clear(),new b;try{let t=await this.getDiscovery(),n=await this.options.transport.refresh({tokenEndpoint:t.tokenEndpoint,clientId:this.options.configuration.clientId,refreshToken:e.refreshToken});if(!n.refreshToken)throw new p("refresh_token_rotation_missing");let i=await this.acceptTokens(n);return await this.options.sessions.save(i),i}catch(t){await this.options.sessions.clear();let n=oe(t);throw n==="invalid_grant"||n==="invalid_client"||n==="unauthorized_client"||n==="registration_disabled"?new b: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 p("issuer_mismatch");return e}catch(e){throw this.discovery=void 0,e}}transactionKey(e){let{issuer:t,clientId:n,redirectUri:i}=this.options.configuration;return`${e}|${O(t)}|${n}|${i}`}async acceptTokens(e,t){if(e.tokenType.toLowerCase()!=="bearer")throw new p("unsupported_token_type");let n=await this.options.tokenValidator.validateAccessToken(e.accessToken);if(this.assertPrincipal(n,t,!1),t!==void 0){if(!e.idToken||!this.options.tokenValidator.validateIdToken)throw new p("id_token_validation_required");let a=await this.options.tokenValidator.validateIdToken(e.idToken);if(this.assertIdentity(a,t),a.subject!==n.subject||a.sessionId!==n.sessionId)throw new p("token_subject_mismatch")}let i=this.clock.now();return{accessToken:e.accessToken,refreshToken:e.refreshToken,idToken:e.idToken,tokenType:"Bearer",expiresAt:i+e.expiresInSeconds*1e3,refreshExpiresAt:e.refreshExpiresInSeconds===void 0?void 0:i+e.refreshExpiresInSeconds*1e3,principal:n}}assertPrincipal(e,t,n){let i=this.options.configuration,a=typeof e.audience=="string"?[e.audience]:e.audience;if(O(e.issuer)!==O(i.issuer))throw new p("issuer_mismatch");if(!a.includes(i.audience))throw new p("audience_mismatch");if(e.authorizedParty!==i.clientId)throw new p("client_mismatch");if(e.environment!==i.environment)throw new p("environment_mismatch");if(!e.subject||!e.sessionId||!e.tokenId)throw new p("required_claim_missing");if(n&&e.nonce!==t)throw new p("nonce_mismatch")}assertIdentity(e,t){let n=this.options.configuration,i=typeof e.audience=="string"?[e.audience]:e.audience;if(O(e.issuer)!==O(n.issuer))throw new p("issuer_mismatch");if(!i.includes(n.clientId))throw new p("client_mismatch");if(e.authorizedParty!==n.clientId)throw new p("client_mismatch");if(!e.subject||!e.sessionId)throw new p("required_claim_missing");if(e.nonce!==t)throw new p("nonce_mismatch")}};function O(r){return r.replace(/\/+$/u,"")}var Se=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 br(r){let e=r.transport??globalThis.fetch.bind(globalThis),t=new M(r.apiUrl,r.environment,r.getBearerToken,e,r.business?{organizationId:r.organizationId}:void 0);return new z(void 0,{api:t,applicationId:r.applicationId,organizationId:r.organizationId,masterKeys:r.masterKeys,masterKey:r.masterKey,assetDecoder:Kt,reconstructor:r.reconstructor??new q(r.reconstruction??{}),...r.keyVault===void 0?{}:{keyVault:r.keyVault},...r.state===void 0?{}:{state:r.state}})}export{q as BrowserPlanMaterialReconstructor,k as BusinessOrganizationSelectionError,ae as CoreSdkContainerRequired,T as ElementsApiRequestFailed,z as ElementsClient,M as HttpElementsApiPort,Ee as HttpOperatorAuthTransport,j as MasterKeyRelayExpired,$ as MasterKeyRelayTimedOut,I as MasterKeyRequired,U as MemoryKeyVault,L as MemoryStatePort,p as OAuthProtocolError,Ae as OperatorAuthClient,N as OperatorAuthError,b as OperatorReauthenticationRequired,Se as OperatorSessionController,Br as PassphraseMasterKeySource,G as PlanMaterialReconstructorRequired,Hr as RawMasterKeySource,K as RelayMasterKeySource,ne as RevealAuthorizationEnded,h as RevealFieldAccessError,re as RevealHandleClosed,de as StaticMasterKeyResolver,H as SystemOAuthClock,B as WebOAuthCrypto,Wr as computePassphraseVerifier,br as createBrowserElementsClient,Y as createMasterKeyResolver,Kt as decodeAssetContainer,$r as deriveMasterKey,jr as generateHexSeed,pe as masterKeyRefFor,w as masterKeyRefKey,oe as oauthErrorCode,ge as openScopedReveal,Ne as parseAssetFieldSelector,Me as revealPhaseOf,Mt as selectBusinessOrganization,Re as unwrapDekWithMasterKey};
|
package/dist/index.d.ts
CHANGED
|
@@ -6,4 +6,6 @@ export { default as useClient } from "./src/auth/use-client";
|
|
|
6
6
|
export { getAvailableEnvs } from "./src/auth/get-available-envs";
|
|
7
7
|
export { SDKContainer };
|
|
8
8
|
export * from './src/elements';
|
|
9
|
+
export { selectBusinessOrganization, BusinessOrganizationSelectionError } from './src/business/organizations';
|
|
10
|
+
export type { BusinessOrganization } from './src/business/organizations';
|
|
9
11
|
export * from './src/operator-auth';
|