@safetech/inheriti-client-sdk 1.17.20 → 1.17.21
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 +14 -14
- package/dist/node-base.js +1 -1
- package/dist/node.js +1 -1
- package/dist/sdk-types.d.ts +4 -1
- package/dist/src/business/inbox/inbox-response-validator.d.ts +1 -0
- package/dist/src/elements/http-elements-api-port.d.ts +2 -1
- package/dist/src/operator-auth/operator-auth-client.d.ts +1 -0
- package/dist/src/operator-auth/types.d.ts +1 -0
- package/package.json +2 -2
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"],je={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},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(F(i,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Qe(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(F(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(Ye(n.matchOrigins),!n.isBinary){let s=je[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(F(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")}Xe(i)}function Ye(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 Xe(i){let e=i.policy;if(e&&F(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"){F(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){F(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;F(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 Qe(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 F(i,e,n){if(Object.keys(i).some(t=>!e.includes(t)))throw new y(n)}var Je=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Ze=["DIRECT","GOVERNED"],ye=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],en=["ACTIVE","REVOKED"],nn=["SK_MOBILE"],tn=["ACTIVE","INACTIVE"],rn=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function fe(i){let e=v(i);return{items:A(e.items).map(Pe),nextCursor:e.nextCursor===null?null:m(e.nextCursor,"nextCursor")}}function xe(i){let e=v(i);return{total:O(e.total,"total"),items:A(e.items).map(n=>{let t=v(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:U(t.status),title:m(t.title,"log.title"),details:A(t.details).map(r=>{let s=v(r);return{label:m(s.label,"log.detail.label"),value:m(s.value,"log.detail.value")}})}})}}function he(i){let e=v(i),n=Pe(e),t=v(e.source),r=m(t.kind,"source.kind");return{...n,assets:A(e.assets).map(s=>{let o=v(s);return{id:m(o.id,"asset.id"),code:U(o.code),type:E(m(o.type,"asset.type"),j),name:m(o.name,"asset.name"),isBinary:on(o.isBinary,"asset.isBinary"),fieldNames:A(o.fieldNames).map(a=>m(a,"asset.fieldNames")),fileName:U(o.fileName),mimeType:U(o.mimeType),size:o.size===void 0||o.size===null?void 0:O(o.size,"asset.size"),matchOrigins:o.matchOrigins===void 0?void 0:A(o.matchOrigins).map(a=>m(a,"asset.matchOrigins"))}}),participants:A(e.participants).map(s=>{let o=v(s);return{id:m(o.id,"participant.id"),displayName:m(o.displayName,"participant.displayName"),relationships:A(o.relationships).map(a=>E(m(a,"relationship"),ye)),lifecycle:E(m(o.lifecycle,"participant.lifecycle"),en)}}),revealPolicy:(()=>{let s=v(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=v(e.dms);return{subjectEmail:m(s.subjectEmail,"dms.subjectEmail"),countdownDays:O(s.countdownDays,"dms.countdownDays"),countdownHours:O(s.countdownHours,"dms.countdownHours"),countdownMinutes:O(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=v(i);return{operationId:m(e.operationId,"operationId"),stage:E(m(e.stage,"stage"),me),outcome:E(m(e.outcome,"outcome"),rn),planId:U(e.planId),lastErrorCode:U(e.lastErrorCode),participants:e.participants===void 0?void 0:A(e.participants).map(n=>{let t=v(n);return{clientParticipantRef:m(t.clientParticipantRef,"clientParticipantRef"),planParticipantId:m(t.planParticipantId,"planParticipantId"),relationships:A(t.relationships).map(r=>sn(m(r,"relationship"),ye))}})}}function Pe(i){let e=v(i),n=v(e.assetSummary),t=v(e.governance),r=v(e.participantSummary);return{id:m(e.id,"id"),name:m(e.name,"name"),description:U(e.description),status:E(m(e.status,"status"),Je),createdAt:m(e.createdAt,"createdAt"),configuredAt:U(e.configuredAt),assetSummary:{count:O(n.count,"assetSummary.count"),types:A(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"),Ze),minimumApprovals:O(t.minimumApprovals,"minimumApprovals")},participantSummary:{owners:O(r.owners,"owners"),mergers:O(r.mergers,"mergers"),moderators:O(r.moderators,"moderators")},authentication:be(e.authentication).map(s=>{let o=v(s);return{id:E(m(o.id,"authentication.id"),nn),status:E(m(o.status,"authentication.status"),tn)}})}}function E(i,e){return e.includes(i)?i:{kind:"UNKNOWN",raw:i}}function sn(i,e){if(!e.includes(i))throw new Error("invalid_elements_response");return i}function v(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("invalid_elements_response");return i}function be(i){return i==null?[]:A(i)}function A(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 U(i){return i==null?void 0:m(i,"optional")}function O(i,e){if(typeof i!="number"||!Number.isFinite(i))throw new Error("invalid_elements_response");return i}function on(i,e){if(typeof i!="boolean")throw new Error("invalid_elements_response");return i}function ve(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 an(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)}}function we(i){let e=b(i);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(an),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 Se(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 Ee(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 Ae(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)}}),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 Re(i){return{readThroughSequence:u(b(i).readThroughSequence,0)}}function _e(i){return{clearedThroughSequence:u(b(i).clearedThroughSequence,0)}}function Ce(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 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:R(e.createdAt),updatedAt:R(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: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 Te(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 Me(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 Ke(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 Ne(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 Oe(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}})),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: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 De(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 V(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 B(i){return typeof i.error=="object"&&i.error?.requestId?i.error.requestId:i.description}var k=class extends Error{constructor(n,t,r){super(t??`elements_api_request_failed_${n}`);this.status=n;this.code=t;this.detail=r;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;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 Te(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 Me(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 Ke(await this.request(`v1/inbox/members${r}`,"GET",void 0,void 0,void 0,n))}async getInboxSendPreparation(e,n){return Ne(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,n))}async getNormalInboxSendPreparation(e,n){return Ee(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 we(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 Se(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 Ae(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 Ce(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 Re(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 k(a.status,V(c),B(c))}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 De(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=[],P=0;try{for(;;){o?.throwIfAborted();let N=await g.read();if(N.done)break;if(P+=N.value.length,P>14*1024*1024)throw new Error("invalid_inbox_share_size");f.push(N.value)}}catch(N){throw await g.cancel().catch(()=>{}),N}let K=new Uint8Array(P),T=0;for(let N of f)K.set(N,T),T+=N.length;return K}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 Oe(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(ve)}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 he(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 xe(await this.request(`v1/plans/${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[P,K]of Object.entries(s??{}))c.set(P,K);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 k(g.status,V(f),B(f));if(!f.ok||f.result===void 0)throw new k(g.status,V(f),B(f));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 k(c.status,V(l),B(l))}return c}async requestWithoutResult(e,n){this.requireBusinessSelection(e);let t=await this.getBearerToken(),r=new Headers({"x-elements-environment":this.environment});t&&r.set("authorization",`Bearer ${t}`),this.business?.organizationId&&r.set("x-organization-id",this.business.organizationId),n&&r.set("content-type","application/json");let s=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,o=await this.transport(new URL(e,s),{method:"POST",headers:r,body:n?JSON.stringify(n):void 0}),a=await Q(o);if(!o.ok||!a.ok)throw new k(o.status,V(a),B(a))}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 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{createHash as dn,webcrypto as cn}from"node:crypto";import{canonicalInboxManifest as ln,decodeInboxManifest as pn,decodeInboxContentFrame as mn,decodeInboxText as un,decryptInboxShare as In,encodeInboxContentFrame as oe,encodeInboxText as gn,encryptInboxShare as Ue,inboxProtectedUnitCommitment as bn,inboxTextMetadataDigest as Le,openInboxContent as yn,sealInboxContent as fn,signInboxFrame as xn,unwrapInboxContentKey as hn,unwrapInboxShareKey as Pn,verifyInboxFrame as Fe,wrapInboxContentKey as vn,wrapInboxShareKey as wn}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as Sn}from"@safetech/inheriti-core-sdk/workers/inbox.node";var M=cn,h=M,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)},_=(i,e)=>i.length===e.length&&i.every((n,t)=>n===e[t]),Z=async i=>new Uint8Array(await h.subtle.digest("SHA-256",Uint8Array.from(i))),z=i=>dn("sha256").update(i).digest("hex"),q=class{constructor(e,n=new Sn){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=ln(r),o=await Z(s),{contentKey:a,frame:c}=await fn(gn(e.text),o,h),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),P=await wn(I,x(e.tenantKeyHex),o,r.tenantId,r.messageId,h);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(P).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 bn(o,oe(l),p(t.signature),h)))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||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: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 Le(h)}}async signFrame(e,n,t,r){let s=await h.subtle.importKey("pkcs8",p(t),"Ed25519",!1,["sign"]),o=await xn(e,n,s,h),a=await h.subtle.importKey("spki",p(r),"Ed25519",!1,["verify"]);if(!await Fe(e,n,o,a,h))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=h.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 Ue(r.dataShares[a],s,t,e.messageId,h)).toString("base64")}),o.push({kind:"KEY",index:a,shareId:c.keyShareId,layerId:c.id,ciphertext:Buffer.from(await Ue(r.keyShares[a],s,t,e.messageId,h)).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 h.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 vn(n,o,t,h)).toString("base64")}}))}async verifyOpening(e,n,t){let r=p(n.canonicalManifest),s=pn(r);if(s.tenantId!==e.identity.tenantId||s.conversationId!==e.conversationId||s.messageId!==e.messageId||s.expiresAtEpochMs<=Date.now()||!_(s.metadataDigest,t??await Le(h)))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,x(z(p(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let a=p(n.senderSigningPublicKey);if(n.senderSigningKeyFingerprint!==z(a)||!_(s.senderSigningKeyFingerprint,x(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 Pn(p(e.tenantWrappedShareKey),x(r),t,n.tenantId,n.messageId,h),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 In(p(I.ciphertext),s,t,n.messageId,I.kind==="DATA"?"data":"key",I.index,h);(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 mn(l)}async decryptText(e,n,t,r,s,o){return un(await this.decryptContent(e,n,t,r,s,o))}async decryptContent(e,n,t,r,s,o){let a=await h.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Fe(t,n,p(e.signature),a,h))throw new Error("inbox_signature_invalid");let c=await h.subtle.importKey("pkcs8",p(o),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),l=await hn(p(e.wrappedContentKey),c,r,h);return yn(n,l,r,h)}};import{canonicalInboxManifest as En,decodeInboxContentFrame as An,decodeInboxFile as Rn,decryptInboxShare as _n,encodeInboxContentFrame as Cn,encodeInboxFile as Tn,encryptInboxShare as qe,inboxFileMetadataDigest as $e,sealInboxContent as Mn,unwrapInboxShareKey as Kn,wrapInboxShareKey as Nn}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=En(s),a=await Z(o),c=Tn(n.file),l;try{l=await Mn(c,a,M)}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 P=await this.worker.split(Cn(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 K=M.getRandomValues(new Uint8Array(32)),T=[];for(let w=0;w<t.total;w++){let L=t.shareLayers[w];T.push({reference:{kind:"DATA",index:w,shareId:L.dataShareId,layerId:L.id},bytes:await qe(P.dataShares[w],K,a,t.messageId,M)}),T.push({reference:{kind:"KEY",index:w,shareId:L.keyShareId,layerId:L.id},bytes:await qe(P.keyShares[w],K,a,t.messageId,M)})}let N=await this.wrapRecipientKeys(t,I,a),We=await Nn(K,x(n.tenantKeyHex),a,s.tenantId,s.messageId,M);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(We).toString("base64"),recipients:N,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 L=T[w];await this.fileApi.uploadInboxFileShare(n.conversationId,t.messageId,L.reference.shareId,L.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 $e(M)),I=await this.recoverFileFrame(n,t,a,c);s=await this.decryptContent(t,I,a,c,l,n.identity.encryptionPrivateKey),r=Rn(s),n.signal?.throwIfAborted(),await n.save(r),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 $e(M)}}async recoverFileFrame(n,t,r,s){let o=await Kn(p(t.tenantWrappedShareKey),x(n.tenantKeyHex),s,r.tenantId,r.messageId,M),a=[],c=[],l=new Set;for(let g=0;g<t.shares.length;g++){n.signal?.throwIfAborted();let f=t.shares[g],P=`${f.kind}:${f.index}`;if(l.has(P))throw new Error("duplicate_inbox_share");l.add(P);let K=await this.fileApi.downloadInboxFileShare(n.conversationId,n.messageId,f.shareId,n.identity.deviceId,t.leaseId,n.signal),T=await _n(K,o,s,r.messageId,f.kind==="DATA"?"data":"key",f.index,M);(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(),An(I)}};import{createHash as Ve,webcrypto as On}from"node:crypto";import{canonicalInboxParentManifest as kn,decodeInboxParentManifest as Dn,encodeInboxParentNormalFrame as Un,decodeInboxParentNormalFrame as Ln,sealInboxParentNormalBody as Fn,openInboxParentNormalBody as qn,wrapInboxParentNormalKey as $n,unwrapInboxParentNormalKey as Gn,signInboxParentNormalFrame as Vn,verifyInboxParentNormalFrame as Ge,encodeInboxText as Bn,decodeInboxText as zn}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var C=On,H=i=>Ve("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 Ve("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: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=kn(r),{contentKey:o,frame:a}=await Fn(Bn(e.text),r,C),c=await C.subtle.importKey("pkcs8",p(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),l=await Vn(r,a,c,C),I=await C.subtle.importKey("spki",p(t.signingPublicKey),"Ed25519",!1,["verify"]);if(!await Ge(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(Un(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 $n(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=Dn(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,x(H(p(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let s=p(n.senderSigningPublicKey);if(!_(t.senderSigningKeyFingerprint,x(H(s))))throw new Error("inbox_sender_key_mismatch");let o=Ln(p(n.frame)),a=await C.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Ge(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 Gn(p(n.wrappedContentKey),c,t,C),I=zn(await qn(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 He,webcrypto as Hn}from"node:crypto";import{canonicalInboxParentManifest as Wn,decodeInboxParentManifest as jn,decodeInboxManifest as Yn,encodeInboxParentNormalFrame as Xn,decodeInboxParentNormalFrame as Qn,sealInboxParentNormalBody as Jn,openInboxParentNormalBody as Zn,wrapInboxParentNormalKey as et,unwrapInboxParentNormalKey as nt,signInboxParentNormalFrame as tt,verifyInboxParentNormalFrame as Be,signInboxProtectedParent as rt,verifyInboxProtectedParent as ze,inboxProtectedUnitCommitment as it,encodeInboxText as st,decodeInboxText as ot}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var S=Hn,ne=i=>Buffer.from(i).toString("base64"),W=i=>He("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=He("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(P=>"protectedText"in P).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(P=>"text"in P))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(Wn(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=Yn(p(l.submission.canonicalManifest));this.validateChildSnapshot(I,e,n,t);let g=await it(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,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 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 rt(e,n,S);if(!await ze(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 Jn(st(JSON.stringify(s)),n,S),a=await tt(n,o.frame,t,S);if(!await Be(n,o.frame,a,r,S))throw new Error("inbox_identity_mismatch");return{frame:ne(Xn(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 et(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=jn(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,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.encryptionKeyFingerprint,x(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,x(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 ze(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=Qn(p(n.frame));if(!await Be(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 nt(p(n.wrappedContentKey),o,t,S),c=JSON.parse(ot(await Zn(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};
|
|
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"],je={"PLAIN-TEXT":["text"],"USER-PSWD":["appOrWebsite","email","username","password"],"RECOVERY-CODE":["appOrWebsite","code"],"PIN-CODE":["deviceOrApp","code"],"API-KEY":["app","apiKey"],"PRIVATE-KEY":["publicAddress","privateKey"],"SEED-PHRASE":["words"],"PAYMENT-DEBIT-CARD":["cardNumber","cardHolderName","expiryDate","code"],"PAYMENT-CREDIT-CARD":["cardNumber","cardHolderName","expiryDate","code"]},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(q(i,["idempotencyKey","name","description","assets","participants","policy"],"plan_creation_field_unknown"),!Qe(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(q(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(Ye(n.matchOrigins),!n.isBinary){let s=je[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(q(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")}Xe(i)}function Ye(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 Xe(i){let e=i.policy;if(e&&q(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"){q(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){q(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;q(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 Qe(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 q(i,e,n){if(Object.keys(i).some(t=>!e.includes(t)))throw new y(n)}var Je=["DRAFT","ACTIVE","CONFIGURED","ARCHIVED"],Ze=["DIRECT","GOVERNED"],ye=["OWNER","MERGER","MODERATOR","CUSTODIAN","ALLOW","DENY"],en=["ACTIVE","REVOKED"],nn=["SK_MOBILE"],tn=["ACTIVE","INACTIVE"],rn=["IN_PROGRESS","COMPLETED","CANCELED","FAILED_RETRYABLE","FAILED_TERMINAL","RECONCILIATION_REQUIRED"];function fe(i){let e=v(i);return{items:A(e.items).map(Pe),nextCursor:e.nextCursor===null?null:m(e.nextCursor,"nextCursor")}}function xe(i){let e=v(i);return{total:O(e.total,"total"),items:A(e.items).map(n=>{let t=v(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:U(t.status),title:m(t.title,"log.title"),details:A(t.details).map(r=>{let s=v(r);return{label:m(s.label,"log.detail.label"),value:m(s.value,"log.detail.value")}})}})}}function he(i){let e=v(i),n=Pe(e),t=v(e.source),r=m(t.kind,"source.kind");return{...n,assets:A(e.assets).map(s=>{let o=v(s);return{id:m(o.id,"asset.id"),code:U(o.code),type:E(m(o.type,"asset.type"),j),name:m(o.name,"asset.name"),isBinary:on(o.isBinary,"asset.isBinary"),fieldNames:A(o.fieldNames).map(a=>m(a,"asset.fieldNames")),fileName:U(o.fileName),mimeType:U(o.mimeType),size:o.size===void 0||o.size===null?void 0:O(o.size,"asset.size"),matchOrigins:o.matchOrigins===void 0?void 0:A(o.matchOrigins).map(a=>m(a,"asset.matchOrigins"))}}),participants:A(e.participants).map(s=>{let o=v(s);return{id:m(o.id,"participant.id"),displayName:m(o.displayName,"participant.displayName"),relationships:A(o.relationships).map(a=>E(m(a,"relationship"),ye)),lifecycle:E(m(o.lifecycle,"participant.lifecycle"),en)}}),revealPolicy:(()=>{let s=v(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=v(e.dms);return{subjectEmail:m(s.subjectEmail,"dms.subjectEmail"),countdownDays:O(s.countdownDays,"dms.countdownDays"),countdownHours:O(s.countdownHours,"dms.countdownHours"),countdownMinutes:O(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=v(i);return{operationId:m(e.operationId,"operationId"),stage:E(m(e.stage,"stage"),me),outcome:E(m(e.outcome,"outcome"),rn),planId:U(e.planId),lastErrorCode:U(e.lastErrorCode),participants:e.participants===void 0?void 0:A(e.participants).map(n=>{let t=v(n);return{clientParticipantRef:m(t.clientParticipantRef,"clientParticipantRef"),planParticipantId:m(t.planParticipantId,"planParticipantId"),relationships:A(t.relationships).map(r=>sn(m(r,"relationship"),ye))}})}}function Pe(i){let e=v(i),n=v(e.assetSummary),t=v(e.governance),r=v(e.participantSummary);return{id:m(e.id,"id"),name:m(e.name,"name"),description:U(e.description),status:E(m(e.status,"status"),Je),createdAt:m(e.createdAt,"createdAt"),configuredAt:U(e.configuredAt),assetSummary:{count:O(n.count,"assetSummary.count"),types:A(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"),Ze),minimumApprovals:O(t.minimumApprovals,"minimumApprovals")},participantSummary:{owners:O(r.owners,"owners"),mergers:O(r.mergers,"mergers"),moderators:O(r.moderators,"moderators")},authentication:be(e.authentication).map(s=>{let o=v(s);return{id:E(m(o.id,"authentication.id"),nn),status:E(m(o.status,"authentication.status"),tn)}})}}function E(i,e){return e.includes(i)?i:{kind:"UNKNOWN",raw:i}}function sn(i,e){if(!e.includes(i))throw new Error("invalid_elements_response");return i}function v(i){if(!i||typeof i!="object"||Array.isArray(i))throw new Error("invalid_elements_response");return i}function be(i){return i==null?[]:A(i)}function A(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 U(i){return i==null?void 0:m(i,"optional")}function O(i,e){if(typeof i!="number"||!Number.isFinite(i))throw new Error("invalid_elements_response");return i}function on(i,e){if(typeof i!="boolean")throw new Error("invalid_elements_response");return i}function ve(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 an(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)}}function we(i){let e=b(i);if(!Array.isArray(e.items))throw new Error("invalid_inbox_response");return{items:e.items.map(an),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 Se(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 Ee(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 Ae(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)}}),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 Re(i){return{readThroughSequence:u(b(i).readThroughSequence,0)}}function _e(i){return{clearedThroughSequence:u(b(i).clearedThroughSequence,0)}}function Ce(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 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:R(e.createdAt),updatedAt:R(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: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 Te(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 Me(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 Ke(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 Ne(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 Oe(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}})),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: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 De(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 V(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 B(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}},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;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 Te(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 Me(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 Ke(await this.request(`v1/inbox/members${r}`,"GET",void 0,void 0,void 0,n))}async getInboxSendPreparation(e,n){return Ne(await this.request(`v1/inbox/conversations/${encodeURIComponent(e)}/preparation`,"GET",void 0,void 0,void 0,n))}async getNormalInboxSendPreparation(e,n){return Ee(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 we(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 Se(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 Ae(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 Ce(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 Re(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 k(a.status,V(c),B(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 De(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(),f=[],P=0;try{for(;;){o?.throwIfAborted();let N=await I.read();if(N.done)break;if(P+=N.value.length,P>14*1024*1024)throw new Error("invalid_inbox_share_size");f.push(N.value)}}catch(N){throw await I.cancel().catch(()=>{}),N}let K=new Uint8Array(P),T=0;for(let N of f)K.set(N,T),T+=N.length;return K}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 Oe(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(ve)}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 he(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 xe(await this.request(`v1/plans/${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[P,K]of Object.entries(s??{}))c.set(P,K);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 f=await Q(I,o);if(o?.throwIfAborted(),!I.ok)throw new k(I.status,V(f),B(f),I.headers.get("x-request-id")??void 0);if(!f.ok||f.result===void 0)throw new k(I.status,V(f),B(f),I.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 k(c.status,V(l),B(l),c.headers.get("x-request-id")??void 0)}return c}async requestWithoutResult(e,n){this.requireBusinessSelection(e);let t=await this.getBearerToken(),r=new Headers({"x-elements-environment":this.environment});t&&r.set("authorization",`Bearer ${t}`),this.business?.organizationId&&r.set("x-organization-id",this.business.organizationId),n&&r.set("content-type","application/json");let s=this.apiUrl.endsWith("/")?this.apiUrl:`${this.apiUrl}/`,o=await this.transport(new URL(e,s),{method:"POST",headers:r,body:n?JSON.stringify(n):void 0}),a=await Q(o);if(!o.ok||!a.ok)throw new k(o.status,V(a),B(a),o.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 k(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{createHash as dn,webcrypto as cn}from"node:crypto";import{canonicalInboxManifest as ln,decodeInboxManifest as pn,decodeInboxContentFrame as mn,decodeInboxText as un,decryptInboxShare as In,encodeInboxContentFrame as oe,encodeInboxText as gn,encryptInboxShare as Ue,inboxProtectedUnitCommitment as bn,inboxTextMetadataDigest as Le,openInboxContent as yn,sealInboxContent as fn,signInboxFrame as xn,unwrapInboxContentKey as hn,unwrapInboxShareKey as Pn,verifyInboxFrame as qe,wrapInboxContentKey as vn,wrapInboxShareKey as wn}from"@safetech/inheriti-core-sdk/core/protocols/inbox";import{NodeInboxWorkerProcessor as Sn}from"@safetech/inheriti-core-sdk/workers/inbox.node";var M=cn,h=M,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)},_=(i,e)=>i.length===e.length&&i.every((n,t)=>n===e[t]),Z=async i=>new Uint8Array(await h.subtle.digest("SHA-256",Uint8Array.from(i))),z=i=>dn("sha256").update(i).digest("hex"),F=class{constructor(e,n=new Sn){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=ln(r),o=await Z(s),{contentKey:a,frame:c}=await fn(gn(e.text),o,h),l=await this.signFrame(r,c,e.identity.signingPrivateKey,t.signingPublicKey),{shareKey:g,shares:I}=await this.protectShares(n,c,o),f=await this.wrapRecipientKeys(n,a,o),P=await wn(g,x(e.tenantKeyHex),o,r.tenantId,r.messageId,h);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(P).toString("base64"),recipients:f,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&&!_(n,await bn(o,oe(l),p(t.signature),h)))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||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: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 Le(h)}}async signFrame(e,n,t,r){let s=await h.subtle.importKey("pkcs8",p(t),"Ed25519",!1,["sign"]),o=await xn(e,n,s,h),a=await h.subtle.importKey("spki",p(r),"Ed25519",!1,["verify"]);if(!await qe(e,n,o,a,h))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=h.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 Ue(r.dataShares[a],s,t,e.messageId,h)).toString("base64")}),o.push({kind:"KEY",index:a,shareId:c.keyShareId,layerId:c.id,ciphertext:Buffer.from(await Ue(r.keyShares[a],s,t,e.messageId,h)).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 h.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 vn(n,o,t,h)).toString("base64")}}))}async verifyOpening(e,n,t){let r=p(n.canonicalManifest),s=pn(r);if(s.tenantId!==e.identity.tenantId||s.conversationId!==e.conversationId||s.messageId!==e.messageId||s.expiresAtEpochMs<=Date.now()||!_(s.metadataDigest,t??await Le(h)))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,x(z(p(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let a=p(n.senderSigningPublicKey);if(n.senderSigningKeyFingerprint!==z(a)||!_(s.senderSigningKeyFingerprint,x(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 Pn(p(e.tenantWrappedShareKey),x(r),t,n.tenantId,n.messageId,h),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 f=await In(p(g.ciphertext),s,t,n.messageId,g.kind==="DATA"?"data":"key",g.index,h);(g.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 mn(l)}async decryptText(e,n,t,r,s,o){return un(await this.decryptContent(e,n,t,r,s,o))}async decryptContent(e,n,t,r,s,o){let a=await h.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await qe(t,n,p(e.signature),a,h))throw new Error("inbox_signature_invalid");let c=await h.subtle.importKey("pkcs8",p(o),{name:"RSA-OAEP",hash:"SHA-256"},!1,["decrypt"]),l=await hn(p(e.wrappedContentKey),c,r,h);return yn(n,l,r,h)}};import{canonicalInboxManifest as En,decodeInboxContentFrame as An,decodeInboxFile as Rn,decryptInboxShare as _n,encodeInboxContentFrame as Cn,encodeInboxFile as Tn,encryptInboxShare as Fe,inboxFileMetadataDigest as $e,sealInboxContent as Mn,unwrapInboxShareKey as Kn,wrapInboxShareKey as Nn}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var ae=class extends F{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=En(s),a=await Z(o),c=Tn(n.file),l;try{l=await Mn(c,a,M)}finally{c.fill(0)}let{contentKey:g,frame:I}=l,f=await this.signFrame(s,I,n.identity.signingPrivateKey,r.signingPublicKey);n.signal?.throwIfAborted();let P=await this.worker.split(Cn(I),{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 K=M.getRandomValues(new Uint8Array(32)),T=[];for(let w=0;w<t.total;w++){let L=t.shareLayers[w];T.push({reference:{kind:"DATA",index:w,shareId:L.dataShareId,layerId:L.id},bytes:await Fe(P.dataShares[w],K,a,t.messageId,M)}),T.push({reference:{kind:"KEY",index:w,shareId:L.keyShareId,layerId:L.id},bytes:await Fe(P.keyShares[w],K,a,t.messageId,M)})}let N=await this.wrapRecipientKeys(t,g,a),We=await Nn(K,x(n.tenantKeyHex),a,s.tenantId,s.messageId,M);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(We).toString("base64"),recipients:N,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 L=T[w];await this.fileApi.uploadInboxFileShare(n.conversationId,t.messageId,L.reference.shareId,L.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 $e(M)),g=await this.recoverFileFrame(n,t,a,c);s=await this.decryptContent(t,g,a,c,l,n.identity.encryptionPrivateKey),r=Rn(s),n.signal?.throwIfAborted(),await n.save(r),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 $e(M)}}async recoverFileFrame(n,t,r,s){let o=await Kn(p(t.tenantWrappedShareKey),x(n.tenantKeyHex),s,r.tenantId,r.messageId,M),a=[],c=[],l=new Set;for(let I=0;I<t.shares.length;I++){n.signal?.throwIfAborted();let f=t.shares[I],P=`${f.kind}:${f.index}`;if(l.has(P))throw new Error("duplicate_inbox_share");l.add(P);let K=await this.fileApi.downloadInboxFileShare(n.conversationId,n.messageId,f.shareId,n.identity.deviceId,t.leaseId,n.signal),T=await _n(K,o,s,r.messageId,f.kind==="DATA"?"data":"key",f.index,M);(f.kind==="DATA"?a:c).push(T),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(),An(g)}};import{createHash as Ve,webcrypto as On}from"node:crypto";import{canonicalInboxParentManifest as kn,decodeInboxParentManifest as Dn,encodeInboxParentNormalFrame as Un,decodeInboxParentNormalFrame as Ln,sealInboxParentNormalBody as qn,openInboxParentNormalBody as Fn,wrapInboxParentNormalKey as $n,unwrapInboxParentNormalKey as Gn,signInboxParentNormalFrame as Vn,verifyInboxParentNormalFrame as Ge,encodeInboxText as Bn,decodeInboxText as zn}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var C=On,H=i=>Ve("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 Ve("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: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=kn(r),{contentKey:o,frame:a}=await qn(Bn(e.text),r,C),c=await C.subtle.importKey("pkcs8",p(e.identity.signingPrivateKey),"Ed25519",!1,["sign"]),l=await Vn(r,a,c,C),g=await C.subtle.importKey("spki",p(t.signingPublicKey),"Ed25519",!1,["verify"]);if(!await Ge(r,a,l,g,C))throw new Error("inbox_identity_mismatch");let I=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(Un(a)),signature:ee(l),recipients:I}}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 $n(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=Dn(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||!_(r.encryptionKeyFingerprint,x(H(p(e.identity.encryptionPublicKey)))))throw new Error("inbox_recipient_mismatch");let s=p(n.senderSigningPublicKey);if(!_(t.senderSigningKeyFingerprint,x(H(s))))throw new Error("inbox_sender_key_mismatch");let o=Ln(p(n.frame)),a=await C.subtle.importKey("spki",s,"Ed25519",!1,["verify"]);if(!await Ge(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 Gn(p(n.wrappedContentKey),c,t,C),g=zn(await Fn(o,l,t,C));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 He,webcrypto as Hn}from"node:crypto";import{canonicalInboxParentManifest as Wn,decodeInboxParentManifest as jn,decodeInboxManifest as Yn,encodeInboxParentNormalFrame as Xn,decodeInboxParentNormalFrame as Qn,sealInboxParentNormalBody as Jn,openInboxParentNormalBody as Zn,wrapInboxParentNormalKey as et,unwrapInboxParentNormalKey as nt,signInboxParentNormalFrame as tt,verifyInboxParentNormalFrame as Be,signInboxProtectedParent as rt,verifyInboxProtectedParent as ze,inboxProtectedUnitCommitment as it,encodeInboxText as st,decodeInboxText as ot}from"@safetech/inheriti-core-sdk/core/protocols/inbox";var S=Hn,ne=i=>Buffer.from(i).toString("base64"),W=i=>He("sha256").update(i).digest("hex"),ce=class{constructor(e,n){this.api=e;this.child=n??new F(e)}pending=new Map;child;async send(e){let n=He("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(P=>"protectedText"in P).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(P=>"text"in P))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:f}=await this.signAndWrap(e,r,s,l);return{parentId:o,idempotencyKey:o,senderDeviceId:s.deviceId,mode:t,participantRevision:r.participantRevision,canonicalManifest:ne(Wn(l)),signature:ne(I),frame:g,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}),g=Yn(p(l.submission.canonicalManifest));this.validateChildSnapshot(g,e,n,t);let I=await it(g,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: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&&_(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 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 rt(e,n,S);if(!await ze(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(g=>g.position===l).unitId}),o=await Jn(st(JSON.stringify(s)),n,S),a=await tt(n,o.frame,t,S);if(!await Be(n,o.frame,a,r,S))throw new Error("inbox_identity_mismatch");return{frame:ne(Xn(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 et(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=jn(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,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.encryptionKeyFingerprint,x(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,x(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 ze(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=Qn(p(n.frame));if(!await Be(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 nt(p(n.wrappedContentKey),o,t,S),c=JSON.parse(ot(await Zn(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,F as NodeInboxText};
|