@wowok/wowok 2.6.9 → 2.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -1
- package/dist/esm/{arb-rqktLphb.mjs → arb-UmbIfnyY.mjs} +1 -1
- package/dist/esm/{base-00x0AcXp.mjs → base-BzTUCV2r.mjs} +1 -1
- package/dist/esm/{call-BRj5YNax.mjs → call-D7-YH2s4.mjs} +1 -1
- package/dist/esm/client/index.d.mts +1 -1
- package/dist/esm/client/index.mjs +1 -1
- package/dist/esm/{client-Bdse0cJJ.mjs → client-B2NwgKQ6.mjs} +1 -1
- package/dist/esm/cryptography/index.d.mts +1 -1
- package/dist/esm/{evm-account-Bk7Axxmu.d.mts → evm-account-C-WmGOoz.d.mts} +2 -2
- package/dist/esm/graphql/index.d.mts +1 -1
- package/dist/esm/graphql/index.mjs +1 -1
- package/dist/esm/{graphql-Bv-Tk9oL.mjs → graphql-Bf8yuSuF.mjs} +1 -1
- package/dist/esm/grpc/index.d.mts +1 -1
- package/dist/esm/grpc/index.mjs +1 -1
- package/dist/esm/{grpc-RbdERoNT.mjs → grpc-B8ovObdJ.mjs} +1 -1
- package/dist/esm/{index-B7WTNwlN.d.mts → index-BZkrZ63s.d.mts} +20 -4
- package/dist/esm/index.d.mts +5 -5
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/jsonRpc/index.d.mts +1 -1
- package/dist/esm/jsonRpc/index.mjs +1 -1
- package/dist/esm/keypairs/ed25519/index.d.mts +1 -1
- package/dist/esm/keypairs/falcon512/index.d.mts +1 -1
- package/dist/esm/keypairs/passkey/index.d.mts +1 -1
- package/dist/esm/keypairs/secp256k1/index.d.mts +1 -1
- package/dist/esm/keypairs/secp256r1/index.d.mts +1 -1
- package/dist/esm/messenger-DEHzSxhH.mjs +1 -0
- package/dist/esm/messenger-api-DSPJm9_J.mjs +1 -0
- package/dist/esm/multisig/index.d.mts +1 -1
- package/dist/esm/{object-BmdhYqx6.mjs → object-Dma1VY-1.mjs} +1 -1
- package/dist/esm/{passport-BrEhjz98.mjs → passport-CQFR2dfo.mjs} +1 -1
- package/dist/esm/{proof-DI739r7_.mjs → proof-BcyNI5NQ.mjs} +1 -1
- package/dist/esm/query-cAnGkFPh.mjs +1 -0
- package/dist/esm/{received-4rzVMF_W.mjs → received-4odTK5AJ.mjs} +1 -1
- package/dist/esm/{secure-storage-lI6ZR9sW.d.mts → secure-storage-CJdIxkx3.d.mts} +1 -1
- package/dist/esm/{service-DumRJ5zQ.mjs → service-B3jMoJ_p.mjs} +1 -1
- package/dist/esm/{storage-B8nW4YTJ.d.mts → storage-DGOllc0e.d.mts} +13 -0
- package/dist/esm/transactions/index.d.mts +1 -1
- package/dist/esm/{util-CYLtIQ4d.mjs → util-BC-TmINX.mjs} +1 -1
- package/dist/esm/verify/index.d.mts +1 -1
- package/dist/esm/w/call/allocation.d.mts +1 -1
- package/dist/esm/w/call/allocation.mjs +1 -1
- package/dist/esm/w/call/arbitration.d.mts +1 -1
- package/dist/esm/w/call/arbitration.mjs +1 -1
- package/dist/esm/w/call/base.d.mts +1 -1
- package/dist/esm/w/call/base.mjs +1 -1
- package/dist/esm/w/call/demand.d.mts +1 -1
- package/dist/esm/w/call/demand.mjs +1 -1
- package/dist/esm/w/call/guard.d.mts +1 -1
- package/dist/esm/w/call/guard.mjs +1 -1
- package/dist/esm/w/call/index.d.mts +1 -1
- package/dist/esm/w/call/index.mjs +1 -1
- package/dist/esm/w/call/machine.d.mts +1 -1
- package/dist/esm/w/call/machine.mjs +1 -1
- package/dist/esm/w/call/passport.d.mts +1 -1
- package/dist/esm/w/call/passport.mjs +1 -1
- package/dist/esm/w/call/payment.d.mts +1 -1
- package/dist/esm/w/call/payment.mjs +1 -1
- package/dist/esm/w/call/permission.d.mts +1 -1
- package/dist/esm/w/call/permission.mjs +1 -1
- package/dist/esm/w/call/progress.d.mts +1 -1
- package/dist/esm/w/call/progress.mjs +1 -1
- package/dist/esm/w/call/repository.d.mts +1 -1
- package/dist/esm/w/call/repository.mjs +1 -1
- package/dist/esm/w/call/reward.d.mts +1 -1
- package/dist/esm/w/call/reward.mjs +1 -1
- package/dist/esm/w/call/service.d.mts +1 -1
- package/dist/esm/w/call/service.mjs +1 -1
- package/dist/esm/w/call/treasury.d.mts +1 -1
- package/dist/esm/w/call/treasury.mjs +1 -1
- package/dist/esm/w/common.d.mts +1 -1
- package/dist/esm/w/index.d.mts +5 -5
- package/dist/esm/w/index.mjs +1 -1
- package/dist/esm/w/local/account.d.mts +2 -2
- package/dist/esm/w/local/account.mjs +1 -1
- package/dist/esm/w/local/evm-account.d.mts +1 -1
- package/dist/esm/w/local/index.d.mts +5 -5
- package/dist/esm/w/local/index.mjs +1 -1
- package/dist/esm/w/local/secure-storage.d.mts +1 -1
- package/dist/esm/w/local/storage.d.mts +1 -1
- package/dist/esm/w/local/storage.mjs +1 -1
- package/dist/esm/w/local/token.d.mts +1 -1
- package/dist/esm/w/local/token.mjs +1 -1
- package/dist/esm/w/messenger/index.d.mts +1 -1
- package/dist/esm/w/messenger/index.mjs +1 -1
- package/dist/esm/w/messenger/messenger-api.d.mts +1 -1
- package/dist/esm/w/messenger/messenger-api.mjs +1 -1
- package/dist/esm/w/messenger/messenger.d.mts +1 -1
- package/dist/esm/w/messenger/messenger.mjs +1 -1
- package/dist/esm/w/messenger/reply.d.mts +27 -0
- package/dist/esm/w/messenger/reply.mjs +1 -0
- package/dist/esm/w/messenger/storage.d.mts +1 -1
- package/dist/esm/w/messenger/storage.mjs +1 -1
- package/dist/esm/w/messenger/types.d.mts +2 -2
- package/dist/esm/w/query/index.d.mts +1 -1
- package/dist/esm/w/query/index.mjs +1 -1
- package/dist/esm/w/query/object.d.mts +1 -1
- package/dist/esm/w/query/object.mjs +1 -1
- package/dist/esm/{w-Bm2k913h.mjs → w-Dp4KXRLj.mjs} +1 -1
- package/package.json +4 -1
- package/dist/esm/messenger-DNHxCZZr.mjs +0 -1
- package/dist/esm/messenger-api-Czo7Mnx2.mjs +0 -1
- package/dist/esm/query-Bjma0bd-.mjs +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $C as
|
|
1
|
+
import { $C as PaginatedCheckpoints, $S as WowObjectChangeWrapped, $w as WowParsedData, $x as TBalanceParams, A as isWowJsonRpcClient, AC as DynamicFieldName, AS as WGetChainIdentifierParams, Aw as WowEventFilter, Ax as GetDynamicFieldObjectParams, BC as MoveCallParams, BS as WGetObjectParams, Bw as WowMoveNormalizedFunction, Bx as GetOwnedObjectsParams, C as JsonRpcError, CC as ConsensusDeterminedVersionAssignments, CS as UnsafeSplitCoinEqualParams, Cw as ValidatorsApy, Cx as GetAllCoinsParams, D as PaginationArguments, DC as DisplayFieldsResponse, DS as WDevInspectTransactionBlockParams, Dw as WowCoinMetadata, Dx as GetCoinMetadataParams, E as OrderArguments, EC as DevInspectResults, ES as UnsafeTransferWowParams, Ew as WowChangeEpoch, Ex as GetCheckpointsParams, FC as ExecuteTransactionRequestType, FS as WGetMoveFunctionArgTypesParams, Fw as WowMoveAbort, Fx as GetNormalizedMoveFunctionParams, GC as MultiSigLegacy, GS as WMultiGetTransactionBlocksParams, Gw as WowMoveVisibility, Gx as GetTotalSupplyParams, HC as MoveValue, HS as WGetTotalTransactionBlocksParams, Hw as WowMoveNormalizedStruct, Hx as GetReferenceGasPriceParams, IC as ExecutionStatus, IS as WGetNormalizedMoveFunctionParams, Iw as WowMoveFunctionArgType, Ix as GetNormalizedMoveModuleParams, JC as ObjectOwner, JS as WowObjectChangeCreated, Jw as WowObjectDataFilter, Jx as MultiGetTransactionBlocksParams, KC as MultiSigPublicKey, KS as WTryGetPastObjectParams, Kw as WowObjectChange, Kx as GetTransactionBlockParams, LC as GasCostSummary, LS as WGetNormalizedMoveModuleParams, Lw as WowMoveModuleId, Lx as GetNormalizedMoveModulesByPackageParams, MC as ECMHLiveObjectSetDigest, MS as WGetCheckpointsParams, Mw as WowGasData, Mx as GetLatestCheckpointSequenceNumberParams, NC as EndOfEpochData, NS as WGetEventsParams, Nw as WowMoveAbility, Nx as GetLatestWowSystemStateParams, O as WowJsonRpcClient, OC as DryRunTransactionBlockResponse, OS as WDryRunTransactionBlockParams, Ow as WowEndOfEpochTransactionKind, Ox as GetCoinsParams, PC as EventId, PS as WGetLatestCheckpointSequenceNumberParams, Pw as WowMoveAbilitySet, Px as GetMoveFunctionArgTypesParams, QC as OwnedObjectRef, QS as WowObjectChangeTransferred, Qw as WowObjectResponseQuery, Qx as TAllCoinsParams, RC as GetPastObjectRequest, RS as WGetNormalizedMoveModulesByPackageParams, Rw as WowMoveNormalizedEnum, Rx as GetNormalizedMoveStructParams, S as getJsonRpcFullnodeUrl, SC as CompressedSignature, SS as UnsafeRequestWithdrawStakeParams, Sw as ValidatorApy, Sx as GetAllBalancesParams, T as WowHTTPTransportError, TC as DevInspectArgs, TS as UnsafeTransferObjectParams, Tw as WowCallArg, Tx as GetCheckpointParams, UC as MoveVariant, US as WGetTransactionBlockParams, Uw as WowMoveNormalizedType, Ux as GetStakesByIdsParams, VC as MoveStruct, VS as WGetProtocolConfigParams, Vw as WowMoveNormalizedModule, Vx as GetProtocolConfigParams, WC as MultiSig, WS as WMultiGetObjectsParams, Ww as WowMoveStructTypeParameter, Wx as GetStakesParams, XC as ObjectResponseError, XS as WowObjectChangeMutated, Xw as WowObjectRef, Xx as QueryTransactionBlocksParams, YC as ObjectRead, YS as WowObjectChangeDeleted, Yw as WowObjectDataOptions, Yx as QueryEventsParams, ZC as ObjectValueKind, ZS as WowObjectChangePublished, Zw as WowObjectResponse, Zx as TAllBalancesParams, _C as CheckpointCommitment, _S as UnsafePayAllWowParams, _T as JsonRpcTransportRequestOptions, _w as TransactionEffects, _x as DevInspectTransactionBlockParams, aC as EpochInfo, aS as TLatestWowSystemStateParams, aT as WowTransactionBlockBuilderMode, aw as Party, bC as CoinSupply, bS as UnsafePublishParams, bw as TypeOrigin, bx as EryTransactionBlocksParams, cC as WowMoveNormalizedModules, cS as TStakesByIdsParams, cT as WowTransactionBlockResponseOptions, cw as ProtocolConfigValue, dC as AccumulatorEvent, dS as TValidatorsApyParams, dT as WowWithdrawFrom, dw as RawData, eC as Order, eS as TCoinMetadataParams, eT as WowProgrammableMoveCall, ew as PaginatedCoins, fC as AccumulatorOperation, fS as TryGetPastObjectParams, fT as WowWithdrawalTypeArg, fw as Signature, gC as Checkpoint, gS as UnsafeMoveCallParams, gT as JsonRpcTransport, gw as TransactionBlockEffectsModifiedAtVersions, gx as BscribeTransactionParams, hC as BalanceChange, hS as UnsafeMergeCoinsParams, hT as JsonRpcHTTPTransportOptions, hw as TransactionBlockData, hx as BscribeEventParams, iC as EndOfEpochInfo, iS as TDynamicFieldsParams, iT as WowTransactionBlock, iw as PaginatedTransactionResponse, jC as DynamicFieldType, jS as WGetCheckpointParams, jw as WowExecutionResult, jx as GetDynamicFieldsParams, k as WowJsonRpcClientOptions, kC as DynamicFieldInfo, kS as WExecuteTransactionBlockParams, kw as WowEvent, kx as GetCommitteeInfoParams, lC as WowMoveObject, lS as TStakesParams, lT as WowTransactionBlockResponseQuery, lw as PublicKey, mC as Balance, mS as UnsafeBatchTransactionParams, mT as JsonRpcHTTPTransport, mw as TransactionBlockBytes, nC as CheckpointPage, nS as TCommitteeInfoParams, nT as WowSystemStateSummary, nw as PaginatedEvents, oC as EpochPage, oS as TOwnedObjectsParams, oT as WowTransactionBlockKind, ow as PasskeyAuthenticator, pC as AccumulatorValue, pS as TryMultiGetPastObjectsParams, pT as HttpHeaders, pw as StakeObject, qC as MultiSigPublicKeyLegacy, qS as WTryMultiGetPastObjectsParams, qw as WowObjectData, qx as MultiGetObjectsParams, rC as DynamicFieldPage, rS as TDynamicFieldObjectParams, rT as WowTransaction, rw as PaginatedObjectsResponse, sC as ProgrammableTransaction, sS as TReferenceGasPriceParams, sT as WowTransactionBlockResponse, sw as ProtocolConfig, tC as CoinBalance, tS as TCoinsParams, tT as WowReservation, tw as PaginatedDynamicFieldInfos, uC as WowMovePackage, uS as TTotalSupplyParams, uT as WowValidatorSummary, uw as RPCTransactionRequestParams, vC as CheckpointId, vS as UnsafePayParams, vw as TransactionFilter, vx as DryRunTransactionBlockParams, w as WowHTTPStatusError, wC as DelegatedStake, wS as UnsafeSplitCoinParams, ww as WowArgument, wx as GetBalanceParams, xC as CommitteeInfo, xS as UnsafeRequestAddStakeParams, xw as UpgradeInfo, xx as ExecuteTransactionBlockParams, yC as CoinStruct, yS as UnsafePayWowParams, yw as TransferObjectParams, yx as EryEventsParams, zC as InputObjectKind, zS as WGetNormalizedMoveStructParams, zw as WowMoveNormalizedField, zx as GetObjectParams } from "../index-BZkrZ63s.mjs";
|
|
2
2
|
export { type AccumulatorEvent, type AccumulatorOperation, type AccumulatorValue, type Balance, type BalanceChange, type BscribeEventParams, type BscribeTransactionParams, type Checkpoint, type CheckpointCommitment, type CheckpointId, type CheckpointPage, type CoinBalance, type CoinStruct, type CoinSupply, type CommitteeInfo, type CompressedSignature, type ConsensusDeterminedVersionAssignments, type DelegatedStake, type DevInspectArgs, type DevInspectResults, type DevInspectTransactionBlockParams, type DisplayFieldsResponse, type DryRunTransactionBlockParams, type DryRunTransactionBlockResponse, type DynamicFieldInfo, type DynamicFieldName, type DynamicFieldPage, type DynamicFieldType, type ECMHLiveObjectSetDigest, type EndOfEpochData, type EndOfEpochInfo, type EpochInfo, type EpochPage, type EryEventsParams, type EryTransactionBlocksParams, type EventId, type ExecuteTransactionBlockParams, type ExecuteTransactionRequestType, type ExecutionStatus, type GasCostSummary, type GetAllBalancesParams, type GetAllCoinsParams, type GetBalanceParams, type GetCheckpointParams, type GetCheckpointsParams, type GetCoinMetadataParams, type GetCoinsParams, type GetCommitteeInfoParams, type GetDynamicFieldObjectParams, type GetDynamicFieldsParams, type GetLatestCheckpointSequenceNumberParams, type GetLatestWowSystemStateParams, type GetMoveFunctionArgTypesParams, type GetNormalizedMoveFunctionParams, type GetNormalizedMoveModuleParams, type GetNormalizedMoveModulesByPackageParams, type GetNormalizedMoveStructParams, type GetObjectParams, type GetOwnedObjectsParams, type GetPastObjectRequest, type GetProtocolConfigParams, type GetReferenceGasPriceParams, type GetStakesByIdsParams, type GetStakesParams, type GetTotalSupplyParams, type GetTransactionBlockParams, type HttpHeaders, type InputObjectKind, JsonRpcError, JsonRpcHTTPTransport, type JsonRpcHTTPTransportOptions, type JsonRpcTransport, type JsonRpcTransportRequestOptions, type MoveCallParams, type MoveStruct, type MoveValue, type MoveVariant, type MultiGetObjectsParams, type MultiGetTransactionBlocksParams, type MultiSig, type MultiSigLegacy, type MultiSigPublicKey, type MultiSigPublicKeyLegacy, type ObjectOwner, type ObjectRead, type ObjectResponseError, type ObjectValueKind, type Order, type OrderArguments, type OwnedObjectRef, type PaginatedCheckpoints, type PaginatedCoins, type PaginatedDynamicFieldInfos, type PaginatedEvents, type PaginatedObjectsResponse, type PaginatedTransactionResponse, type PaginationArguments, type Party, type PasskeyAuthenticator, type ProgrammableTransaction, type ProtocolConfig, type ProtocolConfigValue, type PublicKey, type QueryEventsParams, type QueryTransactionBlocksParams, type RPCTransactionRequestParams, type RawData, type Signature, type StakeObject, type TAllBalancesParams, type TAllCoinsParams, type TBalanceParams, type TCoinMetadataParams, type TCoinsParams, type TCommitteeInfoParams, type TDynamicFieldObjectParams, type TDynamicFieldsParams, type TLatestWowSystemStateParams, type TOwnedObjectsParams, type TReferenceGasPriceParams, type TStakesByIdsParams, type TStakesParams, type TTotalSupplyParams, type TValidatorsApyParams, type TransactionBlockBytes, type TransactionBlockData, type TransactionBlockEffectsModifiedAtVersions, type TransactionEffects, type TransactionFilter, type TransferObjectParams, type TryGetPastObjectParams, type TryMultiGetPastObjectsParams, type TypeOrigin, type UnsafeBatchTransactionParams, type UnsafeMergeCoinsParams, type UnsafeMoveCallParams, type UnsafePayAllWowParams, type UnsafePayParams, type UnsafePayWowParams, type UnsafePublishParams, type UnsafeRequestAddStakeParams, type UnsafeRequestWithdrawStakeParams, type UnsafeSplitCoinEqualParams, type UnsafeSplitCoinParams, type UnsafeTransferObjectParams, type UnsafeTransferWowParams, type UpgradeInfo, type ValidatorApy, type ValidatorsApy, type WDevInspectTransactionBlockParams, type WDryRunTransactionBlockParams, type WExecuteTransactionBlockParams, type WGetChainIdentifierParams, type WGetCheckpointParams, type WGetCheckpointsParams, type WGetEventsParams, type WGetLatestCheckpointSequenceNumberParams, type WGetMoveFunctionArgTypesParams, type WGetNormalizedMoveFunctionParams, type WGetNormalizedMoveModuleParams, type WGetNormalizedMoveModulesByPackageParams, type WGetNormalizedMoveStructParams, type WGetObjectParams, type WGetProtocolConfigParams, type WGetTotalTransactionBlocksParams, type WGetTransactionBlockParams, type WMultiGetObjectsParams, type WMultiGetTransactionBlocksParams, type WTryGetPastObjectParams, type WTryMultiGetPastObjectsParams, type WowArgument, type WowCallArg, type WowChangeEpoch, type WowCoinMetadata, type WowEndOfEpochTransactionKind, type WowEvent, type WowEventFilter, type WowExecutionResult, type WowGasData, WowHTTPStatusError, WowHTTPTransportError, WowJsonRpcClient, type WowJsonRpcClientOptions, type WowMoveAbility, type WowMoveAbilitySet, type WowMoveAbort, type WowMoveFunctionArgType, type WowMoveModuleId, type WowMoveNormalizedEnum, type WowMoveNormalizedField, type WowMoveNormalizedFunction, type WowMoveNormalizedModule, type WowMoveNormalizedModules, type WowMoveNormalizedStruct, type WowMoveNormalizedType, type WowMoveObject, type WowMovePackage, type WowMoveStructTypeParameter, type WowMoveVisibility, type WowObjectChange, type WowObjectChangeCreated, type WowObjectChangeDeleted, type WowObjectChangeMutated, type WowObjectChangePublished, type WowObjectChangeTransferred, type WowObjectChangeWrapped, type WowObjectData, type WowObjectDataFilter, type WowObjectDataOptions, type WowObjectRef, type WowObjectResponse, type WowObjectResponseQuery, type WowParsedData, type WowProgrammableMoveCall, type WowReservation, type WowSystemStateSummary, type WowTransaction, type WowTransactionBlock, type WowTransactionBlockBuilderMode, type WowTransactionBlockKind, type WowTransactionBlockResponse, type WowTransactionBlockResponseOptions, type WowTransactionBlockResponseQuery, type WowValidatorSummary, type WowWithdrawFrom, type WowWithdrawalTypeArg, getJsonRpcFullnodeUrl, isWowJsonRpcClient };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as a22a,i as a22b,n as a22c,o as a22d,r as a22e,s as a22f}from'../client-
|
|
1
|
+
import{a as a22a,i as a22b,n as a22c,o as a22d,r as a22e,s as a22f}from'../client-B2NwgKQ6.mjs';import{t as a22g}from'../jsonRpc-1qOo1zjv.mjs';export{a22a as JsonRpcError,a22b as JsonRpcHTTPTransport,a22d as WowHTTPStatusError,a22f as WowHTTPTransportError,a22c as WowJsonRpcClient,a22g as getJsonRpcFullnodeUrl,a22e as isWowJsonRpcClient};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Db as
|
|
1
|
+
import { Db as Ed25519Keypair, Eb as DEFAULT_ED25519_DERIVATION_PATH, Ob as Ed25519KeypairData, kb as Ed25519PublicKey } from "../../index-BZkrZ63s.mjs";
|
|
2
2
|
export { DEFAULT_ED25519_DERIVATION_PATH, Ed25519Keypair, type Ed25519KeypairData, Ed25519PublicKey };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { cb as
|
|
1
|
+
import { cb as DEFAULT_FALCON512_DERIVATION_PATH, db as Falcon512PublicKey, lb as Falcon512Keypair, ub as Falcon512KeypairData } from "../../index-BZkrZ63s.mjs";
|
|
2
2
|
export { DEFAULT_FALCON512_DERIVATION_PATH, Falcon512Keypair, type Falcon512KeypairData, Falcon512PublicKey };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { _b as findCommonPublicKey, fb as PasskeyPublicKey, gb as PasskeyProvider, hb as PasskeyKeypair, mb as BrowserPasswordProviderOptions, pb as BrowserPasskeyProvider } from "../../index-BZkrZ63s.mjs";
|
|
2
2
|
export { BrowserPasskeyProvider, type BrowserPasswordProviderOptions, PasskeyKeypair, type PasskeyProvider, PasskeyPublicKey, type findCommonPublicKey };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Cb as
|
|
1
|
+
import { Cb as DEFAULT_SECP256K1_DERIVATION_PATH, Sb as Secp256k1PublicKey, Tb as Secp256k1KeypairData, wb as Secp256k1Keypair } from "../../index-BZkrZ63s.mjs";
|
|
2
2
|
export { DEFAULT_SECP256K1_DERIVATION_PATH, Secp256k1Keypair, type Secp256k1KeypairData, Secp256k1PublicKey };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { bb as Secp256r1Keypair, vb as Secp256r1PublicKey, xb as Secp256r1KeypairData, yb as DEFAULT_SECP256R1_DERIVATION_PATH } from "../../index-BZkrZ63s.mjs";
|
|
2
2
|
export { DEFAULT_SECP256R1_DERIVATION_PATH, Secp256r1Keypair, type Secp256r1KeypairData, Secp256r1PublicKey };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as a32a}from'./wow-types-DcqbnAaK.mjs';import{r as a32b}from'./logger-Cs5Mf7Mf.mjs';import{PQSessionCipher}from'./w/messenger/pq/session.mjs';import{PQSessionStoreAdapter}from'./w/messenger/pq/store-adapter.mjs';import{DEFAULT_MESSENGER_CONFIG,MessengerError,NORMAL_MESSAGE_BYTES_LIMIT,WTS_FILE_BYTES_LIMIT}from'./w/messenger/types.mjs';import{MessageStorage,SessionStateStorage,getDatabase}from'./w/messenger/storage.mjs';import{base64ToBytes,bytesToBase64,hashPlaintext,verifyMessage}from'./w/messenger/crypto.mjs';import{REPLY_HEADER,buildReplyPlaintext,parseReplyPlaintext}from'./w/messenger/reply.mjs';import{randomBytes}from'@noble/hashes/utils.js';import*as a32c from'path';import*as a32d from'fs';import{createHash}from'crypto';const logger=a32b('messenger:server');var MessengerServerClient=class{constructor(a){this['config']={...DEFAULT_MESSENGER_CONFIG,...a};}async['fetchWithTimeout'](a,b={},c){const d=c??this['config']['requestTimeoutMs']??0x7530,e=new AbortController(),f=setTimeout(()=>e['abort'](),d);try{return await fetch(a,{...b,'signal':e['signal']});}finally{clearTimeout(f);}}async['registerDevice'](a){try{const b=await this['fetchWithTimeout'](this['config']['serverUrl']+'/v1/register',{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](a)});if(!b['ok']){const d=await b['text']();if(b['status']===0x199){if(d['includes']('different\x20key'))throw new MessengerError('IDENTITY_CONFLICT','Identity\x20already\x20exists\x20with\x20different\x20key:\x20'+d);return{'success':!![],'uploadedCount':0x0,'failedPrekeys':[],'currentTotal':0x0,'maxAllowed':0x64};}throw new MessengerError('SERVER_ERROR','Registration\x20failed:\x20'+b['status']+'\x20'+b['statusText']+'\x20-\x20'+d);}const c=await b['json']();if(c['failedPrekeys']&&c['failedPrekeys']['length']>0x0){}return{'success':c['success'],'uploadedCount':c['uploaded_count'],'failedPrekeys':c['failed_prekeys']||[],'currentTotal':c['current_total'],'maxAllowed':c['max_allowed']};}catch(e){if(e instanceof MessengerError)throw e;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20register\x20device',e);}}async['uploadPreKeys'](a){try{const b=await this['fetchWithTimeout'](this['config']['serverUrl']+'/v1/prekeys/upload',{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](a)});if(!b['ok']){const d=await b['text']();throw new MessengerError('SERVER_ERROR','Failed\x20to\x20upload\x20prekeys:\x20'+b['status']+'\x20'+b['statusText']+'\x20-\x20'+d);}const c=await b['json']();if(c['failedPrekeys']&&c['failedPrekeys']['length']>0x0)throw new MessengerError('SERVER_ERROR','Some\x20prekeys\x20failed\x20to\x20upload:\x20'+JSON['stringify'](c['failedPrekeys']));return{'success':c['success'],'uploadedCount':c['uploaded_count'],'failedPrekeys':c['failed_prekeys']||[],'currentTotal':c['current_total'],'maxAllowed':c['max_allowed']};}catch(e){if(e instanceof MessengerError)throw e;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20upload\x20prekeys',e);}}async['fetchRemoteBundle'](a,b,c,d,e){try{const f=await this['fetchWithTimeout'](this['config']['serverUrl']+'/v1/bundle/'+a,{'headers':{'X-PublicKey':c,'X-SignatureScheme':d['signatureScheme'],'X-Signature':d['signature'],'X-Timestamp':d['timestamp']['toString'](),'X-Nonce':d['nonce']}});if(!f['ok']){if(f['status']===0x194)throw new MessengerError('IDENTITY_NOT_FOUND','User\x20'+a+'\x20not\x20found\x20on\x20server');throw new MessengerError('SERVER_ERROR','Failed\x20to\x20fetch\x20remote\x20bundle:\x20'+f['statusText']);}return await f['json']();}catch(g){if(g instanceof MessengerError)throw g;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20fetch\x20remote\x20bundle',g);}}async['sendMessage'](a){try{const b=await this['fetchWithTimeout'](this['config']['serverUrl']+'/v1/message',{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](a)}),c=await b['json']();if(!b['ok']){const d=new MessengerError('SERVER_ERROR',c?.['error']?.['message']||c?.['message']||b['statusText']);d['guardList']=c?.['error']?.['guard_list']||c?.['guard_list'];throw d;}return c;}catch(e){if(e instanceof MessengerError)throw e;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20send\x20message',e);}}async['pullMessages'](a,b,c,d){try{const e=new URL(this['config']['serverUrl']+'/v1/messages/'+a);if(d!==void 0x0)e['searchParams']['set']('limit',d['toString']());const f=await this['fetchWithTimeout'](e['toString'](),{'headers':{'X-PublicKey':b,'X-SignatureScheme':c['signatureScheme'],'X-Signature':c['signature'],'X-Timestamp':c['timestamp']['toString'](),'X-Nonce':c['nonce']}});if(!f['ok'])throw new MessengerError('SERVER_ERROR','Failed\x20to\x20pull\x20messages:\x20'+f['statusText']);return await f['json']();}catch(g){if(g instanceof MessengerError)throw g;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20pull\x20messages',g);}}async['popPreKey'](a,b){try{const c=await this['fetchWithTimeout'](this['config']['serverUrl']+'/v1/prekeys/'+a+'/one',{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify']({'publicKey':b['publicKey'],'signatureScheme':b['signatureScheme'],'signature':b['signature'],'timestamp':b['timestamp'],'nonce':b['nonce']})});if(c['status']===0x1ad)throw new MessengerError('SERVER_ERROR','Rate\x20limited:\x20too\x20many\x20pop\x20prekey\x20requests');if(c['status']===0x191)throw new MessengerError('SERVER_ERROR','Unauthorized:\x20signature\x20verification\x20failed\x20or\x20address\x20mismatch');if(!c['ok'])throw new MessengerError('SERVER_ERROR','Failed\x20to\x20pop\x20prekey:\x20'+c['statusText']);return await c['json']();}catch(d){if(d instanceof MessengerError)throw d;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20pop\x20prekey',d);}}async['getPrekeyStatus'](a,b,c){try{const d=await this['fetchWithTimeout'](this['config']['serverUrl']+'/v1/prekeys/'+a+'/status',{'headers':{'X-PublicKey':b,'X-SignatureScheme':c['signatureScheme'],'X-Signature':c['signature'],'X-Timestamp':c['timestamp']['toString'](),'X-Nonce':c['nonce']}});if(!d['ok'])throw new MessengerError('SERVER_ERROR','Failed\x20to\x20get\x20prekey\x20status:\x20'+d['statusText']);const e=await d['json']();return{'currentCount':e['currentCount'],'maxAllowed':e['maxAllowed'],'threshold':e['threshold'],'shouldRefill':e['shouldRefill']};}catch(f){if(f instanceof MessengerError)throw f;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20get\x20prekey\x20status',f);}}async['acknowledgeMessages'](a,b,c){try{const d=await this['fetchWithTimeout'](this['config']['serverUrl']+'/v1/messages/ack',{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify']({'publicKey':c['publicKey'],'messageIds':a,'senderPublicKey':b,'signatureScheme':c['signatureScheme'],'signature':c['signature'],'timestamp':c['timestamp'],'nonce':c['nonce']})});if(!d['ok'])throw new MessengerError('SERVER_ERROR','Failed\x20to\x20acknowledge\x20messages:\x20'+d['statusText']);}catch(e){if(e instanceof MessengerError)throw e;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20acknowledge\x20messages',e);}}async['addToBlacklist'](a,b){return this['_listOperation'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/blacklist',b,'POST');}async['removeFromBlacklist'](a,b){return this['_listOperation'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/blacklist',b,'DELETE');}async['clearBlacklist'](a,b){return this['_listOperation'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/blacklist/clear',b,'POST');}async['getBlacklist'](a,b){try{const c=await this['fetchWithTimeout'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/blacklist/get',{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](b)});if(!c['ok']){const d=await c['text']();logger['error']('getBlacklist\x20error\x20response:',d);throw new MessengerError('SERVER_ERROR','Failed\x20to\x20get\x20blacklist:\x20'+c['statusText']+'\x20-\x20'+d);}return await c['json']();}catch(e){if(e instanceof MessengerError)throw e;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20get\x20blacklist',e);}}async['existInBlacklist'](a,b){return this['_listOperation'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/blacklist/exist',b,'POST');}async['addToFriendsList'](a,b){return this['_listOperation'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/friends-list',b,'POST');}async['removeFromFriendsList'](a,b){return this['_listOperation'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/friends-list',b,'DELETE');}async['clearFriendsList'](a,b){return this['_listOperation'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/friends-list/clear',b,'POST');}async['getFriendsList'](a,b){try{const c=await this['fetchWithTimeout'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/friends-list/get',{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](b)});if(!c['ok'])throw new MessengerError('SERVER_ERROR','Failed\x20to\x20get\x20friends\x20list:\x20'+c['statusText']);return await c['json']();}catch(d){if(d instanceof MessengerError)throw d;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20get\x20friends\x20list',d);}}async['existInFriendsList'](a,b){return this['_listOperation'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/friends-list/exist',b,'POST');}async['addToGuardList'](a,b){return this['_listOperation'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/guard-list',b,'POST');}async['removeFromGuardList'](a,b){return this['_listOperation'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/guard-list',b,'DELETE');}async['getGuardList'](a,b){try{const c=await this['fetchWithTimeout'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/guard-list/get',{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](b)});if(!c['ok'])throw new MessengerError('SERVER_ERROR','Failed\x20to\x20get\x20guard\x20list:\x20'+c['statusText']);return await c['json']();}catch(d){if(d instanceof MessengerError)throw d;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20get\x20guard\x20list',d);}}async['updateSettings'](a,b){try{const c=await this['fetchWithTimeout'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/settings',{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](b)});if(!c['ok']){const d=await c['text']();throw new MessengerError('SERVER_ERROR','Failed\x20to\x20update\x20settings:\x20'+c['statusText']+'\x20-\x20'+d);}return(await c['json']())['success'];}catch(e){if(e instanceof MessengerError)throw e;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20update\x20settings',e);}}async['getSettings'](a,b){try{const c=await this['fetchWithTimeout'](this['config']['serverUrl']+'/v1/spam-protection/'+a+'/settings/get',{'method':'POST','headers':{'Content-Type':'application/json'},'body':JSON['stringify'](b)});if(!c['ok']){const d=await c['text']();throw new MessengerError('SERVER_ERROR','Failed\x20to\x20get\x20settings:\x20'+c['statusText']+'\x20-\x20'+d);}return await c['json']();}catch(e){if(e instanceof MessengerError)throw e;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20get\x20settings',e);}}async['_listOperation'](a,b,c='POST'){try{const d=await this['fetchWithTimeout'](a,{'method':c,'headers':{'Content-Type':'application/json'},'body':JSON['stringify'](b)});if(!d['ok']){const e=await d['text']();throw new MessengerError('SERVER_ERROR','List\x20operation\x20failed:\x20'+d['statusText']+'\x20-\x20'+e);}return await d['json']();}catch(f){if(f instanceof MessengerError)throw f;throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20perform\x20list\x20operation',f);}}};new MessengerServerClient();async function getAccount$1(){const {Account:a}=await import('./w/local/account.mjs');return a['Instance']();}var MessengerSession=class{constructor(a,b){this['identity']=null,this['config']={...DEFAULT_MESSENGER_CONFIG,...b},this['serverClient']=new MessengerServerClient(this['config']),this['userAddress']=a;const c=getDatabase(a);this['pqStore']=new PQSessionStoreAdapter(c,a),this['pqCipher']=new PQSessionCipher(this['pqStore'],async()=>{return(await(await getAccount$1())['deriveX25519Identity'](a))['falcon512KeyPair'];});}get['store'](){return this['pqStore'];}get['cipher'](){return this['pqCipher'];}async['ensureIdentity'](a){if(this['identity'])return this['identity'];const b=await this['pqStore']['getIdentityKeyPair'](),c=await this['pqStore']['getRegistrationId']();if(b&&c)return this['identity']={'x25519KeyPair':b,'registrationId':c},this['identity'];const d=await(await getAccount$1())['deriveX25519Identity'](this['userAddress']);return await this['pqStore']['setIdentityKeyPair'](d['x25519KeyPair']),await this['pqStore']['setRegistrationId'](d['registrationId']),this['identity']={'x25519KeyPair':d['x25519KeyPair'],'registrationId':d['registrationId']},this['identity'];}['deriveRegistrationId'](a){const b=a[0x0]<<0x8|a[0x1];return b===0x0?0x1:b;}async['registerDevice'](a){const b=await this['ensureIdentity'](a),c=0x1,d=0x1;let e,f;const g=await this['pqStore']['getSignedPreKeySignature'](c),h=await this['pqStore']['getSignedPreKey'](c),i=await this['pqStore']['getPQPreKey'](d),j=await this['pqStore']['getPQPreKeySignature'](d);if(h&&g&&i&&j)e=h['publicKey'],f=g;else{const u=await this['pqCipher']['generatePreKeyBundle'](c,d,this['config']['prekey_count']);e=u['signedPreKey']['keyPair']['publicKey'],f=u['signedPreKey']['signature'];}const k=await this['generatePreKeyBatch'](this['config']['prekey_count'],a),l=await(await getAccount$1())['get'](a,![],!![]);if(!l?.['pubkey'])throw new MessengerError('IDENTITY_NOT_FOUND','Account\x20not\x20found\x20for\x20'+a);const m=Date['now'](),n=this['generateNonce'](),o='register:'+l['pubkey']+':'+m+':'+n,p=await(await getAccount$1())['signData'](a,o),q=Buffer['from'](p['signature']['slice'](0x2),'hex'),r=await this['pqStore']['getPQPreKey'](d),s=await this['pqStore']['getPQPreKeySignature'](d),t={'userAddress':a,'deviceId':0x1,'registrationId':b['registrationId'],'identityKey':bytesToBase64(b['x25519KeyPair']['publicKey']),'falcon512PublicKey':bytesToBase64(base64ToBytes(l['pubkey'])['slice'](0x1)),'signedPrekey':{'keyId':c,'publicKey':bytesToBase64(e),'signature':bytesToBase64(f)},'prekeys':k,'publicKey':l['pubkey'],'signatureScheme':'Falcon512','signature':bytesToBase64(q),'timestamp':m,'nonce':n};if(r&&s)t['pqPrekey']={'keyId':d,'publicKey':bytesToBase64(r['publicKey']),'signature':bytesToBase64(s)};if(h){let v=bytesToBase64(h['publicKey']);try{const z=Date['now'](),A=this['generateNonce'](),B='get_bundle:'+a+':'+z+':'+A,C=await(await getAccount$1())['signData'](a,B),D=Buffer['from'](C['signature']['slice'](0x2),'hex'),E=await this['serverClient']['fetchRemoteBundle'](a,a,l['pubkey'],{'signatureScheme':'Falcon512','signature':bytesToBase64(new Uint8Array(D)),'timestamp':z,'nonce':A});if(E?.['signedPrekey']?.['publicKey'])v=E['signedPrekey']['publicKey'];}catch{}const w=new TextEncoder()['encode'](v),x=await(await getAccount$1())['signData'](a,w),y=Buffer['from'](x['signature']['slice'](0x2),'hex');t['oldSignedPrekeySignature']=bytesToBase64(new Uint8Array(y));}await this['serverClient']['registerDevice'](t),await this['verifyRegistrationComplete'](a);}async['verifyRegistrationComplete'](a,b=0xa,c=0x1f4){for(let d=0x0;d<b;d++)try{const e=await(await getAccount$1())['get'](a,![],!![]);if(!e?.['pubkey'])throw new MessengerError('IDENTITY_NOT_FOUND','Account\x20not\x20found\x20for\x20'+a);const f=Date['now'](),g=this['generateNonce'](),h='prekey_status:'+a+':'+f+':'+g,j=await(await getAccount$1())['signData'](a,h),k=Buffer['from'](j['signature']['slice'](0x2),'hex');await this['serverClient']['getPrekeyStatus'](a,e['pubkey'],{'signatureScheme':'Falcon512','signature':bytesToBase64(new Uint8Array(k)),'timestamp':f,'nonce':g});return;}catch(l){if(l?.['message']?.['includes']('404')||l?.['status']===0x194){if(d<b-0x1){await new Promise(m=>setTimeout(m,c));continue;}}throw l;}throw new MessengerError('REGISTRATION_FAILED','Registration\x20verification\x20failed\x20after\x20'+b+'\x20attempts');}async['isDeviceRegistered'](a){try{if(!await this['pqStore']['getSignedPreKeySignature'](0x1))return![];const b=await(await getAccount$1())['get'](a,![],!![]);if(!b?.['pubkey'])return![];const c=Date['now'](),d=this['generateNonce'](),e='prekey_status:'+a+':'+c+':'+d,f=await(await getAccount$1())['signData'](a,e),g=Buffer['from'](f['signature']['slice'](0x2),'hex');return await this['serverClient']['getPrekeyStatus'](a,b['pubkey'],{'signatureScheme':'Falcon512','signature':bytesToBase64(new Uint8Array(g)),'timestamp':c,'nonce':d}),!![];}catch(h){if(h?.['message']?.['includes']('404')||h?.['status']===0x194)return![];return![];}}async['generatePreKeyBatch'](a,b){if(a<=0x0)return[];const c=[],{generateX25519KeyPair:d}=await import('./w/messenger/pq/crypto.mjs'),e=randomBytes(0x4),f=(e[0x0]<<0x18|e[0x1]<<0x10|e[0x2]<<0x8|e[0x3])&0x7fffff00;for(let g=0x0;g<a;g++){const h=f+g,j=await this['pqStore']['getOneTimePreKey'](h);if(j){const n=bytesToBase64(j['publicKey']),o=await(await getAccount$1())['signData'](b,j['publicKey']),p=Buffer['from'](o['signature']['slice'](0x2),'hex');c['push']({'keyId':h,'publicKey':n,'signature':bytesToBase64(p)});continue;}const k=d(),l=await(await getAccount$1())['signData'](b,k['publicKey']),m=Buffer['from'](l['signature']['slice'](0x2),'hex');await this['pqStore']['setOneTimePreKey'](h,k),c['push']({'keyId':h,'publicKey':bytesToBase64(k['publicKey']),'signature':bytesToBase64(m)});}return c;}async['ensurePreKeys'](a,b=![]){const c=await(await getAccount$1())['get'](a,![],!![]);if(!c?.['pubkey'])throw new MessengerError('IDENTITY_NOT_FOUND','Account\x20not\x20found\x20for\x20'+a);const d=Date['now'](),e=this['generateNonce'](),f='prekey_status:'+a+':'+d+':'+e,g=await(await getAccount$1())['signData'](a,f),h=Buffer['from'](g['signature']['slice'](0x2),'hex'),i=await this['serverClient']['getPrekeyStatus'](a,c['pubkey'],{'signatureScheme':'Falcon512','signature':bytesToBase64(new Uint8Array(h)),'timestamp':d,'nonce':e});if(!b&&i['currentCount']>=i['maxAllowed'])return;const j=i['maxAllowed']-i['currentCount'];if(j<=0x0)return;await this['ensureIdentity'](a);const k=await this['generatePreKeyBatch'](j,a);if(k['length']===0x0)return;const l=Date['now'](),m=this['generateNonce'](),n='upload_prekeys:'+c['pubkey']+':'+l+':'+m,o=await(await getAccount$1())['signData'](a,n),p=Buffer['from'](o['signature']['slice'](0x2),'hex');await this['serverClient']['uploadPreKeys']({'userAddress':a,'prekeys':k,'publicKey':c['pubkey'],'signatureScheme':'Falcon512','signature':bytesToBase64(p),'timestamp':l,'nonce':m});}['generateNonce'](){const a=new Uint8Array(0x10);return crypto['getRandomValues'](a),Array['from'](a,c=>c['toString'](0x10)['padStart'](0x2,'0'))['join']('');}async['establishSession'](a,b,c=0x1,d){if(await this['pqCipher']['hasSession'](b,c))return;if(!d){const k=await(await getAccount$1())['get'](a,![],!![]);if(!k?.['pubkey'])throw new MessengerError('IDENTITY_NOT_FOUND','Account\x20not\x20found\x20for\x20'+a);const l=Date['now'](),m=this['generateNonce'](),n=k['pubkey'],o='get_bundle:'+a+':'+l+':'+m,p=await(await getAccount$1())['signData'](a,o),q=Buffer['from'](p['signature']['slice'](0x2),'hex');d=await this['serverClient']['fetchRemoteBundle'](b,a,n,{'signatureScheme':'Falcon512','signature':bytesToBase64(new Uint8Array(q)),'timestamp':l,'nonce':m},c);}const e=d['signedPrekey'];if(!e)throw new MessengerError('IDENTITY_NOT_FOUND','No\x20signed\x20prekey\x20available\x20for\x20'+b);const f=base64ToBytes(d['identityKey']),g=d['falcon512PublicKey']?base64ToBytes(d['falcon512PublicKey']):f,h=base64ToBytes(e['publicKey']),i=base64ToBytes(e['signature']),j={'registrationId':d['registrationId'],'deviceId':c,'identityKey':f,'falcon512PublicKey':g,'signedPreKey':{'keyId':e['keyId'],'publicKey':h,'signature':i},'pqPreKey':d['pqPrekey']?{'keyId':d['pqPrekey']['keyId'],'publicKey':base64ToBytes(d['pqPrekey']['publicKey']),'signature':base64ToBytes(d['pqPrekey']['signature'])}:void 0x0};if(d['oneTimePrekey']){const r=base64ToBytes(d['oneTimePrekey']['publicKey']);j['oneTimePreKey']={'keyId':d['oneTimePrekey']['keyId'],'publicKey':r};}if(d['pqPrekey']){const s=base64ToBytes(d['pqPrekey']['publicKey']),t=base64ToBytes(d['pqPrekey']['signature']);j['pqPreKey']={'keyId':d['pqPrekey']['keyId'],'publicKey':s,'signature':t};}await this['pqCipher']['processPreKeyBundle'](b,c,j);}async['encryptMessage'](a,b,c,d=0x1){let e=0x0;const f=0x5;while(e<=f)try{if(!await this['pqCipher']['hasSession'](b,d))await this['establishSession'](a,b,d);const g=new TextEncoder()['encode'](c),h=await this['pqCipher']['encryptMessage'](b,g,d);return{'type':h['type'],'body':h['body']['buffer'],'registrationId':h['registrationId']};}catch(i){if(e>=f)throw i;try{await this['pqStore']['removeSession'](b,d),e++,await new Promise(j=>setTimeout(j,0x64));}catch(j){throw i;}}throw new MessengerError('ENCRYPTION_FAILED','Encryption\x20failed\x20after\x20multiple\x20attempts');}async['decryptMessage'](a,b,c,d,e=0x1){const f=new TextDecoder(),g=new Uint8Array(c);let h=0x0;const i=0x5,j=await this['pqCipher']['hasSession'](b,e);if(d!==0x3&&!j)throw new Error('收到\x20WHISPER_MESSAGE\x20但无现有会话,需要等待\x20PREKEY_MESSAGE');while(h<=i)try{let k;if(d===0x3)try{return k=await this['pqCipher']['decryptMessage'](b,g,e),f['decode'](k);}catch(l){if(j&&h===0x0){if(a['toLowerCase']()<b['toLowerCase']())throw new Error('PREKEY\x20竞争:我的地址较小,保留我的会话');else return await this['pqStore']['removeSession'](b,e),k=await this['pqCipher']['decryptMessage'](b,g,e),f['decode'](k);}else throw l;}else k=await this['pqCipher']['decryptMessage'](b,g,e);return f['decode'](k);}catch(m){if(h>=i)throw m;try{if(j)await this['pqStore']['removeSession'](b,e);if(d===0x3){}h++,await new Promise(n=>setTimeout(n,0x64));}catch(n){throw m;}}throw new MessengerError('DECRYPTION_FAILED','Decryption\x20failed\x20after\x20multiple\x20attempts');}async['getIdentityKey'](){return bytesToBase64((await this['ensureIdentity']())['x25519KeyPair']['publicKey']);}async['getRegistrationId'](){return(await this['ensureIdentity']())['registrationId'];}},SessionStateManager=class{constructor(a){this['store']=a;}async['snapshotSession'](a,b){const c=await this['store']['getSession'](a,b);return{'sessionData':c?JSON['stringify'](c):null,'timestamp':Date['now']()};}async['rollbackSession'](a,b,c){if(c['sessionData']){const d=JSON['parse'](c['sessionData']);await this['store']['setSession'](a,b,d);}else await this['store']['removeSession'](a,b);}async['commitSession'](a,b){}},DecryptionEngine=class{constructor(a,b){this['store']=a,this['cipher']=new PQSessionCipher(a,b),this['sessionManager']=new SessionStateManager(a);}async['decryptMessage'](a,b,c,d,e=0x1){const f=await this['sessionManager']['snapshotSession'](b,e);try{if(d===0x3)return await this['handlePreKeyMessage'](a,b,c,e,f);else return await this['handleWhisperMessage'](a,b,c,e,f);}catch(g){return await this['sessionManager']['rollbackSession'](b,e,f),{'success':![],'sessionUpdated':![],'sessionRolledBack':!![],'messageType':d===0x3?'PREKEY':'WHISPER','error':g instanceof Error?g['message']:String(g)};}}async['handlePreKeyMessage'](a,b,c,d,e){const f=new TextDecoder(),g=new Uint8Array(c),h=await this['cipher']['decryptMessage'](b,g,d),i=f['decode'](h);await this['sessionManager']['commitSession'](b,d);if(a['toLowerCase']()<b['toLowerCase']()){}return{'success':!![],'plaintext':i,'sessionUpdated':!![],'sessionRolledBack':![],'messageType':'PREKEY'};}async['handleWhisperMessage'](a,b,c,d,e){if(!await this['cipher']['hasSession'](b,d))throw new Error('No\x20session\x20for\x20WHISPER_MESSAGE');const f=new TextDecoder(),g=new Uint8Array(c),h=await this['cipher']['decryptMessage'](b,g,d);return{'success':!![],'plaintext':f['decode'](h),'sessionUpdated':!![],'sessionRolledBack':![],'messageType':'WHISPER'};}};function canonicalizeJson(a){if(a===void 0x0)return'null';if(a===null||typeof a!=='object')return JSON['stringify'](a);if(Array['isArray'](a))return'['+a['map'](canonicalizeJson)['join'](',')+']';const b=a;return'{'+Object['keys'](b)['sort']()['filter'](c=>b[c]!==void 0x0)['map'](c=>'\x22'+c+'\x22:'+canonicalizeJson(b[c]))['join'](',')+'}';}async function getAccount(){const {Account:a}=await import('./w/local/account.mjs');return a['Instance']();}var Messenger=class{constructor(a,b){this['userAddress']=null,this['onMessageCallback']=null,this['pollingTimer']=null,this['messageConsecutiveEmptyPulls']=0x0,this['prekeyConsecutiveOkCount']=0x0,this['isPollingRunning']=![],this['waitingMessages']=new Map(),this['failedMessages']=new Map(),this['waitingMessageRetries']=new Map(),this['sendPromise']=Promise['resolve'](),this['userAddress']=a,this['config']={...DEFAULT_MESSENGER_CONFIG,...b},this['session']=new MessengerSession(a,this['config']),this['serverClient']=new MessengerServerClient(this['config']),this['messageStorage']=new MessageStorage(a),this['sessionStateStorage']=new SessionStateStorage(a),this['decryptionEngine']=new DecryptionEngine(this['session']['store'],async()=>{return(await(await getAccount())['deriveX25519Identity'](a))['falcon512KeyPair'];}),this['currentMessageInterval']=this['config']['message_poll_default_interval_ms']??0x168*0x3e8;}['getUserAddress'](){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');return this['userAddress'];}async['getPublicKey'](){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');return(await(await getAccount())['get'](this['userAddress'],![],!![]))?.['pubkey']||'';}['isValidGuardMessage'](a,b){return Boolean(a&&b&&a32a(a)&&a32a(b));}async['generateSignatureParams'](a){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const b=await(await getAccount())['get'](this['userAddress'],![]);if(!b?.['secret'])throw new MessengerError('IDENTITY_NOT_FOUND','Account\x20not\x20found\x20or\x20no\x20secret\x20key\x20for\x20'+this['userAddress']);const {Falcon512Keypair:c}=await import('./keypairs/falcon512/index.mjs'),d=c['fromSecretKey'](b['secret']),e=d['getPublicKey']()['toWowPublicKey'](),f=Date['now'](),g=this['generateNonce'](),h=a+':'+e+':'+f+':'+g,i=await d['sign'](new TextEncoder()['encode'](h));return{'signatureScheme':'Falcon512','signature':Buffer['from'](i)['toString']('base64'),'timestamp':f,'nonce':g};}['generateNonce'](){const a=new Uint8Array(0x10);return crypto['getRandomValues'](a),Array['from'](a,c=>c['toString'](0x10)['padStart'](0x2,'0'))['join']('');}async['initialize'](){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');await this['session']['ensureIdentity'](this['userAddress']),await this['session']['registerDevice'](this['userAddress']),await this['session']['ensurePreKeys'](this['userAddress']),await this['checkAndRefillPrekeys'](),this['startPollingTimer']();}async['checkAndRefillPrekeys'](){if(!this['userAddress'])return;await this['session']['ensurePreKeys'](this['userAddress'],![]);}['startPollingTimer'](){if(this['pollingTimer'])clearTimeout(this['pollingTimer']);this['isPollingRunning']=!![],this['scheduleNextPoll']();}['stopPollingTimer'](){this['isPollingRunning']=![],this['pollingTimer']&&(clearTimeout(this['pollingTimer']),this['pollingTimer']=null);}['scheduleNextPoll'](){if(!this['isPollingRunning'])return;const a=this['getNextPollInterval']();this['pollingTimer']=setTimeout(()=>{this['poll']()['catch'](b=>{})['finally'](()=>{this['scheduleNextPoll']();});},a);}['getNextPollInterval'](){if(this['waitingMessages']['size']>0x0)return this['config']['message_poll_waiting_interval_ms']??0x3*0x3e8;return this['currentMessageInterval'];}async['poll'](){if(!this['userAddress'])return;try{const a=await this['pullMessages']();if(a['messages']['length']>0x0){this['messageConsecutiveEmptyPulls']=0x0,this['currentMessageInterval']=this['config']['message_poll_fast_interval_ms']??0x6*0x3e8;if(this['onMessageCallback'])this['onMessageCallback'](a['messages']);}else this['messageConsecutiveEmptyPulls']++,this['messageConsecutiveEmptyPulls']>=(this['config']['message_poll_consecutive_empty_limit']??0x3)&&(this['currentMessageInterval']=this['config']['message_poll_default_interval_ms']??0x168*0x3e8,this['messageConsecutiveEmptyPulls']=0x0);if(a['prekey_status']){if(a['prekey_status']['shouldRefill'])this['prekeyConsecutiveOkCount']=0x0,await this['checkAndRefillPrekeys']();else{this['prekeyConsecutiveOkCount']++;if(this['prekeyConsecutiveOkCount']>=(this['config']['prekey_poll_consecutive_ok_limit']??0x3))this['prekeyConsecutiveOkCount']=0x0;}}}catch(b){}}['triggerFastPoll'](){this['currentMessageInterval']=this['config']['message_poll_fast_interval_ms']??0x6*0x3e8,this['messageConsecutiveEmptyPulls']=0x0;if(this['isPollingRunning']){if(this['pollingTimer'])clearTimeout(this['pollingTimer']);this['scheduleNextPoll']();}}async['sendMessage'](a,b,c){const d=this['sendPromise'];let e;this['sendPromise']=new Promise(f=>{e=f;}),await d;try{if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');if(c?.['replyTo']){const B=this['messageStorage']['getMessageById'](c['replyTo']['messageId']);if(!B)throw new MessengerError('INVALID_INPUT','sendMessage.replyTo.messageId\x20'+c['replyTo']['messageId']+'\x20not\x20found\x20in\x20local\x20storage');const C=this['userAddress']['toLowerCase'](),D=a['toLowerCase'](),E=B['fromAddress']['toLowerCase'](),F=B['toAddress']['toLowerCase']();if(!(E===C&&F===D||E===D&&F===C))throw new MessengerError('INVALID_INPUT','sendMessage.replyTo.messageId\x20'+c['replyTo']['messageId']+'\x20does\x20not\x20belong\x20to\x20this\x20conversation');}else{if(b['startsWith']('@REPLY@'))throw new MessengerError('INVALID_INPUT','Message\x20content\x20cannot\x20start\x20with\x20the\x20reserved\x20prefix\x20\x22'+REPLY_HEADER+'\x22.\x20Use\x20the\x20reply\x20feature\x20to\x20send\x20a\x20quoted\x20message,\x20or\x20rephrase\x20your\x20content.');}const f=Date['now'](),g=Date['now'](),h=this['generateNonce'](),i=c?.['replyTo']?buildReplyPlaintext(b,c['replyTo']):b,j=new TextEncoder()['encode'](i)['length'];if(j>0x2800)throw new MessengerError('INVALID_INPUT','Message\x20size\x20('+j+'\x20bytes)\x20exceeds\x20maximum\x20allowed\x20size\x20('+NORMAL_MESSAGE_BYTES_LIMIT+'\x20bytes).\x20Consider\x20using\x20sendZipFile\x20for\x20large\x20content.');await this['pullMessages']();const k=this['messageStorage']['getLastReceivedLeafIndex'](this['userAddress'],a),l=await this['session']['encryptMessage'](this['userAddress'],a,i),m=Buffer['from'](new Uint8Array(l['body']))['toString']('base64'),n=hashPlaintext(i,f,c?.['guardAddress'],c?.['passportAddress'],k),o=await(await getAccount())['get'](this['userAddress'],![],!![]);if(!o)throw new MessengerError('IDENTITY_NOT_FOUND','User\x20account\x20not\x20found');const p=o['pubkey'],q=c?.['guardAddress']||'',r=c?.['passportAddress']||'',s=c?.['network']||'',t=k>=0x0?k['toString']():'',u=c?.['force']?'true':'false',v='send_message:'+this['userAddress']+':'+a+':'+q+':'+r+':'+n+':'+t+':'+p+':'+g+':'+h+':'+u+':'+s,w=await(await getAccount())['signData'](this['userAddress'],v),x=Buffer['from'](w['signature']['slice'](0x2),'hex'),y=bytesToBase64(new Uint8Array(x)),z=await this['serverClient']['sendMessage']({'sender':w['publicKey'],'recipient':a,'ciphertext':m,'plaintextHash':n,'clientTimestamp':f,'msgType':l['type'],'signatureScheme':'Falcon512','signature':y,'timestamp':g,'nonce':h,'guardAddress':c?.['guardAddress'],'passportAddress':c?.['passportAddress'],'network':c?.['network'],'force':c?.['force'],'lastReceivedLeafIndex':k>=0x0?k:void 0x0}),A={'messageId':z['messageId'],'fromAddress':this['userAddress'],'toAddress':a,'plaintextHash':n,'plaintext':i,'replyTo':c?.['replyTo'],'guardAddress':c?.['guardAddress'],'passportAddress':c?.['passportAddress'],'lastReceivedLeafIndex':k,'direction':'sent','status':z['status']==='confirmed'?'confirmed':'pending','msgType':l['type'],'createdAt':f};z['merkleData']&&(A['leafIndex']=z['merkleData']['leafIndex'],A['prevRoot']=z['merkleData']['prevRoot'],A['newRoot']=z['merkleData']['newRoot'],A['serverSignature']=z['merkleData']['serverSignature'],A['serverTimestamp']=z['merkleData']['serverTimestamp'],A['serverPublicKey']=z['merkleData']['serverPublicKey'],this['sessionStateStorage']['updateSessionState'](this['userAddress'],a,{'currentRoot':z['merkleData']['newRoot'],'prevRoot':z['merkleData']['prevRoot'],'lastLeafIndex':z['merkleData']['leafIndex'],'lastSyncAt':Date['now']()}));this['messageStorage']['saveMessage'](A);if(z['pendingMerkleData'])for(const [G,H]of Object['entries'](z['pendingMerkleData'])){const I=this['messageStorage']['getMessage'](G);if(I&&I['status']==='pending')this['messageStorage']['updateMessageStatus'](G,'confirmed',{'leafIndex':H['leafIndex'],'newRoot':H['newRoot'],'serverSignature':H['serverSignature'],'serverTimestamp':H['serverTimestamp'],'serverPublicKey':H['serverPublicKey']});}return this['triggerFastPoll'](),{'messageId':z['messageId'],'status':A['status'],'merkleData':z['merkleData'],'guardList':z['guard_list'],'lastReceivedLeafIndex':k>=0x0?k:void 0x0};}finally{e();}}async['pullMessages'](a){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const b=Date['now'](),c=this['generateNonce'](),d='fetch_messages:'+this['userAddress']+':'+(a||0x64)+':'+b+':'+c,e=(await(await getAccount())['get'](this['userAddress'],![],!![]))?.['pubkey']||'',f=await(await getAccount())['signData'](this['userAddress'],d),g={'signatureScheme':'Falcon512','signature':bytesToBase64(Buffer['from'](f['signature']['slice'](0x2),'hex')),'timestamp':b,'nonce':c},h=await this['serverClient']['pullMessages'](this['userAddress'],e,g,a);if(h['messages']['length']===0x0)return{'messages':[],'prekey_status':h['prekey_status']};const i=[],j=[],k=[...h['messages']]['sort'](function(l,m){return(l['clientTimestamp']||0x0)-(m['clientTimestamp']||0x0);});await this['processWaitingMessages'](i,j);for(const l of k){if(this['waitingMessages']['has'](l['id'])){j['push'](l['id']);continue;}if(this['failedMessages']['has'](l['id'])){j['push'](l['id']);continue;}if(this['messageStorage']['getMessage'](l['id'])){j['push'](l['id']);continue;}const m=await this['tryDecryptMessage'](l);if(m['success']&&m['message']&&m['decryptedData'])this['messageStorage']['saveMessage'](m['message']),i['push'](m['decryptedData']),j['push'](l['id']),this['waitingMessages']['delete'](l['id']);else{if(m['shouldRetry'])this['waitingMessages']['set'](l['id'],l);else this['failedMessages']['set'](l['id'],{'message':l,'error':m['error']||'Unknown\x20error'}),await this['saveFailedMessage'](l,m['error']||'Unknown\x20error'),j['push'](l['id']);}}if(this['waitingMessages']['size']>0x0&&this['isPollingRunning'])this['reschedulePolling']();if(j['length']>0x0&&this['userAddress']){const n=Date['now'](),o=this['generateNonce'](),p=await(await getAccount())['get'](this['userAddress'],![],!![]);if(p?.['pubkey']){const q='ack_messages:'+this['userAddress']+':'+j['join'](',')+':'+p['pubkey']+':'+n+':'+o,r=await(await getAccount())['signData'](this['userAddress'],q),s=Buffer['from'](r['signature']['slice'](0x2),'hex'),t=bytesToBase64(new Uint8Array(s));await this['serverClient']['acknowledgeMessages'](j,r['publicKey'],{'publicKey':r['publicKey'],'signatureScheme':'Falcon512','signature':t,'timestamp':n,'nonce':o});}}return{'messages':i,'prekey_status':h['prekey_status']};}['getLastSentLeafIndex'](a){if(!this['userAddress'])return-0x1;const b=this['messageStorage']['getMessagesBySession'](this['userAddress'],a)['filter'](c=>c['direction']==='sent'&&c['leafIndex']!==void 0x0);if(b['length']===0x0)return-0x1;return Math['max'](...b['map'](c=>c['leafIndex']));}['getSessionMessages'](a){if(!this['userAddress'])return[];return this['messageStorage']['getMessagesBySession'](this['userAddress'],a);}['getSessionState'](a){if(!this['userAddress'])return;return this['sessionStateStorage']['getSessionState'](this['userAddress'],a);}async['submitChainProof'](a,b,c){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const d=this['sessionStateStorage']['getSessionState'](this['userAddress'],b);if(!d||!d['currentRoot'])throw new MessengerError('SESSION_NOT_ESTABLISHED','No\x20session\x20state\x20found');const e=this['messageStorage']['getMessagesBySession'](this['userAddress'],b),f=e[e['length']-0x1];if(!f||!f['serverPublicKey']||!f['serverSignature'])throw new MessengerError('INVALID_PROOF','No\x20temporal\x20proof\x20(missing\x20server\x20public\x20key\x20or\x20signature),\x20cannot\x20submit\x20Proof\x20to\x20WoWok\x20blockchain');const g=f['serverPublicKey'],h=f['serverSignature'],i={'sessionId':d['sessionId'],'merkleRoot':d['currentRoot'],'messageCount':d['messageCount'],'timestamp':Date['now']()},{CallProof:j}=await import('./proof-BcyNI5NQ.mjs')['then'](l=>l['r']),k=await new j({'proof':JSON['stringify'](i),'server_pubkey':g,'server_signature':h,'proof_type':0x1,'description':c||'Messenger\x20session\x20proof\x20for\x20'+this['userAddress']+'\x20<->\x20'+b,'item_count':d['messageCount'],'about_address':b})['call'](a);return{'proofAddress':(k?.['objectChanges'])?.['find'](l=>l['objectType']?.['includes']('Proof'))?.['objectId']||'','txHash':k?.['digest']||''};}['destroy'](){this['stopPollingTimer']();}['disconnect'](){this['destroy']();}['setOnMessageCallback'](a){this['onMessageCallback']=a;}async['sendZipFile'](a,b,c){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const d=await this['loadFileData'](b),{ZipWriter:e,BlobWriter:f,Uint8ArrayReader:g}=await import('@zip.js/zip.js'),h=c?.['fileName']||a32c['basename'](b)||'file.zip',i=c?.['contentType']||this['detectContentType'](h),j=new f('application/zip'),k=new e(j);await k['add'](h,new g(d)),await k['close']();const l=await j['getData'](),m=new Uint8Array(await l['arrayBuffer']());if(m['length']>0x500000)throw new MessengerError('INVALID_INPUT','ZIP\x20file\x20size\x20('+m['length']+'\x20bytes)\x20exceeds\x20local\x20maximum\x20allowed\x20size\x20('+WTS_FILE_BYTES_LIMIT+'\x20bytes)');const n='0x'+createHash('sha256')['update'](m)['digest']('hex'),o=Buffer['from'](m)['toString']('base64'),p={'fileName':h+'.zip','fileSize':m['length'],'fileHash':n,'contentType':i};await this['pullMessages']();const q=this['messageStorage']['getLastReceivedLeafIndex'](this['userAddress'],a),r=Date['now'](),s=await this['session']['encryptMessage'](this['userAddress'],a,o),t=Buffer['from'](new Uint8Array(s['body']))['toString']('base64'),u=c?.['guardAddress']||'',v=c?.['passportAddress']||'',w=c?.['network']||'',x=hashPlaintext(o,r,u,v,q),y=Date['now'](),z=this['generateNonce'](),A=await(await getAccount())['get'](this['userAddress'],![],!![]);if(!A)throw new MessengerError('IDENTITY_NOT_FOUND','User\x20account\x20not\x20found');const B=A['pubkey'],C=q>=0x0?q['toString']():'',D=c?.['force']?'true':'false',E='send_message:'+this['userAddress']+':'+a+':'+u+':'+v+':'+x+':'+C+':'+B+':'+y+':'+z+':'+D+':'+w,F=await(await getAccount())['signData'](this['userAddress'],E),G=Buffer['from'](F['signature']['slice'](0x2),'hex'),H=bytesToBase64(new Uint8Array(G)),I=await this['serverClient']['sendMessage']({'sender':F['publicKey'],'recipient':a,'ciphertext':t,'plaintextHash':x,'clientTimestamp':r,'msgType':s['type'],'zipMetadata':p,'guardAddress':c?.['guardAddress'],'passportAddress':c?.['passportAddress'],'network':c?.['network'],'force':c?.['force'],'lastReceivedLeafIndex':q>=0x0?q:void 0x0,'signatureScheme':'Falcon512','signature':H,'timestamp':y,'nonce':z}),J={'messageId':I['messageId'],'fromAddress':this['userAddress'],'toAddress':a,'plaintextHash':x,'plaintext':o,'guardAddress':c?.['guardAddress'],'passportAddress':c?.['passportAddress'],'lastReceivedLeafIndex':q,'direction':'sent','status':I['status']==='confirmed'?'confirmed':'pending','msgType':s['type'],'zipMetadata':p,'createdAt':r};I['merkleData']&&(J['leafIndex']=I['merkleData']['leafIndex'],J['prevRoot']=I['merkleData']['prevRoot'],J['newRoot']=I['merkleData']['newRoot'],J['serverSignature']=I['merkleData']['serverSignature'],J['serverTimestamp']=I['merkleData']['serverTimestamp'],J['serverPublicKey']=I['merkleData']['serverPublicKey'],this['sessionStateStorage']['updateSessionState'](this['userAddress'],a,{'currentRoot':I['merkleData']['newRoot'],'prevRoot':I['merkleData']['prevRoot'],'lastLeafIndex':I['merkleData']['leafIndex'],'lastSyncAt':Date['now']()}));this['messageStorage']['saveMessage'](J);if(I['pendingMerkleData'])for(const [K,L]of Object['entries'](I['pendingMerkleData'])){const M=this['messageStorage']['getMessage'](K);if(M&&M['status']==='pending')this['messageStorage']['updateMessageStatus'](K,'confirmed',{'leafIndex':L['leafIndex'],'newRoot':L['newRoot'],'serverSignature':L['serverSignature'],'serverTimestamp':L['serverTimestamp'],'serverPublicKey':L['serverPublicKey']});}return this['triggerFastPoll'](),{'messageId':I['messageId'],'status':J['status'],'merkleData':I['merkleData'],'guardList':I['guard_list'],'lastReceivedLeafIndex':q>=0x0?q:void 0x0};}async['loadFileData'](a){if(a['startsWith']('http://')||a['startsWith']('https://')){const d=await fetch(a);if(!d['ok'])throw new MessengerError('NETWORK_ERROR','Failed\x20to\x20fetch\x20file\x20from\x20'+a+':\x20'+d['statusText']);const e=await d['arrayBuffer']();return new Uint8Array(e);}const b=a32c['resolve'](a);if(!a32d['existsSync'](b))throw new MessengerError('FILE_NOT_FOUND','File\x20not\x20found:\x20'+b);const c=a32d['readFileSync'](b);return new Uint8Array(c);}['detectContentType'](a){switch(a32c['extname'](a)['toLowerCase']()){case'.wts':return'wts';case'.wip':return'wip';default:return'zip';}}async['_createSignedRequest'](a){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const b=Date['now'](),c=this['generateNonce'](),d=b+':'+c+':'+canonicalizeJson(a),e=await(await getAccount())['signData'](this['userAddress'],d),f=Buffer['from'](e['signature']['slice'](0x2),'hex'),g=bytesToBase64(new Uint8Array(f)),h=await(await getAccount())['get'](this['userAddress'],![],!![]);if(!h||!h['pubkey'])throw new MessengerError('IDENTITY_NOT_FOUND','Account\x20public\x20key\x20not\x20found');return{'userAddress':this['userAddress'],'publicKey':h['pubkey'],'signatureScheme':'Falcon512','signature':g,'timestamp':b,'nonce':c,'data':a};}['_validateAddresses'](a){const b=[],c=[];for(const d of a)if(a32a(d))b['push'](d);else c['push'](d);return{'valid':b,'invalid':c};}async['addToBlacklist'](a){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const {valid:b,invalid:c}=this['_validateAddresses'](a);if(c['length']>0x0)return{'success':![],'operation':'add','modifiedCount':0x0,'currentCount':0x0,'maxCount':0x0,'invalidAddresses':c,'message':'Invalid\x20addresses:\x20'+c['join'](',\x20')};const d={'addresses':b},e=await this['_createSignedRequest'](d);return this['serverClient']['addToBlacklist'](this['userAddress'],e);}async['removeFromBlacklist'](a){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const {valid:b,invalid:c}=this['_validateAddresses'](a);if(c['length']>0x0)return{'success':![],'operation':'remove','modifiedCount':0x0,'currentCount':0x0,'maxCount':0x0,'invalidAddresses':c,'message':'Invalid\x20addresses:\x20'+c['join'](',\x20')};const d={'addresses':b},e=await this['_createSignedRequest'](d);return this['serverClient']['removeFromBlacklist'](this['userAddress'],e);}async['clearBlacklist'](){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const a=await this['_createSignedRequest']({});return this['serverClient']['clearBlacklist'](this['userAddress'],a);}async['getBlacklist'](){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const a=await this['_createSignedRequest']({});return this['serverClient']['getBlacklist'](this['userAddress'],a);}async['existInBlacklist'](a){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const {valid:b,invalid:c}=this['_validateAddresses'](a);if(c['length']>0x0)return{'success':![],'operation':'exist','modifiedCount':0x0,'currentCount':0x0,'maxCount':0x0,'invalidAddresses':c,'message':'Invalid\x20addresses:\x20'+c['join'](',\x20')};const d={'addresses':b},e=await this['_createSignedRequest'](d);return this['serverClient']['existInBlacklist'](this['userAddress'],e);}async['addToFriendsList'](a){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const {valid:b,invalid:c}=this['_validateAddresses'](a);if(c['length']>0x0)return{'success':![],'operation':'add','modifiedCount':0x0,'currentCount':0x0,'maxCount':0x0,'invalidAddresses':c,'message':'Invalid\x20addresses:\x20'+c['join'](',\x20')};const d={'addresses':b},e=await this['_createSignedRequest'](d);return this['serverClient']['addToFriendsList'](this['userAddress'],e);}async['removeFromFriendsList'](a){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const {valid:b,invalid:c}=this['_validateAddresses'](a);if(c['length']>0x0)return{'success':![],'operation':'remove','modifiedCount':0x0,'currentCount':0x0,'maxCount':0x0,'invalidAddresses':c,'message':'Invalid\x20addresses:\x20'+c['join'](',\x20')};const d={'addresses':b},e=await this['_createSignedRequest'](d);return this['serverClient']['removeFromFriendsList'](this['userAddress'],e);}async['clearFriendsList'](){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const a=await this['_createSignedRequest']({});return this['serverClient']['clearFriendsList'](this['userAddress'],a);}async['getFriendsList'](){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const a=await this['_createSignedRequest']({});return this['serverClient']['getFriendsList'](this['userAddress'],a);}async['existInFriendsList'](a){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const {valid:b,invalid:c}=this['_validateAddresses'](a);if(c['length']>0x0)return{'success':![],'operation':'exist','modifiedCount':0x0,'currentCount':0x0,'maxCount':0x0,'invalidAddresses':c,'message':'Invalid\x20addresses:\x20'+c['join'](',\x20')};const d={'addresses':b},e=await this['_createSignedRequest'](d);return this['serverClient']['existInFriendsList'](this['userAddress'],e);}async['addToGuardList'](a){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const b={'guards':a},c=await this['_createSignedRequest'](b);return this['serverClient']['addToGuardList'](this['userAddress'],c);}async['removeFromGuardList'](a){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const {valid:b,invalid:c}=this['_validateAddresses'](a);if(c['length']>0x0)return{'success':![],'operation':'remove','modifiedCount':0x0,'currentCount':0x0,'maxCount':0x0,'invalidAddresses':c,'message':'Invalid\x20addresses:\x20'+c['join'](',\x20')};const d={'addresses':b},e=await this['_createSignedRequest'](d);return this['serverClient']['removeFromGuardList'](this['userAddress'],e);}async['getGuardList'](){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const a=await this['_createSignedRequest']({});return this['serverClient']['getGuardList'](this['userAddress'],a);}async['getSettings'](){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const a=await this['_createSignedRequest']({});return this['serverClient']['getSettings'](this['userAddress'],a);}async['setSettings'](a){if(!this['userAddress'])throw new MessengerError('IDENTITY_NOT_FOUND','User\x20address\x20not\x20set');const b={'allowStrangerMessages':a['allowStrangerMessages'],'maxInboxSize':a['maxInboxSize']},c=await this['_createSignedRequest'](b);return this['serverClient']['updateSettings'](this['userAddress'],c);}async['tryDecryptMessage'](a){try{const b=Uint8Array['from'](Buffer['from'](a['bodyB64'],'base64')),c=await this['decryptionEngine']['decryptMessage'](this['userAddress'],a['from'],b['buffer'],a['msgType']);if(!c['success'])return{'success':![],'shouldRetry':this['isRetryableError'](c['error']||''),'error':c['error'],'sessionUpdated':c['sessionUpdated']};const d=c['plaintext'],e=parseReplyPlaintext(d);if(!a['clientTimestamp'])throw new Error('Missing\x20clientTimestamp\x20for\x20message\x20'+a['id']);if(!a['plaintextHash'])throw new Error('Missing\x20plaintextHash\x20for\x20message\x20'+a['id']);const f=verifyMessage({'messageId':a['id'],'plaintext':d,'plaintextHash':a['plaintextHash'],'createdAt':a['clientTimestamp'],'guardAddress':a['guardAddress'],'passportAddress':a['passportAddress'],'lastReceivedLeafIndex':a['lastReceivedLeafIndex'],'serverSignature':a['merkleMetadata']?.['serverSignature'],'serverPublicKey':a['merkleMetadata']?.['serverPublicKey'],'merkleMetadata':a['merkleMetadata']?{'prevRoot':a['merkleMetadata']['prevRoot'],'newRoot':a['merkleMetadata']['newRoot'],'serverTimestamp':a['merkleMetadata']['serverTimestamp'],'leafIndex':a['merkleMetadata']['leafIndex'],'proofSiblings':a['merkleMetadata']['proofSiblings'],'proofIndices':a['merkleMetadata']['proofIndices']}:void 0x0});if(!f['valid'])throw new Error(f['error']);const g={'messageId':a['id'],'fromAddress':a['from'],'toAddress':this['userAddress'],'plaintextHash':a['plaintextHash'],'plaintext':d,'replyTo':e['replyTo'],'guardAddress':a['guardAddress'],'passportAddress':a['passportAddress'],'lastReceivedLeafIndex':a['lastReceivedLeafIndex'],'direction':'received','status':'decrypted','msgType':a['msgType'],'leafIndex':a['merkleMetadata']?.['leafIndex'],'prevRoot':a['merkleMetadata']?.['prevRoot'],'newRoot':a['merkleMetadata']?.['newRoot'],'serverSignature':a['merkleMetadata']?.['serverSignature'],'serverTimestamp':a['merkleMetadata']?.['serverTimestamp'],'serverPublicKey':a['merkleMetadata']?.['serverPublicKey'],'createdAt':a['clientTimestamp'],'receivedAt':Date['now'](),'zipMetadata':a['zipMetadata']};if(a['merkleMetadata'])this['sessionStateStorage']['updateSessionState'](this['userAddress'],a['from'],{'currentRoot':a['merkleMetadata']['newRoot'],'prevRoot':a['merkleMetadata']['prevRoot'],'lastLeafIndex':a['merkleMetadata']['leafIndex'],'lastSyncAt':Date['now']()});const h=a['merkleMetadata']?.['serverTimestamp']||a['clientTimestamp']||Date['now']();if(a['lastReceivedLeafIndex']!==void 0x0&&a['lastReceivedLeafIndex']>=0x0){const i=this['messageStorage']['getMessagesBySession'](this['userAddress'],a['from'])['filter'](j=>j['direction']==='sent'&&j['status']==='confirmed'&&j['leafIndex']!==void 0x0&&j['leafIndex']<=a['lastReceivedLeafIndex']);for(const j of i)this['messageStorage']['updateMessageStatus'](j['messageId'],'read');}return{'success':!![],'shouldRetry':![],'message':g,'decryptedData':{'id':a['id'],'from':a['from'],'plaintext':d,'timestamp':h,'merkleVerified':!!a['merkleMetadata'],'merkleData':a['merkleMetadata']?{'leafIndex':a['merkleMetadata']['leafIndex'],'rootHash':a['merkleMetadata']['newRoot']}:void 0x0},'sessionUpdated':c['sessionUpdated']};}catch(k){const l=k instanceof Error?k['message']:String(k);return{'success':![],'shouldRetry':this['isRetryableError'](l),'error':l};}}['isRetryableError'](a){return[/message number/i,/chain key/i,/session not found/i,/prekey not found/i,/PREKEY 竞争:我的地址较小,保留我的会话/i,/The operation failed for an operation-specific reason/i,/DOMException/i,/收到 WHISPER_MESSAGE 但无现有会话,需要等待 PREKEY_MESSAGE/i]['some'](b=>b['test'](a));}async['processWaitingMessages'](a,b){if(this['waitingMessages']['size']===0x0)return;const c=[],d=Array['from'](this['waitingMessages']['values']())['sort'](function(e,f){return(e['clientTimestamp']||0x0)-(f['clientTimestamp']||0x0);});for(const e of d){const f=e['id'],g=await this['tryDecryptMessage'](e);if(g['success']&&g['message']&&g['decryptedData'])this['messageStorage']['saveMessage'](g['message']),a['push'](g['decryptedData']),b['push'](f),c['push'](f),this['waitingMessageRetries']['delete'](f);else{if(!g['shouldRetry'])this['failedMessages']['set'](f,{'message':e,'error':g['error']||'Unknown\x20error'}),await this['saveFailedMessage'](e,g['error']||'Unknown\x20error'),b['push'](f),c['push'](f),this['waitingMessageRetries']['delete'](f);else{const h=(this['waitingMessageRetries']['get'](f)||0x0)+0x1;if(h>=0x3)this['failedMessages']['set'](f,{'message':e,'error':g['error']||'Retry\x20limit\x20exceeded'}),await this['saveFailedMessage'](e,g['error']||'Retry\x20limit\x20exceeded'),b['push'](f),c['push'](f),this['waitingMessageRetries']['delete'](f);else this['waitingMessageRetries']['set'](f,h);}}}for(const i of c)this['waitingMessages']['delete'](i);if(c['length']>0x0){}}async['saveFailedMessage'](a,b){const c={'messageId':a['id'],'fromAddress':a['from'],'toAddress':this['userAddress'],'plaintextHash':a['plaintextHash']||'','guardAddress':a['guardAddress'],'passportAddress':a['passportAddress'],'lastReceivedLeafIndex':a['lastReceivedLeafIndex'],'direction':'received','status':'decrypt_failed','msgType':a['msgType'],'leafIndex':a['merkleMetadata']?.['leafIndex'],'prevRoot':a['merkleMetadata']?.['prevRoot'],'newRoot':a['merkleMetadata']?.['newRoot'],'serverSignature':a['merkleMetadata']?.['serverSignature'],'serverTimestamp':a['merkleMetadata']?.['serverTimestamp'],'serverPublicKey':a['merkleMetadata']?.['serverPublicKey'],'createdAt':a['clientTimestamp']||Date['now'](),'receivedAt':Date['now'](),'zipMetadata':a['zipMetadata'],'decryptError':b,'decryptAttempts':0x1,'lastDecryptAttemptAt':Date['now']()};this['messageStorage']['saveMessage'](c);}['reschedulePolling'](){if(!this['isPollingRunning']||!this['pollingTimer'])return;clearTimeout(this['pollingTimer']),this['pollingTimer']=null,this['scheduleNextPoll']();}['getFailedMessages'](){return Array['from'](this['failedMessages']['entries']())['map'](([a,b])=>({'messageId':a,'from':b['message']['from'],'error':b['error'],'leafIndex':b['message']['merkleMetadata']?.['leafIndex']}));}['clearFailedMessages'](a){if(a)this['failedMessages']['delete'](a);else this['failedMessages']['clear']();}['getWaitingMessageCount'](){return this['waitingMessages']['size'];}};export{canonicalizeJson as n,Messenger as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{J as a33a}from'./common-BDlb-AoC.mjs';import{o as a33b}from'./exception-C6IYkBi6.mjs';import{LocalMark}from'./w/local/local.mjs';import{r as a33c}from'./logger-Cs5Mf7Mf.mjs';import{Account}from'./w/local/account.mjs';import{GetAccountOrMark_Address,GetManyAccountOrMark_Address}from'./w/local/index.mjs';import{L as a33d}from'./object-Dma1VY-1.mjs';import{DEFAULT_MESSENGER_CONFIG,MessengerError,WTS_SCHEMA_URL}from'./w/messenger/types.mjs';import{n as a33e,t as a33f}from'./messenger-DEHzSxhH.mjs';import{MessageStorage,MessengerPersistStorage}from'./w/messenger/storage.mjs';import{generateNonce,hashPlaintext,verifyFalcon512Signature,verifySingleMerkleRoot}from'./w/messenger/crypto.mjs';import{parseReplyPlaintext}from'./w/messenger/reply.mjs';import*as a33g from'path';import*as a33h from'fs';import{createHash}from'crypto';const logger$1=a33c('messenger:manager'),MAX_ACCOUNTS=0x64,sleep=a=>new Promise(b=>setTimeout(b,a));var MessengerManager=class{constructor(a){this['accounts']=new Map(),this['messageListeners']=new Set(),this['isWatching']=![],this['accountRefreshTimer']=null,this['pollingLockedAccounts']=new Set(),this['config']={...DEFAULT_MESSENGER_CONFIG,...a?.['messengerConfig']},this['instanceId']=a?.['instanceId']||'default',this['persistStorage']=new MessengerPersistStorage();}['findAccount'](a){return this['accounts']['get'](a['toLowerCase']());}['getConfig'](){return this['config'];}['get_accounts'](){return Array['from'](this['accounts']['values']())['map'](a=>a['address']);}async['refresh_accounts'](){const {Account:a}=await import('./w/local/account.mjs'),b=await a['Instance']()['list_messenger_accounts'](),c=new Set(this['accounts']['keys']()),d=new Set(b['map'](e=>e['address']['toLowerCase']()));for(const e of c)if(!d['has'](e))this['remove_account_internal'](e);for(const f of b){const g=f['address']['toLowerCase']();if(!this['accounts']['has'](g))try{await this['add_account_internal'](f['address']);}catch(h){}}if(this['accounts']['size']>0x0&&!this['isWatching'])this['startPolling']();else{if(this['accounts']['size']===0x0&&this['isWatching'])this['stopPolling']();}await this['syncAllContactLists']();}async['start'](){await this['refresh_accounts']();for(const a of this['accounts']['values']()){if(!a['initialized']||!a['messenger'])continue;this['persistStorage']['tryAcquirePollingLock'](a['address'],this['instanceId'])&&(this['pollingLockedAccounts']['add'](a['address']['toLowerCase']()),a['messenger']['setOnMessageCallback'](b=>{for(const c of this['messageListeners'])c(b);}));}if(!this['isWatching'])this['startPolling']();if(this['accountRefreshTimer'])clearInterval(this['accountRefreshTimer']);this['accountRefreshTimer']=setInterval(()=>{this['refresh_accounts']()['catch'](b=>{});},this['config']['watch_interval_ms']);}['stop'](){this['accountRefreshTimer']&&(clearInterval(this['accountRefreshTimer']),this['accountRefreshTimer']=null);for(const a of this['pollingLockedAccounts'])this['persistStorage']['releasePollingLock'](a,this['instanceId']);this['pollingLockedAccounts']['clear'](),this['stopPolling'](),this['clear_accounts']();}async['ensureAccountReady'](a){const b=a['toLowerCase'](),c=this['accounts']['get'](b);if(c?.['initialized'])return c;if(c?.['initializing']){await c['initializing'];const d=this['accounts']['get'](b);if(d?.['initialized'])return d;throw new MessengerError('SERVER_ERROR','Account\x20'+a+'\x20initialization\x20failed');}return this['initializeAccount'](b);}async['initializeAccount'](a){const b=a['toLowerCase']();if(this['accounts']['size']>=MAX_ACCOUNTS)throw new MessengerError('INVALID_INPUT','Maximum\x20'+MAX_ACCOUNTS+'\x20accounts\x20allowed');const c=this['doInitialize'](b),d={'address':b,'messenger':null,'initialized':![],'initializing':c,'contactLists':{'friends':[],'guards':[],'lastUpdatedAt':0x0}};this['accounts']['set'](b,d);try{await c;const e=this['accounts']['get'](b);if(!e||!e['initialized'])throw new MessengerError('SERVER_ERROR','Account\x20'+a+'\x20initialization\x20failed');return e;}catch(f){this['accounts']['delete'](b);throw f;}}async['doInitialize'](a){const b=new a33f(a,this['config']);try{await b['initialize']();}catch(c){throw new MessengerError('SERVER_ERROR','Failed\x20to\x20initialize\x20account\x20'+a+':\x20'+(c instanceof Error?c['message']:String(c)));}await sleep(0x3e8),this['accounts']['set'](a,{'address':a,'messenger':b,'initialized':!![],'contactLists':{'friends':[],'guards':[],'lastUpdatedAt':0x0}}),this['isWatching']&&(this['persistStorage']['tryAcquirePollingLock'](a,this['instanceId'])&&(this['pollingLockedAccounts']['add'](a),b['setOnMessageCallback'](d=>{for(const e of this['messageListeners'])e(d);})));}async['add_account_internal'](a){await this['ensureAccountReady'](a);}['remove_account_internal'](a){const b=a['toLowerCase'](),c=this['accounts']['get'](b);if(!c)return![];if(c['initialized']&&c['messenger'])c['messenger']['disconnect']();return this['persistStorage']['releasePollingLock'](b,this['instanceId']),this['pollingLockedAccounts']['delete'](b),this['accounts']['delete'](b);}['clear_accounts'](){this['stopPolling']();for(const a of this['accounts']['values']())if(a['messenger'])a['messenger']['disconnect']();this['accounts']['clear']();}async['send'](a,b,c,d){const {Account:e}=await import('./w/local/account.mjs'),f=await e['Instance']()['get'](a,![]);if(!f)throw new MessengerError('IDENTITY_NOT_FOUND','Account\x20'+a+'\x20not\x20found');if(!f['messenger']){if(!d?.['enable_messenger'])throw new MessengerError('ACCOUNT_MESSENGER_NOT_ENABLED','Account\x20messenger\x20not\x20enabled.\x20Use\x20enable_messenger\x20parameter\x20to\x20enable\x20it\x20automatically.');await e['Instance']()['set_messenger'](a,!![]);}const g=await this['ensureAccountReady'](a);try{return await g['messenger']['sendMessage'](b,c,{'guardAddress':d?.['guardAddress'],'passportAddress':d?.['passportAddress'],'force':d?.['force'],'network':d?.['network'],'replyTo':d?.['replyTo']});}catch(h){if(h instanceof MessengerError&&h['code']==='IDENTITY_NOT_FOUND'){const i=h['message']||'',j=a['toLowerCase'](),k=b['toLowerCase'](),l=i['toLowerCase']()['includes'](j);if((i['toLowerCase']()['includes'](k)||i['toLowerCase']()['includes']('recipient')||i['toLowerCase']()['includes']('no\x20signed\x20prekey'))&&!l)throw new MessengerError('IDENTITY_NOT_FOUND','Recipient\x20'+b+'\x20is\x20not\x20registered\x20on\x20the\x20messenger\x20server.\x20Please\x20ask\x20them\x20to\x20enable\x20messenger\x20first.');logger$1['info']('Sender\x20'+a+'\x20not\x20found\x20on\x20server,\x20re-registering...'),await this['reinitializeAccount'](a);const m=this['accounts']['get'](a['toLowerCase']());if(m?.['initialized'])return await m['messenger']['sendMessage'](b,c,{'guardAddress':d?.['guardAddress'],'passportAddress':d?.['passportAddress'],'force':d?.['force'],'network':d?.['network'],'replyTo':d?.['replyTo']});}throw h;}}async['reinitializeAccount'](a){const b=a['toLowerCase'](),c=this['accounts']['get'](b);if(c){if(c['messenger'])c['messenger']['disconnect']();this['accounts']['delete'](b);}await this['initializeAccount'](b);}async['send_file'](a,b,c,d){const {Account:e}=await import('./w/local/account.mjs'),f=await e['Instance']()['get'](a,![]);if(!f)throw new MessengerError('IDENTITY_NOT_FOUND','Account\x20'+a+'\x20not\x20found');if(!f['messenger']){if(!d?.['enable_messenger'])throw new MessengerError('ACCOUNT_MESSENGER_NOT_ENABLED','Account\x20messenger\x20not\x20enabled.\x20Use\x20enable_messenger\x20parameter\x20to\x20enable\x20it\x20automatically.');await e['Instance']()['set_messenger'](a,!![]);}const g=await this['ensureAccountReady'](a);try{return await g['messenger']['sendZipFile'](b,c,{'fileName':d?.['fileName'],'contentType':d?.['contentType'],'guardAddress':d?.['guardAddress'],'passportAddress':d?.['passportAddress'],'force':d?.['force'],'network':d?.['network']});}catch(h){if(h instanceof MessengerError&&h['code']==='IDENTITY_NOT_FOUND'){const i=h['message']||'',j=a['toLowerCase'](),k=b['toLowerCase'](),l=i['toLowerCase']()['includes'](j);if((i['toLowerCase']()['includes'](k)||i['toLowerCase']()['includes']('recipient')||i['toLowerCase']()['includes']('no\x20signed\x20prekey'))&&!l)throw new MessengerError('IDENTITY_NOT_FOUND','Recipient\x20'+b+'\x20is\x20not\x20registered\x20on\x20the\x20messenger\x20server.\x20Please\x20ask\x20them\x20to\x20enable\x20messenger\x20first.');logger$1['info']('Sender\x20'+a+'\x20not\x20found\x20on\x20server,\x20re-registering...'),await this['reinitializeAccount'](a);const m=this['accounts']['get'](a['toLowerCase']());if(m?.['initialized'])return await m['messenger']['sendZipFile'](b,c,{'fileName':d?.['fileName'],'contentType':d?.['contentType'],'guardAddress':d?.['guardAddress'],'passportAddress':d?.['passportAddress'],'force':d?.['force'],'network':d?.['network']});}throw h;}}async['watch'](a){let b=[];if(a?.['account']!==void 0x0){const i=a['account']['toLowerCase'](),j=this['accounts']['get'](i);if(j?.['messenger'])await j['messenger']['pullMessages']();b=new MessageStorage(i)['getAllMessages'](i);}else for(const k of this['accounts']['values']()){if(k['messenger'])await k['messenger']['pullMessages']();const l=new MessageStorage(k['address'])['getAllMessages'](k['address']);b['push'](...l);}if(a){const m=a['peerAddress']?await GetAccountOrMark_Address(a['peerAddress']):void 0x0;b=b['filter'](n=>{if(a?.['account']!==void 0x0){const p=a['account']['toLowerCase'](),q=n['fromAddress']['toLowerCase'](),r=n['toAddress']['toLowerCase']();if(q!==p&&r!==p)return![];}if(a['direction']&&n['direction']!==a['direction'])return![];if(a['status']&&n['status']!==a['status'])return![];if(a['msgType']!==void 0x0&&n['msgType']!==a['msgType'])return![];if(a['contentType'])switch(a['contentType']){case'text':if(n['msgType']!==0x1)return![];break;case'zip':if(!n['zipMetadata'])return![];break;case'wts':if(!n['zipMetadata']||n['zipMetadata']?.['contentType']!=='wts')return![];break;case'wip':if(!n['zipMetadata']||n['zipMetadata']?.['contentType']!=='wip')return![];break;}if(a['peerAddress']&&m){const s=m['toLowerCase'](),t=n['fromAddress']['toLowerCase'](),u=n['toAddress']['toLowerCase']();if(t!==s&&u!==s)return![];}const o=a['timeField']||'createdAt';if(a['startTime']!==void 0x0||a['endTime']!==void 0x0){const v=n[o];if(v!==void 0x0){if(a['startTime']!==void 0x0&&v<a['startTime'])return![];if(a['endTime']!==void 0x0&&v>a['endTime'])return![];}}if(a['createdAtStart']!==void 0x0&&n['createdAt']<a['createdAtStart'])return![];if(a['createdAtEnd']!==void 0x0&&n['createdAt']>a['createdAtEnd'])return![];if(a['receivedAtStart']!==void 0x0){if(n['receivedAt']===void 0x0||n['receivedAt']<a['receivedAtStart'])return![];}if(a['receivedAtEnd']!==void 0x0){if(n['receivedAt']===void 0x0||n['receivedAt']>a['receivedAtEnd'])return![];}if(a['serverTimestampStart']!==void 0x0){if(n['serverTimestamp']===void 0x0||n['serverTimestamp']<a['serverTimestampStart'])return![];}if(a['serverTimestampEnd']!==void 0x0){if(n['serverTimestamp']===void 0x0||n['serverTimestamp']>a['serverTimestampEnd'])return![];}if(a['decryptedOnly']&&!n['plaintext'])return![];if(a['confirmedOnly']&&n['status']!=='confirmed')return![];if(a['arkConfirmedOnly']){if(!n['arkConfirmed'])return![];}if(a['proofedOnly']){if(!n['proof'])return![];}if(a['arkTimestampStart']!==void 0x0){if(n['arkConfirmed']===void 0x0||n['arkConfirmed']['timestamp']<a['arkTimestampStart'])return![];}if(a['arkTimestampEnd']!==void 0x0){if(n['arkConfirmed']===void 0x0||n['arkConfirmed']['timestamp']>a['arkTimestampEnd'])return![];}if(a['hasLastReceivedIndexOnly']){if(n['lastReceivedLeafIndex']===void 0x0||n['lastReceivedLeafIndex']===null)return![];}if(a['lastReceivedIndexMin']!==void 0x0){if(n['lastReceivedLeafIndex']===void 0x0||n['lastReceivedLeafIndex']<a['lastReceivedIndexMin'])return![];}if(a['lastReceivedIndexMax']!==void 0x0){if(n['lastReceivedLeafIndex']===void 0x0||n['lastReceivedLeafIndex']>a['lastReceivedIndexMax'])return![];}if(a['keyword']&&n['plaintext']){if(!n['plaintext']['toLowerCase']()['includes'](a['keyword']['toLowerCase']()))return![];}if(a['listFilterMode']&&a['listFilterMode']!=='any'){const w=this['findAccount'](n['toAddress']);if(!w)return![];const x=n['fromAddress']['toLowerCase'](),y=w['contactLists'],z=new Set(y['friends']['map'](E=>E['toLowerCase']())),A=new Set(y['guards']['map'](E=>E['guardAddress']['toLowerCase']())),B=z['has'](x),C=A['has'](x),D=!B&&!C;switch(a['listFilterMode']){case'friends':if(!B)return![];break;case'guard':if(!C)return![];break;case'stranger':if(!D)return![];break;}if(a['customListFilter']){const {includeAddresses:E,excludeAddresses:F,relation:relation='union'}=a['customListFilter'];if(F){if(new Set(F['map'](G=>G['toLowerCase']()))['has'](x))return![];}if(E&&E['length']>0x0){const G=new Set(E['map'](H=>H['toLowerCase']()))['has'](x);if(relation==='union'){const H=a['listFilterMode']==='friends'&&B||a['listFilterMode']==='guard'&&C||a['listFilterMode']==='stranger'&&D;if(!G&&!H)return![];}else{if(!G)return![];}}}}if(a['viewed']!==void 0x0){const I=n['viewedAt']!==void 0x0;if(a['viewed']!==I)return![];}if(a['viewedAtStart']!==void 0x0){if(n['viewedAt']===void 0x0||n['viewedAt']<a['viewedAtStart'])return![];}if(a['viewedAtEnd']!==void 0x0){if(n['viewedAt']===void 0x0||n['viewedAt']>a['viewedAtEnd'])return![];}return!![];});}const c=a?.['sortOrder']??'desc',d=a?.['timeField']||'createdAt';b['sort']((n,o)=>{const p=n[d]||0x0,q=o[d]||0x0;return c==='asc'?p-q:q-p;});const {MAX_QUERY_LIMIT:e}=await import('./w/messenger/types.mjs'),f=this['config']['defaultQueryLimit']??0x32,g=Math['min'](a?.['limit']??f,e),h=a?.['offset']??0x0;b=b['slice'](h,h+g);if(b['some'](n=>n['plaintext']!==void 0x0)){const {parseReplyPlaintext:n}=await import('./w/messenger/reply.mjs');b=b['map'](o=>{if(o['plaintext']===void 0x0)return o;const p=n(o['plaintext']);if(!p['replyTo'])return o;return{...o,'plaintext':p['content']};});}return b;}['startPolling'](){if(this['isWatching'])return;this['isWatching']=!![];}['stopPolling'](){this['isWatching']=![];}['onMessage'](a){this['messageListeners']['add'](a);}['offMessage'](a){this['messageListeners']['delete'](a);}['destroy'](){this['stop'](),this['messageListeners']['clear']();}async['syncContactLists'](a){const b=this['findAccount'](a);if(!b)return{'success':![],'friends':[],'guards':[],'error':'Account\x20not\x20found:\x20'+a};try{const [c,d]=await Promise['all']([b['messenger']['getFriendsList'](),b['messenger']['getGuardList']()]),e=d['currentGuardList']||[];return b['contactLists']={'friends':c,'guards':e,'lastUpdatedAt':Date['now']()},{'success':!![],'friends':c,'guards':e};}catch(f){return{'success':![],'friends':b['contactLists']['friends'],'guards':b['contactLists']['guards'],'error':f instanceof Error?f['message']:String(f)};}}async['syncAllContactLists'](){const a=new Map();for(const b of this['accounts']['values']()){const c=await this['syncContactLists'](b['address']);a['set'](b['address'],c);}return a;}['getContactLists'](a){return this['findAccount'](a)?.['contactLists'];}['setContactLists'](a,b){const c=this['findAccount'](a);if(!c)return![];return c['contactLists']={...c['contactLists'],...b,'lastUpdatedAt':Date['now']()},!![];}['isStranger'](a,b){const c=this['findAccount'](a);if(!c)return!![];const d=b['toLowerCase'](),e=c['contactLists'],f=e['friends']['some'](h=>h['toLowerCase']()===d),g=e['guards']['some'](h=>h['guardAddress']['toLowerCase']()===d);return!f&&!g;}['recordGuardSender'](a,b){const c=this['findAccount'](a);if(!c)return![];const d=b['toLowerCase']();return!c['contactLists']['guards']['some'](e=>e['guardAddress']['toLowerCase']()===d)&&(c['contactLists']['guards']['push']({'guardAddress':b,'passportValiditySeconds':0x15180}),c['contactLists']['lastUpdatedAt']=Date['now']()),!![];}['generateNonce'](){return generateNonce();}async['watch_paginated'](a){const {MAX_QUERY_LIMIT:b}=await import('./w/messenger/types.mjs'),c=await this['watch'](a),d=c['length'],e=this['config']['defaultQueryLimit']??0x32,f=Math['min'](a?.['limit']??e,b),g=a?.['offset']??0x0;return{'messages':c['slice'](g,g+f),'total':d,'offset':g,'limit':f};}async['get_conversations'](a){const b=a?{'account':a}:void 0x0,c=await this['watch'](b),d=new Map();for(const e of c){const f=a?.['toLowerCase'](),g=e['fromAddress']['toLowerCase']()===f?e['toAddress']:e['fromAddress'];if(!d['has'](g))d['set'](g,{'peerAddress':g,'lastMessageAt':e['createdAt'],'messageCount':0x0,'unreadCount':0x0,'lastMessagePreview':e['plaintext']});const h=d['get'](g);h['messageCount']++;e['createdAt']>h['lastMessageAt']&&(h['lastMessageAt']=e['createdAt'],h['lastMessagePreview']=e['plaintext']);if(e['status']!=='read'&&e['toAddress']['toLowerCase']()===f)h['unreadCount']++;}return Array['from'](d['values']())['sort']((i,j)=>j['lastMessageAt']-i['lastMessageAt']);}async['generate_wts'](a,b,c,d,e){const f=await import('fs'),g=await import('path'),h=b['toLowerCase'](),k=c['toLowerCase']();let l=new MessageStorage(h)['getAllMessages'](h)['filter'](u=>{const v=u['fromAddress']['toLowerCase'](),w=u['toAddress']['toLowerCase']();return v===h&&w===k||v===k&&w===h;});l=l['filter'](u=>u['leafIndex']!==void 0x0&&u['serverTimestamp']!==void 0x0)['reduce']((u,v)=>{if(!u['find'](w=>w['messageId']===v['messageId']))u['push'](v);return u;},[])['sort']((u,v)=>{const w=u['serverTimestamp']-v['serverTimestamp'];if(w!==0x0)return w;return u['leafIndex']-v['leafIndex'];});if(d)switch(d['type']){case'time':{const u=Math['min'](d['start'],d['end']),v=Math['max'](d['start'],d['end']);l=l['filter'](w=>w['createdAt']>=u&&w['createdAt']<=v);break;}case'messageId':{const w=d['start'],x=d['end'];l=l['filter'](y=>y['messageId']>=w&&y['messageId']<=x);break;}case'seqIndex':{const y=Math['min'](d['start'],d['end']),z=Math['max'](d['start'],d['end']);l=l['filter'](A=>A['leafIndex']>=y&&A['leafIndex']<=z);break;}}if(l['length']===0x0)throw new MessengerError('INVALID_INPUT','No\x20messages\x20found\x20for\x20the\x20given\x20criteria');const m=l['map'](A=>A['leafIndex'])['filter'](A=>A!==void 0x0)['sort']((A,B)=>A-B),n=[];for(let A=0x1;A<m['length'];A++){const B=m[A-0x1]+0x1,C=m[A];if(C!==B){for(let D=B;D<C;D++)n['push'](D);}}if(n['length']>0x0){}if(l['length']>0x1f4)throw new MessengerError('INVALID_INPUT','Message\x20count\x20('+l['length']+')\x20exceeds\x20maximum\x20allowed\x20(500)');if(!f['existsSync'](a))f['mkdirSync'](a,{'recursive':!![]});const o=h['slice'](0x0,0x6)+'_'+k['slice'](0x0,0x6),p=[];let q=[];for(let E=0x0;E<l['length'];E++){const F=l[E];if(q['length']===0x0)q['push'](F);else{const G=q[q['length']-0x1]['leafIndex']+0x1;if(q['length']>=0x1f4||F['leafIndex']!==G)p['push'](q),q=[F];else q['push'](F);}}if(q['length']>0x0)p['push'](q);p['forEach']((H,I)=>{H['map'](J=>J['leafIndex'])['join'](',\x20');});const r=[];for(const H of p){const I=H['map'](a0=>a0['leafIndex'])['filter'](a0=>a0!==void 0x0),J=Math['min'](...I),K=Math['max'](...I),L=H[0x0]['createdAt'],M=H[H['length']-0x1]['createdAt'];for(const a0 of H){if(a0['serverTimestamp']===void 0x0)throw new MessengerError('INVALID_INPUT','Message\x20'+a0['messageId']+'\x20missing\x20serverTimestamp');if(a0['leafIndex']===void 0x0)throw new MessengerError('INVALID_INPUT','Message\x20'+a0['messageId']+'\x20missing\x20leafIndex');if(!a0['prevRoot'])throw new MessengerError('INVALID_INPUT','Message\x20'+a0['messageId']+'\x20missing\x20prevRoot');if(!a0['newRoot'])throw new MessengerError('INVALID_INPUT','Message\x20'+a0['messageId']+'\x20missing\x20newRoot');if(!a0['serverSignature'])throw new MessengerError('INVALID_INPUT','Message\x20'+a0['messageId']+'\x20missing\x20serverSignature');}const N=H['map'](a1=>{const a2={'id':a1['messageId'],'from':a1['fromAddress'],'to':a1['toAddress'],'plaintextHash':a1['plaintextHash'],'clientTimestamp':a1['createdAt'],'timestamp':a1['serverTimestamp'],'leafIndex':a1['leafIndex'],'prevRoot':a1['prevRoot'],'merkleRoot':a1['newRoot'],'serverSignature':a1['serverSignature'],'serverPublicKeyIndex':0x0,'msgType':a1['msgType']};if(!e&&a1['plaintext']!==void 0x0)a2['plaintext']=a1['plaintext'];if(a1['guardAddress']!==void 0x0)a2['guardAddress']=a1['guardAddress'];if(a1['passportAddress']!==void 0x0)a2['passportAddress']=a1['passportAddress'];if(a1['arkConfirmed']!==void 0x0)a2['arkConfirmed']={'recipient':a1['arkConfirmed']['recipient'],'recipientPublicKey':a1['arkConfirmed']['recipientPublicKey'],'signature':a1['arkConfirmed']['signature'],'timestamp':a1['arkConfirmed']['timestamp']};if(a1['zipMetadata']!==void 0x0)a2['zipMetadata']=a1['zipMetadata'];if(a1['lastReceivedLeafIndex']!==void 0x0&&a1['lastReceivedLeafIndex']!==-0x1)a2['lastReceivedLeafIndex']=a1['lastReceivedLeafIndex'];return a2;}),O=[h,k]['sort'](),P={'id':o+'_'+J+'-'+K,'participants':O},Q=[],R=new Map();for(const a1 of N){const a2=H['find'](a4=>a4['messageId']===a1['id'])?.['serverPublicKey']||'';if(!a2)continue;let a3=R['get'](a2);a3===void 0x0&&(a3=Q['length'],R['set'](a2,a3),Q['push']({'publicKey':a2,'validFrom':0x0})),a1['serverPublicKeyIndex']=a3;}const S={'session':P,'messages':N},{sha256:T}=await import('@noble/hashes/sha2.js'),{bytesToHex:U}=await import('@noble/hashes/utils.js'),V={'wts':WTS_SCHEMA_URL,...S},W=U(T(new TextEncoder()['encode'](a33e(V)))),X={'wts':WTS_SCHEMA_URL,'payload':S,'meta':{'type':'wts','version':'1.0','created':new Date()['toISOString'](),'hash':W,'algorithm':'sha256','startTime':L,'endTime':M,'messageCount':N['length'],'merkleRoot':N[N['length']-0x1]['merkleRoot'],'creator':h,'participant':k,'serverPublicKeys':Q}},Y=o+'_'+J+'-'+K+'.wts',Z=g['join'](a,Y);f['writeFileSync'](Z,JSON['stringify'](X,null,0x2)),r['push'](Z);}const s=l[0x0]?.['createdAt']||0x0,t=l[l['length']-0x1]?.['createdAt']||0x0;return{'files':r,'totalMessageCount':l['length'],'timeRange':{'start':s,'end':t}};}async['addToBlacklist'](a,b){const c=this['findAccount'](a);if(!c)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return c['messenger']['addToBlacklist'](b);}async['removeFromBlacklist'](a,b){const c=this['findAccount'](a);if(!c)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return c['messenger']['removeFromBlacklist'](b);}async['clearBlacklist'](a){const b=this['findAccount'](a);if(!b)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return b['messenger']['clearBlacklist']();}async['getBlacklist'](a){const b=this['findAccount'](a);if(!b)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return b['messenger']['getBlacklist']();}async['existInBlacklist'](a,b){const c=this['findAccount'](a);if(!c)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return c['messenger']['existInBlacklist'](b);}async['addToFriendsList'](a,b){const c=this['findAccount'](a);if(!c)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return c['messenger']['addToFriendsList'](b);}async['removeFromFriendsList'](a,b){const c=this['findAccount'](a);if(!c)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return c['messenger']['removeFromFriendsList'](b);}async['clearFriendsList'](a){const b=this['findAccount'](a);if(!b)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return b['messenger']['clearFriendsList']();}async['getFriendsList'](a){const b=this['findAccount'](a);if(!b)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return b['messenger']['getFriendsList']();}async['existInFriendsList'](a,b){const c=this['findAccount'](a);if(!c)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return c['messenger']['existInFriendsList'](b);}async['addToGuardList'](a,b){const c=this['findAccount'](a);if(!c)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return c['messenger']['addToGuardList'](b);}async['removeFromGuardList'](a,b){const c=this['findAccount'](a);if(!c)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return c['messenger']['removeFromGuardList'](b);}async['getGuardList'](a){const b=this['findAccount'](a);if(!b)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return b['messenger']['getGuardList']();}async['getSettings'](a){const b=this['findAccount'](a);if(!b)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return b['messenger']['getSettings']();}async['setSettings'](a,b){const c=this['findAccount'](a);if(!c)throw new MessengerError('ACCOUNT_NOT_FOUND','Account\x20'+a+'\x20not\x20in\x20managed\x20accounts');return c['messenger']['setSettings'](b);}};function escapeHtml(a){if(!a)return'';return a['replace'](/&/g,'&')['replace'](/</g,'<')['replace'](/>/g,'>')['replace'](/"/g,'"')['replace'](/'/g,''');}function formatFileSize(a){if(a<0x400)return a+'\x20B';if(a<0x400*0x400)return(a/0x400)['toFixed'](0x1)+'\x20KB';return(a/(0x400*0x400))['toFixed'](0x1)+'\x20MB';}function isNonTextMessage(a){return!!a['zipMetadata'];}function getFileTypeLabel(a){if(a['zipMetadata']?.['contentType'])return a['zipMetadata']['contentType']['toUpperCase']();const b=a['zipMetadata']?.['fileName']||'';if(b['endsWith']('.wts'))return'WTS';if(b['endsWith']('.wip'))return'WIP';if(b['endsWith']('.zip'))return'ZIP';if(b['endsWith']('.json'))return'JSON';if(b['endsWith']('.txt'))return'TXT';if(a['zipMetadata'])return'ZIP';return'FILE';}function getThemeColors(a){return{'bgColor':a==='dark'?'#1a1a1a':'#ffffff','textColor':a==='dark'?'#e0e0e0':'#333333','borderColor':a==='dark'?'#444444':'#e0e0e0'};}function getMessageColors(a,b){if(b)return{'bgColor':a==='dark'?'#1a365d':'#e3f2fd','borderColor':a==='dark'?'#3b82f6':'#90caf9'};else return{'bgColor':a==='dark'?'#1e3a2f':'#e8f5e9','borderColor':a==='dark'?'#10b981':'#a5d6a7'};}function generateFileButton(a,b,c){if(!a['plaintext']||!a['zipMetadata']?.['fileName'])return'';const d=a['zipMetadata']['fileName'],e=a['plaintext'],f=a['zipMetadata']['fileSize']||0x0,g=getFileTypeLabel(a),h=c==='dark'?'#2a3f2a':'#e8f5e9',i=c==='dark'?'#4caf50':'#4caf50',j=c==='dark'?'#81c784':'#2e7d32',k='#4caf50';return'\x0a\x09\x09<div\x20style=\x22margin:\x2012px\x200;\x20padding:\x2016px;\x20background:\x20'+h+';\x20border:\x201px\x20solid\x20'+i+';\x20border-radius:\x208px;\x20text-align:\x20center;\x22>\x0a\x09\x09\x09<div\x20style=\x22font-size:\x2014px;\x20color:\x20'+j+';\x20margin-bottom:\x208px;\x22>\x0a\x09\x09\x09\x09📎\x20'+escapeHtml(g)+'\x20File\x0a\x09\x09\x09\x09<span\x20style=\x22font-size:\x2012px;\x20color:\x20#666;\x22>('+formatFileSize(f)+')</span>\x0a\x09\x09\x09</div>\x0a\x09\x09\x09<button\x20\x0a\x09\x09\x09\x09onclick=\x22saveFile'+b+'()\x22\x0a\x09\x09\x09\x09style=\x22padding:\x2010px\x2024px;\x20background:\x20'+k+';\x20color:\x20white;\x20border:\x20none;\x20border-radius:\x204px;\x20cursor:\x20pointer;\x20font-size:\x2014px;\x22\x0a\x09\x09\x09\x09onmouseover=\x22this.style.background=\x27#45a049\x27\x22\x0a\x09\x09\x09\x09onmouseout=\x22this.style.background=\x27'+k+'\x27\x22\x0a\x09\x09\x09>\x0a\x09\x09\x09\x09💾\x20Save\x20'+escapeHtml(d)+'\x0a\x09\x09\x09</button>\x0a\x09\x09</div>\x0a\x09\x09<script>\x0a\x09\x09\x09function\x20saveFile'+b+'()\x20{\x0a\x09\x09\x09\x09try\x20{\x0a\x09\x09\x09\x09\x09const\x20base64Data\x20=\x20'+JSON['stringify'](e)+';\x0a\x09\x09\x09\x09\x09const\x20byteCharacters\x20=\x20atob(base64Data);\x0a\x09\x09\x09\x09\x09const\x20byteNumbers\x20=\x20new\x20Array(byteCharacters.length);\x0a\x09\x09\x09\x09\x09for\x20(let\x20i\x20=\x200;\x20i\x20<\x20byteCharacters.length;\x20i++)\x20{\x0a\x09\x09\x09\x09\x09\x09byteNumbers[i]\x20=\x20byteCharacters.charCodeAt(i);\x0a\x09\x09\x09\x09\x09}\x0a\x09\x09\x09\x09\x09const\x20byteArray\x20=\x20new\x20Uint8Array(byteNumbers);\x0a\x09\x09\x09\x09\x09\x0a\x09\x09\x09\x09\x09let\x20mimeType\x20=\x20\x22application/octet-stream\x22;\x0a\x09\x09\x09\x09\x09const\x20fileName\x20=\x20'+JSON['stringify'](d)+';\x0a\x09\x09\x09\x09\x09if\x20(fileName.endsWith(\x27.json\x27))\x20mimeType\x20=\x20\x22application/json\x22;\x0a\x09\x09\x09\x09\x09else\x20if\x20(fileName.endsWith(\x27.zip\x27))\x20mimeType\x20=\x20\x22application/zip\x22;\x0a\x09\x09\x09\x09\x09else\x20if\x20(fileName.endsWith(\x27.txt\x27))\x20mimeType\x20=\x20\x22text/plain\x22;\x0a\x09\x09\x09\x09\x09\x0a\x09\x09\x09\x09\x09const\x20blob\x20=\x20new\x20Blob([byteArray],\x20{\x20type:\x20mimeType\x20});\x0a\x09\x09\x09\x09\x09const\x20url\x20=\x20URL.createObjectURL(blob);\x0a\x09\x09\x09\x09\x09const\x20a\x20=\x20document.createElement(\x22a\x22);\x0a\x09\x09\x09\x09\x09a.href\x20=\x20url;\x0a\x09\x09\x09\x09\x09a.download\x20=\x20fileName;\x0a\x09\x09\x09\x09\x09document.body.appendChild(a);\x0a\x09\x09\x09\x09\x09a.click();\x0a\x09\x09\x09\x09\x09document.body.removeChild(a);\x0a\x09\x09\x09\x09\x09URL.revokeObjectURL(url);\x0a\x09\x09\x09\x09}\x20catch\x20(e)\x20{\x0a\x09\x09\x09\x09\x09alert(\x27保存文件失败:\x20\x27\x20+\x20e.message);\x0a\x09\x09\x09\x09}\x0a\x09\x09\x09}\x0a\x09\x09</script>\x0a\x09';}function generateReplyQuoteHtml(a,b){if(!a['plaintext'])return'';const c=parseReplyPlaintext(a['plaintext'])['replyTo'];if(!c)return'';const {theme:d}=b,e=b['payload']['messages']['find'](j=>j['id']===c['messageId']),f=d==='dark'?'#2b2b2b':'#f5f5f5';if(!e)return'\x0a\x09\x09\x09<div\x20style=\x22margin:\x208px\x200;\x20padding:\x208px\x2010px;\x20background:\x20'+f+';\x20border-left:\x203px\x20solid\x20'+(d==='dark'?'#b45309':'#f59e0b')+';\x20border-radius:\x204px;\x22>\x0a\x09\x09\x09\x09<div\x20style=\x22font-size:\x2011px;\x20color:\x20'+(d==='dark'?'#fbbf24':'#b45309')+';\x20word-break:\x20break-all;\x22>\x0a\x09\x09\x09\x09\x09⚠\x20Replied\x20message\x20not\x20found\x20—\x20message\x20ID:\x20'+escapeHtml(c['messageId'])+'\x0a\x09\x09\x09\x09</div>\x0a\x09\x09\x09</div>\x0a\x09\x09';let g='';if(e['zipMetadata']?.['fileName'])g='[File]\x20'+e['zipMetadata']['fileName'];else{if(e['plaintext'])g=parseReplyPlaintext(e['plaintext'])['content'];}const h=e['from']['slice'](0x0,0x6)+'...'+e['from']['slice'](-0x3),i=(g||'Original\x20message')['replace'](/\s+/g,'\x20')['trim']()['slice'](0x0,0x78);return'\x0a\x09\x09<div\x20style=\x22margin:\x208px\x200;\x20padding:\x208px\x2010px;\x20background:\x20'+f+';\x20border-left:\x203px\x20solid\x20'+(d==='dark'?'#5a5a5a':'#c9c9c9')+';\x20border-radius:\x204px;\x22>\x0a\x09\x09\x09<div\x20style=\x22font-size:\x2011px;\x20color:\x20#888;\x20margin-bottom:\x202px;\x22>↩\x20Replied\x20to\x20'+escapeHtml(h)+'</div>\x0a\x09\x09\x09<div\x20style=\x22font-size:\x2013px;\x20color:\x20'+(d==='dark'?'#bbbbbb':'#555555')+';\x20word-break:\x20break-word;\x22>'+escapeHtml(i)+'</div>\x0a\x09\x09</div>\x0a\x09';}function generateMessageHtml(a,b,c){const {theme:d,borderColor:e,myAddress:f,maxLastReceivedLeafIndex:g}=c,h=isNonTextMessage(a),i=a['from']['toLowerCase']()===f['toLowerCase'](),j=i&&g>=0x0&&a['leafIndex']<=g,k=getMessageColors(d,i),l=d==='dark'?'#333333':'#ffffff';let m='';if(h)m=generateFileButton(a,b,d);else{if(a['plaintext']){const o=parseReplyPlaintext(a['plaintext']);m=generateReplyQuoteHtml(a,c)+('<div\x20style=\x22margin:\x2012px\x200;\x20padding:\x2012px;\x20background:\x20'+l+';\x20border:\x201px\x20solid\x20'+e+';\x20border-radius:\x204px;\x20font-size:\x2014px;\x20line-height:\x201.6;\x20max-height:\x20calc(1.6em\x20*\x206);\x20overflow-y:\x20auto;\x20white-space:\x20pre-wrap;\x20word-break:\x20break-word;\x22>'+escapeHtml(o['content'])+'</div>');}else m='<div\x20style=\x22margin:\x2012px\x200;\x20padding:\x2012px;\x20background:\x20'+l+';\x20border:\x201px\x20solid\x20'+e+';\x20border-radius:\x204px;\x20font-size:\x2013px;\x20color:\x20#999;\x22>Plaintext\x20unavailable\x20locally\x20—\x20content\x20hash\x20verification\x20will\x20fail\x20for\x20this\x20message.</div>';}const n=['<div>Merkle\x20Root:\x20'+escapeHtml(a['merkleRoot'])+'</div>',a['arkConfirmed']?'<div>ARK\x20Confirmed:\x20'+escapeHtml(a['arkConfirmed']['recipient'])+'\x20at\x20'+new Date(a['arkConfirmed']['timestamp'])['toLocaleString']()+'</div>':'',a['guardAddress']?'<div>Guard:\x20'+escapeHtml(a['guardAddress'])+'</div>':'',a['passportAddress']?'<div>Passport:\x20'+escapeHtml(a['passportAddress'])+'</div>':'']['filter'](Boolean)['join']('');return'\x0a\x09\x09<div\x20style=\x22margin:\x2016px\x200;\x20padding:\x2016px;\x20border:\x201px\x20solid\x20'+k['borderColor']+';\x20border-radius:\x208px;\x20background:\x20'+k['bgColor']+';\x22>\x0a\x09\x09\x09<div\x20style=\x22display:\x20flex;\x20justify-content:\x20space-between;\x20margin-bottom:\x208px;\x20font-size:\x2012px;\x20color:\x20#666;\x22>\x0a\x09\x09\x09\x09<span>From:\x20'+escapeHtml(a['from']['slice'](0x0,0x6))+'...'+escapeHtml(a['from']['slice'](-0x3))+'\x20To:\x20'+escapeHtml(a['to']['slice'](0x0,0x6))+'...'+escapeHtml(a['to']['slice'](-0x3))+'</span>\x0a\x09\x09\x09\x09<span>'+new Date(a['timestamp'])['toLocaleString']()+'</span>\x0a\x09\x09\x09</div>\x0a\x09\x09\x09'+m+'\x0a\x09\x09\x09<div\x20style=\x22margin:\x208px\x200;\x20font-size:\x2011px;\x20color:\x20#666;\x22>\x0a\x09\x09\x09\x09'+n+'\x0a\x09\x09\x09</div>\x0a\x09\x09\x09<div\x20style=\x22font-size:\x2011px;\x20color:\x20#888;\x20margin-top:\x208px;\x20padding-top:\x208px;\x20border-top:\x201px\x20solid\x20'+e+';\x20display:\x20flex;\x20justify-content:\x20space-between;\x20align-items:\x20center;\x22>\x0a\x09\x09\x09\x09<div>Leaf\x20Index:\x20'+a['leafIndex']+'</div>\x0a\x09\x09\x09\x09'+(j?'<span\x20style=\x22color:\x20#4caf50;\x22>Delivered\x20&\x20Decrypted</span>':'')+'\x0a\x09\x09\x09</div>\x0a\x09\x09</div>\x0a\x09';}function generateSignatureHtml(a,b,c){if(!a['signatures']||a['signatures']['length']===0x0)return'';const d=a['valid'],e=d?b==='dark'?'#2a3f2a':'#e8f5e9':b==='dark'?'#3a2a2a':'#fff3e0',f=d?b==='dark'?'#81c784':'#2e7d32':b==='dark'?'#ffab40':'#e65100',g=a['signatures']['map']((h,i)=>'\x0a\x09\x09\x09<div\x20style=\x22font-size:\x2010px;\x20color:\x20'+c+';\x20margin-left:\x208px;\x22>\x0a\x09\x09\x09\x09'+(i+0x1)+'.\x20'+(h['address']?escapeHtml(h['address']['slice'](0x0,0x6))+'...'+escapeHtml(h['address']['slice'](-0x3)):'Unknown')+':\x0a\x09\x09\x09\x09'+(h['valid']?'<span\x20style=\x22color:\x20#4caf50;\x22>✓\x20Valid</span>':'<span\x20style=\x22color:\x20#f44336;\x22>✗\x20Invalid</span>')+'\x0a\x09\x09\x09</div>\x0a\x09\x09')['join']('');return'\x0a\x09\x09<div\x20style=\x22margin-top:\x208px;\x20padding:\x208px;\x20background:\x20'+e+';\x20border-radius:\x204px;\x22>\x0a\x09\x09\x09<div\x20style=\x22font-size:\x2011px;\x20color:\x20'+f+';\x20margin-bottom:\x204px;\x22>\x0a\x09\x09\x09\x09'+(d?'✓':'⚠')+'\x20Signature\x20Verification\x20('+a['signatures']['length']+'\x20signature'+(a['signatures']['length']>0x1?'s':'')+')'+(d?'':'\x20(signature\x20valid\x20but\x20content\x20hash\x20verification\x20failed)')+'\x0a\x09\x09\x09</div>\x0a\x09\x09\x09'+g+'\x0a\x09\x09</div>\x0a\x09';}const MESSAGES_PER_PAGE=0x64;function generateHtmlPage(a){const {title:b,theme:c,bgColor:d,textColor:e,borderColor:f,meta:g,payload:h,verifyResult:i,maxLastReceivedLeafIndex:j}=a,k=h['messages']['length'],l=Math['ceil'](k/MESSAGES_PER_PAGE),m=[];for(let s=0x0;s<l;s++){const t=s*MESSAGES_PER_PAGE,u=Math['min'](t+MESSAGES_PER_PAGE,k),v=h['messages']['slice'](t,u)['map']((w,x)=>generateMessageHtml(w,t+x,a))['join']('');m['push']({'pageNum':s+0x1,'html':'<div\x20class=\x22page\x22\x20data-page=\x22'+(s+0x1)+'\x22\x20style=\x22display:\x20'+(s===0x0?'block':'none')+';\x22>'+v+'</div>'});}const n=l>0x1?generatePaginationHtml(l,c,e):'',o=m['map'](w=>w['html'])['join'](''),p=generateSignatureHtml(i,c,e),q=i['valid']?'<span\x20style=\x22color:\x20#4caf50;\x20margin-left:\x208px;\x22>✓\x20The\x20accuracy,\x20sequentiality,\x20and\x20integrity\x20of\x20the\x20messages\x20are\x20verified\x20without\x20tampering</span>':'<span\x20style=\x22color:\x20#ff9800;\x20margin-left:\x208px;\x22>⚠\x20'+(i['error']||'Hash\x20mismatch\x20-\x20content\x20has\x20been\x20tampered')+'</span>',r=j>=0x0?'<div>Delivered\x20&\x20Decrypted\x20Leaf\x20Index:\x20'+j+'\x20(sent\x20messages\x20are\x20only\x20confirmed\x20as\x20decrypted\x20after\x20receiving\x20a\x20reply\x20from\x20the\x20other\x20party)</div>':'';return'<!DOCTYPE\x20html>\x0a<html\x20lang=\x22en\x22>\x0a<head>\x0a\x20\x20\x20\x20<meta\x20charset=\x22UTF-8\x22>\x0a\x20\x20\x20\x20<meta\x20name=\x22viewport\x22\x20content=\x22width=device-width,\x20initial-scale=1.0\x22>\x0a\x20\x20\x20\x20<title>'+escapeHtml(b)+'</title>\x0a\x20\x20\x20\x20<style>\x0a\x20\x20\x20\x20\x20\x20\x20\x20body\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20font-family:\x20-apple-system,\x20BlinkMacSystemFont,\x20\x22Segoe\x20UI\x22,\x20Roboto,\x20sans-serif;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20max-width:\x20800px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20margin:\x200\x20auto;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20padding:\x2020px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20background:\x20'+d+';\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20color:\x20'+e+';\x0a\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20.header\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20border-bottom:\x202px\x20solid\x20'+f+';\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20padding-bottom:\x2016px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20margin-bottom:\x2024px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20.meta\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20font-size:\x2012px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20color:\x20#666;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20margin-top:\x208px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20.note\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20font-size:\x2011px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20color:\x20#999;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20margin-top:\x2012px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20padding:\x208px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20background:\x20'+(c==='dark'?'#2a2a2a':'#f5f5f5')+';\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20border-radius:\x204px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20font-style:\x20italic;\x0a\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20.pagination\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20display:\x20flex;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20justify-content:\x20center;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20align-items:\x20center;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20gap:\x208px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20margin-top:\x2024px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20padding:\x2016px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20border-top:\x201px\x20solid\x20'+f+';\x0a\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20.pagination\x20button\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20padding:\x208px\x2016px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20border:\x201px\x20solid\x20'+f+';\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20background:\x20'+(c==='dark'?'#333':'#fff')+';\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20color:\x20'+e+';\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20cursor:\x20pointer;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20border-radius:\x204px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20font-size:\x2014px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20.pagination\x20button:hover:not(:disabled)\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20background:\x20'+(c==='dark'?'#444':'#f0f0f0')+';\x0a\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20.pagination\x20button:disabled\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20opacity:\x200.5;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20cursor:\x20not-allowed;\x0a\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20.pagination\x20.page-info\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20font-size:\x2014px;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20color:\x20#666;\x0a\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20.page\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20animation:\x20fadeIn\x200.3s\x20ease-in;\x0a\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20@keyframes\x20fadeIn\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20from\x20{\x20opacity:\x200;\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20to\x20{\x20opacity:\x201;\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x20\x20\x20\x20</style>\x0a</head>\x0a<body>\x0a\x20\x20\x20\x20<div\x20class=\x22header\x22>\x0a\x20\x20\x20\x20\x20\x20\x20\x20<h1>Witness\x20Timestamped\x20Sequence</h1>\x0a\x20\x20\x20\x20\x20\x20\x20\x20<div\x20class=\x22note\x22>\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20Important\x20Note:\x20This\x20page\x20is\x20for\x20message\x20browsing\x20and\x20verification\x20reference\x20only.\x20Please\x20verify\x20whether\x20the\x20message\x20sequence\x20has\x20been\x20tampered\x20with\x20through\x20the\x20\x27verify_wts\x27\x20API\x20using\x20the\x20WTS\x20file.\x0a\x20\x20\x20\x20\x20\x20\x20\x20</div>\x0a\x20\x20\x20\x20\x20\x20\x20\x20<div\x20style=\x22font-size:\x2014px;\x20color:\x20#666;\x20margin-top:\x204px;\x22>\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'+new Date(g['startTime'])['toLocaleDateString']()+'\x20-\x20'+new Date(g['endTime'])['toLocaleDateString']()+'\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'+q+'\x0a\x20\x20\x20\x20\x20\x20\x20\x20</div>\x0a\x20\x20\x20\x20\x20\x20\x20\x20<div\x20class=\x22meta\x22>\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<div>Messages:\x20'+g['messageCount']+'\x20|\x20Time:\x20'+new Date(g['startTime'])['toLocaleString']()+'\x20-\x20'+new Date(g['endTime'])['toLocaleString']()+'</div>\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<div\x20style=\x22word-break:\x20break-all;\x22>Merkle\x20Root:\x20'+escapeHtml(g['merkleRoot'])+'</div>\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'+r+'\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<div\x20style=\x22color:\x20'+(c==='dark'?'#3b82f6':'#1976d2')+';\x22>Creator:\x20'+escapeHtml(g['creator'])+'</div>\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<div\x20style=\x22color:\x20'+(c==='dark'?'#10b981':'#2e7d32')+';\x22>Participant:\x20'+escapeHtml(g['participant'])+'</div>\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'+p+'\x0a\x20\x20\x20\x20\x20\x20\x20\x20</div>\x0a\x20\x20\x20\x20</div>\x0a\x20\x20\x20\x20<div\x20id=\x22messages-container\x22>\x0a\x20\x20\x20\x20\x20\x20\x20\x20'+o+'\x0a\x20\x20\x20\x20</div>\x0a\x20\x20\x20\x20'+n+'\x0a\x20\x20\x20\x20<script>\x0a\x20\x20\x20\x20\x20\x20\x20\x20(function()\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20let\x20currentPage\x20=\x201;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20const\x20totalPages\x20=\x20'+l+';\x0a\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20function\x20showPage(pageNum)\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20//\x20隐藏所有页面\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20document.querySelectorAll(\x27.page\x27).forEach(page\x20=>\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20page.style.display\x20=\x20\x27none\x27;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20});\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20//\x20显示目标页面\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20const\x20targetPage\x20=\x20document.querySelector(\x27.page[data-page=\x22\x27\x20+\x20pageNum\x20+\x20\x27\x22]\x27);\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20if\x20(targetPage)\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20targetPage.style.display\x20=\x20\x27block\x27;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20currentPage\x20=\x20pageNum;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20updatePaginationButtons();\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20function\x20updatePaginationButtons()\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20const\x20prevBtn\x20=\x20document.getElementById(\x27prev-btn\x27);\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20const\x20nextBtn\x20=\x20document.getElementById(\x27next-btn\x27);\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20const\x20pageInfo\x20=\x20document.getElementById(\x27page-info\x27);\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20if\x20(prevBtn)\x20prevBtn.disabled\x20=\x20currentPage\x20===\x201;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20if\x20(nextBtn)\x20nextBtn.disabled\x20=\x20currentPage\x20===\x20totalPages;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20if\x20(pageInfo)\x20pageInfo.textContent\x20=\x20\x27Page\x20\x27\x20+\x20currentPage\x20+\x20\x27\x20of\x20\x27\x20+\x20totalPages;\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20//\x20绑定按钮事件\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20const\x20prevBtn\x20=\x20document.getElementById(\x27prev-btn\x27);\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20const\x20nextBtn\x20=\x20document.getElementById(\x27next-btn\x27);\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20if\x20(prevBtn)\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20prevBtn.addEventListener(\x27click\x27,\x20function()\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20if\x20(currentPage\x20>\x201)\x20showPage(currentPage\x20-\x201);\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20});\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20if\x20(nextBtn)\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20nextBtn.addEventListener(\x27click\x27,\x20function()\x20{\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20if\x20(currentPage\x20<\x20totalPages)\x20showPage(currentPage\x20+\x201);\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20});\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20}\x0a\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20//\x20初始化\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20updatePaginationButtons();\x0a\x20\x20\x20\x20\x20\x20\x20\x20})();\x0a\x20\x20\x20\x20</script>\x0a</body>\x0a</html>';}function generatePaginationHtml(a,b,c){return'\x0a\x20\x20\x20\x20<div\x20class=\x22pagination\x22>\x0a\x20\x20\x20\x20\x20\x20\x20\x20<button\x20id=\x22prev-btn\x22\x20disabled>←\x20Previous</button>\x0a\x20\x20\x20\x20\x20\x20\x20\x20<span\x20class=\x22page-info\x22\x20id=\x22page-info\x22>Page\x201\x20of\x20'+a+'</span>\x0a\x20\x20\x20\x20\x20\x20\x20\x20<button\x20id=\x22next-btn\x22\x20'+(a<=0x1?'disabled':'')+'>Next\x20→</button>\x0a\x20\x20\x20\x20</div>';}const logger=a33c('messenger:api');let managerInstance=null,isInitialized=![],backgroundTimer=null;async function autoRegisterMessengerAccounts(){const a=await Account['Instance']()['list_messenger_accounts']();for(const b of a){if(!b['address']||!b['messenger'])continue;try{await new a33f(b['address'])['initialize']();}catch(c){logger['error']('Failed\x20to\x20initialize\x20account\x20'+b['address']+':',c);}}}function getMessengerManager(){if(!managerInstance)managerInstance=new MessengerManager();return!isInitialized&&(isInitialized=!![],autoRegisterMessengerAccounts()['then'](()=>{return managerInstance['start']();})['catch'](a=>{return logger['error']('Failed\x20to\x20auto-register\x20messenger\x20accounts:',a),managerInstance['start']();})['catch'](a=>{logger['error']('Failed\x20to\x20auto-start\x20messenger\x20manager:',a);})),managerInstance;}function registerCleanupHandler(){const a=()=>{backgroundTimer&&(clearInterval(backgroundTimer),backgroundTimer=null);if(managerInstance)managerInstance['stop']();};process['on']('exit',a),process['on']('SIGINT',()=>{a();}),process['on']('SIGTERM',()=>{a();});}registerCleanupHandler();async function watch_conversations(a){const b=await Account['Instance']()['get_address'](a?.['account']);if(!b)a33b('account\x20not\x20found','watch_conversations.account\x20'+a?.['account']);const c=b['toLowerCase']();await(await getMessengerManager()['ensureAccountReady'](b))['messenger']['pullMessages']();const d=new MessageStorage(c),e=d['getAllMessages'](c),f=new Map(),g=a?.['previewMessageCount']??0x2,h=a?.['skipAutoMarkViewed']??![],i=m=>{if(!m['plaintext'])return m['plaintext'];return parseReplyPlaintext(m['plaintext'])['content'];};for(const m of e){const n=m['fromAddress']['toLowerCase']()===c?m['toAddress']:m['fromAddress'];if(!f['has'](n))f['set'](n,{'peerAddress':n,'lastMessageAt':m['createdAt'],'messageCount':0x0,'unreadCount':0x0,'lastMessagePreview':i(m),'messages':[]});const o=f['get'](n);o['messages']['push'](m),o['messageCount']++;m['createdAt']>o['lastMessageAt']&&(o['lastMessageAt']=m['createdAt'],o['lastMessagePreview']=i(m));if(m['direction']==='received'&&m['viewedAt']===void 0x0)o['unreadCount']++;}const j=[];for(const [,p]of f){if(a?.['startTime']!==void 0x0&&p['lastMessageAt']<a['startTime'])continue;if(a?.['endTime']!==void 0x0&&p['lastMessageAt']>a['endTime'])continue;if(a?.['unreadOnly']&&p['unreadCount']===0x0)continue;const q=[];if(g>0x0){const r=p['messages']['sort']((s,t)=>t['createdAt']-s['createdAt'])['slice'](0x0,g);q['push'](...r['reverse']());if(!h){const s=r['filter'](t=>t['direction']==='received'&&t['viewedAt']===void 0x0)['map'](t=>t['messageId']);if(s['length']>0x0)d['updateMessagesViewed'](s);}}j['push']({'peerAddress':p['peerAddress'],'lastMessageAt':p['lastMessageAt'],'messageCount':p['messageCount'],'unreadCount':p['unreadCount'],'lastMessagePreview':p['lastMessagePreview'],...g>0x0&&{'previewMessages':q}});}const k=a?.['sortBy']??'lastMessageAt',l=a?.['sortOrder']??'desc';return j['sort']((t,u)=>{let v=0x0;switch(k){case'lastMessageAt':v=t['lastMessageAt']-u['lastMessageAt'];break;case'unreadCount':v=t['unreadCount']-u['unreadCount'];break;case'messageCount':v=t['messageCount']-u['messageCount'];break;}return l==='asc'?v:-v;}),j;}async function mark_messages_as_viewed(a,b){if(!a||a['length']===0x0)return 0x0;const c=await Account['Instance']()['get_address'](b);if(!c)a33b('account\x20not\x20found','mark_messages_as_viewed.account\x20'+b);return new MessageStorage(c['toLowerCase']())['updateMessagesViewed'](a);}async function mark_conversation_as_viewed(a,b){const c=await Account['Instance']()['get_address'](b);if(!c)a33b('account\x20not\x20found','mark_conversation_as_viewed.account\x20'+b);const d=c['toLowerCase'](),e=await GetAccountOrMark_Address(a);if(!e)a33b('account\x20not\x20found','mark_conversation_as_viewed.peerAddress\x20'+a+'\x20is\x20not\x20a\x20valid\x20account/address');const f=e['toLowerCase'](),g=new MessageStorage(d),h=g['getMessagesBySession'](d,f)['filter'](i=>i['direction']==='received'&&i['viewedAt']===void 0x0)['map'](i=>i['messageId']);if(h['length']===0x0)return 0x0;return g['updateMessagesViewed'](h);}async function send_message(a,b,c,d){const e=await Account['Instance']()['get_address'](a);if(!e)a33b('account\x20not\x20found','send_message.from\x20'+a);const f=await GetAccountOrMark_Address(b);if(!f)a33b('account\x20not\x20found','send_message.to\x20'+b+'\x20is\x20not\x20a\x20valid\x20account/address');if(d?.['guardAddress']!=null&&d?.['passportAddress']!=null){[d['guardAddress'],d['passportAddress']]=await LocalMark['Instance']()['get_many_address']([d['guardAddress'],d['passportAddress']]);if(!d['guardAddress']||!d['passportAddress'])a33b('account\x20not\x20found','send_message.guardAddress\x20or\x20passportAddress\x20not\x20found');}return getMessengerManager()['send'](e,f,c,d);}async function send_file(a,b,c,d){const e=await Account['Instance']()['get_address'](a);if(!e)a33b('account\x20not\x20found','send_file.from\x20'+a);const f=await GetAccountOrMark_Address(b);if(!f)a33b('account\x20not\x20found','send_file.to\x20'+b+'\x20is\x20not\x20a\x20valid\x20account/address');if(d?.['guardAddress']!=null&&d?.['passportAddress']!=null){[d['guardAddress'],d['passportAddress']]=await LocalMark['Instance']()['get_many_address']([d['guardAddress'],d['passportAddress']]);if(!d['guardAddress']||!d['passportAddress'])a33b('account\x20not\x20found','send_file.guardAddress\x20or\x20passportAddress\x20not\x20found');}return getMessengerManager()['send_file'](e,f,c,d);}async function watch_messages(a){if(a?.['account']!==void 0x0){a['account']=await Account['Instance']()['get_address'](a['account']);if(!a['account'])a33b('account\x20not\x20found','watch_messages.account\x20'+a['account']);}if(a?.['customListFilter']?.['includeAddresses']!=null)a['customListFilter']['includeAddresses']=(await Account['Instance']()['get_many_address'](a['customListFilter']['includeAddresses']))['filter'](c=>c!=null);if(a?.['customListFilter']?.['excludeAddresses']!=null)a['customListFilter']['excludeAddresses']=(await Account['Instance']()['get_many_address'](a['customListFilter']['excludeAddresses']))['filter'](c=>c!=null);const b=await getMessengerManager()['watch'](a);if(!(a?.['skipAutoMarkViewed']??![])&&b['length']>0x0&&a?.['account']){const c=new MessageStorage(a['account']['toLowerCase']()),d=b['filter'](e=>e['direction']==='received'&&e['viewedAt']===void 0x0)['map'](e=>e['messageId']);if(d['length']>0x0)c['updateMessagesViewed'](d);}return b;}async function pull_messages(a,b){const c=await Account['Instance']()['get_address'](a);if(!c)a33b('account\x20not\x20found','pull_messages.account\x20'+a);return(await(await getMessengerManager()['ensureAccountReady'](c))['messenger']['pullMessages'](b))['messages']['map'](d=>d);}async function extract_zip_message(a,b){if(!a['zipMetadata'])throw new MessengerError('INVALID_MESSAGE_TYPE','Message\x20is\x20not\x20a\x20ZIP\x20archive');if(!a['plaintext'])throw new MessengerError('MESSAGE_NOT_DECRYPTED','Message\x20plaintext\x20not\x20available');const c=Buffer['from'](a['plaintext'],'base64');if(a['zipMetadata']?.['fileHash']){const f=createHash('sha256')['update'](c)['digest']('hex'),g=a['zipMetadata']['fileHash']['replace']('0x','');if(f!==g)throw new MessengerError('HASH_MISMATCH','ZIP\x20file\x20hash\x20mismatch:\x20expected\x20'+g+',\x20got\x20'+f);}const d=await extractZipFromPlaintext(a['plaintext']);if(!a33h['existsSync'](b))a33h['mkdirSync'](b,{'recursive':!![]});const e=[];for(const h of d){const i=a33g['join'](b,h['filename']);a33h['writeFileSync'](i,h['content']),e['push'](i);}return e['length']>0x0&&a['zipMetadata']&&(a['zipMetadata']={'fileName':a['zipMetadata']['fileName'],'fileSize':a['zipMetadata']['fileSize'],'fileHash':a['zipMetadata']['fileHash'],'contentType':a['zipMetadata']['contentType'],'localCachePath':e[0x0],'downloadedAt':Date['now']()},new MessageStorage(a['direction']==='sent'?a['fromAddress']:a['toAddress'])['saveMessage'](a)),e[0x0]||'';}async function extractZipFromPlaintext(a){if(!a)throw new MessengerError('INVALID_INPUT','plaintext\x20is\x20empty');const b=Buffer['from'](a,'base64');if(b['length']<0x4||b[0x0]!==0x50||b[0x1]!==0x4b)throw new MessengerError('INVALID_INPUT','Invalid\x20ZIP\x20data:\x20magic\x20bytes\x20mismatch\x20(expected\x20PK,\x20got\x20'+b['slice'](0x0,0x2)['toString']('hex')+')');const {ZipReader:c,BlobReader:d,BlobWriter:e}=await import('@zip.js/zip.js'),f=new c(new d(new Blob([b]))),g=await f['getEntries']();if(g['length']===0x0){await f['close']();throw new MessengerError('INVALID_INPUT','ZIP\x20archive\x20contains\x20no\x20files');}const h=[];for(const i of g)if(!i['directory']){const j=i,k=new e(),l=await j['getData'](k),m=Buffer['from'](await l['arrayBuffer']());h['push']({'filename':i['filename'],'content':m});}return await f['close'](),h;}async function extract_zip_messages(a,b,c){const d=[],f=await Account['Instance']()['get_address'](a);if(!f)throw new MessengerError('INVALID_INPUT','account\x20is\x20required\x20when\x20extracting\x20by\x20message\x20IDs');for(const g of b)try{let h;if(typeof g==='string'){const j=g,k=new MessageStorage(f)['getMessageById'](j);if(!k){logger['error']('Message\x20not\x20found:\x20'+j);continue;}h=k;}else h=g;if(!h['zipMetadata']){logger['error']('Message\x20'+h['messageId']+'\x20is\x20not\x20a\x20ZIP\x20archive');continue;}const i=await extract_zip_message(h,c);d['push'](i);}catch(l){const m=typeof g==='string'?g:g['messageId'];logger['error']('Failed\x20to\x20extract\x20message\x20'+m+':',l);}return d;}async function generate_wts(a){const b=await Account['Instance']()['get_address'](a['myAccount']);if(!b)a33b('account\x20not\x20found','generate_wts.myAccount\x20'+a['myAccount']);const c=await GetAccountOrMark_Address(a['peerAccount']);if(!c)a33b('account\x20not\x20found','generate_wts.peerAccount\x20'+a['peerAccount']);return getMessengerManager()['generate_wts'](a['outputDir'],b,c,a['range'],a['excludePlaintext']);}function load_wts(a){const b=a33h['readFileSync'](a,'utf-8');return JSON['parse'](b);}function save_wts(a,b){const c=a33g['dirname'](b);if(!a33h['existsSync'](c))a33h['mkdirSync'](c,{'recursive':!![]});a33h['writeFileSync'](b,JSON['stringify'](a,null,0x2),'utf-8');}function resolveServerPublicKey(a,b){if(b['serverPublicKeys']&&a['serverPublicKeyIndex']!==void 0x0&&a['serverPublicKeyIndex']>=0x0&&a['serverPublicKeyIndex']<b['serverPublicKeys']['length'])return b['serverPublicKeys'][a['serverPublicKeyIndex']]['publicKey'];const c=a;if(c['serverPublicKey'])return c['serverPublicKey'];return null;}async function verify_wts(a){try{const b=load_wts(a);if(!b['payload']||!b['meta'])return{'valid':![],'error':'Invalid\x20WTS\x20file\x20structure','hashValid':![],'hasSignature':![]};if(b['meta']['type']!=='wts')return{'valid':![],'error':'Invalid\x20meta.type:\x20'+b['meta']['type'],'hashValid':![],'hasSignature':!!b['meta']['signature']};const {payload:c,meta:d}=b,e=[...c['messages']]['sort']((m,n)=>{if(m['leafIndex']===void 0x0||n['leafIndex']===void 0x0)return 0x0;return m['leafIndex']-n['leafIndex'];});for(let m=0x0;m<e['length'];m++){const n=e[m];if(!n)return{'valid':![],'error':'Message\x20'+m+':\x20Message\x20is\x20null\x20or\x20undefined','hashValid':![],'hasSignature':!!d['signature']};if(!n['prevRoot'])return{'valid':![],'error':'Message\x20'+m+':\x20Missing\x20prevRoot','hashValid':![],'hasSignature':!!d['signature']};if(!n['merkleRoot'])return{'valid':![],'error':'Message\x20'+m+':\x20Missing\x20merkleRoot','hashValid':![],'hasSignature':!!d['signature']};if(!n['plaintextHash'])return{'valid':![],'error':'Message\x20'+m+':\x20Missing\x20plaintextHash','hashValid':![],'hasSignature':!!d['signature']};if(n['timestamp']===void 0x0||n['timestamp']===null)return{'valid':![],'error':'Message\x20'+m+':\x20Missing\x20timestamp','hashValid':![],'hasSignature':!!d['signature']};if(n['leafIndex']===void 0x0||n['leafIndex']===null)return{'valid':![],'error':'Message\x20'+m+':\x20Missing\x20leafIndex','hashValid':![],'hasSignature':!!d['signature']};const o=verifySingleMerkleRoot(n['prevRoot'],n['merkleRoot'],n['plaintextHash'],n['timestamp'],n['leafIndex']);if(!o['valid'])return{'valid':![],'error':o['error']+'\x20at\x20message\x20'+m+',\x20leafIndex\x20'+n['leafIndex'],'hashValid':![],'hasSignature':!!d['signature']};if(m>0x0){const p=e[m-0x1];if(n['leafIndex']!==p['leafIndex']+0x1)return{'valid':![],'error':'Merkle\x20chain\x20discontinuity:\x20leafIndex\x20'+p['leafIndex']+'\x20->\x20'+n['leafIndex']+'\x20(expected\x20'+(p['leafIndex']+0x1)+')','hashValid':![],'hasSignature':!!d['signature']};if(n['prevRoot']['toLowerCase']()!==p['merkleRoot']['toLowerCase']())return{'valid':![],'error':'Merkle\x20root\x20mismatch\x20at\x20leafIndex\x20'+n['leafIndex']+':\x20expected\x20prevRoot='+p['merkleRoot']+',\x20got\x20'+n['prevRoot'],'hashValid':![],'hasSignature':!!d['signature']};}}for(let q=0x0;q<c['messages']['length'];q++){const r=c['messages'][q];if(!r)return{'valid':![],'error':'Message\x20'+q+':\x20Message\x20is\x20null\x20or\x20undefined','hashValid':![],'hasSignature':!!d['signature']};if(!!!r['zipMetadata']){if(!r['plaintextHash']['startsWith']('0x')||r['plaintextHash']['length']!==0x42)return{'valid':![],'error':'Message\x20'+q+':\x20Invalid\x20plaintextHash\x20format','hashValid':![],'hasSignature':!!d['signature']};if(r['plaintext']){if(hashPlaintext(r['plaintext'],r['clientTimestamp'],r['guardAddress'],r['passportAddress'],r['lastReceivedLeafIndex'])['toLowerCase']()!==r['plaintextHash']['toLowerCase']())return{'valid':![],'error':'Message\x20'+q+':\x20Plaintext\x20hash\x20mismatch','hashValid':![],'hasSignature':!!d['signature']};}}const s=resolveServerPublicKey(r,d);if(r['serverSignature']&&s){if(!r['timestamp'])return{'valid':![],'error':'Message\x20'+q+':\x20Missing\x20timestamp\x20for\x20signature\x20verification','hashValid':![],'hasSignature':!!d['signature']};if(!r['merkleRoot'])return{'valid':![],'error':'Message\x20'+q+':\x20Missing\x20merkleRoot\x20for\x20signature\x20verification','hashValid':![],'hasSignature':!!d['signature']};if(!r['prevRoot'])return{'valid':![],'error':'Message\x20'+q+':\x20Missing\x20prevRoot\x20for\x20signature\x20verification','hashValid':![],'hasSignature':!!d['signature']};if(!verifyFalcon512Signature(s,r['prevRoot']+':'+r['merkleRoot']+':'+r['timestamp']+':'+s,r['serverSignature']))return{'valid':![],'error':'Message\x20'+q+':\x20Server\x20signature\x20verification\x20failed','hashValid':![],'hasSignature':!!d['signature']};}}const {sha256:f}=await import('@noble/hashes/sha2.js'),{bytesToHex:g}=await import('@noble/hashes/utils.js'),h={'wts':b['wts'],...c};if(g(f(new TextEncoder()['encode'](a33e(h))))!==d['hash'])return{'valid':![],'error':'Hash\x20mismatch\x20-\x20content\x20has\x20been\x20tampered','hashValid':![],'hasSignature':!!d['signature']};if(d['messageCount']!==c['messages']['length'])return{'valid':![],'error':'messageCount\x20mismatch:\x20meta='+d['messageCount']+',\x20actual='+c['messages']['length'],'hashValid':!![],'hasSignature':!!d['signature']};const j=c['messages'][c['messages']['length']-0x1];if(d['merkleRoot']['toLowerCase']()!==j['merkleRoot']['toLowerCase']())return{'valid':![],'error':'merkleRoot\x20mismatch:\x20meta='+d['merkleRoot']+',\x20lastMessage='+j['merkleRoot'],'hashValid':!![],'hasSignature':!!d['signature']};const k=[];let l;if(d['signature']){const {Falcon512PublicKey:t}=await import('./publickey-CvCDfw_N.mjs')['then'](z=>z['n']),{signature:u,...v}=d,w=g(f(new TextEncoder()['encode'](a33e(v)))),x=Array['isArray'](d['signature'])?d['signature']:[d['signature']];let y=!![];for(const z of x){let A;const B=z['publicKey'];if(B['startsWith']('0x')){const C=Buffer['from'](B['slice'](0x2),'hex');if(C['length']===0x382)A=C['slice'](0x1);else{if(C['length']===0x381)A=C;else{let D;try{D=new t(B['slice'](0x2))['toWowAddress']();}catch{}k['push']({'publicKey':B,'address':D,'valid':![]}),y=![];continue;}}}else try{const E=Buffer['from'](B,'base64');if(E['length']===0x382)A=E['slice'](0x1);else{if(E['length']===0x381)A=E;else{let F;try{F=new t(B)['toWowAddress']();}catch{}k['push']({'publicKey':B,'address':F,'valid':![]}),y=![];continue;}}}catch{A=Buffer['from'](B,'base64');}try{const G=new t(A),H=Uint8Array['from'](Buffer['from'](z['value'],'base64')),I=await G['verify'](new TextEncoder()['encode'](w),H);let J;try{J=G['toWowAddress']();}catch{}k['push']({'publicKey':B,'address':J,'valid':I});if(!I)y=![];}catch{let K;try{K=new t(A)['toWowAddress']();}catch{}k['push']({'publicKey':B,'address':K,'valid':![]}),y=![];}}l=y;if(!l)return{'valid':![],'error':'Signatures\x20from\x20the\x20following\x20addresses\x20are\x20invalid:\x20'+k['filter'](L=>!L['valid']&&L['address'])['map'](L=>L['address'])['join'](',\x20'),'hashValid':!![],'hasSignature':!![],'signatureValid':![],'signatures':k};}return{'valid':!![],'hashValid':!![],'hasSignature':!!d['signature'],'signatureValid':l,'signatures':k['length']>0x0?k:void 0x0};}catch(L){return{'valid':![],'error':'Verification\x20error:\x20'+L,'hashValid':![],'hasSignature':![]};}}async function sign_wts(a,b,c){const d=await verify_wts(a);if(!d['valid'])throw new MessengerError('INVALID_INPUT','WTS\x20file\x20verification\x20failed:\x20'+d['error']);const e=load_wts(a),f=await Account['Instance']()['get_address'](b);if(!f)a33b('account\x20not\x20found','sign_wts.account\x20'+b);const {sha256:g}=await import('@noble/hashes/sha2.js'),{bytesToHex:h}=await import('@noble/hashes/utils.js'),{signature:i,...j}=e['meta'],k=h(g(new TextEncoder()['encode'](a33e(j)))),l=await Account['Instance']()['signData'](f,k);let m;const n=l['publicKey'];if(n['startsWith']('0x')){const s=Buffer['from'](n['slice'](0x2),'hex');if(s['length']===0x382)m=s['slice'](0x1)['toString']('base64');else{if(s['length']===0x381)m=s['toString']('base64');else throw new MessengerError('INVALID_INPUT','Invalid\x20public\x20key\x20length:\x20'+s['length']+',\x20expected\x20897\x20or\x20898\x20bytes');}}else m=n;const o={'value':Buffer['from'](l['signature']['slice'](0x2),'hex')['toString']('base64'),'publicKey':m,'algorithm':'Falcon512','address':l['address']};let p;if(e['meta']['signature']){const t=Array['isArray'](e['meta']['signature'])?[...e['meta']['signature']]:[e['meta']['signature']],u=t['findIndex'](v=>v['publicKey']===m);if(u>=0x0)t[u]=o,p=t;else p=[...t,o];}else p=[o];const q={...e,'meta':{...e['meta'],'signature':p}};let r;if(c)r=c;else{const v=a33g['dirname'](a),w=a33g['extname'](a),x=a33g['basename'](a,w);r=a33g['join'](v,'signed_'+x+w);}return save_wts(q,r),r;}async function wts2html(a,b={}){const c=await import('fs'),d=await import('path');if(c['statSync'](a)['isDirectory']()){const f=c['readdirSync'](a)['filter'](h=>h['endsWith']('.wts'));if(f['length']===0x0)throw new MessengerError('INVALID_INPUT','No\x20.wts\x20files\x20found\x20in\x20directory:\x20'+a);const g=[];for(const h of f){const i=await convertWtsToHtml(d['join'](a,h),b),j=toHtmlFileName(h),k=b['outputPath']?d['join'](b['outputPath'],j):d['join'](a,j),l=d['dirname'](k);if(!c['existsSync'](l))c['mkdirSync'](l,{'recursive':!![]});c['writeFileSync'](k,i,'utf-8'),g['push'](k);}return g;}const e=await convertWtsToHtml(a,b);if(b['outputPath']){const m=toHtmlFileName(d['basename'](a)),n=d['join'](b['outputPath'],m),o=d['dirname'](n);if(!c['existsSync'](o))c['mkdirSync'](o,{'recursive':!![]});return c['writeFileSync'](n,e,'utf-8'),n;}return e;}function toHtmlFileName(a){if(a['endsWith']('.wts.json'))return a['slice'](0x0,-0x9)+'.html';if(a['endsWith']('.wts'))return a['slice'](0x0,-0x4)+'.html';const b=a['lastIndexOf']('.');if(b>0x0)return a['slice'](0x0,b)+'.html';return a+'.html';}async function convertWtsToHtml(a,b={}){const {title:title='WTS\x20Document',theme:theme='light'}=b,c=await verify_wts(a),{payload:d,meta:e}=load_wts(a),{bgColor:f,textColor:g,borderColor:h}=getThemeColors(theme),i=e['creator'];let j=-0x1;for(const k of d['messages'])if(k['to']['toLowerCase']()===i['toLowerCase']()){if(k['lastReceivedLeafIndex']!==void 0x0&&k['lastReceivedLeafIndex']>=0x0){if(k['lastReceivedLeafIndex']>j)j=k['lastReceivedLeafIndex'];}}return generateHtmlPage({'title':title,'theme':theme,'bgColor':f,'textColor':g,'borderColor':h,'meta':e,'payload':d,'verifyResult':c,'maxLastReceivedLeafIndex':j,'myAddress':i});}async function proof_message(a,b,c){const d=await Account['Instance']()['get_address'](a);if(!d)a33b('account\x20not\x20found','proof_message.account\x20'+a);const e=new MessageStorage(d),f=e['getMessageById'](b);if(!f)throw new MessengerError('INVALID_INPUT','Message\x20not\x20found:\x20'+b);if(f['fromAddress']['toLowerCase']()!==d['toLowerCase']()&&f['toAddress']['toLowerCase']()!==d['toLowerCase']())throw new MessengerError('INVALID_INPUT','Message\x20does\x20not\x20belong\x20to\x20account\x20'+d);if(!f['serverSignature'])throw new MessengerError('INVALID_PROOF','Message\x20does\x20not\x20have\x20server\x20signature');if(!f['serverPublicKey'])throw new MessengerError('INVALID_PROOF','Message\x20does\x20not\x20have\x20server\x20public\x20key');if(!f['plaintext'])throw new MessengerError('INVALID_PROOF','Message\x20does\x20not\x20have\x20plaintext');const {verifyMessage:g}=await import('./w/messenger/crypto.mjs'),h={'messageId':f['messageId'],'plaintext':f['plaintext'],'plaintextHash':f['plaintextHash'],'createdAt':f['createdAt'],'guardAddress':f['guardAddress'],'passportAddress':f['passportAddress'],'lastReceivedLeafIndex':f['lastReceivedLeafIndex'],'serverSignature':f['serverSignature'],'serverPublicKey':f['serverPublicKey']};if(f['newRoot']&&f['leafIndex']!==void 0x0){if(!f['serverTimestamp'])throw new MessengerError('INVALID_PROOF','Message\x20'+f['messageId']+'\x20missing\x20server\x20timestamp\x20for\x20verification');h['merkleMetadata']={'newRoot':f['newRoot'],'prevRoot':f['prevRoot'],'leafIndex':f['leafIndex'],'serverTimestamp':f['serverTimestamp']};}const i=g(h);if(!i['valid'])throw new MessengerError('INVALID_PROOF','Message\x20verification\x20failed:\x20'+i['error']);if(!f['serverPublicKey'])throw new MessengerError('INVALID_PROOF','Message\x20does\x20not\x20have\x20server\x20public\x20key');const {CallProof:j}=await import('./proof-BcyNI5NQ.mjs')['then'](p=>p['r']),k=new j({'proof':f['newRoot'],'server_pubkey':f['serverPublicKey'],'server_signature':f['serverSignature'],'proof_type':0x1,'description':'Message\x20proof\x20for\x20'+b,'item_count':f['leafIndex']??0x1,'about_address':f['fromAddress']['toLowerCase']()===d['toLowerCase']()?f['toAddress']:f['fromAddress']}),l={'network':c,'account':d},m=await k['call'](l),{ResponseData:n}=await import('./w/call/base.mjs'),o=n(m)['find'](p=>p['type']==='Proof');if(!o||!o['object'])throw new MessengerError('INVALID_PROOF','Failed\x20to\x20get\x20proof\x20address\x20from\x20transaction\x20result');return f['proof']=o['object'],e['saveMessage'](f),{'proofAddress':o['object']};}const MIN_PASSPORT_VALIDITY=0xa,MAX_PASSPORT_VALIDITY=0xa*0x16d*0x18*0x3c*0x3c,MAX_BLACKLIST_SIZE_ONCE=0x64,MAX_FRIENDS_SIZE_ONCE=0x64,MAX_GUARDS_SIZE_ONCE=0xa;async function blacklist(a){const b=await Account['Instance']()['get_address'](a['account']);if(!b)a33b('account\x20not\x20found','blacklist.account\x20'+a['account']);const c=getMessengerManager();await c['ensureAccountReady'](b);switch(a['op']){case'add':{let d=await GetManyAccountOrMark_Address(a['users']);if(d['length']===0x0)a33b('invalid\x20parameter','blacklist.add.users\x20'+a['users']+'\x20have\x20not\x20valid\x20addresses');d=[...new Set(d['map'](e=>e['toLowerCase']()))];if(d['length']>MAX_BLACKLIST_SIZE_ONCE)a33b('invalid\x20parameter','blacklist.add.users\x20'+a['users']+'\x20have\x20too\x20many\x20addresses,\x20max\x20'+MAX_BLACKLIST_SIZE_ONCE);return{'op':'add','result':await c['addToBlacklist'](b,d)};}case'remove':{let e=await GetManyAccountOrMark_Address(a['users']);if(e['length']===0x0)a33b('invalid\x20parameter','blacklist.remove.users\x20'+a['users']+'\x20have\x20not\x20valid\x20addresses');e=[...new Set(e['map'](f=>f['toLowerCase']()))];if(e['length']>MAX_BLACKLIST_SIZE_ONCE)a33b('invalid\x20parameter','blacklist.remove.users\x20'+a['users']+'\x20have\x20too\x20many\x20addresses,\x20max\x20'+MAX_BLACKLIST_SIZE_ONCE);return{'op':'remove','result':await c['removeFromBlacklist'](b,e)};}case'clear':return{'op':'clear','result':await c['clearBlacklist'](b)};case'get':return{'op':'get','result':await c['getBlacklist'](b)};case'exist':{let f=await GetManyAccountOrMark_Address(a['users']);if(f['length']===0x0)a33b('invalid\x20parameter','blacklist.exist.users\x20'+a['users']+'\x20have\x20not\x20valid\x20addresses');f=[...new Set(f['map'](g=>g['toLowerCase']()))];if(f['length']>MAX_BLACKLIST_SIZE_ONCE)a33b('invalid\x20parameter','blacklist.exist.users\x20'+a['users']+'\x20have\x20too\x20many\x20addresses,\x20max\x20'+MAX_BLACKLIST_SIZE_ONCE);return{'op':'exist','result':await c['existInBlacklist'](b,f)};}default:throw new MessengerError('INVALID_INPUT','blacklist.unknown\x20op:\x20'+a);}}async function friendslist(a){const b=await Account['Instance']()['get_address'](a['account']);if(!b)a33b('account\x20not\x20found','friendslist.account\x20'+a['account']);const c=getMessengerManager();await c['ensureAccountReady'](b);switch(a['op']){case'add':{let d=await GetManyAccountOrMark_Address(a['users']);if(d['length']===0x0)a33b('invalid\x20parameter','friendslist.add.users\x20'+a['users']+'\x20have\x20not\x20valid\x20addresses');return d=[...new Set(d['map'](e=>e['toLowerCase']()))],{'op':'add','result':await c['addToFriendsList'](b,d)};}case'remove':{let e=await GetManyAccountOrMark_Address(a['users']);if(e['length']===0x0)a33b('invalid\x20parameter','friendslist.remove.users\x20'+a['users']+'\x20have\x20not\x20valid\x20addresses');e=[...new Set(e['map'](f=>f['toLowerCase']()))];if(e['length']>MAX_FRIENDS_SIZE_ONCE)a33b('invalid\x20parameter','friendslist.remove.users\x20'+a['users']+'\x20have\x20too\x20many\x20addresses,\x20max\x20'+MAX_FRIENDS_SIZE_ONCE);return{'op':'remove','result':await c['removeFromFriendsList'](b,e)};}case'clear':return{'op':'clear','result':await c['clearFriendsList'](b)};case'get':return{'op':'get','result':await c['getFriendsList'](b)};case'exist':{let f=await GetManyAccountOrMark_Address(a['users']);if(f['length']===0x0)a33b('invalid\x20parameter','friendslist.exist.users\x20'+a['users']+'\x20have\x20not\x20valid\x20addresses');f=[...new Set(f['map'](g=>g['toLowerCase']()))];if(f['length']>MAX_FRIENDS_SIZE_ONCE)a33b('invalid\x20parameter','friendslist.exist.users\x20'+a['users']+'\x20have\x20too\x20many\x20addresses,\x20max\x20'+MAX_FRIENDS_SIZE_ONCE);return{'op':'exist','result':await c['existInFriendsList'](b,f)};}default:throw new MessengerError('INVALID_INPUT','friendslist.unknown\x20op:\x20'+a);}}async function guardlist(a){const b=await Account['Instance']()['get_address'](a['account']);if(!b)a33b('account\x20not\x20found','guardlist.account\x20'+a['account']);const c=getMessengerManager();await c['ensureAccountReady'](b);switch(a['op']){case'add':{const d=new Map();for(const j of a['guards'])d['set'](j['guard']['toLowerCase'](),j);const e=Array['from'](d['values']());if(e['length']===0x0)a33b('invalid\x20parameter','guardlist.add.guards\x20'+a['guards']+'\x20have\x20not\x20valid\x20guards');if(e['length']>MAX_GUARDS_SIZE_ONCE)a33b('invalid\x20parameter','guardlist.add.guards\x20'+a['guards']+'\x20have\x20too\x20many\x20guards,\x20max\x20'+MAX_GUARDS_SIZE_ONCE);for(const k of e)if(!a33a(k['passportValiditySeconds'])||k['passportValiditySeconds']<MIN_PASSPORT_VALIDITY||k['passportValiditySeconds']>MAX_PASSPORT_VALIDITY)a33b('invalid\x20parameter','Guard\x20'+k['guard']+':\x20passport\x20validity\x20'+k['passportValiditySeconds']+'\x20must\x20be\x20between\x20'+MIN_PASSPORT_VALIDITY+'\x20and\x20'+MAX_PASSPORT_VALIDITY+'\x20seconds');const f=await LocalMark['Instance']()['get_many_address'](e['map'](l=>l['guard']));if(f['length']!==e['length']){const l=new Set(f),m=[];for(const n of e)if(!l['has'](n['guard'])&&!n['guard']['startsWith']('0x'))m['push'](n['guard']);a33b('invalid\x20parameter','Guard\x20not\x20found:\x20'+m['join'](',\x20'));}const h=await a33d({'objects':f,'no_cache':![],'network':c['getConfig']()['network']});if(!h||!h['objects']||h['objects']['length']===0x0)a33b('invalid\x20parameter','Guard\x20not\x20found:\x20'+e['map'](o=>o['guard'])['join'](',\x20'));h['objects']['forEach'](o=>{if(o['type']!=='Guard')a33b('invalid\x20parameter','Guard\x20'+o['object']+'\x20is\x20not\x20a\x20Guard');});const i=e['map']((o,p)=>({'guardAddress':f[p],'passportValiditySeconds':o['passportValiditySeconds']}));return{'op':'add','result':await c['addToGuardList'](b,i)};}case'remove':{const o=[...new Set(a['guards']['map'](q=>q['toLowerCase']()))];if(o['length']===0x0)a33b('invalid\x20parameter','guardlist.remove.guards\x20'+a['guards']+'\x20have\x20not\x20valid\x20guards');if(o['length']>MAX_GUARDS_SIZE_ONCE)a33b('invalid\x20parameter','guardlist.remove.guards\x20'+a['guards']+'\x20have\x20too\x20many\x20guards,\x20max\x20'+MAX_GUARDS_SIZE_ONCE);const p=await LocalMark['Instance']()['get_many_address'](o);if(p['length']!==o['length']){const q=new Set(p),r=[];for(const s of o)if(!q['has'](s)&&!s['startsWith']('0x'))r['push'](s);a33b('invalid\x20parameter','Guard\x20not\x20found:\x20'+r['join'](',\x20'));}return{'op':'remove','result':await c['removeFromGuardList'](b,p)};}case'get':return{'op':'get','result':await c['getGuardList'](b)};default:throw new MessengerError('INVALID_INPUT','guardlist.unknown\x20op:\x20'+a);}}async function settings(a){const b=await Account['Instance']()['get_address'](a['account']);if(!b)a33b('account\x20not\x20found','settings.account\x20'+a['account']);const c=getMessengerManager();await c['ensureAccountReady'](b);switch(a['op']){case'get':return{'op':'get','result':await c['getSettings'](b)};case'set':{const d={};if(a['allowStrangerMessages']!==void 0x0)d['allowStrangerMessages']=a['allowStrangerMessages'];if(a['maxInboxSize']!==void 0x0)d['maxInboxSize']=a['maxInboxSize'];return{'op':'set','result':await c['setSettings'](b,d)};}default:throw new MessengerError('INVALID_INPUT','settings.unknown\x20op:\x20'+a);}}export{watch_conversations as _,generate_wts as a,MessengerManager as b,mark_conversation_as_viewed as c,pull_messages as d,send_file as f,verify_wts as g,sign_wts as h,friendslist as i,mark_messages_as_viewed as l,settings as m,extractZipFromPlaintext as n,getMessengerManager as o,send_message as p,extract_zip_messages as r,guardlist as s,blacklist as t,proof_message as u,watch_messages as v,wts2html as y};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { B as parsePartialSignatures, R as MultiSigPublicKey,
|
|
1
|
+
import { B as parsePartialSignatures, R as MultiSigPublicKey, sb as MultiSigSigner, z as MultiSigStruct } from "../index-BZkrZ63s.mjs";
|
|
2
2
|
export { MultiSigPublicKey, MultiSigSigner, type MultiSigStruct, parsePartialSignatures };
|