@safetech/inheriti-client-sdk 1.17.28 → 1.17.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/automation.js +1 -1
- package/dist/browser.js +1 -1
- package/dist/inbox.js +1 -1
- package/dist/index.js +1 -1
- package/dist/inheriti-client-sdk.umd.js +41 -41
- package/dist/node-base.js +1 -1
- package/dist/node.js +1 -1
- package/dist/sdk-types.d.ts +103 -1
- package/dist/src/elements/elements-api-port.d.ts +4 -0
- package/dist/src/elements/elements-client.d.ts +5 -0
- package/dist/src/elements/http-elements-api-port.d.ts +6 -0
- package/dist/src/elements/index.d.ts +1 -0
- package/dist/src/elements/organization-queries.d.ts +92 -0
- package/dist/src/elements/plan-operations.d.ts +1 -0
- package/package.json +1 -1
package/dist/inbox.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
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"],Xe={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},me=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],y=class extends Error{constructor(n){super(n);this.code=n;this.name="InvalidPlanDeclaration"}},D=class extends Error{constructor(n){super(n);this.code=n;this.name="InvalidPlanMaterial"}};function ue(i){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(i).some(n=>!e.includes(n)))throw new D("plan_material_field_unknown");if(re(i.dataShards,"data_shards_invalid"),re(i.backupShards,"backup_shards_invalid"),i.validatorShares!==void 0&&re(i.validatorShares,"validator_shares_invalid"),i.validatorShares?.length&&!i.encryptedKey)throw new D("validator_shares_require_encrypted_key");if(i.protectionProtocol!==void 0&&i.protectionProtocol!=="SSDP_PLUS_V1"&&i.protectionProtocol!=="SSDP_PLUS_V2")throw new D("protection_protocol_invalid");if(i.operation!==void 0&&i.operation!=="DRAFT"&&i.operation!=="FINALIZE")throw new D("material_operation_invalid")}function re(i,e){if(!Array.isArray(i))throw new D(e);for(let n of i){if(typeof n!="object"||n===null||typeof n.id!="string"||!n.id)throw new D(e);if(n.data!==void 0&&typeof n.data!="string")throw new D(e)}}function Ie(i){if(L(i,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Ze(i.idempotencyKey))throw new y("idempotency_key_invalid");if(!i.name?.trim())throw new y("plan_name_required");if(!i.assets.length)throw new y("assets_required");let e=new Set;for(let n of i.assets){if(L(n,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!n.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(n.clientAssetRef)||e.has(n.clientAssetRef))throw new y("client_asset_ref_invalid");if(e.add(n.clientAssetRef),!j.includes(n.type))throw new y("asset_type_invalid");let t=n.type==="DOCUMENT"||n.type==="IMAGE"||n.type==="VIDEO";if(n.isBinary!==t)throw new y("asset_binary_representation_invalid");let r=n.fieldNames??[];if(n.isBinary&&(r.length||!n.fileName||!n.mimeType||!Number.isSafeInteger(n.size)||n.size<0))throw new y("binary_asset_metadata_invalid");if(!n.isBinary&&(!r.length||n.fileName!==void 0||n.mimeType!==void 0||n.size!==void 0))throw new y("structured_asset_metadata_invalid");if(new Set(r).size!==r.length||r.some(s=>!s.trim()))throw new y("asset_field_names_invalid");if(Qe(n.matchOrigins),!n.isBinary){let s=Xe[n.type];if(!s||r.some(o=>!s.includes(o)))throw new y("asset_field_name_not_canonical")}}if(!i.participants.length)throw new y("participants_required");for(let n of i.participants){if(L(n,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!n.clientParticipantRef?.trim()||!n.displayName?.trim()||!ge(n.routingEmail))throw new y("participant_invalid");if(!n.relationships.length||n.relationships.includes("ALLOW")&&n.relationships.includes("DENY"))throw new y("participant_relationships_invalid")}Je(i)}function Qe(i){if(i===void 0)return;if(!i.length)throw new y("asset_match_origins_invalid");let e=i.map(n=>{if(typeof n!="string"||!n.trim())throw new y("asset_match_origin_invalid");try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol)||t.origin!==n.trim())throw new y("asset_match_origin_invalid");return t.origin}catch(t){throw t instanceof y?t:new y("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new y("asset_match_origins_duplicated")}function Je(i){let e=i.policy;if(e&&L(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new y("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){L(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new y("authentication_mode_invalid")}if(e.moderation){L(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=i.participants.filter(c=>c.relationships.includes("MODERATOR"));if(s.length===0)throw new y("moderation_requires_moderators");let o=e.moderation.minimumApprovals;if(o!==void 0&&(!Number.isInteger(o)||o<1||o>s.length))throw new y("minimum_approvals_invalid");let a=e.moderation.approvalMode;if(a!==void 0&&a!=="THRESHOLD"&&a!=="UNANIMOUS")throw new y("approval_mode_invalid")}let n=e.dms;if(!n)return;L(n,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let t=n.countdownHours??0,r=n.countdownMinutes??0;if(!ge(n.subjectEmail))throw new y("dms_subject_invalid");if(!i.participants.some(s=>pe(s.routingEmail)===pe(n.subjectEmail)))throw new y("dms_subject_not_participant");if(!Number.isInteger(n.countdownDays)||!Number.isInteger(t)||!Number.isInteger(r)||n.countdownDays<0||t<0||t>23||r<0||r>59||n.countdownDays+t+r===0)throw new y("dms_countdown_invalid")}function Ze(i){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(i)}function ge(i){return typeof i=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(i.normalize("NFC").trim())}function pe(i){return i.normalize("NFC").trim().toLowerCase()}function L(i,e,n){if(Object.keys(i).some(t=>!e.includes(t)))throw new y(n)}var en=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],nn=["DIRECT","GOVERNED"],ye=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],tn=["ACTIVE","REVOKED"],rn=["SK_MOBILE"],sn=["ACTIVE","INACTIVE"],on=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function fe(i){let e=P(i);return{items:R(e.items).map(ve),nextCursor:e.nextCursor===null?null:m(e.nextCursor,"nextCursor")}}function he(i){let e=P(i);return{total:M(e.total,"total"),items:R(e.items).map(n=>{let t=P(n);if("eventData"in t)throw new Error("invalid_elements_response");return{id:m(t.id,"log.id"),planId:m(t.planId,"log.planId"),tenantId:m(t.tenantId,"log.tenantId"),event:m(t.event,"log.event"),occurredOn:m(t.occurredOn,"log.occurredOn"),status:k(t.status),title:m(t.title,"log.title"),details:R(t.details).map(r=>{let s=P(r);return{label:m(s.label,"log.detail.label"),value:m(s.value,"log.detail.value")}})}})}}function xe(i){let e=P(i);return{total:M(e.total,"total"),items:R(e.items).map(n=>{let t=P(n);if("eventData"in t)throw new Error("invalid_elements_response");let r=m(t.source,"log.source");if(r!=="MEMBER"&&r!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:m(t.id,"log.id"),memberId:m(t.memberId,"log.memberId"),source:r,event:m(t.event,"log.event"),occurredOn:m(t.occurredOn,"log.occurredOn"),status:k(t.status)}})}}function Pe(i){let e=P(i),n=ve(e),t=P(e.source),r=m(t.kind,"source.kind");return{...n,assets:R(e.assets).map(s=>{let o=P(s);return{id:m(o.id,"asset.id"),code:k(o.code),type:E(m(o.type,"asset.type"),j),name:m(o.name,"asset.name"),isBinary:dn(o.isBinary,"asset.isBinary"),fieldNames:R(o.fieldNames).map(a=>m(a,"asset.fieldNames")),fileName:k(o.fileName),mimeType:k(o.mimeType),size:o.size===void 0||o.size===null?void 0:M(o.size,"asset.size"),matchOrigins:o.matchOrigins===void 0?void 0:R(o.matchOrigins).map(a=>m(a,"asset.matchOrigins"))}}),participants:R(e.participants).map(s=>{let o=P(s);return{id:m(o.id,"participant.id"),displayName:m(o.displayName,"participant.displayName"),relationships:R(o.relationships).map(a=>E(m(a,"relationship"),ye)),lifecycle:E(m(o.lifecycle,"participant.lifecycle"),tn)}}),revealPolicy:(()=>{let s=P(e.revealPolicy);return{masterKeyRelease:E(m(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:E(m(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=P(e.dms);return{subjectEmail:m(s.subjectEmail,"dms.subjectEmail"),countdownDays:M(s.countdownDays,"dms.countdownDays"),countdownHours:M(s.countdownHours,"dms.countdownHours"),countdownMinutes:M(s.countdownMinutes,"dms.countdownMinutes")}})(),source:r==="NATIVE"?{kind:"NATIVE"}:r==="BRIDGED"?{kind:"BRIDGED",system:E(m(t.system,"source.system"),["INHERITI_BUSINESS"]),status:E(m(t.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:r}}}function G(i){let e=P(i);return{operationId:m(e.operationId,"operationId"),stage:E(m(e.stage,"stage"),me),outcome:E(m(e.outcome,"outcome"),on),planId:k(e.planId),lastErrorCode:k(e.lastErrorCode),participants:e.participants===void 0?void 0:R(e.participants).map(n=>{let t=P(n);return{clientParticipantRef:m(t.clientParticipantRef,"clientParticipantRef"),planParticipantId:m(t.planParticipantId,"planParticipantId"),relationships:R(t.relationships).map(r=>an(m(r,"relationship"),ye))}})}}function ve(i){let e=P(i),n=P(e.assetSummary),t=P(e.governance),r=P(e.participantSummary);return{id:m(e.id,"id"),name:m(e.name,"name"),description:k(e.description),status:E(m(e.status,"status"),en),createdAt:m(e.createdAt,"createdAt"),configuredAt:k(e.configuredAt),assetSummary:{count:M(n.count,"assetSummary.count"),types:R(n.types).map(s=>E(m(s,"assetType"),j)),names:be(n.names).map(s=>m(s,"assetSummary.names"))},governance:{mode:E(m(t.mode,"governance.mode"),nn),minimumApprovals:M(t.minimumApprovals,"minimumApprovals")},participantSummary:{owners:M(r.owners,"owners"),mergers:M(r.mergers,"mergers"),moderators:M(r.moderators,"moderators")},authentication:be(e.authentication).map(s=>{let o=P(s);return{id:E(m(o.id,"authentication.id"),rn),status:E(m(o.status,"authentication.status"),sn)}})}}function E(i,e){return e.includes(i)?i:{kind:"UNKNOWN",raw:i}}function an(i,e){if(!e.includes(i))throw new Error("invalid_elements_response");return i}function P(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("invalid_elements_response");return i}function be(i){return i==null?[]:R(i)}function R(i){if(!Array.isArray(i))throw new Error("invalid_elements_response");return i}function m(i,e){if(typeof i!="string"||!i)throw new Error("invalid_elements_response");return i}function k(i){return i==null?void 0:m(i,"optional")}function M(i,e){if(typeof i!="number"||!Number.isFinite(i))throw new Error("invalid_elements_response");return i}function dn(i,e){if(typeof i!="boolean")throw new Error("invalid_elements_response");return i}function we(i){if(!i||typeof i!="object"||!("items"in i)||!Array.isArray(i.items)||!i.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 i.items.map(({id:e,name:n})=>({id:e,name:n}))}function cn(i){let e=b(i);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:u(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:u(e.participantRevision,1),createdAt:A(e.createdAt),...Se(e)}}function Se(i){if(i.recipientStatuses===void 0)return{};if(!Array.isArray(i.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:i.recipientStatuses.map(e=>{let n=b(e);if(n.secrets!==void 0&&!Array.isArray(n.secrets))throw new Error("invalid_inbox_response");if(n.read!==void 0&&typeof n.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:d(n.memberId),...n.read!==void 0?{read:n.read}:{},...n.readAt!==void 0?{readAt:n.readAt===null?null:A(n.readAt)}:{},...Array.isArray(n.secrets)?{secrets:n.secrets.map(t=>{let r=b(t);if(r.status!=="UNREAD"&&r.status!=="LEASED"&&r.status!=="CONSUMED"&&r.status!=="EXPIRED"&&r.status!=="REVOKED"&&r.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:u(r.position,0),status:r.status,...r.revealedAt!==void 0?{revealedAt:r.revealedAt===null?null:A(r.revealedAt)}:{}}})}:{}}})}}function Ae(i){let e=b(i);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(cn),total:u(e.total,0),limit:u(e.limit,1),offset:u(e.offset,0),unreadCount:u(e.unreadCount,0),readThroughSequence:u(e.readThroughSequence,0)}}function Ee(i){let e=b(i);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:u(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:u(e.participantRevision,1),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:u(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(n=>{let t=b(n);return{unitId:d(t.unitId),position:u(t.position,0),commitment:d(t.commitment),status:d(t.status)}})}}function ie(i){let e=b(i);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:u(e.sequence,1),status:e.status}}function Re(i){let e=b(i);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:d(e.conversationId),parentId:d(e.parentId),participantRevision:u(e.participantRevision,1),recipients:e.recipients.map(se)}}function _e(i){let e=b(i);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(n=>{let t=b(n);return{parentId:d(t.parentId),sequence:u(t.sequence,1),senderMemberId:d(t.senderMemberId),senderDeviceId:d(t.senderDeviceId),participantRevision:u(t.participantRevision,1),createdAt:A(t.createdAt),...Se(t)}}),total:u(e.total,0),limit:u(e.limit,1),offset:u(e.offset,0),unreadCount:u(e.unreadCount,0),readThroughSequence:u(e.readThroughSequence,0)}}function Ce(i){return{readThroughSequence:u(b(i).readThroughSequence,0)}}function Te(i){return{clearedThroughSequence:u(b(i).clearedThroughSequence,0)}}function Me(i){let e=b(i);return{parentId:d(e.parentId),sequence:u(e.sequence,1),senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:u(e.participantRevision,1),canonicalManifest:d(e.canonicalManifest),frame:d(e.frame),signature:d(e.signature),wrappedContentKey:d(e.wrappedContentKey),senderSigningPublicKey:d(e.senderSigningPublicKey)}}function b(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("invalid_inbox_response");return i}function d(i){if(typeof i!="string"||!i)throw new Error("invalid_inbox_response");return i}function A(i){let e=d(i);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function u(i,e){if(!Number.isSafeInteger(i)||i<e)throw new Error("invalid_inbox_response");return i}function se(i){let e=b(i);return{memberId:d(e.memberId),deviceId:d(e.deviceId),deviceVersion:u(e.deviceVersion,1),encryptionPublicKey:d(e.encryptionPublicKey),encryptionKeyFingerprint:d(e.encryptionKeyFingerprint),signingPublicKey:d(e.signingPublicKey),signingKeyFingerprint:d(e.signingKeyFingerprint)}}function $(i){let e=b(i);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:d(e.id),tenantId:d(e.tenantId),memberId:d(e.memberId),version:e.version,encryptionPublicKey:d(e.encryptionPublicKey),encryptionKeyFingerprint:d(e.encryptionKeyFingerprint),signingPublicKey:d(e.signingPublicKey),signingKeyFingerprint:d(e.signingKeyFingerprint),status:e.status,createdAt:A(e.createdAt),updatedAt:A(e.updatedAt)}}function Y(i){let e=b(i);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let n={id:d(e.id),tenantId:d(e.tenantId),creatorMemberId:d(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(d),participantRevision:e.participantRevision,status:e.status,createdAt:A(e.createdAt),updatedAt:A(e.updatedAt)};if(e.unreadCount!==void 0&&(n.unreadCount=e.unreadCount),e.latestMessage===null&&(n.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let t=b(e.latestMessage);if(t.contentKind!=="TEXT"&&t.contentKind!=="FILE"&&t.contentKind!=="NORMAL"&&t.contentKind!=="MIXED"&&t.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");n.latestMessage={contentKind:t.contentKind,senderMemberId:d(t.senderMemberId),createdAt:A(t.createdAt)}}return n}function Ke(i){let e=b(i);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(Y),total:e.total,limit:e.limit,offset:e.offset}}function Ne(i){let e=b(i);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(n=>{let t=se(n);return{memberId:t.memberId,name:d(b(n).name),deviceId:t.deviceId,deviceVersion:t.deviceVersion,encryptionPublicKey:t.encryptionPublicKey,encryptionKeyFingerprint:t.encryptionKeyFingerprint,signingPublicKey:t.signingPublicKey,signingKeyFingerprint:t.signingKeyFingerprint}}),limit:u(e.limit,1),offset:u(e.offset,0),nextOffset:e.nextOffset===null?null:u(e.nextOffset,0)}}function Oe(i){let e=b(i);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(n=>{let t=b(n);if(typeof t.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:d(t.memberId),name:d(t.name),ready:t.ready,...t.profilePicture===void 0?{}:{profilePicture:{url:d(b(t.profilePicture).url)}}}}),limit:u(e.limit,1),offset:u(e.offset,0),nextOffset:e.nextOffset===null?null:u(e.nextOffset,0)}}function Ue(i){let e=b(i);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:d(e.conversationId),messageId:d(e.messageId),participantRevision:u(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(se),shareLayers:e.shareLayers.map(n=>{let t=b(n),r=d(t.id),s=d(t.dataShareId),o=d(t.keyShareId);if(t.type==="INHERITI_CHAIN")return{id:r,type:t.type,contractAddress:d(t.contractAddress),dataShareId:s,keyShareId:o};if(t.type==="INHERITI_VAULT"||t.type==="GOOGLE_DRIVE"||t.type==="DROPBOX"||t.type==="ONEDRIVE")return{id:r,type:t.type,dataShareId:s,keyShareId:o};throw new Error("invalid_inbox_response")})}}function X(i){let e=b(i);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:d(e.messageId),status:e.status}}function De(i){let e=b(i);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(n=>{let t=b(n);if(t.status!=="PREPARING"&&t.status!=="AVAILABLE"&&t.status!=="FAILED"&&t.status!=="DELETING")throw new Error("invalid_inbox_response");if(t.contentKind!==void 0&&t.contentKind!=="TEXT"&&t.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(t.recipientStatus!==void 0&&t.recipientStatus!=="UNREAD"&&t.recipientStatus!=="LEASED"&&t.recipientStatus!=="CONSUMED"&&t.recipientStatus!=="EXPIRED"&&t.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(t.recipientStatuses!==void 0&&!Array.isArray(t.recipientStatuses))throw new Error("invalid_inbox_response");let r={id:d(t.id),status:t.status,senderMemberId:d(t.senderMemberId),senderDeviceId:d(t.senderDeviceId),createdAt:A(t.createdAt),updatedAt:A(t.updatedAt),expiresAt:A(t.expiresAt)};return t.contentKind&&(r.contentKind=t.contentKind),t.recipientStatus&&(r.recipientStatus=t.recipientStatus),Array.isArray(t.recipientStatuses)&&(r.recipientStatuses=t.recipientStatuses.map(s=>{let o=b(s);if(o.status!=="UNREAD"&&o.status!=="LEASED"&&o.status!=="CONSUMED"&&o.status!=="EXPIRED"&&o.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:d(o.memberId),status:o.status,...o.consumedAt!==void 0?{consumedAt:o.consumedAt===null?null:A(o.consumedAt)}:{}}})),r}),total:u(e.total,0),limit:u(e.limit,1),offset:u(e.offset,0)}}function ke(i){let e=b(i);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:d(e.leaseId),leaseExpiresAt:A(e.leaseExpiresAt),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:u(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),tenantWrappedShareKey:d(e.tenantWrappedShareKey),wrappedContentKey:d(e.wrappedContentKey),shares:e.shares.map(n=>{let t=b(n);if(t.kind!=="DATA"&&t.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:t.kind,index:u(t.index,0),shareId:d(t.shareId),layerId:d(t.layerId),ciphertext:d(t.ciphertext)}})}}function Fe(i){let e=b(i);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:d(e.leaseId),leaseExpiresAt:A(e.leaseExpiresAt),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:u(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),tenantWrappedShareKey:d(e.tenantWrappedShareKey),wrappedContentKey:d(e.wrappedContentKey),shares:e.shares.map(n=>{let t=b(n);if(t.kind!=="DATA"&&t.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:t.kind,index:u(t.index,0),shareId:d(t.shareId),layerId:d(t.layerId)}})}}function B(i){return typeof i.error=="string"?/^[a-z][a-z0-9_]*$/.test(i.error)?i.error:typeof i.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(i.validationErrors)?i.validationErrors:i.error||void 0:i.error?.code??i.name??i.message}function V(i){return typeof i.error=="object"&&i.error?.requestId?i.error.requestId:i.description}var U=class extends Error{constructor(n,t,r,s){super(t??`elements_api_request_failed_${n}`);this.status=n;this.code=t;this.detail=r;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},J=class{constructor(e,n,t,r,s){this.apiUrl=e;this.environment=n;this.getBearerToken=t;this.transport=r;this.business=s?Object.freeze({...s}):void 0}business;getFileAccess(e,n){return this.request(`v1/file-accesses/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,n)}requestFileAccessOpening(e,n){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings`,"POST",n)}readFileAccessOpening(e,n,t,r){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(n)}`,"GET",void 0,void 0,{"x-client-key-hash":t},r)}confirmFileAccessDelivery(e,n,t){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(n)}/confirm-delivery`,void 0,{"x-client-key-hash":t})}createInboxFileAccess(e,n,t,r){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/file-accesses`,"POST",t,void 0,void 0,r)}createRevealFileAccess(e,n,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",n,void 0,void 0,t)}cancelRevealFileAccess(e,n,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(n)}`,void 0,void 0,"DELETE",t)}cancelInboxFileAccess(e,n,t,r){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",r)}async getOwnFileAccessIdentityKey(e){let n=await this.request("v1/inbox/devices/me/identity-key","GET",void 0,void 0,void 0,e);if(n===null)return null;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_file_access_identity_key");let t=n;if(typeof t.publicKey!="string"||!t.publicKey||typeof t.fingerprint!="string"||!t.fingerprint||t.status!=="ACTIVE"&&t.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:t.publicKey,fingerprint:t.fingerprint,status:t.status}}async getOwnInboxDevice(e){let n=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return n===null?null:$(n)}async getMemberInboxDevice(e,n){let t=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,n);return t===null?null:$(t)}async registerInboxDevice(e){return $(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return $(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return $(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return Y(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,n){return Y(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:n.action,memberId:n.memberId,expectedRevision:n.expectedRevision}))}async listInboxConversations(e={},n){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset));let r=t.size?`?${t}`:"";return Ke(await this.request(`v1/inbox/conversations${r}`,"GET",void 0,void 0,void 0,n))}async listInboxParticipants(e={},n){let t=new URLSearchParams;e.q!==void 0&&t.set("q",e.q),e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset));let r=t.size?`?${t}`:"";return Ne(await this.request(`v1/inbox/participants${r}`,"GET",void 0,void 0,void 0,n))}async listInboxMembers(e={},n){let t=new URLSearchParams;e.q!==void 0&&t.set("q",e.q),e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset));let r=t.size?`?${t}`:"";return Oe(await this.request(`v1/inbox/members${r}`,"GET",void 0,void 0,void 0,n))}async getInboxSendPreparation(e,n){return Ue(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,n))}async getNormalInboxSendPreparation(e,n){return Re(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,n))}async publishInboxMessage(e,n){let t={messageId:n.messageId,senderDeviceId:n.senderDeviceId,participantRevision:n.participantRevision,expiresAt:n.expiresAt,idempotencyKey:n.idempotencyKey,canonicalManifest:n.canonicalManifest,signature:n.signature,tenantWrappedShareKey:n.tenantWrappedShareKey,recipients:n.recipients.map(r=>({memberId:r.memberId,deviceId:r.deviceId,deviceVersion:r.deviceVersion,keyFingerprint:r.keyFingerprint,wrappedContentKey:r.wrappedContentKey})),shares:n.shares.map(r=>({kind:r.kind,index:r.index,shareId:r.shareId,layerId:r.layerId,ciphertext:r.ciphertext}))};return X(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",t))}async publishNormalInboxMessage(e,n){return ie(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",n))}async publishInboxParent(e,n){return ie(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",n))}async listInboxParents(e,n={},t){let r=new URLSearchParams;n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let s=r.size?`?${r}`:"";return Ae(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,t))}async openInboxParent(e,n,t,r){let s=new URLSearchParams({deviceId:t});return Ee(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(n)}?${s}`,"GET",void 0,void 0,void 0,r))}async clearInboxHistory(e,n){return Te(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,n))}async listNormalInboxMessages(e,n={},t){let r=new URLSearchParams;n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let s=r.size?`?${r}`:"";return _e(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,t))}async openNormalInboxMessage(e,n,t,r){let s=new URLSearchParams({deviceId:t});return Me(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(n)}?${s}`,"GET",void 0,void 0,void 0,r))}async markNormalInboxMessageRead(e,n,t){return Ce(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(n)}/read`,"POST",{deviceId:t}))}async stageInboxFile(e,n,t){return X(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",n,void 0,void 0,t))}async uploadInboxFileShare(e,n,t,r,s){if(r.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let o=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/shares/${encodeURIComponent(t)}`,a=await this.requestBinary(o,"PUT",r,s),c=await Q(a,s);if(!c.ok||c.result?.shareId!==t||c.result.status!=="STORED")throw new U(a.status,B(c),V(c),a.headers.get("x-request-id")??void 0)}async publishInboxFile(e,n,t){return X(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/publish`,"POST",void 0,void 0,void 0,t))}async openInboxFile(e,n,t,r){return Fe(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/open/file`,"POST",{deviceId:t},void 0,void 0,r))}async downloadInboxFileShare(e,n,t,r,s,o){let a=new URLSearchParams({deviceId:r,leaseId:s}),c=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/shares/${encodeURIComponent(t)}?${a}`,l=await this.requestBinary(c,"GET",void 0,o);if(!l.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let I=Number(l.headers.get("content-length"));if(Number.isFinite(I)&&I>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!l.body)throw new Error("invalid_inbox_share_response");let g=l.body.getReader(),f=[],v=0;try{for(;;){o?.throwIfAborted();let O=await g.read();if(O.done)break;if(v+=O.value.length,v>14*1024*1024)throw new Error("invalid_inbox_share_size");f.push(O.value)}}catch(O){throw await g.cancel().catch(()=>{}),O}let N=new Uint8Array(v),T=0;for(let O of f)N.set(O,T),T+=O.length;return N}async listInboxMessages(e,n={},t){let r=new URLSearchParams;n.status&&r.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:n.status}])),n.limit!==void 0&&r.set("filter[limit]",String(n.limit)),n.offset!==void 0&&r.set("filter[skip]",String(n.offset));let s=r.size?`?${r}`:"";return De(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,t))}async openInboxMessage(e,n,t){return ke(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/open`,"POST",{deviceId:t}))}async ackInboxMessage(e,n,t,r,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/ack`,"POST",{deviceId:t,leaseId:r},void 0,void 0,s)}async releaseInboxMessage(e,n,t,r){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/release`,"POST",{deviceId:t,leaseId:r})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(we)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let n=new URLSearchParams;e.cursor&&n.set("cursor",e.cursor),e.limit!==void 0&&n.set("limit",String(e.limit));for(let r of e.status??[])n.append("status",r);e.assetType&&n.set("assetType",e.assetType),e.namePrefix&&n.set("namePrefix",e.namePrefix);let t=n.size?`?${n}`:"";return fe(await this.request(`v1/plans${t}`,"GET"))}async getPlan(e){return Pe(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,n={}){let t=new URLSearchParams;n.limit!==void 0&&t.set("limit",String(n.limit)),n.offset!==void 0&&t.set("offset",String(n.offset));let r=t.size?`?${t}`:"";return he(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${r}`,"GET"))}async listMemberLogs(e,n={}){let t=new URLSearchParams;n.source&&t.set("source",n.source),n.from&&t.set("from",n.from),n.to&&t.set("to",n.to),n.limit!==void 0&&t.set("limit",String(n.limit)),n.offset!==void 0&&t.set("offset",String(n.offset));let r=t.size?`?${t}`:"";return xe(await this.request(`v1/members/${encodeURIComponent(e)}/logs${r}`,"GET"))}async startPlanCreation(e){Ie(e);let{idempotencyKey:n,...t}=e;return G(await this.request("v1/plan-creations","POST",t,void 0,{"idempotency-key":n}))}async getPlanCreation(e){return G(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,n){return ue(n),G(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",n))}async cancelPlanCreation(e){return G(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,n){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(n)}`,"GET")}startMasterKeyRelaySession(e,n){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...n})}readMasterKeyRelaySession(e,n){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,n)}async cancelMasterKeyRelaySession(e,n){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,n)}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,n){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,n)}initializeGovernedReveal(e,n){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,n)}getGovernedReveal(e,n){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,n)}collectGovernedValidatorShares(e,n){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,n)}collectGovernedShares(e,n){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,n)}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,n){let{idempotencyKey:t,...r}=n;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",r,void 0,{"idempotency-key":t})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,n){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,n)}releaseRevealMaterial(e,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:n})}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,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,n)}getRevealCustodianShare(e,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,n)}getRevealCustodianClaimable(e,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,n)}claimRevealCustodianShare(e,n,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:n,deviceId:t})}collectRevealCustodianShare(e,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:n})}reportRevealReconstruction(e,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",n)}closeReveal(e,n,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:n},void 0,void 0,t)}abortPlanAccess(e,n){let t=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(n?`${t}?revealId=${encodeURIComponent(n)}`:t,"DELETE")}authorizeRevealAction(e,n){let{idempotencyKey:t,...r}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",r,void 0,{"idempotency-key":t})}reportRevealActionOutcome(e,n,t){let{idempotencyKey:r,...s}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(n)}/outcome`,"PUT",s,void 0,{"idempotency-key":r})}getCustodianShare(e,n){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,n)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,n){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",n)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,n,t,r,s,o){this.requireBusinessSelection(e),o?.throwIfAborted();let a=await this.getBearerToken();o?.throwIfAborted();let c=new Headers({"x-elements-environment":this.environment});a&&c.set("authorization",`Bearer ${a}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&c.set("x-organization-id",this.business.organizationId),r?.requestId&&c.set("x-elements-step-up-request",r.requestId);for(let[v,N]of Object.entries(s??{}))c.set(v,N);t&&c.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,I={method:n,headers:c,body:t?JSON.stringify(t):void 0};o&&(I.signal=o);let g=await this.transport(new URL(e,l),I);o?.throwIfAborted();let f=await Q(g,o);if(o?.throwIfAborted(),!g.ok)throw new U(g.status,B(f),V(f),g.headers.get("x-request-id")??void 0);if(!f.ok||f.result===void 0)throw new U(g.status,B(f),V(f),g.headers.get("x-request-id")??void 0);return f.result}async requestBinary(e,n,t,r){this.requireBusinessSelection(e),r?.throwIfAborted();let s=await this.getBearerToken();r?.throwIfAborted();let o=new Headers({"x-elements-environment":this.environment});s&&o.set("authorization",`Bearer ${s}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId),t&&o.set("content-type","application/octet-stream");let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,a),{method:n,headers:o,body:t?Buffer.from(t):void 0,signal:r});if(r?.throwIfAborted(),!c.ok){let l=await Q(c,r);throw new U(c.status,B(l),V(l),c.headers.get("x-request-id")??void 0)}return c}async requestWithoutResult(e,n,t,r="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let o=await this.getBearerToken(),a=new Headers({"x-elements-environment":this.environment});o&&a.set("authorization",`Bearer ${o}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId);for(let[g,f]of Object.entries(t??{}))a.set(g,f);n&&a.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l=await this.transport(new URL(e,c),{method:r,headers:a,body:n?JSON.stringify(n):void 0,signal:s}),I=await Q(l,s);if(s?.throwIfAborted(),!l.ok||!I.ok)throw new U(l.status,B(I),V(I),l.headers.get("x-request-id")??void 0)}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new U(400,"organization_selection_required")}};async function Q(i,e){try{return await i.json()}catch(n){if(e?.throwIfAborted(),n instanceof Error&&n.name==="AbortError")throw n;return{ok:!1}}}import{generateInheritiFileKey as ln,sealInheritiFile as pn,readInheritiFileHeader as St,openInheritiFile as At,InheritiFileInvalid as Et,MAX_INHERITI_FILE_BYTES as Rt}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as mn,openInheritiFileKey as Tt}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{createHash as un,webcrypto as In}from"node:crypto";import{canonicalInboxManifest as gn,decodeInboxManifest as bn,decodeInboxContentFrame as yn,decodeInboxText as fn,decryptInboxShare as hn,encodeInboxContentFrame as oe,encodeInboxText as xn,encryptInboxShare as Le,inboxProtectedUnitCommitment as Pn,inboxTextMetadataDigest as qe,openInboxContent as vn,sealInboxContent as wn,signInboxFrame as Sn,unwrapInboxContentKey as An,unwrapInboxShareKey as En,verifyInboxFrame as $e,wrapInboxContentKey as Rn,wrapInboxShareKey as _n}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as Cn}from"@safetech/inheriti-core-sdk/workers/inbox.node";var K=In,x=K,h=i=>{if(!/^[0-9a-fA-F]{64}$/.test(i))throw new Error("invalid_inbox_key");return Buffer.from(i,"hex")},p=i=>{let e=Buffer.from(i,"base64");if(!i||e.toString("base64")!==i)throw new Error("invalid_inbox_base64");return Uint8Array.from(e)},_=(i,e)=>i.length===e.length&&i.every((n,t)=>n===e[t]),Z=async i=>new Uint8Array(await x.subtle.digest("SHA-256",Uint8Array.from(i))),z=i=>un("sha256").update(i).digest("hex"),q=class{constructor(e,n=new Cn){this.api=e;this.worker=n}async send(e){let n=await this.prepare(e);return this.api.publishInboxMessage(e.conversationId,n.submission)}async prepare(e){let{preparation:n,sender:t}=await this.prepareSender(e),r=await this.textManifest(e,n,t),s=gn(r),o=await Z(s),{contentKey:a,frame:c}=await wn(xn(e.text),o,x),l=await this.signFrame(r,c,e.identity.signingPrivateKey,t.signingPublicKey),{shareKey:I,shares:g}=await this.protectShares(n,c,o),f=await this.wrapRecipientKeys(n,a,o),v=await _n(I,h(e.tenantKeyHex),o,r.tenantId,r.messageId,x);return{frame:Buffer.from(oe(c)).toString("base64"),submission:{messageId:n.messageId,senderDeviceId:t.deviceId,participantRevision:n.participantRevision,expiresAt:e.expiresAt,idempotencyKey:n.messageId,canonicalManifest:Buffer.from(s).toString("base64"),signature:Buffer.from(l).toString("base64"),tenantWrappedShareKey:Buffer.from(v).toString("base64"),recipients:f,shares:g}}}async open(e){return this.openWithCommitment(e)}openCommitted(e,n){return this.openWithCommitment(e,n)}async openWithCommitment(e,n){let t=await this.api.openInboxMessage(e.conversationId,e.messageId,e.identity.deviceId),r;try{e.signal?.throwIfAborted();let{manifest:o,manifestDigest:a,senderPublicDer:c}=await this.verifyOpening(e,t),l=await this.recoverFrame(t,o,a,e.tenantKeyHex);if(n&&!_(n,await Pn(o,oe(l),p(t.signature),x)))throw new Error("inbox_parent_unit_mismatch");r=await this.decryptText(t,l,o,a,c,e.identity.encryptionPrivateKey),e.signal?.throwIfAborted()}catch(o){try{await this.api.releaseInboxMessage(e.conversationId,e.messageId,e.identity.deviceId,t.leaseId)}catch{}throw o}let s=await this.ack(e.conversationId,e.messageId,e.identity.deviceId,t.leaseId,e.signal);return e.signal?.throwIfAborted(),{text:r,leaseId:t.leaseId,leaseExpiresAt:t.leaseExpiresAt,acknowledgement:s}}async ack(e,n,t,r,s){for(let o=0;o<2;o++){s?.throwIfAborted();try{return await this.api.ackInboxMessage(e,n,t,r,s),s?.throwIfAborted(),"ACKNOWLEDGED"}catch(a){if(s?.throwIfAborted(),a instanceof U&&a.status>=400&&a.status<500)throw a}}return"PENDING"}async prepareSender(e){let n=await this.api.getInboxSendPreparation(e.conversationId);if(n.conversationId!==e.conversationId||n.threshold!==n.total||n.total!==n.shareLayers.length||n.total<2)throw new Error("invalid_inbox_preparation");let t=n.recipients.find(r=>r.memberId===e.identity.memberId);if(!t||t.deviceId!==e.identity.deviceId||t.signingPublicKey!==e.identity.signingPublicKey||t.encryptionPublicKey!==e.identity.encryptionPublicKey||z(p(t.signingPublicKey))!==t.signingKeyFingerprint||z(p(t.encryptionPublicKey))!==t.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return{preparation:n,sender:t}}async textManifest(e,n,t){let r=Date.parse(e.expiresAt);if(!Number.isSafeInteger(r)||r<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:e.identity.tenantId,conversationId:e.conversationId,messageId:n.messageId,senderId:e.identity.memberId,senderDeviceId:t.deviceId,senderSigningKeyFingerprint:h(t.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(s=>({memberId:s.memberId,deviceId:s.deviceId,encryptionKeyFingerprint:h(s.encryptionKeyFingerprint)})),expiresAtEpochMs:r,metadataDigest:await qe(x)}}async signFrame(e,n,t,r){let s=await x.subtle.importKey("pkcs8",p(t),"Ed25519",!1,["sign"]),o=await Sn(e,n,s,x),a=await x.subtle.importKey("spki",p(r),"Ed25519",!1,["verify"]);if(!await $e(e,n,o,a,x))throw new Error("inbox_identity_mismatch");return o}async protectShares(e,n,t){let r=await this.worker.split(oe(n),{threshold:e.threshold,total:e.total,messageId:e.messageId,manifestDigest:t}),s=x.getRandomValues(new Uint8Array(32)),o=[];for(let a=0;a<e.total;a++){let c=e.shareLayers[a];o.push({kind:"DATA",index:a,shareId:c.dataShareId,layerId:c.id,ciphertext:Buffer.from(await Le(r.dataShares[a],s,t,e.messageId,x)).toString("base64")}),o.push({kind:"KEY",index:a,shareId:c.keyShareId,layerId:c.id,ciphertext:Buffer.from(await Le(r.keyShares[a],s,t,e.messageId,x)).toString("base64")})}return{shareKey:s,shares:o}}async wrapRecipientKeys(e,n,t){return Promise.all(e.recipients.map(async r=>{let s=p(r.encryptionPublicKey);if(z(s)!==r.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let o=await x.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:r.memberId,deviceId:r.deviceId,deviceVersion:r.deviceVersion,keyFingerprint:r.encryptionKeyFingerprint,wrappedContentKey:Buffer.from(await Rn(n,o,t,x)).toString("base64")}}))}async verifyOpening(e,n,t){let r=p(n.canonicalManifest),s=bn(r);if(s.tenantId!==e.identity.tenantId||s.conversationId!==e.conversationId||s.messageId!==e.messageId||s.expiresAtEpochMs<=Date.now()||!_(s.metadataDigest,t??await qe(x)))throw new Error("inbox_manifest_mismatch");let o=s.recipients.find(c=>c.memberId===e.identity.memberId&&c.deviceId===e.identity.deviceId);if(!o||!_(o.encryptionKeyFingerprint,h(z(p(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let a=p(n.senderSigningPublicKey);if(n.senderSigningKeyFingerprint!==z(a)||!_(s.senderSigningKeyFingerprint,h(n.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return{manifest:s,manifestDigest:await Z(r),senderPublicDer:a}}async recoverFrame(e,n,t,r){let s=await En(p(e.tenantWrappedShareKey),h(r),t,n.tenantId,n.messageId,x),o=[],a=[],c=new Set;for(let I of e.shares){let g=`${I.kind}:${I.index}`;if(c.has(g))throw new Error("duplicate_inbox_share");c.add(g);let f=await hn(p(I.ciphertext),s,t,n.messageId,I.kind==="DATA"?"data":"key",I.index,x);(I.kind==="DATA"?o:a).push(f)}if(o.length!==a.length||o.length<2)throw new Error("incomplete_inbox_shares");let l=await this.worker.reconstruct(o,a,{threshold:o.length,total:o.length,messageId:n.messageId,manifestDigest:t});return yn(l)}async decryptText(e,n,t,r,s,o){return fn(await this.decryptContent(e,n,t,r,s,o))}async decryptContent(e,n,t,r,s,o){let a=await x.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await $e(t,n,p(e.signature),a,x))throw new Error("inbox_signature_invalid");let c=await x.subtle.importKey("pkcs8",p(o),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),l=await An(p(e.wrappedContentKey),c,r,x);return vn(n,l,r,x)}};import{canonicalInboxManifest as Tn,decodeInboxContentFrame as Mn,decodeInboxFile as Kn,decryptInboxShare as Nn,encodeInboxContentFrame as On,encodeInboxFile as Un,encryptInboxShare as Ge,inboxFileMetadataDigest as Be,sealInboxContent as Dn,unwrapInboxShareKey as kn,wrapInboxShareKey as Fn}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var ae=class extends q{constructor(n){super(n);this.fileApi=n}async sendFile(n){n.signal?.throwIfAborted();let{preparation:t,sender:r}=await this.prepareSender(n),s=await this.fileManifest(n,t,r),o=Tn(s),a=await Z(o),c=Un(n.file),l;try{l=await Dn(c,a,K)}finally{c.fill(0)}let{contentKey:I,frame:g}=l,f=await this.signFrame(s,g,n.identity.signingPrivateKey,r.signingPublicKey);n.signal?.throwIfAborted();let v=await this.worker.split(On(g),{threshold:t.threshold,total:t.total,messageId:t.messageId,manifestDigest:a},n.signal,w=>n.onProgress?.(0,t.total*2,w.stage));n.signal?.throwIfAborted();let N=K.getRandomValues(new Uint8Array(32)),T=[];for(let w=0;w<t.total;w++){let F=t.shareLayers[w];T.push({reference:{kind:"DATA",index:w,shareId:F.dataShareId,layerId:F.id},bytes:await Ge(v.dataShares[w],N,a,t.messageId,K)}),T.push({reference:{kind:"KEY",index:w,shareId:F.keyShareId,layerId:F.id},bytes:await Ge(v.keyShares[w],N,a,t.messageId,K)})}let O=await this.wrapRecipientKeys(t,I,a),Ye=await Fn(N,h(n.tenantKeyHex),a,s.tenantId,s.messageId,K);n.signal?.throwIfAborted();let le=await this.fileApi.stageInboxFile(n.conversationId,{messageId:t.messageId,senderDeviceId:r.deviceId,participantRevision:t.participantRevision,expiresAt:n.expiresAt,idempotencyKey:t.messageId,canonicalManifest:Buffer.from(o).toString("base64"),signature:Buffer.from(f).toString("base64"),tenantWrappedShareKey:Buffer.from(Ye).toString("base64"),recipients:O,shares:T.map(w=>w.reference)},n.signal);if(le.messageId!==t.messageId||le.status!=="PREPARING")throw new Error("invalid_inbox_stage");for(let w=0;w<T.length;w++){n.signal?.throwIfAborted();let F=T[w];await this.fileApi.uploadInboxFileShare(n.conversationId,t.messageId,F.reference.shareId,F.bytes,n.signal),n.onProgress?.(w+1,T.length,"UPLOADING")}n.signal?.throwIfAborted();let te=await this.fileApi.publishInboxFile(n.conversationId,t.messageId,n.signal);if(te.messageId!==t.messageId||te.status!=="AVAILABLE")throw new Error("invalid_inbox_publish");return te}async openFile(n){n.signal?.throwIfAborted();let t=await this.fileApi.openInboxFile(n.conversationId,n.messageId,n.identity.deviceId,n.signal),r,s;try{let{manifest:a,manifestDigest:c,senderPublicDer:l}=await this.verifyOpening(n,t,await Be(K)),I=await this.recoverFileFrame(n,t,a,c);s=await this.decryptContent(t,I,a,c,l,n.identity.encryptionPrivateKey),r=Kn(s),n.signal?.throwIfAborted(),await n.save(r,{leaseId:t.leaseId,leaseExpiresAt:t.leaseExpiresAt}),n.signal?.throwIfAborted()}catch(a){try{await this.fileApi.releaseInboxMessage(n.conversationId,n.messageId,n.identity.deviceId,t.leaseId)}catch{}throw a}finally{s?.fill(0)}let o=await this.ack(n.conversationId,n.messageId,n.identity.deviceId,t.leaseId,n.signal);return n.signal?.throwIfAborted(),{name:r.name,mimeType:r.mimeType,size:r.bytes.length,leaseId:t.leaseId,leaseExpiresAt:t.leaseExpiresAt,acknowledgement:o}}async fileManifest(n,t,r){let s=Date.parse(n.expiresAt);if(!Number.isSafeInteger(s)||s<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:n.identity.tenantId,conversationId:n.conversationId,messageId:t.messageId,senderId:n.identity.memberId,senderDeviceId:r.deviceId,senderSigningKeyFingerprint:h(r.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(o=>({memberId:o.memberId,deviceId:o.deviceId,encryptionKeyFingerprint:h(o.encryptionKeyFingerprint)})),expiresAtEpochMs:s,metadataDigest:await Be(K)}}async recoverFileFrame(n,t,r,s){let o=await kn(p(t.tenantWrappedShareKey),h(n.tenantKeyHex),s,r.tenantId,r.messageId,K),a=[],c=[],l=new Set;for(let g=0;g<t.shares.length;g++){n.signal?.throwIfAborted();let f=t.shares[g],v=`${f.kind}:${f.index}`;if(l.has(v))throw new Error("duplicate_inbox_share");l.add(v);let N=await this.fileApi.downloadInboxFileShare(n.conversationId,n.messageId,f.shareId,n.identity.deviceId,t.leaseId,n.signal),T=await Nn(N,o,s,r.messageId,f.kind==="DATA"?"data":"key",f.index,K);(f.kind==="DATA"?a:c).push(T),n.onProgress?.(g+1,t.shares.length,"DOWNLOADING")}if(a.length!==c.length||a.length<2)throw new Error("incomplete_inbox_shares");n.signal?.throwIfAborted();let I=await this.worker.reconstruct(a,c,{threshold:a.length,total:a.length,messageId:r.messageId,manifestDigest:s},n.signal,g=>n.onProgress?.(t.shares.length,t.shares.length,g.stage));return n.signal?.throwIfAborted(),Mn(I)}};import{createHash as ze,webcrypto as Ln}from"node:crypto";import{canonicalInboxParentManifest as qn,decodeInboxParentManifest as $n,encodeInboxParentNormalFrame as Gn,decodeInboxParentNormalFrame as Bn,sealInboxParentNormalBody as Vn,openInboxParentNormalBody as zn,wrapInboxParentNormalKey as Hn,unwrapInboxParentNormalKey as Wn,signInboxParentNormalFrame as jn,verifyInboxParentNormalFrame as Ve,encodeInboxText as Yn,decodeInboxText as Xn}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var C=Ln,H=i=>ze("sha256").update(i).digest("hex"),ee=i=>Buffer.from(i).toString("base64"),de=class{constructor(e){this.api=e}pending=new Map;async send(e){let n=this.digestInput(e),t=e.parentId?this.pending.get(e.parentId):void 0;if(t){if(t.inputDigest!==n)throw new Error("inbox_idempotency_conflict");let l=await this.api.publishNormalInboxMessage(e.conversationId,t.submission);return this.pending.delete(e.parentId),l}let r=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validatePreparation(e,r),o=this.createManifest(e,r,s),a=await this.createSubmission(e,r,s,o);this.rememberSubmission(o.parentId,n,a);let c=await this.api.publishNormalInboxMessage(e.conversationId,a);return this.pending.delete(o.parentId),c}digestInput(e){return ze("sha256").update(JSON.stringify([e.conversationId,e.parentId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.text])).digest("hex")}validatePreparation(e,n){if(n.conversationId!==e.conversationId||n.recipients.length<2||n.recipients.length>50)throw new Error("invalid_inbox_preparation");let t=n.recipients.find(r=>r.memberId===e.identity.memberId&&r.deviceId===e.identity.deviceId);if(!t||t.signingPublicKey!==e.identity.signingPublicKey||t.encryptionPublicKey!==e.identity.encryptionPublicKey||H(p(t.signingPublicKey))!==t.signingKeyFingerprint||H(p(t.encryptionPublicKey))!==t.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return t}createManifest(e,n,t){return{mode:"NORMAL",tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:e.parentId??n.parentId,senderId:e.identity.memberId,senderDeviceId:t.deviceId,senderSigningKeyFingerprint:h(t.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(r=>({memberId:r.memberId,deviceId:r.deviceId,encryptionKeyFingerprint:h(r.encryptionKeyFingerprint)})),protectedUnits:[]}}async createSubmission(e,n,t,r){let s=qn(r),{contentKey:o,frame:a}=await Vn(Yn(e.text),r,C),c=await C.subtle.importKey("pkcs8",p(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),l=await jn(r,a,c,C),I=await C.subtle.importKey("spki",p(t.signingPublicKey),"Ed25519",!1,["verify"]);if(!await Ve(r,a,l,I,C))throw new Error("inbox_identity_mismatch");let g=await Promise.all(n.recipients.map(f=>this.wrapRecipientKey(f,o,r)));return{parentId:r.parentId,idempotencyKey:r.parentId,senderDeviceId:t.deviceId,participantRevision:n.participantRevision,canonicalManifest:ee(s),frame:ee(Gn(a)),signature:ee(l),recipients:g}}async wrapRecipientKey(e,n,t){let r=p(e.encryptionPublicKey);if(H(r)!==e.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await C.subtle.importKey("spki",r,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:e.memberId,deviceId:e.deviceId,deviceVersion:e.deviceVersion,keyFingerprint:e.encryptionKeyFingerprint,wrappedContentKey:ee(await Hn(n,s,t,C))}}rememberSubmission(e,n,t){if(this.pending.size>=32){let r=this.pending.keys().next().value;r&&this.pending.delete(r)}this.pending.set(e,{inputDigest:n,submission:t})}list(e,n,t){return this.api.listNormalInboxMessages(e,n,t)}async open(e){e.signal?.throwIfAborted();let n=await this.api.openNormalInboxMessage(e.conversationId,e.parentId,e.identity.deviceId,e.signal),t=$n(p(n.canonicalManifest));if(t.mode!=="NORMAL"||t.tenantId!==e.identity.tenantId||t.conversationId!==e.conversationId||t.parentId!==e.parentId||t.senderId!==n.senderMemberId||t.senderDeviceId!==n.senderDeviceId||t.participantRevision!==n.participantRevision)throw new Error("inbox_manifest_mismatch");let r=t.recipients.find(g=>g.memberId===e.identity.memberId&&g.deviceId===e.identity.deviceId);if(!r||!_(r.encryptionKeyFingerprint,h(H(p(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let s=p(n.senderSigningPublicKey);if(!_(t.senderSigningKeyFingerprint,h(H(s))))throw new Error("inbox_sender_key_mismatch");let o=Bn(p(n.frame)),a=await C.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Ve(t,o,p(n.signature),a,C))throw new Error("inbox_signature_invalid");let c=await C.subtle.importKey("pkcs8",p(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),l=await Wn(p(n.wrappedContentKey),c,t,C),I=Xn(await zn(o,l,t,C));return e.signal?.throwIfAborted(),{text:I,parentId:n.parentId,sequence:n.sequence}}markRead(e){return this.api.markNormalInboxMessageRead(e.conversationId,e.parentId,e.identity.deviceId)}};import{createHash as je,webcrypto as Qn}from"node:crypto";import{canonicalInboxParentManifest as Jn,decodeInboxParentManifest as Zn,decodeInboxManifest as et,encodeInboxParentNormalFrame as nt,decodeInboxParentNormalFrame as tt,sealInboxParentNormalBody as rt,openInboxParentNormalBody as it,wrapInboxParentNormalKey as st,unwrapInboxParentNormalKey as ot,signInboxParentNormalFrame as at,verifyInboxParentNormalFrame as He,signInboxProtectedParent as dt,verifyInboxProtectedParent as We,inboxProtectedUnitCommitment as ct,encodeInboxText as lt,decodeInboxText as pt}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var S=Qn,ne=i=>Buffer.from(i).toString("base64"),W=i=>je("sha256").update(i).digest("hex"),ce=class{constructor(e,n){this.api=e;this.child=n??new q(e)}pending=new Map;child;async send(e){let n=je("sha256").update(JSON.stringify([e.conversationId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.segments])).digest("hex"),t=e.parentId?[e.parentId,this.pending.get(e.parentId)]:[...this.pending.entries()].find(([,a])=>a.digest===n),r=t?.[1];if(r){if(r.digest!==n)throw new Error("inbox_idempotency_conflict");try{e.onProgress?.(r.submission.protectedUnits.length,r.submission.protectedUnits.length)}catch{}let a=await this.api.publishInboxParent(e.conversationId,r.submission);return this.pending.delete(t[0]),a}let s=await this.prepare(e);this.pending.size>=32&&this.pending.delete(this.pending.keys().next().value),this.pending.set(s.parentId,{digest:n,submission:s});let o=await this.api.publishInboxParent(e.conversationId,s);return this.pending.delete(s.parentId),o}async prepare(e){if(!e.segments.length||e.segments.length>9)throw new Error("invalid_inbox_parent_segments");let n=e.segments.filter(v=>"protectedText"in v).length;if(n<1||n>4)throw new Error("invalid_inbox_parent_segments");let t=e.segments.length===1&&n===1?"PROTECTED":"MIXED";if(t==="MIXED"&&!e.segments.some(v=>"text"in v))throw new Error("invalid_inbox_parent_segments");let r=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validateSender(e,r),o=e.parentId??r.parentId,{protectedUnits:a,manifestUnits:c}=await this.prepareChildren(e,r,s),l=this.parentManifest(e,r,s,o,t,c),{frame:I,signature:g,recipients:f}=await this.signAndWrap(e,r,s,l);return{parentId:o,idempotencyKey:o,senderDeviceId:s.deviceId,mode:t,participantRevision:r.participantRevision,canonicalManifest:ne(Jn(l)),signature:ne(g),frame:I,recipients:f,protectedUnits:a}}async prepareChildren(e,n,t){let r=[],s=[],o=e.segments.filter(a=>"protectedText"in a).length;for(let a=0;a<e.segments.length;a++){let c=e.segments[a];if(!("protectedText"in c))continue;let l=await this.child.prepare({conversationId:e.conversationId,text:c.protectedText,expiresAt:c.expiresAt,identity:e.identity,tenantKeyHex:e.tenantKeyHex}),I=et(p(l.submission.canonicalManifest));this.validateChildSnapshot(I,e,n,t);let g=await ct(I,p(l.frame),p(l.submission.signature),S);r.push({position:a,frame:l.frame,child:l.submission}),s.push({unitId:l.submission.messageId,position:a,commitment:g});try{e.onProgress?.(r.length,o)}catch{}}return{protectedUnits:r,manifestUnits:s}}validateChildSnapshot(e,n,t,r){if(e.tenantId!==n.identity.tenantId||e.conversationId!==n.conversationId||e.senderId!==n.identity.memberId||e.senderDeviceId!==r.deviceId||e.participantRevision!==t.participantRevision||e.recipients.length!==t.recipients.length||e.recipients.some(s=>!t.recipients.some(o=>o.memberId===s.memberId&&o.deviceId===s.deviceId&&_(s.encryptionKeyFingerprint,h(o.encryptionKeyFingerprint)))))throw new Error("inbox_child_snapshot_mismatch")}parentManifest(e,n,t,r,s,o){return{mode:s,tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:r,senderId:e.identity.memberId,senderDeviceId:t.deviceId,senderSigningKeyFingerprint:h(t.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(a=>({memberId:a.memberId,deviceId:a.deviceId,encryptionKeyFingerprint:h(a.encryptionKeyFingerprint)})),protectedUnits:o}}async signAndWrap(e,n,t,r){let s=await S.subtle.importKey("pkcs8",p(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),o=await S.subtle.importKey("spki",p(t.signingPublicKey),"Ed25519",!1,["verify"]);if(r.mode==="PROTECTED")return{signature:await this.signProtectedParent(r,s,o),recipients:this.recipientReferences(n)};let{frame:a,signature:c,contentKey:l}=await this.sealMixedParent(e,r,s,o);return{frame:a,signature:c,recipients:await this.wrapRecipients(n,l,r)}}async signProtectedParent(e,n,t){let r=await dt(e,n,S);if(!await We(e,r,t,S))throw new Error("inbox_identity_mismatch");return r}async sealMixedParent(e,n,t,r){let s=e.segments.map((c,l)=>"text"in c?{text:c.text}:{unitId:n.protectedUnits.find(I=>I.position===l).unitId}),o=await rt(lt(JSON.stringify(s)),n,S),a=await at(n,o.frame,t,S);if(!await He(n,o.frame,a,r,S))throw new Error("inbox_identity_mismatch");return{frame:ne(nt(o.frame)),signature:a,contentKey:o.contentKey}}recipientReferences(e){return e.recipients.map(n=>({memberId:n.memberId,deviceId:n.deviceId,deviceVersion:n.deviceVersion,keyFingerprint:n.encryptionKeyFingerprint}))}async wrapRecipients(e,n,t){return Promise.all(e.recipients.map(async r=>{let s=p(r.encryptionPublicKey);if(W(s)!==r.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let o=await S.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:r.memberId,deviceId:r.deviceId,deviceVersion:r.deviceVersion,keyFingerprint:r.encryptionKeyFingerprint,wrappedContentKey:ne(await st(n,o,t,S))}}))}validateSender(e,n){if(n.conversationId!==e.conversationId||n.recipients.length<2||n.recipients.length>50)throw new Error("invalid_inbox_preparation");let t=n.recipients.find(r=>r.memberId===e.identity.memberId&&r.deviceId===e.identity.deviceId);if(!t||t.signingPublicKey!==e.identity.signingPublicKey||t.encryptionPublicKey!==e.identity.encryptionPublicKey||W(p(t.signingPublicKey))!==t.signingKeyFingerprint||W(p(t.encryptionPublicKey))!==t.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return t}list(e,n,t){return this.api.listInboxParents(e,n,t)}clearHistory(e,n){return this.api.clearInboxHistory(e,n)}async open(e){let{opened:n,manifest:t,segments:r}=await this.openAndVerify(e);return{parentId:n.parentId,sequence:n.sequence,mode:t.mode,segments:r}}async openAndVerify(e){e.signal?.throwIfAborted();let n=await this.api.openInboxParent(e.conversationId,e.parentId,e.identity.deviceId,e.signal),{manifest:t,senderKey:r}=await this.verifyOpening(e,n),s=t.mode==="PROTECTED"?await this.openProtectedParent(n,t,r):await this.openMixedParent(e,n,t,r);return e.signal?.throwIfAborted(),{opened:n,manifest:t,segments:s}}async verifyOpening(e,n){let t=Zn(p(n.canonicalManifest));return this.verifyManifestContext(e,n,t),this.verifyManifestUnits(n,t),this.verifyRecipient(e,t),{manifest:t,senderKey:await this.senderKey(n,t)}}verifyManifestContext(e,n,t){if(t.mode!==n.mode||t.tenantId!==e.identity.tenantId||t.conversationId!==e.conversationId||t.parentId!==e.parentId||t.senderId!==n.senderMemberId||t.senderDeviceId!==n.senderDeviceId||t.participantRevision!==n.participantRevision)throw new Error("inbox_manifest_mismatch")}verifyManifestUnits(e,n){if(n.protectedUnits.length!==e.protectedUnits.length||n.protectedUnits.some((t,r)=>t.unitId!==e.protectedUnits[r].unitId||t.position!==e.protectedUnits[r].position||!_(t.commitment,h(e.protectedUnits[r].commitment))))throw new Error("inbox_manifest_mismatch")}verifyRecipient(e,n){let t=n.recipients.find(r=>r.memberId===e.identity.memberId&&r.deviceId===e.identity.deviceId);if(!t||!_(t.encryptionKeyFingerprint,h(W(p(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch")}async senderKey(e,n){let t=p(e.senderSigningPublicKey);if(W(t)!==e.senderSigningKeyFingerprint||!_(n.senderSigningKeyFingerprint,h(e.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return S.subtle.importKey("spki",t,"Ed25519",!1,["verify"])}async openProtectedParent(e,n,t){if(e.frame!==null||e.wrappedContentKey!==null||!await We(n,p(e.signature),t,S))throw new Error("inbox_signature_invalid");return[{unitId:n.protectedUnits[0].unitId,position:0,status:e.protectedUnits[0].status}]}async openMixedParent(e,n,t,r){if(!n.frame||!n.wrappedContentKey)throw new Error("inbox_missing_normal_body");let s=tt(p(n.frame));if(!await He(t,s,p(n.signature),r,S))throw new Error("inbox_signature_invalid");let o=await S.subtle.importKey("pkcs8",p(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),a=await ot(p(n.wrappedContentKey),o,t,S),c=JSON.parse(pt(await it(s,a,t,S)));return this.decodeSegments(c,n,t)}decodeSegments(e,n,t){if(!Array.isArray(e))throw new Error("invalid_inbox_parent_body");let r=e.map((s,o)=>{if(!s||typeof s!="object"||Array.isArray(s))throw new Error("invalid_inbox_parent_body");let a=s;if(typeof a.text=="string"&&Object.keys(a).length===1)return{text:a.text};let c=t.protectedUnits.find(l=>l.position===o);if(!c||a.unitId!==c.unitId||Object.keys(a).length!==1)throw new Error("invalid_inbox_parent_body");return{unitId:c.unitId,position:o,status:n.protectedUnits.find(l=>l.unitId===c.unitId).status}});if(t.protectedUnits.some(s=>!r[s.position]||!("unitId"in r[s.position])))throw new Error("invalid_inbox_parent_body");return r}async revealUnit(e){let{manifest:n,segments:t}=await this.openAndVerify(e);if(!t.some(s=>"unitId"in s&&s.unitId===e.unitId))throw new Error("inbox_parent_unit_mismatch");let r=n.protectedUnits.find(s=>s.unitId===e.unitId);return this.child.openCommitted({conversationId:e.conversationId,messageId:e.unitId,identity:e.identity,tenantKeyHex:e.tenantKeyHex,signal:e.signal},r.commitment)}};export{J as HttpElementsApiPort,ae as NodeInboxFile,de as NodeInboxNormal,ce as NodeInboxParent,q as NodeInboxText,ln as generateInheritiFileKey,pn as sealInheritiFile,mn as sealInheritiFileKey};
|
|
1
|
+
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"],dn={"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"]},he=["VALIDATED","PLAN_CREATED","PARTICIPANTS_PERSISTED","STORAGE_PREPARED","AWAITING_ENCRYPTED_MATERIAL","VALIDATOR_SHARES_DISTRIBUTED","CONFIGURED","COMPLETED"],f=class extends Error{constructor(n){super(n);this.code=n;this.name="InvalidPlanDeclaration"}},L=class extends Error{constructor(n){super(n);this.code=n;this.name="InvalidPlanMaterial"}};function xe(i){let e=["protectionProtocol","validatorShares","dataShards","backupShards","encryptedKey","assetsMetadata","custodianShard","operation"];if(Object.keys(i).some(n=>!e.includes(n)))throw new L("plan_material_field_unknown");if(ce(i.dataShards,"data_shards_invalid"),ce(i.backupShards,"backup_shards_invalid"),i.validatorShares!==void 0&&ce(i.validatorShares,"validator_shares_invalid"),i.validatorShares?.length&&!i.encryptedKey)throw new L("validator_shares_require_encrypted_key");if(i.protectionProtocol!==void 0&&i.protectionProtocol!=="SSDP_PLUS_V1"&&i.protectionProtocol!=="SSDP_PLUS_V2")throw new L("protection_protocol_invalid");if(i.operation!==void 0&&i.operation!=="DRAFT"&&i.operation!=="FINALIZE")throw new L("material_operation_invalid")}function ce(i,e){if(!Array.isArray(i))throw new L(e);for(let n of i){if(typeof n!="object"||n===null||typeof n.id!="string"||!n.id)throw new L(e);if(n.data!==void 0&&typeof n.data!="string")throw new L(e)}}function Pe(i){if(z(i,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!pn(i.idempotencyKey))throw new f("idempotency_key_invalid");if(!i.name?.trim())throw new f("plan_name_required");if(!i.assets.length)throw new f("assets_required");let e=new Set;for(let n of i.assets){if(z(n,["clientAssetRef","type","name","fieldNames","matchOrigins","isBinary","fileName","mimeType","size"],"asset_declaration_field_unknown"),!n.clientAssetRef?.trim()||!/^[A-Za-z0-9_-]+$/u.test(n.clientAssetRef)||e.has(n.clientAssetRef))throw new f("client_asset_ref_invalid");if(e.add(n.clientAssetRef),!J.includes(n.type))throw new f("asset_type_invalid");let t=n.type==="DOCUMENT"||n.type==="IMAGE"||n.type==="VIDEO";if(n.isBinary!==t)throw new f("asset_binary_representation_invalid");let r=n.fieldNames??[];if(n.isBinary&&(r.length||!n.fileName||!n.mimeType||!Number.isSafeInteger(n.size)||n.size<0))throw new f("binary_asset_metadata_invalid");if(!n.isBinary&&(!r.length||n.fileName!==void 0||n.mimeType!==void 0||n.size!==void 0))throw new f("structured_asset_metadata_invalid");if(new Set(r).size!==r.length||r.some(s=>!s.trim()))throw new f("asset_field_names_invalid");if(cn(n.matchOrigins),!n.isBinary){let s=dn[n.type];if(!s||r.some(o=>!s.includes(o)))throw new f("asset_field_name_not_canonical")}}if(!i.participants.length)throw new f("participants_required");for(let n of i.participants){if(z(n,["clientParticipantRef","routingEmail","displayName","relationships"],"participant_field_unknown"),!n.clientParticipantRef?.trim()||!n.displayName?.trim()||!we(n.routingEmail))throw new f("participant_invalid");if(!n.relationships.length||n.relationships.includes("ALLOW")&&n.relationships.includes("DENY"))throw new f("participant_relationships_invalid")}ln(i)}function cn(i){if(i===void 0)return;if(!i.length)throw new f("asset_match_origins_invalid");let e=i.map(n=>{if(typeof n!="string"||!n.trim())throw new f("asset_match_origin_invalid");try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol)||t.origin!==n.trim())throw new f("asset_match_origin_invalid");return t.origin}catch(t){throw t instanceof f?t:new f("asset_match_origin_invalid")}});if(new Set(e).size!==e.length)throw new f("asset_match_origins_duplicated")}function ln(i){let e=i.policy;if(e&&z(e,["authentication","moderation","dms"],"plan_policy_field_unknown"),!e?.authentication&&!e?.moderation&&!e?.dms)throw new f("governance_mechanism_required");if(e.authentication!==void 0&&typeof e.authentication!="boolean"){z(e.authentication,["mode"],"plan_authentication_field_unknown");let s=e.authentication.mode;if(s!==void 0&&s!=="EXCLUSIVE"&&s!=="ALL_REQUIRED")throw new f("authentication_mode_invalid")}if(e.moderation){z(e.moderation,["minimumApprovals","approvalMode"],"plan_moderation_field_unknown");let s=i.participants.filter(c=>c.relationships.includes("MODERATOR"));if(s.length===0)throw new f("moderation_requires_moderators");let o=e.moderation.minimumApprovals;if(o!==void 0&&(!Number.isInteger(o)||o<1||o>s.length))throw new f("minimum_approvals_invalid");let a=e.moderation.approvalMode;if(a!==void 0&&a!=="THRESHOLD"&&a!=="UNANIMOUS")throw new f("approval_mode_invalid")}let n=e.dms;if(!n)return;z(n,["subjectEmail","countdownDays","countdownHours","countdownMinutes"],"plan_dms_field_unknown");let t=n.countdownHours??0,r=n.countdownMinutes??0;if(!we(n.subjectEmail))throw new f("dms_subject_invalid");if(!i.participants.some(s=>ye(s.routingEmail)===ye(n.subjectEmail)))throw new f("dms_subject_not_participant");if(!Number.isInteger(n.countdownDays)||!Number.isInteger(t)||!Number.isInteger(r)||n.countdownDays<0||t<0||t>23||r<0||r>59||n.countdownDays+t+r===0)throw new f("dms_countdown_invalid")}function pn(i){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(i)}function we(i){return typeof i=="string"&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(i.normalize("NFC").trim())}function ye(i){return i.normalize("NFC").trim().toLowerCase()}function z(i,e,n){if(Object.keys(i).some(t=>!e.includes(t)))throw new f(n)}var mn=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],un=["DIRECT","GOVERNED"],Se=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],gn=["ACTIVE","REVOKED"],In=["SK_MOBILE"],bn=["ACTIVE","INACTIVE"],fn=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function Ae(i){let e=w(i);return{items:C(e.items).map(Ce),nextCursor:e.nextCursor===null?null:m(e.nextCursor,"nextCursor")}}function Ee(i){let e=w(i);return{total:K(e.total,"total"),items:C(e.items).map(n=>{let t=w(n);if("eventData"in t)throw new Error("invalid_elements_response");return{id:m(t.id,"log.id"),planId:m(t.planId,"log.planId"),tenantId:m(t.tenantId,"log.tenantId"),event:m(t.event,"log.event"),occurredOn:m(t.occurredOn,"log.occurredOn"),status:F(t.status),title:m(t.title,"log.title"),details:C(t.details).map(r=>{let s=w(r);return{label:m(s.label,"log.detail.label"),value:m(s.value,"log.detail.value")}})}})}}function Re(i){let e=w(i);return{total:K(e.total,"total"),items:C(e.items).map(n=>{let t=w(n);if("eventData"in t)throw new Error("invalid_elements_response");let r=m(t.source,"log.source");if(r!=="MEMBER"&&r!=="AUTOMATION")throw new Error("invalid_elements_response");return{id:m(t.id,"log.id"),memberId:m(t.memberId,"log.memberId"),source:r,event:m(t.event,"log.event"),occurredOn:m(t.occurredOn,"log.occurredOn"),status:F(t.status)}})}}function _e(i){let e=w(i),n=Ce(e),t=w(e.source),r=m(t.kind,"source.kind");return{...n,assets:C(e.assets).map(s=>{let o=w(s);return{id:m(o.id,"asset.id"),code:F(o.code),type:_(m(o.type,"asset.type"),J),name:m(o.name,"asset.name"),isBinary:hn(o.isBinary,"asset.isBinary"),fieldNames:C(o.fieldNames).map(a=>m(a,"asset.fieldNames")),fileName:F(o.fileName),mimeType:F(o.mimeType),size:o.size===void 0||o.size===null?void 0:K(o.size,"asset.size"),matchOrigins:o.matchOrigins===void 0?void 0:C(o.matchOrigins).map(a=>m(a,"asset.matchOrigins"))}}),participants:C(e.participants).map(s=>{let o=w(s);return{id:m(o.id,"participant.id"),displayName:m(o.displayName,"participant.displayName"),relationships:C(o.relationships).map(a=>_(m(a,"relationship"),Se)),lifecycle:_(m(o.lifecycle,"participant.lifecycle"),gn)}}),revealPolicy:(()=>{let s=w(e.revealPolicy);return{masterKeyRelease:_(m(s.masterKeyRelease,"masterKeyRelease"),["REQUIRED"]),custodian:_(m(s.custodian,"custodian"),["FORCE"])}})(),dms:e.dms===void 0?void 0:(()=>{let s=w(e.dms);return{subjectEmail:m(s.subjectEmail,"dms.subjectEmail"),countdownDays:K(s.countdownDays,"dms.countdownDays"),countdownHours:K(s.countdownHours,"dms.countdownHours"),countdownMinutes:K(s.countdownMinutes,"dms.countdownMinutes")}})(),source:r==="NATIVE"?{kind:"NATIVE"}:r==="BRIDGED"?{kind:"BRIDGED",system:_(m(t.system,"source.system"),["INHERITI_BUSINESS"]),status:_(m(t.status,"source.status"),["IN_SYNC","RECONCILIATION_REQUIRED"])}:{kind:"UNKNOWN",raw:r}}}function H(i){let e=w(i);return{operationId:m(e.operationId,"operationId"),stage:_(m(e.stage,"stage"),he),outcome:_(m(e.outcome,"outcome"),fn),planId:F(e.planId),lastErrorCode:F(e.lastErrorCode),participants:e.participants===void 0?void 0:C(e.participants).map(n=>{let t=w(n);return{clientParticipantRef:m(t.clientParticipantRef,"clientParticipantRef"),planParticipantId:m(t.planParticipantId,"planParticipantId"),relationships:C(t.relationships).map(r=>yn(m(r,"relationship"),Se))}})}}function Ce(i){let e=w(i),n=w(e.assetSummary),t=w(e.governance),r=w(e.participantSummary);return{id:m(e.id,"id"),name:m(e.name,"name"),description:F(e.description),status:_(m(e.status,"status"),mn),createdAt:m(e.createdAt,"createdAt"),configuredAt:F(e.configuredAt),assetSummary:{count:K(n.count,"assetSummary.count"),types:C(n.types).map(s=>_(m(s,"assetType"),J)),names:ve(n.names).map(s=>m(s,"assetSummary.names"))},governance:{mode:_(m(t.mode,"governance.mode"),un),minimumApprovals:K(t.minimumApprovals,"minimumApprovals")},participantSummary:{owners:K(r.owners,"owners"),mergers:K(r.mergers,"mergers"),moderators:K(r.moderators,"moderators")},authentication:ve(e.authentication).map(s=>{let o=w(s);return{id:_(m(o.id,"authentication.id"),In),status:_(m(o.status,"authentication.status"),bn)}})}}function _(i,e){return e.includes(i)?i:{kind:"UNKNOWN",raw:i}}function yn(i,e){if(!e.includes(i))throw new Error("invalid_elements_response");return i}function w(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("invalid_elements_response");return i}function ve(i){return i==null?[]:C(i)}function C(i){if(!Array.isArray(i))throw new Error("invalid_elements_response");return i}function m(i,e){if(typeof i!="string"||!i)throw new Error("invalid_elements_response");return i}function F(i){return i==null?void 0:m(i,"optional")}function K(i,e){if(typeof i!="number"||!Number.isFinite(i))throw new Error("invalid_elements_response");return i}function hn(i,e){if(typeof i!="boolean")throw new Error("invalid_elements_response");return i}function M(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("invalid_elements_response");return i}function G(i){if(!Array.isArray(i))throw new Error("invalid_elements_response");return i}function h(i){if(typeof i!="string"||!i)throw new Error("invalid_elements_response");return i}function le(i){return i==null?void 0:h(i)}function v(i){if(typeof i!="number"||!Number.isFinite(i))throw new Error("invalid_elements_response");return i}function xn(i){if(typeof i!="boolean")throw new Error("invalid_elements_response");return i}function Me(i){let e=M(i);return{total:v(e.total),items:G(e.items).map(n=>{let t=M(n);return{id:h(t.id),displayName:h(t.displayName),role:h(t.role),status:h(t.status)}})}}function Te(i){let e=M(i);return{total:v(e.total),shownCount:v(e.shownCount),totalCount:v(e.totalCount),nextCursor:e.nextCursor==null?null:h(e.nextCursor),hasMore:xn(e.hasMore),items:G(e.items).map(n=>{let t=M(n);if("eventData"in t)throw new Error("invalid_elements_response");return{id:h(t.id),occurredOn:h(t.occurredOn),actorName:h(t.actorName),actorRole:h(t.actorRole),category:h(t.category),action:h(t.action),subject:h(t.subject),status:h(t.status),sourceEvent:h(t.sourceEvent),planId:le(t.planId),planName:le(t.planName),responsibleMemberName:le(t.responsibleMemberName)}})}}function Oe(i){let e=M(i),n=M(e.stats),t=M(e.planAccessResults);return{stats:{totalPlans:v(n.totalPlans),plansCreatedThisMonth:v(n.plansCreatedThisMonth),activeMembers:v(n.activeMembers),totalSeats:n.totalSeats==null?null:v(n.totalSeats),accessRequests30d:v(n.accessRequests30d),accessRequestsPrevious30d:v(n.accessRequestsPrevious30d),pendingApprovals:v(n.pendingApprovals)},plansOverTime:G(e.plansOverTime).map(r=>{let s=M(r);return{month:h(s.month),count:v(s.count)}}),planTypes:G(e.planTypes).map(r=>{let s=M(r);return{type:h(s.type),count:v(s.count)}}),accessModerationActivity:G(e.accessModerationActivity).map(r=>{let s=M(r);return{week:h(s.week),requests:v(s.requests),approvals:v(s.approvals)}}),planAccessResults:{success:v(t.success),aborted:v(t.aborted),expired:v(t.expired)}}}function Ne(i){let e=M(i);return{planId:h(e.planId),participants:G(e.participants).map(n=>{let t=M(n);return{id:h(t.id),displayName:h(t.displayName),relationships:G(t.relationships).map(r=>h(r)),lifecycle:h(t.lifecycle)}})}}function Z(i,e){if(Object.keys(i).some(n=>!e.includes(n)))throw new Error("organization_query_field_unknown")}function Ke(i){if(!i||typeof i!="object"||!("items"in i)||!Array.isArray(i.items)||!i.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 i.items.map(({id:e,name:n})=>({id:e,name:n}))}function Pn(i){let e=b(i);if(e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:u(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:u(e.participantRevision,1),createdAt:R(e.createdAt),...ke(e)}}function ke(i){if(i.recipientStatuses===void 0)return{};if(!Array.isArray(i.recipientStatuses))throw new Error("invalid_inbox_response");return{recipientStatuses:i.recipientStatuses.map(e=>{let n=b(e);if(n.secrets!==void 0&&!Array.isArray(n.secrets))throw new Error("invalid_inbox_response");if(n.read!==void 0&&typeof n.read!="boolean")throw new Error("invalid_inbox_response");return{memberId:d(n.memberId),...n.read!==void 0?{read:n.read}:{},...n.readAt!==void 0?{readAt:n.readAt===null?null:R(n.readAt)}:{},...Array.isArray(n.secrets)?{secrets:n.secrets.map(t=>{let r=b(t);if(r.status!=="UNREAD"&&r.status!=="LEASED"&&r.status!=="CONSUMED"&&r.status!=="EXPIRED"&&r.status!=="REVOKED"&&r.status!=="DELETED")throw new Error("invalid_inbox_response");return{position:u(r.position,0),status:r.status,...r.revealedAt!==void 0?{revealedAt:r.revealedAt===null?null:R(r.revealedAt)}:{}}})}:{}}})}}function De(i){let e=b(i);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(Pn),total:u(e.total,0),limit:u(e.limit,1),offset:u(e.offset,0),unreadCount:u(e.unreadCount,0),readThroughSequence:u(e.readThroughSequence,0)}}function Ue(i){let e=b(i);if(!Array.isArray(e.protectedUnits)||e.mode!=="NORMAL"&&e.mode!=="MIXED"&&e.mode!=="PROTECTED"||e.status!=="AVAILABLE"||e.frame!==null&&typeof e.frame!="string"||e.wrappedContentKey!==null&&typeof e.wrappedContentKey!="string")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:u(e.sequence,1),mode:e.mode,status:e.status,senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:u(e.participantRevision,1),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:u(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),frame:e.frame,wrappedContentKey:e.wrappedContentKey,protectedUnits:e.protectedUnits.map(n=>{let t=b(n);return{unitId:d(t.unitId),position:u(t.position,0),commitment:d(t.commitment),status:d(t.status)}})}}function pe(i){let e=b(i);if(e.status!=="AVAILABLE")throw new Error("invalid_inbox_response");return{parentId:d(e.parentId),sequence:u(e.sequence,1),status:e.status}}function qe(i){let e=b(i);if(!Array.isArray(e.recipients)||e.recipients.length<2||e.recipients.length>50)throw new Error("invalid_inbox_response");return{conversationId:d(e.conversationId),parentId:d(e.parentId),participantRevision:u(e.participantRevision,1),recipients:e.recipients.map(me)}}function Le(i){let e=b(i);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(n=>{let t=b(n);return{parentId:d(t.parentId),sequence:u(t.sequence,1),senderMemberId:d(t.senderMemberId),senderDeviceId:d(t.senderDeviceId),participantRevision:u(t.participantRevision,1),createdAt:R(t.createdAt),...ke(t)}}),total:u(e.total,0),limit:u(e.limit,1),offset:u(e.offset,0),unreadCount:u(e.unreadCount,0),readThroughSequence:u(e.readThroughSequence,0)}}function Fe(i){return{readThroughSequence:u(b(i).readThroughSequence,0)}}function $e(i){return{clearedThroughSequence:u(b(i).clearedThroughSequence,0)}}function ze(i){let e=b(i);return{parentId:d(e.parentId),sequence:u(e.sequence,1),senderMemberId:d(e.senderMemberId),senderDeviceId:d(e.senderDeviceId),participantRevision:u(e.participantRevision,1),canonicalManifest:d(e.canonicalManifest),frame:d(e.frame),signature:d(e.signature),wrappedContentKey:d(e.wrappedContentKey),senderSigningPublicKey:d(e.senderSigningPublicKey)}}function b(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("invalid_inbox_response");return i}function d(i){if(typeof i!="string"||!i)throw new Error("invalid_inbox_response");return i}function R(i){let e=d(i);if(Number.isNaN(Date.parse(e)))throw new Error("invalid_inbox_response");return e}function u(i,e){if(!Number.isSafeInteger(i)||i<e)throw new Error("invalid_inbox_response");return i}function me(i){let e=b(i);return{memberId:d(e.memberId),deviceId:d(e.deviceId),deviceVersion:u(e.deviceVersion,1),encryptionPublicKey:d(e.encryptionPublicKey),encryptionKeyFingerprint:d(e.encryptionKeyFingerprint),signingPublicKey:d(e.signingPublicKey),signingKeyFingerprint:d(e.signingKeyFingerprint)}}function V(i){let e=b(i);if(!Number.isSafeInteger(e.version)||e.version<1||e.status!=="ACTIVE"&&e.status!=="REVOKED")throw new Error("invalid_inbox_response");return{id:d(e.id),tenantId:d(e.tenantId),memberId:d(e.memberId),version:e.version,encryptionPublicKey:d(e.encryptionPublicKey),encryptionKeyFingerprint:d(e.encryptionKeyFingerprint),signingPublicKey:d(e.signingPublicKey),signingKeyFingerprint:d(e.signingKeyFingerprint),status:e.status,createdAt:R(e.createdAt),updatedAt:R(e.updatedAt)}}function ee(i){let e=b(i);if(!Array.isArray(e.participantMemberIds)||!Number.isSafeInteger(e.participantRevision)||e.participantRevision<1||e.status!=="ACTIVE"&&e.status!=="CLOSED")throw new Error("invalid_inbox_response");if(e.unreadCount!==void 0&&(!Number.isSafeInteger(e.unreadCount)||e.unreadCount<0))throw new Error("invalid_inbox_response");if(e.title!==null&&(typeof e.title!="string"||!e.title.trim()||e.title.length>80))throw new Error("invalid_inbox_response");let n={id:d(e.id),tenantId:d(e.tenantId),creatorMemberId:d(e.creatorMemberId),title:e.title,participantMemberIds:e.participantMemberIds.map(d),participantRevision:e.participantRevision,status:e.status,createdAt:R(e.createdAt),updatedAt:R(e.updatedAt)};if(e.unreadCount!==void 0&&(n.unreadCount=e.unreadCount),e.latestMessage===null&&(n.latestMessage=null),e.latestMessage!==void 0&&e.latestMessage!==null){let t=b(e.latestMessage);if(t.contentKind!=="TEXT"&&t.contentKind!=="FILE"&&t.contentKind!=="NORMAL"&&t.contentKind!=="MIXED"&&t.contentKind!=="PROTECTED")throw new Error("invalid_inbox_response");n.latestMessage={contentKind:t.contentKind,senderMemberId:d(t.senderMemberId),createdAt:R(t.createdAt)}}return n}function Ge(i){let e=b(i);if(!Array.isArray(e.items)||!Number.isSafeInteger(e.total)||e.total<0||!Number.isSafeInteger(e.limit)||e.limit<1||!Number.isSafeInteger(e.offset)||e.offset<0)throw new Error("invalid_inbox_response");return{items:e.items.map(ee),total:e.total,limit:e.limit,offset:e.offset}}function Be(i){let e=b(i);if(!Array.isArray(e.items)||e.nextOffset!==null&&e.nextOffset!==void 0&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(n=>{let t=me(n);return{memberId:t.memberId,name:d(b(n).name),deviceId:t.deviceId,deviceVersion:t.deviceVersion,encryptionPublicKey:t.encryptionPublicKey,encryptionKeyFingerprint:t.encryptionKeyFingerprint,signingPublicKey:t.signingPublicKey,signingKeyFingerprint:t.signingKeyFingerprint}}),limit:u(e.limit,1),offset:u(e.offset,0),nextOffset:e.nextOffset===null?null:u(e.nextOffset,0)}}function Ve(i){let e=b(i);if(!Array.isArray(e.items)||e.nextOffset!==null&&(!Number.isSafeInteger(e.nextOffset)||e.nextOffset<0))throw new Error("invalid_inbox_response");return{items:e.items.map(n=>{let t=b(n);if(typeof t.ready!="boolean")throw new Error("invalid_inbox_response");return{memberId:d(t.memberId),name:d(t.name),ready:t.ready,...t.profilePicture===void 0?{}:{profilePicture:{url:d(b(t.profilePicture).url)}}}}),limit:u(e.limit,1),offset:u(e.offset,0),nextOffset:e.nextOffset===null?null:u(e.nextOffset,0)}}function He(i){let e=b(i);if(!Array.isArray(e.recipients)||!Array.isArray(e.shareLayers)||e.shareLayers.length<2||e.shareLayers.length>255||e.threshold!==e.total||e.total!==e.shareLayers.length)throw new Error("invalid_inbox_response");return{conversationId:d(e.conversationId),messageId:d(e.messageId),participantRevision:u(e.participantRevision,1),threshold:e.total,total:e.shareLayers.length,recipients:e.recipients.map(me),shareLayers:e.shareLayers.map(n=>{let t=b(n),r=d(t.id),s=d(t.dataShareId),o=d(t.keyShareId);if(t.type==="INHERITI_CHAIN")return{id:r,type:t.type,contractAddress:d(t.contractAddress),dataShareId:s,keyShareId:o};if(t.type==="INHERITI_VAULT"||t.type==="GOOGLE_DRIVE"||t.type==="DROPBOX"||t.type==="ONEDRIVE")return{id:r,type:t.type,dataShareId:s,keyShareId:o};throw new Error("invalid_inbox_response")})}}function ne(i){let e=b(i);if(e.status!=="PREPARING"&&e.status!=="AVAILABLE"&&e.status!=="FAILED"&&e.status!=="DELETING"&&e.status!=="DELETED")throw new Error("invalid_inbox_response");return{messageId:d(e.messageId),status:e.status}}function We(i){let e=b(i);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(n=>{let t=b(n);if(t.status!=="PREPARING"&&t.status!=="AVAILABLE"&&t.status!=="FAILED"&&t.status!=="DELETING")throw new Error("invalid_inbox_response");if(t.contentKind!==void 0&&t.contentKind!=="TEXT"&&t.contentKind!=="FILE")throw new Error("invalid_inbox_response");if(t.recipientStatus!==void 0&&t.recipientStatus!=="UNREAD"&&t.recipientStatus!=="LEASED"&&t.recipientStatus!=="CONSUMED"&&t.recipientStatus!=="EXPIRED"&&t.recipientStatus!=="REVOKED")throw new Error("invalid_inbox_response");if(t.recipientStatuses!==void 0&&!Array.isArray(t.recipientStatuses))throw new Error("invalid_inbox_response");let r={id:d(t.id),status:t.status,senderMemberId:d(t.senderMemberId),senderDeviceId:d(t.senderDeviceId),createdAt:R(t.createdAt),updatedAt:R(t.updatedAt),expiresAt:R(t.expiresAt)};return t.contentKind&&(r.contentKind=t.contentKind),t.recipientStatus&&(r.recipientStatus=t.recipientStatus),Array.isArray(t.recipientStatuses)&&(r.recipientStatuses=t.recipientStatuses.map(s=>{let o=b(s);if(o.status!=="UNREAD"&&o.status!=="LEASED"&&o.status!=="CONSUMED"&&o.status!=="EXPIRED"&&o.status!=="REVOKED")throw new Error("invalid_inbox_response");return{memberId:d(o.memberId),status:o.status,...o.consumedAt!==void 0?{consumedAt:o.consumedAt===null?null:R(o.consumedAt)}:{}}})),r}),total:u(e.total,0),limit:u(e.limit,1),offset:u(e.offset,0)}}function je(i){let e=b(i);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:d(e.leaseId),leaseExpiresAt:R(e.leaseExpiresAt),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:u(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),tenantWrappedShareKey:d(e.tenantWrappedShareKey),wrappedContentKey:d(e.wrappedContentKey),shares:e.shares.map(n=>{let t=b(n);if(t.kind!=="DATA"&&t.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:t.kind,index:u(t.index,0),shareId:d(t.shareId),layerId:d(t.layerId),ciphertext:d(t.ciphertext)}})}}function Ye(i){let e=b(i);if(!Array.isArray(e.shares))throw new Error("invalid_inbox_response");return{leaseId:d(e.leaseId),leaseExpiresAt:R(e.leaseExpiresAt),senderSigningPublicKey:d(e.senderSigningPublicKey),senderSigningKeyFingerprint:d(e.senderSigningKeyFingerprint),senderDeviceVersion:u(e.senderDeviceVersion,1),canonicalManifest:d(e.canonicalManifest),signature:d(e.signature),tenantWrappedShareKey:d(e.tenantWrappedShareKey),wrappedContentKey:d(e.wrappedContentKey),shares:e.shares.map(n=>{let t=b(n);if(t.kind!=="DATA"&&t.kind!=="KEY")throw new Error("invalid_inbox_response");return{kind:t.kind,index:u(t.index,0),shareId:d(t.shareId),layerId:d(t.layerId)}})}}function te(i){return typeof i=="string"&&/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(i)&&Number.isFinite(Date.parse(i))}function W(i){return typeof i.error=="string"?/^[a-z][a-z0-9_]*$/.test(i.error)?i.error:typeof i.validationErrors=="string"&&/^[a-z][a-z0-9_]*$/.test(i.validationErrors)?i.validationErrors:i.error||void 0:i.error?.code??i.name??i.message}function j(i){return typeof i.error=="object"&&i.error?.requestId?i.error.requestId:i.description}var k=class extends Error{constructor(n,t,r,s){super(t??`elements_api_request_failed_${n}`);this.status=n;this.code=t;this.detail=r;this.requestId=s;this.name="ElementsApiRequestFailed"}get stepUpRequestId(){return this.code==="step_up_approval_required"?this.detail:void 0}},ie=class{constructor(e,n,t,r,s){this.apiUrl=e;this.environment=n;this.getBearerToken=t;this.transport=r;this.business=s?Object.freeze({...s}):void 0}business;getFileAccess(e,n){return this.request(`v1/file-accesses/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,n)}requestFileAccessOpening(e,n){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings`,"POST",n)}readFileAccessOpening(e,n,t,r){return this.request(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(n)}`,"GET",void 0,void 0,{"x-client-key-hash":t},r)}confirmFileAccessDelivery(e,n,t){return this.requestWithoutResult(`v1/file-accesses/${encodeURIComponent(e)}/openings/${encodeURIComponent(n)}/confirm-delivery`,void 0,{"x-client-key-hash":t})}createInboxFileAccess(e,n,t,r){return this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/file-accesses`,"POST",t,void 0,void 0,r)}createRevealFileAccess(e,n,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/file-accesses`,"POST",n,void 0,void 0,t)}cancelRevealFileAccess(e,n,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/file-accesses/${encodeURIComponent(n)}`,void 0,void 0,"DELETE",t)}cancelInboxFileAccess(e,n,t,r){return this.requestWithoutResult(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/file-accesses/${encodeURIComponent(t)}`,void 0,void 0,"DELETE",r)}async getOwnFileAccessIdentityKey(e){let n=await this.request("v1/inbox/devices/me/identity-key","GET",void 0,void 0,void 0,e);if(n===null)return null;if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_file_access_identity_key");let t=n;if(typeof t.publicKey!="string"||!t.publicKey||typeof t.fingerprint!="string"||!t.fingerprint||t.status!=="ACTIVE"&&t.status!=="NEEDS_REAPPROVAL")throw new Error("invalid_file_access_identity_key");return{publicKey:t.publicKey,fingerprint:t.fingerprint,status:t.status}}async getOwnInboxDevice(e){let n=await this.request("v1/inbox/devices/me","GET",void 0,void 0,void 0,e);return n===null?null:V(n)}async getMemberInboxDevice(e,n){let t=await this.request(`v1/inbox/devices/members/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,n);return t===null?null:V(t)}async registerInboxDevice(e){return V(await this.request("v1/inbox/devices","POST",e))}async replaceInboxDevice(e){return V(await this.request("v1/inbox/devices/replace","POST",e))}async revokeInboxDevice(e){return V(await this.request("v1/inbox/devices/me","DELETE",e))}async createInboxConversation(e){return ee(await this.request("v1/inbox/conversations","POST",e))}async changeInboxParticipants(e,n){return ee(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/participants`,"POST",{action:n.action,memberId:n.memberId,expectedRevision:n.expectedRevision}))}async listInboxConversations(e={},n){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset));let r=t.size?`?${t}`:"";return Ge(await this.request(`v1/inbox/conversations${r}`,"GET",void 0,void 0,void 0,n))}async listInboxParticipants(e={},n){let t=new URLSearchParams;e.q!==void 0&&t.set("q",e.q),e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset));let r=t.size?`?${t}`:"";return Be(await this.request(`v1/inbox/participants${r}`,"GET",void 0,void 0,void 0,n))}async listInboxMembers(e={},n){let t=new URLSearchParams;e.q!==void 0&&t.set("q",e.q),e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset));let r=t.size?`?${t}`:"";return Ve(await this.request(`v1/inbox/members${r}`,"GET",void 0,void 0,void 0,n))}async getInboxSendPreparation(e,n){return He(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,n))}async getNormalInboxSendPreparation(e,n){return qe(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-preparation`,"GET",void 0,void 0,void 0,n))}async publishInboxMessage(e,n){let t={messageId:n.messageId,senderDeviceId:n.senderDeviceId,participantRevision:n.participantRevision,expiresAt:n.expiresAt,idempotencyKey:n.idempotencyKey,canonicalManifest:n.canonicalManifest,signature:n.signature,tenantWrappedShareKey:n.tenantWrappedShareKey,recipients:n.recipients.map(r=>({memberId:r.memberId,deviceId:r.deviceId,deviceVersion:r.deviceVersion,keyFingerprint:r.keyFingerprint,wrappedContentKey:r.wrappedContentKey})),shares:n.shares.map(r=>({kind:r.kind,index:r.index,shareId:r.shareId,layerId:r.layerId,ciphertext:r.ciphertext}))};return ne(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages`,"POST",t))}async publishNormalInboxMessage(e,n){return pe(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages`,"POST",n))}async publishInboxParent(e,n){return pe(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages`,"POST",n))}async listInboxParents(e,n={},t){let r=new URLSearchParams;n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let s=r.size?`?${r}`:"";return De(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages${s}`,"GET",void 0,void 0,void 0,t))}async openInboxParent(e,n,t,r){let s=new URLSearchParams({deviceId:t});return Ue(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/parent-messages/${encodeURIComponent(n)}?${s}`,"GET",void 0,void 0,void 0,r))}async clearInboxHistory(e,n){return $e(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/clear-history`,"POST",{},void 0,void 0,n))}async listNormalInboxMessages(e,n={},t){let r=new URLSearchParams;n.limit!==void 0&&r.set("limit",String(n.limit)),n.offset!==void 0&&r.set("offset",String(n.offset));let s=r.size?`?${r}`:"";return Le(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages${s}`,"GET",void 0,void 0,void 0,t))}async openNormalInboxMessage(e,n,t,r){let s=new URLSearchParams({deviceId:t});return ze(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(n)}?${s}`,"GET",void 0,void 0,void 0,r))}async markNormalInboxMessageRead(e,n,t){return Fe(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/normal-messages/${encodeURIComponent(n)}/read`,"POST",{deviceId:t}))}async stageInboxFile(e,n,t){return ne(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/file`,"POST",n,void 0,void 0,t))}async uploadInboxFileShare(e,n,t,r,s){if(r.length>14*1024*1024)throw new Error("invalid_inbox_share_size");let o=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/shares/${encodeURIComponent(t)}`,a=await this.requestBinary(o,"PUT",r,s),c=await re(a,s);if(!c.ok||c.result?.shareId!==t||c.result.status!=="STORED")throw new k(a.status,W(c),j(c),a.headers.get("x-request-id")??void 0)}async publishInboxFile(e,n,t){return ne(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/publish`,"POST",void 0,void 0,void 0,t))}async openInboxFile(e,n,t,r){return Ye(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/open/file`,"POST",{deviceId:t},void 0,void 0,r))}async downloadInboxFileShare(e,n,t,r,s,o){let a=new URLSearchParams({deviceId:r,leaseId:s}),c=`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/shares/${encodeURIComponent(t)}?${a}`,l=await this.requestBinary(c,"GET",void 0,o);if(!l.headers.get("content-type")?.toLowerCase().startsWith("application/octet-stream"))throw new Error("invalid_inbox_share_response");let g=Number(l.headers.get("content-length"));if(Number.isFinite(g)&&g>14*1024*1024)throw new Error("invalid_inbox_share_size");if(!l.body)throw new Error("invalid_inbox_share_response");let I=l.body.getReader(),y=[],S=0;try{for(;;){o?.throwIfAborted();let q=await I.read();if(q.done)break;if(S+=q.value.length,S>14*1024*1024)throw new Error("invalid_inbox_share_size");y.push(q.value)}}catch(q){throw await I.cancel().catch(()=>{}),q}let U=new Uint8Array(S),N=0;for(let q of y)U.set(q,N),N+=q.length;return U}async listInboxMessages(e,n={},t){let r=new URLSearchParams;n.status&&r.set("filter[where]",JSON.stringify([{field:"status",operator:"==",value:n.status}])),n.limit!==void 0&&r.set("filter[limit]",String(n.limit)),n.offset!==void 0&&r.set("filter[skip]",String(n.offset));let s=r.size?`?${r}`:"";return We(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages${s}`,"GET",void 0,void 0,void 0,t))}async openInboxMessage(e,n,t){return je(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/open`,"POST",{deviceId:t}))}async ackInboxMessage(e,n,t,r,s){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/ack`,"POST",{deviceId:t,leaseId:r},void 0,void 0,s)}async releaseInboxMessage(e,n,t,r){await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/messages/${encodeURIComponent(n)}/release`,"POST",{deviceId:t,leaseId:r})}listBusinessOrganizations(){if(!this.business)throw new Error("business_context_required");return this.request("v1/organizations","GET").then(Ke)}listInternalBuilds(){return this.request("v1/internal-builds","GET").then(e=>e.items)}requestInternalBuildDownload(e){return this.request(`v1/internal-builds/${encodeURIComponent(e)}/download`,"POST")}async listPlans(e={}){let n=new URLSearchParams;e.cursor&&n.set("cursor",e.cursor),e.limit!==void 0&&n.set("limit",String(e.limit));for(let r of e.status??[])n.append("status",r);e.assetType&&n.set("assetType",e.assetType),e.namePrefix&&n.set("namePrefix",e.namePrefix);let t=n.size?`?${n}`:"";return Ae(await this.request(`v1/plans${t}`,"GET"))}async getPlan(e){return _e(await this.request(`v1/plans/${encodeURIComponent(e)}`,"GET"))}async listPlanLogs(e,n={}){let t=new URLSearchParams;n.limit!==void 0&&t.set("limit",String(n.limit)),n.offset!==void 0&&t.set("offset",String(n.offset));let r=t.size?`?${t}`:"";return Ee(await this.request(`v1/plans/${encodeURIComponent(e)}/logs${r}`,"GET"))}async listMemberLogs(e,n={}){let t=new URLSearchParams;n.source&&t.set("source",n.source),n.from&&t.set("from",n.from),n.to&&t.set("to",n.to),n.q&&t.set("q",n.q),n.limit!==void 0&&t.set("limit",String(n.limit)),n.offset!==void 0&&t.set("offset",String(n.offset));let r=t.size?`?${t}`:"";return Re(await this.request(`v1/members/${encodeURIComponent(e)}/logs${r}`,"GET"))}async listOrganizationMembers(e={}){if(this.requireOrganizationSelection(),Z(e,["limit","offset"]),e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>100))throw new Error("organization_query_limit_invalid");if(e.offset!==void 0&&(!Number.isSafeInteger(e.offset)||e.offset<0))throw new Error("organization_query_offset_invalid");let n=new URLSearchParams;return e.limit!==void 0&&n.set("limit",String(e.limit)),e.offset!==void 0&&n.set("offset",String(e.offset)),Me(await this.request(`v1/organization/members${n.size?`?${n}`:""}`,"GET"))}async listOrganizationAuditTrail(e){if(this.requireOrganizationSelection(),Z(e,["from","to","limit","cursor","category","memberId","responsibleMemberId"]),!te(e.from)||!te(e.to)||Date.parse(e.from)>Date.parse(e.to))throw new Error("organization_query_date_invalid");if(e.limit!==void 0&&(!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>500))throw new Error("organization_query_limit_invalid");if(e.cursor!==void 0&&!/^[1-9]\d*$/.test(e.cursor))throw new Error("organization_query_cursor_invalid");let n=new URLSearchParams({from:e.from,to:e.to});return e.limit!==void 0&&n.set("limit",String(e.limit)),e.cursor!==void 0&&n.set("cursor",e.cursor),e.category!==void 0&&n.set("category",e.category),e.memberId!==void 0&&n.set("memberId",e.memberId),e.responsibleMemberId!==void 0&&n.set("responsibleMemberId",e.responsibleMemberId),Te(await this.request(`v1/organization/audit-trail?${n}`,"GET"))}async getOrganizationInsights(e={}){if(this.requireOrganizationSelection(),Z(e,["from","to"]),e.from===void 0!=(e.to===void 0)||e.from!==void 0&&(!te(e.from)||!te(e.to)||Date.parse(e.from)>Date.parse(e.to)))throw new Error("organization_query_date_invalid");let n=new URLSearchParams;return e.from!==void 0&&e.to!==void 0&&(n.set("from",e.from),n.set("to",e.to)),Oe(await this.request(`v1/organization/insights${n.size?`?${n}`:""}`,"GET"))}async getPlanResponsibilities(e){if(this.requireOrganizationSelection(),!e)throw new Error("plan_id_required");return Ne(await this.request(`v1/plans/${encodeURIComponent(e)}/responsibilities`,"GET"))}async startPlanCreation(e){Pe(e);let{idempotencyKey:n,...t}=e;return H(await this.request("v1/plan-creations","POST",t,void 0,{"idempotency-key":n}))}async getPlanCreation(e){return H(await this.request(`v1/plan-creations/${encodeURIComponent(e)}`,"GET"))}async supplyPlanCreationMaterial(e,n){return xe(n),H(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/material`,"PUT",n))}async cancelPlanCreation(e){return H(await this.request(`v1/plan-creations/${encodeURIComponent(e)}/cancel`,"POST"))}masterKeyAcquisition(){return this.request("v1/master-key/acquisition","GET")}foreignMasterKeyAcquisition(e,n){return this.request(`v1/master-key/acquisition/${encodeURIComponent(e)}/${encodeURIComponent(n)}`,"GET")}startMasterKeyRelaySession(e,n){return this.request("v1/master-key/relay-sessions","POST",{clientPublicKey:e,...n})}readMasterKeyRelaySession(e,n){return this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,n)}async cancelMasterKeyRelaySession(e,n){await this.request(`v1/master-key/relay-sessions/${encodeURIComponent(e)}`,"DELETE",void 0,void 0,void 0,n)}planKeyReference(e){return this.request(`v1/plans/${encodeURIComponent(e)}/material/key-reference`,"GET")}async collectPlanMaterial(e,n){return this.request(`shared-plans/${encodeURIComponent(e)}/material/collect`,"POST",void 0,n)}initializeGovernedReveal(e,n){return this.request(`shared-plans/${encodeURIComponent(e)}/governed-reveal`,"POST",void 0,n)}getGovernedReveal(e,n){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}`,"GET",void 0,n)}collectGovernedValidatorShares(e,n){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/validator-shares`,"POST",void 0,n)}collectGovernedShares(e,n){return this.request(`shared-plans/governed-reveal/${encodeURIComponent(e)}/shares`,"POST",void 0,n)}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,n){let{idempotencyKey:t,...r}=n;return this.request(`v1/plans/${encodeURIComponent(e)}/reveals`,"POST",r,void 0,{"idempotency-key":t})}getActivePlanReveal(e){return this.business?this.request(`v1/plans/${encodeURIComponent(e)}/reveal-access`,"GET"):Promise.resolve(null)}getReveal(e,n){return this.request(`v1/reveals/${encodeURIComponent(e)}`,"GET",void 0,void 0,void 0,n)}releaseRevealMaterial(e,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/material`,"POST",{materialVersion:n})}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,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/access`,"GET",void 0,void 0,void 0,n)}getRevealCustodianShare(e,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,void 0,void 0,n)}getRevealCustodianClaimable(e,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claimable`,"GET",void 0,void 0,void 0,n)}claimRevealCustodianShare(e,n,t){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/claim`,{shareId:n,deviceId:t})}collectRevealCustodianShare(e,n){return this.requestWithoutResult(`v1/reveals/${encodeURIComponent(e)}/custodian-share/collect`,{shareId:n})}reportRevealReconstruction(e,n){return this.request(`v1/reveals/${encodeURIComponent(e)}/reconstruction`,"PUT",n)}closeReveal(e,n,t){return this.request(`v1/reveals/${encodeURIComponent(e)}/close`,"POST",{reason:n},void 0,void 0,t)}abortPlanAccess(e,n){let t=`v1/plans/${encodeURIComponent(e)}/reveal-access`;return this.request(n?`${t}?revealId=${encodeURIComponent(n)}`:t,"DELETE")}authorizeRevealAction(e,n){let{idempotencyKey:t,...r}=n;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions`,"POST",r,void 0,{"idempotency-key":t})}reportRevealActionOutcome(e,n,t){let{idempotencyKey:r,...s}=t;return this.request(`v1/reveals/${encodeURIComponent(e)}/actions/${encodeURIComponent(n)}/outcome`,"PUT",s,void 0,{"idempotency-key":r})}getCustodianShare(e,n){return this.request(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share`,"GET",void 0,n)}releaseCustodianShare(e){return this.requestWithoutResult(`v1/shared-plans/merge/${encodeURIComponent(e)}/custodian-share/release`)}exportPlanBridge(e,n){return this.request(`shared-plans/${encodeURIComponent(e)}/bridge/export`,"POST",n)}importPlanBridge(e){return this.request("shared-plans/bridge/import","POST",{envelope:e})}async request(e,n,t,r,s,o){this.requireBusinessSelection(e),o?.throwIfAborted();let a=await this.getBearerToken();o?.throwIfAborted();let c=new Headers({"x-elements-environment":this.environment});a&&c.set("authorization",`Bearer ${a}`),this.business?.organizationId&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&c.set("x-organization-id",this.business.organizationId),r?.requestId&&c.set("x-elements-step-up-request",r.requestId);for(let[S,U]of Object.entries(s??{}))c.set(S,U);t&&c.set("content-type","application/json");let l=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,g={method:n,headers:c,body:t?JSON.stringify(t):void 0};o&&(g.signal=o);let I=await this.transport(new URL(e,l),g);o?.throwIfAborted();let y=await re(I,o);if(o?.throwIfAborted(),!I.ok)throw new k(I.status,W(y),j(y),I.headers.get("x-request-id")??void 0);if(!y.ok||y.result===void 0)throw new k(I.status,W(y),j(y),I.headers.get("x-request-id")??void 0);return y.result}async requestBinary(e,n,t,r){this.requireBusinessSelection(e),r?.throwIfAborted();let s=await this.getBearerToken();r?.throwIfAborted();let o=new Headers({"x-elements-environment":this.environment});s&&o.set("authorization",`Bearer ${s}`),this.business?.organizationId&&o.set("x-organization-id",this.business.organizationId),t&&o.set("content-type","application/octet-stream");let a=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,c=await this.transport(new URL(e,a),{method:n,headers:o,body:t?Buffer.from(t):void 0,signal:r});if(r?.throwIfAborted(),!c.ok){let l=await re(c,r);throw new k(c.status,W(l),j(l),c.headers.get("x-request-id")??void 0)}return c}async requestWithoutResult(e,n,t,r="POST",s){this.requireBusinessSelection(e),s?.throwIfAborted();let o=await this.getBearerToken(),a=new Headers({"x-elements-environment":this.environment});o&&a.set("authorization",`Bearer ${o}`),this.business?.organizationId&&a.set("x-organization-id",this.business.organizationId);for(let[I,y]of Object.entries(t??{}))a.set(I,y);n&&a.set("content-type","application/json");let c=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,l=await this.transport(new URL(e,c),{method:r,headers:a,body:n?JSON.stringify(n):void 0,signal:s}),g=await re(l,s);if(s?.throwIfAborted(),!l.ok||!g.ok)throw new k(l.status,W(g),j(g),l.headers.get("x-request-id")??void 0)}requireOrganizationSelection(){if(!this.business?.organizationId)throw new k(400,"organization_selection_required")}requireBusinessSelection(e){if(this.business&&e!=="v1/organizations"&&!e.startsWith("v1/internal-builds")&&!this.business.organizationId)throw new k(400,"organization_selection_required")}};async function re(i,e){try{return await i.json()}catch(n){if(e?.throwIfAborted(),n instanceof Error&&n.name==="AbortError")throw n;return{ok:!1}}}import{generateInheritiFileKey as wn,sealInheritiFile as vn,readInheritiFileHeader as qt,openInheritiFile as Lt,InheritiFileInvalid as Ft,MAX_INHERITI_FILE_BYTES as $t}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{sealInheritiFileKey as Sn,openInheritiFileKey as Bt}from"@safetech/inheriti-core-sdk/core/protocols/inheriti-file";import{createHash as An,webcrypto as En}from"node:crypto";import{canonicalInboxManifest as Rn,decodeInboxManifest as _n,decodeInboxContentFrame as Cn,decodeInboxText as Mn,decryptInboxShare as Tn,encodeInboxContentFrame as ue,encodeInboxText as On,encryptInboxShare as Xe,inboxProtectedUnitCommitment as Nn,inboxTextMetadataDigest as Qe,openInboxContent as Kn,sealInboxContent as kn,signInboxFrame as Dn,unwrapInboxContentKey as Un,unwrapInboxShareKey as qn,verifyInboxFrame as Je,wrapInboxContentKey as Ln,wrapInboxShareKey as Fn}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as $n}from"@safetech/inheriti-core-sdk/workers/inbox.node";var D=En,P=D,x=i=>{if(!/^[0-9a-fA-F]{64}$/.test(i))throw new Error("invalid_inbox_key");return Buffer.from(i,"hex")},p=i=>{let e=Buffer.from(i,"base64");if(!i||e.toString("base64")!==i)throw new Error("invalid_inbox_base64");return Uint8Array.from(e)},T=(i,e)=>i.length===e.length&&i.every((n,t)=>n===e[t]),se=async i=>new Uint8Array(await P.subtle.digest("SHA-256",Uint8Array.from(i))),Y=i=>An("sha256").update(i).digest("hex"),B=class{constructor(e,n=new $n){this.api=e;this.worker=n}async send(e){let n=await this.prepare(e);return this.api.publishInboxMessage(e.conversationId,n.submission)}async prepare(e){let{preparation:n,sender:t}=await this.prepareSender(e),r=await this.textManifest(e,n,t),s=Rn(r),o=await se(s),{contentKey:a,frame:c}=await kn(On(e.text),o,P),l=await this.signFrame(r,c,e.identity.signingPrivateKey,t.signingPublicKey),{shareKey:g,shares:I}=await this.protectShares(n,c,o),y=await this.wrapRecipientKeys(n,a,o),S=await Fn(g,x(e.tenantKeyHex),o,r.tenantId,r.messageId,P);return{frame:Buffer.from(ue(c)).toString("base64"),submission:{messageId:n.messageId,senderDeviceId:t.deviceId,participantRevision:n.participantRevision,expiresAt:e.expiresAt,idempotencyKey:n.messageId,canonicalManifest:Buffer.from(s).toString("base64"),signature:Buffer.from(l).toString("base64"),tenantWrappedShareKey:Buffer.from(S).toString("base64"),recipients:y,shares:I}}}async open(e){return this.openWithCommitment(e)}openCommitted(e,n){return this.openWithCommitment(e,n)}async openWithCommitment(e,n){let t=await this.api.openInboxMessage(e.conversationId,e.messageId,e.identity.deviceId),r;try{e.signal?.throwIfAborted();let{manifest:o,manifestDigest:a,senderPublicDer:c}=await this.verifyOpening(e,t),l=await this.recoverFrame(t,o,a,e.tenantKeyHex);if(n&&!T(n,await Nn(o,ue(l),p(t.signature),P)))throw new Error("inbox_parent_unit_mismatch");r=await this.decryptText(t,l,o,a,c,e.identity.encryptionPrivateKey),e.signal?.throwIfAborted()}catch(o){try{await this.api.releaseInboxMessage(e.conversationId,e.messageId,e.identity.deviceId,t.leaseId)}catch{}throw o}let s=await this.ack(e.conversationId,e.messageId,e.identity.deviceId,t.leaseId,e.signal);return e.signal?.throwIfAborted(),{text:r,leaseId:t.leaseId,leaseExpiresAt:t.leaseExpiresAt,acknowledgement:s}}async ack(e,n,t,r,s){for(let o=0;o<2;o++){s?.throwIfAborted();try{return await this.api.ackInboxMessage(e,n,t,r,s),s?.throwIfAborted(),"ACKNOWLEDGED"}catch(a){if(s?.throwIfAborted(),a instanceof k&&a.status>=400&&a.status<500)throw a}}return"PENDING"}async prepareSender(e){let n=await this.api.getInboxSendPreparation(e.conversationId);if(n.conversationId!==e.conversationId||n.threshold!==n.total||n.total!==n.shareLayers.length||n.total<2)throw new Error("invalid_inbox_preparation");let t=n.recipients.find(r=>r.memberId===e.identity.memberId);if(!t||t.deviceId!==e.identity.deviceId||t.signingPublicKey!==e.identity.signingPublicKey||t.encryptionPublicKey!==e.identity.encryptionPublicKey||Y(p(t.signingPublicKey))!==t.signingKeyFingerprint||Y(p(t.encryptionPublicKey))!==t.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return{preparation:n,sender:t}}async textManifest(e,n,t){let r=Date.parse(e.expiresAt);if(!Number.isSafeInteger(r)||r<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:e.identity.tenantId,conversationId:e.conversationId,messageId:n.messageId,senderId:e.identity.memberId,senderDeviceId:t.deviceId,senderSigningKeyFingerprint:x(t.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(s=>({memberId:s.memberId,deviceId:s.deviceId,encryptionKeyFingerprint:x(s.encryptionKeyFingerprint)})),expiresAtEpochMs:r,metadataDigest:await Qe(P)}}async signFrame(e,n,t,r){let s=await P.subtle.importKey("pkcs8",p(t),"Ed25519",!1,["sign"]),o=await Dn(e,n,s,P),a=await P.subtle.importKey("spki",p(r),"Ed25519",!1,["verify"]);if(!await Je(e,n,o,a,P))throw new Error("inbox_identity_mismatch");return o}async protectShares(e,n,t){let r=await this.worker.split(ue(n),{threshold:e.threshold,total:e.total,messageId:e.messageId,manifestDigest:t}),s=P.getRandomValues(new Uint8Array(32)),o=[];for(let a=0;a<e.total;a++){let c=e.shareLayers[a];o.push({kind:"DATA",index:a,shareId:c.dataShareId,layerId:c.id,ciphertext:Buffer.from(await Xe(r.dataShares[a],s,t,e.messageId,P)).toString("base64")}),o.push({kind:"KEY",index:a,shareId:c.keyShareId,layerId:c.id,ciphertext:Buffer.from(await Xe(r.keyShares[a],s,t,e.messageId,P)).toString("base64")})}return{shareKey:s,shares:o}}async wrapRecipientKeys(e,n,t){return Promise.all(e.recipients.map(async r=>{let s=p(r.encryptionPublicKey);if(Y(s)!==r.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let o=await P.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:r.memberId,deviceId:r.deviceId,deviceVersion:r.deviceVersion,keyFingerprint:r.encryptionKeyFingerprint,wrappedContentKey:Buffer.from(await Ln(n,o,t,P)).toString("base64")}}))}async verifyOpening(e,n,t){let r=p(n.canonicalManifest),s=_n(r);if(s.tenantId!==e.identity.tenantId||s.conversationId!==e.conversationId||s.messageId!==e.messageId||s.expiresAtEpochMs<=Date.now()||!T(s.metadataDigest,t??await Qe(P)))throw new Error("inbox_manifest_mismatch");let o=s.recipients.find(c=>c.memberId===e.identity.memberId&&c.deviceId===e.identity.deviceId);if(!o||!T(o.encryptionKeyFingerprint,x(Y(p(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let a=p(n.senderSigningPublicKey);if(n.senderSigningKeyFingerprint!==Y(a)||!T(s.senderSigningKeyFingerprint,x(n.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return{manifest:s,manifestDigest:await se(r),senderPublicDer:a}}async recoverFrame(e,n,t,r){let s=await qn(p(e.tenantWrappedShareKey),x(r),t,n.tenantId,n.messageId,P),o=[],a=[],c=new Set;for(let g of e.shares){let I=`${g.kind}:${g.index}`;if(c.has(I))throw new Error("duplicate_inbox_share");c.add(I);let y=await Tn(p(g.ciphertext),s,t,n.messageId,g.kind==="DATA"?"data":"key",g.index,P);(g.kind==="DATA"?o:a).push(y)}if(o.length!==a.length||o.length<2)throw new Error("incomplete_inbox_shares");let l=await this.worker.reconstruct(o,a,{threshold:o.length,total:o.length,messageId:n.messageId,manifestDigest:t});return Cn(l)}async decryptText(e,n,t,r,s,o){return Mn(await this.decryptContent(e,n,t,r,s,o))}async decryptContent(e,n,t,r,s,o){let a=await P.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Je(t,n,p(e.signature),a,P))throw new Error("inbox_signature_invalid");let c=await P.subtle.importKey("pkcs8",p(o),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),l=await Un(p(e.wrappedContentKey),c,r,P);return Kn(n,l,r,P)}};import{canonicalInboxManifest as zn,decodeInboxContentFrame as Gn,decodeInboxFile as Bn,decryptInboxShare as Vn,encodeInboxContentFrame as Hn,encodeInboxFile as Wn,encryptInboxShare as Ze,inboxFileMetadataDigest as en,sealInboxContent as jn,unwrapInboxShareKey as Yn,wrapInboxShareKey as Xn}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var ge=class extends B{constructor(n){super(n);this.fileApi=n}async sendFile(n){n.signal?.throwIfAborted();let{preparation:t,sender:r}=await this.prepareSender(n),s=await this.fileManifest(n,t,r),o=zn(s),a=await se(o),c=Wn(n.file),l;try{l=await jn(c,a,D)}finally{c.fill(0)}let{contentKey:g,frame:I}=l,y=await this.signFrame(s,I,n.identity.signingPrivateKey,r.signingPublicKey);n.signal?.throwIfAborted();let S=await this.worker.split(Hn(I),{threshold:t.threshold,total:t.total,messageId:t.messageId,manifestDigest:a},n.signal,A=>n.onProgress?.(0,t.total*2,A.stage));n.signal?.throwIfAborted();let U=D.getRandomValues(new Uint8Array(32)),N=[];for(let A=0;A<t.total;A++){let $=t.shareLayers[A];N.push({reference:{kind:"DATA",index:A,shareId:$.dataShareId,layerId:$.id},bytes:await Ze(S.dataShares[A],U,a,t.messageId,D)}),N.push({reference:{kind:"KEY",index:A,shareId:$.keyShareId,layerId:$.id},bytes:await Ze(S.keyShares[A],U,a,t.messageId,D)})}let q=await this.wrapRecipientKeys(t,g,a),an=await Xn(U,x(n.tenantKeyHex),a,s.tenantId,s.messageId,D);n.signal?.throwIfAborted();let fe=await this.fileApi.stageInboxFile(n.conversationId,{messageId:t.messageId,senderDeviceId:r.deviceId,participantRevision:t.participantRevision,expiresAt:n.expiresAt,idempotencyKey:t.messageId,canonicalManifest:Buffer.from(o).toString("base64"),signature:Buffer.from(y).toString("base64"),tenantWrappedShareKey:Buffer.from(an).toString("base64"),recipients:q,shares:N.map(A=>A.reference)},n.signal);if(fe.messageId!==t.messageId||fe.status!=="PREPARING")throw new Error("invalid_inbox_stage");for(let A=0;A<N.length;A++){n.signal?.throwIfAborted();let $=N[A];await this.fileApi.uploadInboxFileShare(n.conversationId,t.messageId,$.reference.shareId,$.bytes,n.signal),n.onProgress?.(A+1,N.length,"UPLOADING")}n.signal?.throwIfAborted();let de=await this.fileApi.publishInboxFile(n.conversationId,t.messageId,n.signal);if(de.messageId!==t.messageId||de.status!=="AVAILABLE")throw new Error("invalid_inbox_publish");return de}async openFile(n){n.signal?.throwIfAborted();let t=await this.fileApi.openInboxFile(n.conversationId,n.messageId,n.identity.deviceId,n.signal),r,s;try{let{manifest:a,manifestDigest:c,senderPublicDer:l}=await this.verifyOpening(n,t,await en(D)),g=await this.recoverFileFrame(n,t,a,c);s=await this.decryptContent(t,g,a,c,l,n.identity.encryptionPrivateKey),r=Bn(s),n.signal?.throwIfAborted(),await n.save(r,{leaseId:t.leaseId,leaseExpiresAt:t.leaseExpiresAt}),n.signal?.throwIfAborted()}catch(a){try{await this.fileApi.releaseInboxMessage(n.conversationId,n.messageId,n.identity.deviceId,t.leaseId)}catch{}throw a}finally{s?.fill(0)}let o=await this.ack(n.conversationId,n.messageId,n.identity.deviceId,t.leaseId,n.signal);return n.signal?.throwIfAborted(),{name:r.name,mimeType:r.mimeType,size:r.bytes.length,leaseId:t.leaseId,leaseExpiresAt:t.leaseExpiresAt,acknowledgement:o}}async fileManifest(n,t,r){let s=Date.parse(n.expiresAt);if(!Number.isSafeInteger(s)||s<=Date.now())throw new Error("invalid_inbox_expiry");return{tenantId:n.identity.tenantId,conversationId:n.conversationId,messageId:t.messageId,senderId:n.identity.memberId,senderDeviceId:r.deviceId,senderSigningKeyFingerprint:x(r.signingKeyFingerprint),participantRevision:t.participantRevision,recipients:t.recipients.map(o=>({memberId:o.memberId,deviceId:o.deviceId,encryptionKeyFingerprint:x(o.encryptionKeyFingerprint)})),expiresAtEpochMs:s,metadataDigest:await en(D)}}async recoverFileFrame(n,t,r,s){let o=await Yn(p(t.tenantWrappedShareKey),x(n.tenantKeyHex),s,r.tenantId,r.messageId,D),a=[],c=[],l=new Set;for(let I=0;I<t.shares.length;I++){n.signal?.throwIfAborted();let y=t.shares[I],S=`${y.kind}:${y.index}`;if(l.has(S))throw new Error("duplicate_inbox_share");l.add(S);let U=await this.fileApi.downloadInboxFileShare(n.conversationId,n.messageId,y.shareId,n.identity.deviceId,t.leaseId,n.signal),N=await Vn(U,o,s,r.messageId,y.kind==="DATA"?"data":"key",y.index,D);(y.kind==="DATA"?a:c).push(N),n.onProgress?.(I+1,t.shares.length,"DOWNLOADING")}if(a.length!==c.length||a.length<2)throw new Error("incomplete_inbox_shares");n.signal?.throwIfAborted();let g=await this.worker.reconstruct(a,c,{threshold:a.length,total:a.length,messageId:r.messageId,manifestDigest:s},n.signal,I=>n.onProgress?.(t.shares.length,t.shares.length,I.stage));return n.signal?.throwIfAborted(),Gn(g)}};import{createHash as tn,webcrypto as Qn}from"node:crypto";import{canonicalInboxParentManifest as Jn,decodeInboxParentManifest as Zn,encodeInboxParentNormalFrame as et,decodeInboxParentNormalFrame as nt,sealInboxParentNormalBody as tt,openInboxParentNormalBody as rt,wrapInboxParentNormalKey as it,unwrapInboxParentNormalKey as st,signInboxParentNormalFrame as ot,verifyInboxParentNormalFrame as nn,encodeInboxText as at,decodeInboxText as dt}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var O=Qn,X=i=>tn("sha256").update(i).digest("hex"),oe=i=>Buffer.from(i).toString("base64"),Ie=class{constructor(e){this.api=e}pending=new Map;async send(e){let n=this.digestInput(e),t=e.parentId?this.pending.get(e.parentId):void 0;if(t){if(t.inputDigest!==n)throw new Error("inbox_idempotency_conflict");let l=await this.api.publishNormalInboxMessage(e.conversationId,t.submission);return this.pending.delete(e.parentId),l}let r=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validatePreparation(e,r),o=this.createManifest(e,r,s),a=await this.createSubmission(e,r,s,o);this.rememberSubmission(o.parentId,n,a);let c=await this.api.publishNormalInboxMessage(e.conversationId,a);return this.pending.delete(o.parentId),c}digestInput(e){return tn("sha256").update(JSON.stringify([e.conversationId,e.parentId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.text])).digest("hex")}validatePreparation(e,n){if(n.conversationId!==e.conversationId||n.recipients.length<2||n.recipients.length>50)throw new Error("invalid_inbox_preparation");let t=n.recipients.find(r=>r.memberId===e.identity.memberId&&r.deviceId===e.identity.deviceId);if(!t||t.signingPublicKey!==e.identity.signingPublicKey||t.encryptionPublicKey!==e.identity.encryptionPublicKey||X(p(t.signingPublicKey))!==t.signingKeyFingerprint||X(p(t.encryptionPublicKey))!==t.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return t}createManifest(e,n,t){return{mode:"NORMAL",tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:e.parentId??n.parentId,senderId:e.identity.memberId,senderDeviceId:t.deviceId,senderSigningKeyFingerprint:x(t.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(r=>({memberId:r.memberId,deviceId:r.deviceId,encryptionKeyFingerprint:x(r.encryptionKeyFingerprint)})),protectedUnits:[]}}async createSubmission(e,n,t,r){let s=Jn(r),{contentKey:o,frame:a}=await tt(at(e.text),r,O),c=await O.subtle.importKey("pkcs8",p(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),l=await ot(r,a,c,O),g=await O.subtle.importKey("spki",p(t.signingPublicKey),"Ed25519",!1,["verify"]);if(!await nn(r,a,l,g,O))throw new Error("inbox_identity_mismatch");let I=await Promise.all(n.recipients.map(y=>this.wrapRecipientKey(y,o,r)));return{parentId:r.parentId,idempotencyKey:r.parentId,senderDeviceId:t.deviceId,participantRevision:n.participantRevision,canonicalManifest:oe(s),frame:oe(et(a)),signature:oe(l),recipients:I}}async wrapRecipientKey(e,n,t){let r=p(e.encryptionPublicKey);if(X(r)!==e.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let s=await O.subtle.importKey("spki",r,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:e.memberId,deviceId:e.deviceId,deviceVersion:e.deviceVersion,keyFingerprint:e.encryptionKeyFingerprint,wrappedContentKey:oe(await it(n,s,t,O))}}rememberSubmission(e,n,t){if(this.pending.size>=32){let r=this.pending.keys().next().value;r&&this.pending.delete(r)}this.pending.set(e,{inputDigest:n,submission:t})}list(e,n,t){return this.api.listNormalInboxMessages(e,n,t)}async open(e){e.signal?.throwIfAborted();let n=await this.api.openNormalInboxMessage(e.conversationId,e.parentId,e.identity.deviceId,e.signal),t=Zn(p(n.canonicalManifest));if(t.mode!=="NORMAL"||t.tenantId!==e.identity.tenantId||t.conversationId!==e.conversationId||t.parentId!==e.parentId||t.senderId!==n.senderMemberId||t.senderDeviceId!==n.senderDeviceId||t.participantRevision!==n.participantRevision)throw new Error("inbox_manifest_mismatch");let r=t.recipients.find(I=>I.memberId===e.identity.memberId&&I.deviceId===e.identity.deviceId);if(!r||!T(r.encryptionKeyFingerprint,x(X(p(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let s=p(n.senderSigningPublicKey);if(!T(t.senderSigningKeyFingerprint,x(X(s))))throw new Error("inbox_sender_key_mismatch");let o=nt(p(n.frame)),a=await O.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await nn(t,o,p(n.signature),a,O))throw new Error("inbox_signature_invalid");let c=await O.subtle.importKey("pkcs8",p(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),l=await st(p(n.wrappedContentKey),c,t,O),g=dt(await rt(o,l,t,O));return e.signal?.throwIfAborted(),{text:g,parentId:n.parentId,sequence:n.sequence}}markRead(e){return this.api.markNormalInboxMessageRead(e.conversationId,e.parentId,e.identity.deviceId)}};import{createHash as on,webcrypto as ct}from"node:crypto";import{canonicalInboxParentManifest as lt,decodeInboxParentManifest as pt,decodeInboxManifest as mt,encodeInboxParentNormalFrame as ut,decodeInboxParentNormalFrame as gt,sealInboxParentNormalBody as It,openInboxParentNormalBody as bt,wrapInboxParentNormalKey as ft,unwrapInboxParentNormalKey as yt,signInboxParentNormalFrame as ht,verifyInboxParentNormalFrame as rn,signInboxProtectedParent as xt,verifyInboxProtectedParent as sn,inboxProtectedUnitCommitment as Pt,encodeInboxText as wt,decodeInboxText as vt}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var E=ct,ae=i=>Buffer.from(i).toString("base64"),Q=i=>on("sha256").update(i).digest("hex"),be=class{constructor(e,n){this.api=e;this.child=n??new B(e)}pending=new Map;child;async send(e){let n=on("sha256").update(JSON.stringify([e.conversationId,e.identity.tenantId,e.identity.memberId,e.identity.deviceId,e.segments])).digest("hex"),t=e.parentId?[e.parentId,this.pending.get(e.parentId)]:[...this.pending.entries()].find(([,a])=>a.digest===n),r=t?.[1];if(r){if(r.digest!==n)throw new Error("inbox_idempotency_conflict");try{e.onProgress?.(r.submission.protectedUnits.length,r.submission.protectedUnits.length)}catch{}let a=await this.api.publishInboxParent(e.conversationId,r.submission);return this.pending.delete(t[0]),a}let s=await this.prepare(e);this.pending.size>=32&&this.pending.delete(this.pending.keys().next().value),this.pending.set(s.parentId,{digest:n,submission:s});let o=await this.api.publishInboxParent(e.conversationId,s);return this.pending.delete(s.parentId),o}async prepare(e){if(!e.segments.length||e.segments.length>9)throw new Error("invalid_inbox_parent_segments");let n=e.segments.filter(S=>"protectedText"in S).length;if(n<1||n>4)throw new Error("invalid_inbox_parent_segments");let t=e.segments.length===1&&n===1?"PROTECTED":"MIXED";if(t==="MIXED"&&!e.segments.some(S=>"text"in S))throw new Error("invalid_inbox_parent_segments");let r=await this.api.getNormalInboxSendPreparation(e.conversationId),s=this.validateSender(e,r),o=e.parentId??r.parentId,{protectedUnits:a,manifestUnits:c}=await this.prepareChildren(e,r,s),l=this.parentManifest(e,r,s,o,t,c),{frame:g,signature:I,recipients:y}=await this.signAndWrap(e,r,s,l);return{parentId:o,idempotencyKey:o,senderDeviceId:s.deviceId,mode:t,participantRevision:r.participantRevision,canonicalManifest:ae(lt(l)),signature:ae(I),frame:g,recipients:y,protectedUnits:a}}async prepareChildren(e,n,t){let r=[],s=[],o=e.segments.filter(a=>"protectedText"in a).length;for(let a=0;a<e.segments.length;a++){let c=e.segments[a];if(!("protectedText"in c))continue;let l=await this.child.prepare({conversationId:e.conversationId,text:c.protectedText,expiresAt:c.expiresAt,identity:e.identity,tenantKeyHex:e.tenantKeyHex}),g=mt(p(l.submission.canonicalManifest));this.validateChildSnapshot(g,e,n,t);let I=await Pt(g,p(l.frame),p(l.submission.signature),E);r.push({position:a,frame:l.frame,child:l.submission}),s.push({unitId:l.submission.messageId,position:a,commitment:I});try{e.onProgress?.(r.length,o)}catch{}}return{protectedUnits:r,manifestUnits:s}}validateChildSnapshot(e,n,t,r){if(e.tenantId!==n.identity.tenantId||e.conversationId!==n.conversationId||e.senderId!==n.identity.memberId||e.senderDeviceId!==r.deviceId||e.participantRevision!==t.participantRevision||e.recipients.length!==t.recipients.length||e.recipients.some(s=>!t.recipients.some(o=>o.memberId===s.memberId&&o.deviceId===s.deviceId&&T(s.encryptionKeyFingerprint,x(o.encryptionKeyFingerprint)))))throw new Error("inbox_child_snapshot_mismatch")}parentManifest(e,n,t,r,s,o){return{mode:s,tenantId:e.identity.tenantId,conversationId:e.conversationId,parentId:r,senderId:e.identity.memberId,senderDeviceId:t.deviceId,senderSigningKeyFingerprint:x(t.signingKeyFingerprint),participantRevision:n.participantRevision,recipients:n.recipients.map(a=>({memberId:a.memberId,deviceId:a.deviceId,encryptionKeyFingerprint:x(a.encryptionKeyFingerprint)})),protectedUnits:o}}async signAndWrap(e,n,t,r){let s=await E.subtle.importKey("pkcs8",p(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),o=await E.subtle.importKey("spki",p(t.signingPublicKey),"Ed25519",!1,["verify"]);if(r.mode==="PROTECTED")return{signature:await this.signProtectedParent(r,s,o),recipients:this.recipientReferences(n)};let{frame:a,signature:c,contentKey:l}=await this.sealMixedParent(e,r,s,o);return{frame:a,signature:c,recipients:await this.wrapRecipients(n,l,r)}}async signProtectedParent(e,n,t){let r=await xt(e,n,E);if(!await sn(e,r,t,E))throw new Error("inbox_identity_mismatch");return r}async sealMixedParent(e,n,t,r){let s=e.segments.map((c,l)=>"text"in c?{text:c.text}:{unitId:n.protectedUnits.find(g=>g.position===l).unitId}),o=await It(wt(JSON.stringify(s)),n,E),a=await ht(n,o.frame,t,E);if(!await rn(n,o.frame,a,r,E))throw new Error("inbox_identity_mismatch");return{frame:ae(ut(o.frame)),signature:a,contentKey:o.contentKey}}recipientReferences(e){return e.recipients.map(n=>({memberId:n.memberId,deviceId:n.deviceId,deviceVersion:n.deviceVersion,keyFingerprint:n.encryptionKeyFingerprint}))}async wrapRecipients(e,n,t){return Promise.all(e.recipients.map(async r=>{let s=p(r.encryptionPublicKey);if(Q(s)!==r.encryptionKeyFingerprint)throw new Error("inbox_recipient_key_mismatch");let o=await E.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{memberId:r.memberId,deviceId:r.deviceId,deviceVersion:r.deviceVersion,keyFingerprint:r.encryptionKeyFingerprint,wrappedContentKey:ae(await ft(n,o,t,E))}}))}validateSender(e,n){if(n.conversationId!==e.conversationId||n.recipients.length<2||n.recipients.length>50)throw new Error("invalid_inbox_preparation");let t=n.recipients.find(r=>r.memberId===e.identity.memberId&&r.deviceId===e.identity.deviceId);if(!t||t.signingPublicKey!==e.identity.signingPublicKey||t.encryptionPublicKey!==e.identity.encryptionPublicKey||Q(p(t.signingPublicKey))!==t.signingKeyFingerprint||Q(p(t.encryptionPublicKey))!==t.encryptionKeyFingerprint)throw new Error("inbox_identity_mismatch");return t}list(e,n,t){return this.api.listInboxParents(e,n,t)}clearHistory(e,n){return this.api.clearInboxHistory(e,n)}async open(e){let{opened:n,manifest:t,segments:r}=await this.openAndVerify(e);return{parentId:n.parentId,sequence:n.sequence,mode:t.mode,segments:r}}async openAndVerify(e){e.signal?.throwIfAborted();let n=await this.api.openInboxParent(e.conversationId,e.parentId,e.identity.deviceId,e.signal),{manifest:t,senderKey:r}=await this.verifyOpening(e,n),s=t.mode==="PROTECTED"?await this.openProtectedParent(n,t,r):await this.openMixedParent(e,n,t,r);return e.signal?.throwIfAborted(),{opened:n,manifest:t,segments:s}}async verifyOpening(e,n){let t=pt(p(n.canonicalManifest));return this.verifyManifestContext(e,n,t),this.verifyManifestUnits(n,t),this.verifyRecipient(e,t),{manifest:t,senderKey:await this.senderKey(n,t)}}verifyManifestContext(e,n,t){if(t.mode!==n.mode||t.tenantId!==e.identity.tenantId||t.conversationId!==e.conversationId||t.parentId!==e.parentId||t.senderId!==n.senderMemberId||t.senderDeviceId!==n.senderDeviceId||t.participantRevision!==n.participantRevision)throw new Error("inbox_manifest_mismatch")}verifyManifestUnits(e,n){if(n.protectedUnits.length!==e.protectedUnits.length||n.protectedUnits.some((t,r)=>t.unitId!==e.protectedUnits[r].unitId||t.position!==e.protectedUnits[r].position||!T(t.commitment,x(e.protectedUnits[r].commitment))))throw new Error("inbox_manifest_mismatch")}verifyRecipient(e,n){let t=n.recipients.find(r=>r.memberId===e.identity.memberId&&r.deviceId===e.identity.deviceId);if(!t||!T(t.encryptionKeyFingerprint,x(Q(p(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch")}async senderKey(e,n){let t=p(e.senderSigningPublicKey);if(Q(t)!==e.senderSigningKeyFingerprint||!T(n.senderSigningKeyFingerprint,x(e.senderSigningKeyFingerprint)))throw new Error("inbox_sender_key_mismatch");return E.subtle.importKey("spki",t,"Ed25519",!1,["verify"])}async openProtectedParent(e,n,t){if(e.frame!==null||e.wrappedContentKey!==null||!await sn(n,p(e.signature),t,E))throw new Error("inbox_signature_invalid");return[{unitId:n.protectedUnits[0].unitId,position:0,status:e.protectedUnits[0].status}]}async openMixedParent(e,n,t,r){if(!n.frame||!n.wrappedContentKey)throw new Error("inbox_missing_normal_body");let s=gt(p(n.frame));if(!await rn(t,s,p(n.signature),r,E))throw new Error("inbox_signature_invalid");let o=await E.subtle.importKey("pkcs8",p(e.identity.encryptionPrivateKey),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),a=await yt(p(n.wrappedContentKey),o,t,E),c=JSON.parse(vt(await bt(s,a,t,E)));return this.decodeSegments(c,n,t)}decodeSegments(e,n,t){if(!Array.isArray(e))throw new Error("invalid_inbox_parent_body");let r=e.map((s,o)=>{if(!s||typeof s!="object"||Array.isArray(s))throw new Error("invalid_inbox_parent_body");let a=s;if(typeof a.text=="string"&&Object.keys(a).length===1)return{text:a.text};let c=t.protectedUnits.find(l=>l.position===o);if(!c||a.unitId!==c.unitId||Object.keys(a).length!==1)throw new Error("invalid_inbox_parent_body");return{unitId:c.unitId,position:o,status:n.protectedUnits.find(l=>l.unitId===c.unitId).status}});if(t.protectedUnits.some(s=>!r[s.position]||!("unitId"in r[s.position])))throw new Error("invalid_inbox_parent_body");return r}async revealUnit(e){let{manifest:n,segments:t}=await this.openAndVerify(e);if(!t.some(s=>"unitId"in s&&s.unitId===e.unitId))throw new Error("inbox_parent_unit_mismatch");let r=n.protectedUnits.find(s=>s.unitId===e.unitId);return this.child.openCommitted({conversationId:e.conversationId,messageId:e.unitId,identity:e.identity,tenantKeyHex:e.tenantKeyHex,signal:e.signal},r.commitment)}};export{ie as HttpElementsApiPort,ge as NodeInboxFile,Ie as NodeInboxNormal,be as NodeInboxParent,B as NodeInboxText,wn as generateInheritiFileKey,vn as sealInheritiFile,Sn as sealInheritiFileKey};
|