wowok 2.1.40 → 2.1.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/bcs/bcs.js +1 -253
- package/dist/cjs/bcs/effects.js +1 -199
- package/dist/cjs/bcs/index.js +1 -51
- package/dist/cjs/bcs/pure.js +1 -36
- package/dist/cjs/bcs/type-tag-serializer.js +1 -104
- package/dist/cjs/bcs/types.js +1 -3
- package/dist/cjs/client/index.js +1 -4
- package/dist/cjs/client/network.js +1 -15
- package/dist/cjs/cryptography/index.js +1 -6
- package/dist/cjs/cryptography/intent.js +1 -14
- package/dist/cjs/cryptography/keypair.js +1 -74
- package/dist/cjs/cryptography/mnemonics.js +1 -20
- package/dist/cjs/cryptography/publickey.js +1 -80
- package/dist/cjs/cryptography/signature-scheme.js +1 -22
- package/dist/cjs/cryptography/signature.js +1 -41
- package/dist/cjs/experimental/cache.js +1 -58
- package/dist/cjs/experimental/client.js +1 -19
- package/dist/cjs/experimental/core.js +1 -80
- package/dist/cjs/experimental/errors.js +1 -24
- package/dist/cjs/experimental/index.js +1 -5
- package/dist/cjs/experimental/persistent-storage.js +1 -220
- package/dist/cjs/experimental/persistent-storage.test.js +1 -144
- package/dist/cjs/experimental/transports/utils.js +1 -96
- package/dist/cjs/experimental/types.js +1 -1
- package/dist/cjs/faucet/faucet.js +1 -99
- package/dist/cjs/faucet/index.js +1 -1
- package/dist/cjs/grpc/client.js +1 -42
- package/dist/cjs/grpc/core.js +1 -587
- package/dist/cjs/grpc/index.js +1 -2
- package/dist/cjs/grpc/proto/google/protobuf/any.js +1 -106
- package/dist/cjs/grpc/proto/google/protobuf/duration.js +1 -58
- package/dist/cjs/grpc/proto/google/protobuf/empty.js +1 -7
- package/dist/cjs/grpc/proto/google/protobuf/field_mask.js +1 -47
- package/dist/cjs/grpc/proto/google/protobuf/struct.js +1 -191
- package/dist/cjs/grpc/proto/google/protobuf/timestamp.js +1 -91
- package/dist/cjs/grpc/proto/google/rpc/error_details.js +1 -265
- package/dist/cjs/grpc/proto/google/rpc/status.js +1 -23
- package/dist/cjs/grpc/proto/sui/rpc/v2/argument.js +1 -46
- package/dist/cjs/grpc/proto/sui/rpc/v2/balance_change.js +1 -29
- package/dist/cjs/grpc/proto/sui/rpc/v2/bcs.js +1 -22
- package/dist/cjs/grpc/proto/sui/rpc/v2/checkpoint.js +1 -54
- package/dist/cjs/grpc/proto/sui/rpc/v2/checkpoint_contents.js +1 -60
- package/dist/cjs/grpc/proto/sui/rpc/v2/checkpoint_summary.js +1 -144
- package/dist/cjs/grpc/proto/sui/rpc/v2/effects.js +1 -271
- package/dist/cjs/grpc/proto/sui/rpc/v2/epoch.js +1 -64
- package/dist/cjs/grpc/proto/sui/rpc/v2/error_reason.js +1 -6
- package/dist/cjs/grpc/proto/sui/rpc/v2/event.js +1 -62
- package/dist/cjs/grpc/proto/sui/rpc/v2/executed_transaction.js +1 -64
- package/dist/cjs/grpc/proto/sui/rpc/v2/execution_status.js +1 -481
- package/dist/cjs/grpc/proto/sui/rpc/v2/gas_cost_summary.js +1 -40
- package/dist/cjs/grpc/proto/sui/rpc/v2/input.js +1 -61
- package/dist/cjs/grpc/proto/sui/rpc/v2/jwk.js +1 -57
- package/dist/cjs/grpc/proto/sui/rpc/v2/ledger_service.client.js +1 -39
- package/dist/cjs/grpc/proto/sui/rpc/v2/ledger_service.js +1 -329
- package/dist/cjs/grpc/proto/sui/rpc/v2/move_package.js +1 -447
- package/dist/cjs/grpc/proto/sui/rpc/v2/move_package_service.client.js +1 -27
- package/dist/cjs/grpc/proto/sui/rpc/v2/move_package_service.js +1 -206
- package/dist/cjs/grpc/proto/sui/rpc/v2/name_service.client.js +1 -19
- package/dist/cjs/grpc/proto/sui/rpc/v2/name_service.js +1 -109
- package/dist/cjs/grpc/proto/sui/rpc/v2/object.js +1 -90
- package/dist/cjs/grpc/proto/sui/rpc/v2/object_reference.js +1 -30
- package/dist/cjs/grpc/proto/sui/rpc/v2/owner.js +1 -39
- package/dist/cjs/grpc/proto/sui/rpc/v2/protocol_config.js +1 -30
- package/dist/cjs/grpc/proto/sui/rpc/v2/signature.js +1 -501
- package/dist/cjs/grpc/proto/sui/rpc/v2/signature_scheme.js +1 -10
- package/dist/cjs/grpc/proto/sui/rpc/v2/signature_verification_service.client.js +1 -15
- package/dist/cjs/grpc/proto/sui/rpc/v2/signature_verification_service.js +1 -62
- package/dist/cjs/grpc/proto/sui/rpc/v2/state_service.client.js +1 -31
- package/dist/cjs/grpc/proto/sui/rpc/v2/state_service.js +1 -504
- package/dist/cjs/grpc/proto/sui/rpc/v2/subscription_service.client.js +1 -15
- package/dist/cjs/grpc/proto/sui/rpc/v2/subscription_service.js +1 -37
- package/dist/cjs/grpc/proto/sui/rpc/v2/system_state.js +1 -709
- package/dist/cjs/grpc/proto/sui/rpc/v2/transaction.js +1 -950
- package/dist/cjs/grpc/proto/sui/rpc/v2/transaction_execution_service.client.js +1 -19
- package/dist/cjs/grpc/proto/sui/rpc/v2/transaction_execution_service.js +1 -144
- package/dist/cjs/index.js +1 -22
- package/dist/cjs/jsonRpc/client.js +1 -516
- package/dist/cjs/jsonRpc/core.js +1 -587
- package/dist/cjs/jsonRpc/errors.js +1 -38
- package/dist/cjs/jsonRpc/http-transport.js +1 -70
- package/dist/cjs/jsonRpc/index.js +1 -3
- package/dist/cjs/jsonRpc/json-rpc-resolver.js +1 -296
- package/dist/cjs/jsonRpc/rpc-websocket-client.js +1 -155
- package/dist/cjs/jsonRpc/types/chain.js +1 -1
- package/dist/cjs/jsonRpc/types/changes.js +1 -1
- package/dist/cjs/jsonRpc/types/coins.js +1 -1
- package/dist/cjs/jsonRpc/types/common.js +1 -1
- package/dist/cjs/jsonRpc/types/generated.js +1 -1
- package/dist/cjs/jsonRpc/types/index.js +1 -1
- package/dist/cjs/jsonRpc/types/params.js +1 -1
- package/dist/cjs/keypairs/ed25519/ed25519-hd-key.js +1 -58
- package/dist/cjs/keypairs/ed25519/index.js +1 -2
- package/dist/cjs/keypairs/ed25519/keypair.js +1 -90
- package/dist/cjs/keypairs/ed25519/publickey.js +1 -50
- package/dist/cjs/keypairs/index.js +1 -4
- package/dist/cjs/keypairs/passkey/index.js +1 -2
- package/dist/cjs/keypairs/passkey/keypair.js +1 -155
- package/dist/cjs/keypairs/passkey/publickey.js +1 -117
- package/dist/cjs/keypairs/passkey/types.js +1 -1
- package/dist/cjs/keypairs/secp256k1/index.js +1 -2
- package/dist/cjs/keypairs/secp256k1/keypair.js +1 -82
- package/dist/cjs/keypairs/secp256k1/publickey.js +1 -51
- package/dist/cjs/keypairs/secp256r1/index.js +1 -2
- package/dist/cjs/keypairs/secp256r1/keypair.js +1 -78
- package/dist/cjs/keypairs/secp256r1/publickey.js +1 -52
- package/dist/cjs/multisig/index.js +1 -2
- package/dist/cjs/multisig/publickey.js +1 -201
- package/dist/cjs/multisig/signer.js +1 -58
- package/dist/cjs/transactions/Arguments.js +1 -9
- package/dist/cjs/transactions/Commands.js +1 -102
- package/dist/cjs/transactions/Inputs.js +1 -52
- package/dist/cjs/transactions/ObjectCache.js +1 -205
- package/dist/cjs/transactions/Transaction.js +1 -574
- package/dist/cjs/transactions/TransactionData.js +1 -409
- package/dist/cjs/transactions/__tests__/Transaction.test.js +1 -160
- package/dist/cjs/transactions/__tests__/bcs.test.js +1 -182
- package/dist/cjs/transactions/data/internal.js +1 -169
- package/dist/cjs/transactions/data/v1.js +1 -469
- package/dist/cjs/transactions/data/v2.js +1 -97
- package/dist/cjs/transactions/executor/caching.js +1 -65
- package/dist/cjs/transactions/executor/parallel.js +1 -347
- package/dist/cjs/transactions/executor/queue.js +1 -59
- package/dist/cjs/transactions/executor/serial.js +1 -99
- package/dist/cjs/transactions/hash.js +1 -8
- package/dist/cjs/transactions/index.js +1 -12
- package/dist/cjs/transactions/intents/CoinWithBalance.js +1 -145
- package/dist/cjs/transactions/object.js +1 -87
- package/dist/cjs/transactions/plugins/NamedPackagesPlugin.js +1 -11
- package/dist/cjs/transactions/pure.js +1 -36
- package/dist/cjs/transactions/resolve.js +1 -69
- package/dist/cjs/transactions/serializer.js +1 -167
- package/dist/cjs/transactions/utils.js +1 -121
- package/dist/cjs/utils/constants.js +1 -18
- package/dist/cjs/utils/derived-objects.js +1 -8
- package/dist/cjs/utils/dynamic-fields.js +1 -17
- package/dist/cjs/utils/format.js +1 -11
- package/dist/cjs/utils/index.js +1 -8
- package/dist/cjs/utils/move-registry.js +1 -24
- package/dist/cjs/utils/sui-types.js +1 -66
- package/dist/cjs/utils/suins.js +1 -33
- package/dist/cjs/verify/index.js +1 -1
- package/dist/cjs/verify/verify.js +1 -87
- package/dist/cjs/version.js +1 -2
- package/dist/cjs/w/call/allocation.js +1 -345
- package/dist/cjs/w/call/arb.js +1 -103
- package/dist/cjs/w/call/arbitration.js +1 -1192
- package/dist/cjs/w/call/base.js +1 -293
- package/dist/cjs/w/call/contact.js +1 -345
- package/dist/cjs/w/call/demand.js +1 -681
- package/dist/cjs/w/call/entity.js +1 -173
- package/dist/cjs/w/call/guard-ins.js +1 -4449
- package/dist/cjs/w/call/guard.d.ts +111 -0
- package/dist/cjs/w/call/guard.js +1 -1048
- package/dist/cjs/w/call/index.js +1 -22
- package/dist/cjs/w/call/machine.js +1 -1127
- package/dist/cjs/w/call/order.js +1 -337
- package/dist/cjs/w/call/passport.js +1 -220
- package/dist/cjs/w/call/payment.js +1 -178
- package/dist/cjs/w/call/permission.js +1 -1162
- package/dist/cjs/w/call/personal.js +1 -139
- package/dist/cjs/w/call/progress.js +1 -678
- package/dist/cjs/w/call/proof.js +1 -66
- package/dist/cjs/w/call/repository.js +1 -1024
- package/dist/cjs/w/call/resource.js +1 -108
- package/dist/cjs/w/call/reward.js +1 -675
- package/dist/cjs/w/call/service.js +1 -1960
- package/dist/cjs/w/call/treasury.js +1 -873
- package/dist/cjs/w/call/util.d.ts +1 -0
- package/dist/cjs/w/call/util.js +1 -566
- package/dist/cjs/w/common.js +1 -571
- package/dist/cjs/w/exception.js +1 -618
- package/dist/cjs/w/index.js +1 -8
- package/dist/cjs/w/local/account.js +1 -656
- package/dist/cjs/w/local/cache.js +1 -161
- package/dist/cjs/w/local/config.js +1 -43
- package/dist/cjs/w/local/index.js +1 -228
- package/dist/cjs/w/local/local.js +1 -574
- package/dist/cjs/w/local/storage.js +1 -185
- package/dist/cjs/w/local/token.js +1 -131
- package/dist/cjs/w/local/util.js +1 -26
- package/dist/cjs/w/local/wip.js +1 -864
- package/dist/cjs/w/messenger/crypto.js +1 -380
- package/dist/cjs/w/messenger/index.js +1 -4
- package/dist/cjs/w/messenger/messenger-api.js +1 -1154
- package/dist/cjs/w/messenger/messenger-manager.js +1 -1003
- package/dist/cjs/w/messenger/messenger.js +1 -1093
- package/dist/cjs/w/messenger/server.js +1 -343
- package/dist/cjs/w/messenger/session.js +1 -628
- package/dist/cjs/w/messenger/storage.js +1 -1023
- package/dist/cjs/w/messenger/templates/wts-html-template.js +1 -371
- package/dist/cjs/w/messenger/types.js +1 -76
- package/dist/cjs/w/messenger/utils.js +1 -12
- package/dist/cjs/w/query/bult-in.js +1 -95
- package/dist/cjs/w/query/event.js +1 -137
- package/dist/cjs/w/query/index.js +1 -5
- package/dist/cjs/w/query/object.js +1 -1550
- package/dist/cjs/w/query/received.js +1 -62
- package/dist/cjs/w/query/util.js +1 -49
- package/dist/cjs/w/util.js +1 -587
- package/dist/esm/bcs/bcs.js +1 -253
- package/dist/esm/bcs/effects.js +1 -199
- package/dist/esm/bcs/index.js +1 -51
- package/dist/esm/bcs/pure.js +1 -36
- package/dist/esm/bcs/type-tag-serializer.js +1 -104
- package/dist/esm/bcs/types.js +1 -3
- package/dist/esm/client/index.js +1 -4
- package/dist/esm/client/network.js +1 -15
- package/dist/esm/cryptography/index.js +1 -6
- package/dist/esm/cryptography/intent.js +1 -14
- package/dist/esm/cryptography/keypair.js +1 -74
- package/dist/esm/cryptography/mnemonics.js +1 -20
- package/dist/esm/cryptography/publickey.js +1 -80
- package/dist/esm/cryptography/signature-scheme.js +1 -22
- package/dist/esm/cryptography/signature.js +1 -41
- package/dist/esm/experimental/cache.js +1 -58
- package/dist/esm/experimental/client.js +1 -19
- package/dist/esm/experimental/core.js +1 -80
- package/dist/esm/experimental/errors.js +1 -24
- package/dist/esm/experimental/index.js +1 -5
- package/dist/esm/experimental/persistent-storage.js +1 -220
- package/dist/esm/experimental/persistent-storage.test.js +1 -144
- package/dist/esm/experimental/transports/utils.js +1 -96
- package/dist/esm/experimental/types.js +1 -1
- package/dist/esm/faucet/faucet.js +1 -99
- package/dist/esm/faucet/index.js +1 -1
- package/dist/esm/grpc/client.js +1 -42
- package/dist/esm/grpc/core.js +1 -587
- package/dist/esm/grpc/index.js +1 -2
- package/dist/esm/grpc/proto/google/protobuf/any.js +1 -106
- package/dist/esm/grpc/proto/google/protobuf/duration.js +1 -58
- package/dist/esm/grpc/proto/google/protobuf/empty.js +1 -7
- package/dist/esm/grpc/proto/google/protobuf/field_mask.js +1 -47
- package/dist/esm/grpc/proto/google/protobuf/struct.js +1 -191
- package/dist/esm/grpc/proto/google/protobuf/timestamp.js +1 -91
- package/dist/esm/grpc/proto/google/rpc/error_details.js +1 -265
- package/dist/esm/grpc/proto/google/rpc/status.js +1 -23
- package/dist/esm/grpc/proto/sui/rpc/v2/argument.js +1 -46
- package/dist/esm/grpc/proto/sui/rpc/v2/balance_change.js +1 -29
- package/dist/esm/grpc/proto/sui/rpc/v2/bcs.js +1 -22
- package/dist/esm/grpc/proto/sui/rpc/v2/checkpoint.js +1 -54
- package/dist/esm/grpc/proto/sui/rpc/v2/checkpoint_contents.js +1 -60
- package/dist/esm/grpc/proto/sui/rpc/v2/checkpoint_summary.js +1 -144
- package/dist/esm/grpc/proto/sui/rpc/v2/effects.js +1 -271
- package/dist/esm/grpc/proto/sui/rpc/v2/epoch.js +1 -64
- package/dist/esm/grpc/proto/sui/rpc/v2/error_reason.js +1 -6
- package/dist/esm/grpc/proto/sui/rpc/v2/event.js +1 -62
- package/dist/esm/grpc/proto/sui/rpc/v2/executed_transaction.js +1 -64
- package/dist/esm/grpc/proto/sui/rpc/v2/execution_status.js +1 -481
- package/dist/esm/grpc/proto/sui/rpc/v2/gas_cost_summary.js +1 -40
- package/dist/esm/grpc/proto/sui/rpc/v2/input.js +1 -61
- package/dist/esm/grpc/proto/sui/rpc/v2/jwk.js +1 -57
- package/dist/esm/grpc/proto/sui/rpc/v2/ledger_service.client.js +1 -39
- package/dist/esm/grpc/proto/sui/rpc/v2/ledger_service.js +1 -329
- package/dist/esm/grpc/proto/sui/rpc/v2/move_package.js +1 -447
- package/dist/esm/grpc/proto/sui/rpc/v2/move_package_service.client.js +1 -27
- package/dist/esm/grpc/proto/sui/rpc/v2/move_package_service.js +1 -206
- package/dist/esm/grpc/proto/sui/rpc/v2/name_service.client.js +1 -19
- package/dist/esm/grpc/proto/sui/rpc/v2/name_service.js +1 -109
- package/dist/esm/grpc/proto/sui/rpc/v2/object.js +1 -90
- package/dist/esm/grpc/proto/sui/rpc/v2/object_reference.js +1 -30
- package/dist/esm/grpc/proto/sui/rpc/v2/owner.js +1 -39
- package/dist/esm/grpc/proto/sui/rpc/v2/protocol_config.js +1 -30
- package/dist/esm/grpc/proto/sui/rpc/v2/signature.js +1 -501
- package/dist/esm/grpc/proto/sui/rpc/v2/signature_scheme.js +1 -10
- package/dist/esm/grpc/proto/sui/rpc/v2/signature_verification_service.client.js +1 -15
- package/dist/esm/grpc/proto/sui/rpc/v2/signature_verification_service.js +1 -62
- package/dist/esm/grpc/proto/sui/rpc/v2/state_service.client.js +1 -31
- package/dist/esm/grpc/proto/sui/rpc/v2/state_service.js +1 -504
- package/dist/esm/grpc/proto/sui/rpc/v2/subscription_service.client.js +1 -15
- package/dist/esm/grpc/proto/sui/rpc/v2/subscription_service.js +1 -37
- package/dist/esm/grpc/proto/sui/rpc/v2/system_state.js +1 -709
- package/dist/esm/grpc/proto/sui/rpc/v2/transaction.js +1 -950
- package/dist/esm/grpc/proto/sui/rpc/v2/transaction_execution_service.client.js +1 -19
- package/dist/esm/grpc/proto/sui/rpc/v2/transaction_execution_service.js +1 -144
- package/dist/esm/index.js +1 -22
- package/dist/esm/jsonRpc/client.js +1 -516
- package/dist/esm/jsonRpc/core.js +1 -587
- package/dist/esm/jsonRpc/errors.js +1 -38
- package/dist/esm/jsonRpc/http-transport.js +1 -70
- package/dist/esm/jsonRpc/index.js +1 -3
- package/dist/esm/jsonRpc/json-rpc-resolver.js +1 -296
- package/dist/esm/jsonRpc/rpc-websocket-client.js +1 -155
- package/dist/esm/jsonRpc/types/chain.js +1 -1
- package/dist/esm/jsonRpc/types/changes.js +1 -1
- package/dist/esm/jsonRpc/types/coins.js +1 -1
- package/dist/esm/jsonRpc/types/common.js +1 -1
- package/dist/esm/jsonRpc/types/generated.js +1 -1
- package/dist/esm/jsonRpc/types/index.js +1 -1
- package/dist/esm/jsonRpc/types/params.js +1 -1
- package/dist/esm/keypairs/ed25519/ed25519-hd-key.js +1 -58
- package/dist/esm/keypairs/ed25519/index.js +1 -2
- package/dist/esm/keypairs/ed25519/keypair.js +1 -90
- package/dist/esm/keypairs/ed25519/publickey.js +1 -50
- package/dist/esm/keypairs/index.js +1 -4
- package/dist/esm/keypairs/passkey/index.js +1 -2
- package/dist/esm/keypairs/passkey/keypair.js +1 -155
- package/dist/esm/keypairs/passkey/publickey.js +1 -117
- package/dist/esm/keypairs/passkey/types.js +1 -1
- package/dist/esm/keypairs/secp256k1/index.js +1 -2
- package/dist/esm/keypairs/secp256k1/keypair.js +1 -82
- package/dist/esm/keypairs/secp256k1/publickey.js +1 -51
- package/dist/esm/keypairs/secp256r1/index.js +1 -2
- package/dist/esm/keypairs/secp256r1/keypair.js +1 -78
- package/dist/esm/keypairs/secp256r1/publickey.js +1 -52
- package/dist/esm/multisig/index.js +1 -2
- package/dist/esm/multisig/publickey.js +1 -201
- package/dist/esm/multisig/signer.js +1 -58
- package/dist/esm/transactions/Arguments.js +1 -9
- package/dist/esm/transactions/Commands.js +1 -102
- package/dist/esm/transactions/Inputs.js +1 -52
- package/dist/esm/transactions/ObjectCache.js +1 -205
- package/dist/esm/transactions/Transaction.js +1 -574
- package/dist/esm/transactions/TransactionData.js +1 -409
- package/dist/esm/transactions/__tests__/Transaction.test.js +1 -160
- package/dist/esm/transactions/__tests__/bcs.test.js +1 -182
- package/dist/esm/transactions/data/internal.js +1 -169
- package/dist/esm/transactions/data/v1.js +1 -469
- package/dist/esm/transactions/data/v2.js +1 -97
- package/dist/esm/transactions/executor/caching.js +1 -65
- package/dist/esm/transactions/executor/parallel.js +1 -347
- package/dist/esm/transactions/executor/queue.js +1 -59
- package/dist/esm/transactions/executor/serial.js +1 -99
- package/dist/esm/transactions/hash.js +1 -8
- package/dist/esm/transactions/index.js +1 -12
- package/dist/esm/transactions/intents/CoinWithBalance.js +1 -145
- package/dist/esm/transactions/object.js +1 -87
- package/dist/esm/transactions/plugins/NamedPackagesPlugin.js +1 -11
- package/dist/esm/transactions/pure.js +1 -36
- package/dist/esm/transactions/resolve.js +1 -69
- package/dist/esm/transactions/serializer.js +1 -167
- package/dist/esm/transactions/utils.js +1 -121
- package/dist/esm/utils/constants.js +1 -18
- package/dist/esm/utils/derived-objects.js +1 -8
- package/dist/esm/utils/dynamic-fields.js +1 -17
- package/dist/esm/utils/format.js +1 -11
- package/dist/esm/utils/index.js +1 -8
- package/dist/esm/utils/move-registry.js +1 -24
- package/dist/esm/utils/sui-types.js +1 -66
- package/dist/esm/utils/suins.js +1 -33
- package/dist/esm/verify/index.js +1 -1
- package/dist/esm/verify/verify.js +1 -87
- package/dist/esm/version.js +1 -2
- package/dist/esm/w/call/allocation.js +1 -345
- package/dist/esm/w/call/arb.js +1 -103
- package/dist/esm/w/call/arbitration.js +1 -1192
- package/dist/esm/w/call/base.js +1 -293
- package/dist/esm/w/call/contact.js +1 -345
- package/dist/esm/w/call/demand.js +1 -681
- package/dist/esm/w/call/entity.js +1 -173
- package/dist/esm/w/call/guard-ins.js +1 -4449
- package/dist/esm/w/call/guard.d.ts +111 -0
- package/dist/esm/w/call/guard.js +1 -1048
- package/dist/esm/w/call/index.js +1 -22
- package/dist/esm/w/call/machine.js +1 -1127
- package/dist/esm/w/call/order.js +1 -337
- package/dist/esm/w/call/passport.js +1 -220
- package/dist/esm/w/call/payment.js +1 -178
- package/dist/esm/w/call/permission.js +1 -1162
- package/dist/esm/w/call/personal.js +1 -139
- package/dist/esm/w/call/progress.js +1 -678
- package/dist/esm/w/call/proof.js +1 -66
- package/dist/esm/w/call/repository.js +1 -1024
- package/dist/esm/w/call/resource.js +1 -108
- package/dist/esm/w/call/reward.js +1 -675
- package/dist/esm/w/call/service.js +1 -1960
- package/dist/esm/w/call/treasury.js +1 -873
- package/dist/esm/w/call/util.d.ts +1 -0
- package/dist/esm/w/call/util.js +1 -566
- package/dist/esm/w/common.js +1 -571
- package/dist/esm/w/exception.js +1 -618
- package/dist/esm/w/index.js +1 -8
- package/dist/esm/w/local/account.js +1 -656
- package/dist/esm/w/local/cache.js +1 -161
- package/dist/esm/w/local/config.js +1 -43
- package/dist/esm/w/local/index.js +1 -228
- package/dist/esm/w/local/local.js +1 -574
- package/dist/esm/w/local/storage.js +1 -185
- package/dist/esm/w/local/token.js +1 -131
- package/dist/esm/w/local/util.js +1 -26
- package/dist/esm/w/local/wip.js +1 -864
- package/dist/esm/w/messenger/crypto.js +1 -380
- package/dist/esm/w/messenger/index.js +1 -4
- package/dist/esm/w/messenger/messenger-api.js +1 -1154
- package/dist/esm/w/messenger/messenger-manager.js +1 -1003
- package/dist/esm/w/messenger/messenger.js +1 -1093
- package/dist/esm/w/messenger/server.js +1 -343
- package/dist/esm/w/messenger/session.js +1 -628
- package/dist/esm/w/messenger/storage.js +1 -1023
- package/dist/esm/w/messenger/templates/wts-html-template.js +1 -371
- package/dist/esm/w/messenger/types.js +1 -76
- package/dist/esm/w/messenger/utils.js +1 -12
- package/dist/esm/w/query/bult-in.js +1 -95
- package/dist/esm/w/query/event.js +1 -137
- package/dist/esm/w/query/index.js +1 -5
- package/dist/esm/w/query/object.js +1 -1550
- package/dist/esm/w/query/received.js +1 -62
- package/dist/esm/w/query/util.js +1 -49
- package/dist/esm/w/util.js +1 -587
- package/package.json +5 -2
|
@@ -1,1154 +1 @@
|
|
|
1
|
-
import { MessengerManager } from "./messenger-manager.js";
|
|
2
|
-
import { Account } from "../local/account.js";
|
|
3
|
-
import { W_ERROR, WErrors } from "../exception.js";
|
|
4
|
-
import { LocalMark } from "../local/local.js";
|
|
5
|
-
import { MessageStorage } from "./storage.js";
|
|
6
|
-
import { MessengerError, MessengerErrorCode, CHAIN_PROOF_TYPE, MessageDirection, } from "./types.js";
|
|
7
|
-
import { createHash } from "crypto";
|
|
8
|
-
import * as fs from "fs";
|
|
9
|
-
import * as path from "path";
|
|
10
|
-
import { isValidU64 } from "../common.js";
|
|
11
|
-
import { verifySingleMerkleRoot, hashPlaintext, verifyEd25519Signature, } from "./crypto.js";
|
|
12
|
-
import { canonicalizeJson } from "./utils.js";
|
|
13
|
-
import { generateHtmlPage, getThemeColors, } from "./templates/wts-html-template.js";
|
|
14
|
-
import { GetAccountOrMark_Address, GetManyAccountOrMark_Address, } from "../local/index.js";
|
|
15
|
-
import { query_objects } from "../query/object.js";
|
|
16
|
-
import { Messenger } from "./messenger.js";
|
|
17
|
-
let managerInstance = null;
|
|
18
|
-
let isInitialized = false;
|
|
19
|
-
let backgroundTimer = null;
|
|
20
|
-
async function autoRegisterMessengerAccounts() {
|
|
21
|
-
const accounts = await Account.Instance().list_messenger_accounts();
|
|
22
|
-
for (const account of accounts) {
|
|
23
|
-
if (!account.address || !account.m) {
|
|
24
|
-
continue;
|
|
25
|
-
}
|
|
26
|
-
try {
|
|
27
|
-
const messenger = new Messenger(account.address);
|
|
28
|
-
await messenger.initialize();
|
|
29
|
-
}
|
|
30
|
-
catch (error) {
|
|
31
|
-
console.error(`Failed to initialize account ${account.address}:`, error);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
export function getMessengerManager() {
|
|
36
|
-
if (!managerInstance) {
|
|
37
|
-
managerInstance = new MessengerManager();
|
|
38
|
-
}
|
|
39
|
-
if (!isInitialized) {
|
|
40
|
-
isInitialized = true;
|
|
41
|
-
autoRegisterMessengerAccounts().catch((err) => {
|
|
42
|
-
console.error("Failed to auto-register messenger accounts:", err);
|
|
43
|
-
});
|
|
44
|
-
managerInstance.start().catch((err) => {
|
|
45
|
-
console.error("Failed to auto-start messenger manager:", err);
|
|
46
|
-
});
|
|
47
|
-
}
|
|
48
|
-
return managerInstance;
|
|
49
|
-
}
|
|
50
|
-
function registerCleanupHandler() {
|
|
51
|
-
const cleanup = () => {
|
|
52
|
-
if (backgroundTimer) {
|
|
53
|
-
clearInterval(backgroundTimer);
|
|
54
|
-
backgroundTimer = null;
|
|
55
|
-
}
|
|
56
|
-
if (managerInstance) {
|
|
57
|
-
managerInstance.stop();
|
|
58
|
-
}
|
|
59
|
-
};
|
|
60
|
-
process.on("exit", cleanup);
|
|
61
|
-
process.on("SIGINT", () => {
|
|
62
|
-
cleanup();
|
|
63
|
-
process.exit();
|
|
64
|
-
});
|
|
65
|
-
process.on("SIGTERM", () => {
|
|
66
|
-
cleanup();
|
|
67
|
-
process.exit();
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
registerCleanupHandler();
|
|
71
|
-
export async function watch_conversations(filter) {
|
|
72
|
-
const address = await Account.Instance().get_address(filter?.account);
|
|
73
|
-
if (!address) {
|
|
74
|
-
W_ERROR(WErrors.AccountNotFound, `watch_conversations.account ${filter?.account}`);
|
|
75
|
-
}
|
|
76
|
-
const myAddress = address.toLowerCase();
|
|
77
|
-
const manager = getMessengerManager();
|
|
78
|
-
if (!isInitialized) {
|
|
79
|
-
await manager.start();
|
|
80
|
-
}
|
|
81
|
-
const accountInfo = await manager.ensureAccountReady(address);
|
|
82
|
-
await accountInfo.messenger.pullMessages();
|
|
83
|
-
const messageStorage = new MessageStorage(myAddress);
|
|
84
|
-
const allMessages = messageStorage.getAllMessages(myAddress);
|
|
85
|
-
const conversations = new Map();
|
|
86
|
-
const previewMessageCount = filter?.previewMessageCount ?? 2;
|
|
87
|
-
const skipAutoMarkViewed = filter?.skipAutoMarkViewed ?? false;
|
|
88
|
-
for (const msg of allMessages) {
|
|
89
|
-
const peerAddress = msg.fromAddress.toLowerCase() === myAddress
|
|
90
|
-
? msg.toAddress
|
|
91
|
-
: msg.fromAddress;
|
|
92
|
-
if (!conversations.has(peerAddress)) {
|
|
93
|
-
conversations.set(peerAddress, {
|
|
94
|
-
peerAddress,
|
|
95
|
-
lastMessageAt: msg.createdAt,
|
|
96
|
-
messageCount: 0,
|
|
97
|
-
unreadCount: 0,
|
|
98
|
-
lastMessagePreview: msg.plaintext,
|
|
99
|
-
messages: [],
|
|
100
|
-
});
|
|
101
|
-
}
|
|
102
|
-
const conv = conversations.get(peerAddress);
|
|
103
|
-
conv.messages.push(msg);
|
|
104
|
-
conv.messageCount++;
|
|
105
|
-
if (msg.createdAt > conv.lastMessageAt) {
|
|
106
|
-
conv.lastMessageAt = msg.createdAt;
|
|
107
|
-
conv.lastMessagePreview = msg.plaintext;
|
|
108
|
-
}
|
|
109
|
-
if (msg.direction === MessageDirection.RECEIVED &&
|
|
110
|
-
msg.viewedAt === undefined) {
|
|
111
|
-
conv.unreadCount++;
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
const result = [];
|
|
115
|
-
for (const [, conv] of conversations) {
|
|
116
|
-
if (filter?.startTime !== undefined &&
|
|
117
|
-
conv.lastMessageAt < filter.startTime) {
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
if (filter?.endTime !== undefined &&
|
|
121
|
-
conv.lastMessageAt > filter.endTime) {
|
|
122
|
-
continue;
|
|
123
|
-
}
|
|
124
|
-
if (filter?.unreadOnly && conv.unreadCount === 0) {
|
|
125
|
-
continue;
|
|
126
|
-
}
|
|
127
|
-
const previewMessages = [];
|
|
128
|
-
if (previewMessageCount > 0) {
|
|
129
|
-
const sortedMessages = conv.messages.sort((a, b) => b.createdAt - a.createdAt);
|
|
130
|
-
const selectedMessages = sortedMessages.slice(0, previewMessageCount);
|
|
131
|
-
previewMessages.push(...selectedMessages.reverse());
|
|
132
|
-
if (!skipAutoMarkViewed) {
|
|
133
|
-
const unviewedIds = selectedMessages
|
|
134
|
-
.filter((m) => m.direction === MessageDirection.RECEIVED &&
|
|
135
|
-
m.viewedAt === undefined)
|
|
136
|
-
.map((m) => m.messageId);
|
|
137
|
-
if (unviewedIds.length > 0) {
|
|
138
|
-
messageStorage.updateMessagesViewed(unviewedIds);
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
result.push({
|
|
143
|
-
peerAddress: conv.peerAddress,
|
|
144
|
-
lastMessageAt: conv.lastMessageAt,
|
|
145
|
-
messageCount: conv.messageCount,
|
|
146
|
-
unreadCount: conv.unreadCount,
|
|
147
|
-
lastMessagePreview: conv.lastMessagePreview,
|
|
148
|
-
...(previewMessageCount > 0 && { previewMessages }),
|
|
149
|
-
});
|
|
150
|
-
}
|
|
151
|
-
const sortBy = filter?.sortBy ?? "lastMessageAt";
|
|
152
|
-
const sortOrder = filter?.sortOrder ?? "desc";
|
|
153
|
-
result.sort((a, b) => {
|
|
154
|
-
let comparison = 0;
|
|
155
|
-
switch (sortBy) {
|
|
156
|
-
case "lastMessageAt":
|
|
157
|
-
comparison = a.lastMessageAt - b.lastMessageAt;
|
|
158
|
-
break;
|
|
159
|
-
case "unreadCount":
|
|
160
|
-
comparison = a.unreadCount - b.unreadCount;
|
|
161
|
-
break;
|
|
162
|
-
case "messageCount":
|
|
163
|
-
comparison = a.messageCount - b.messageCount;
|
|
164
|
-
break;
|
|
165
|
-
}
|
|
166
|
-
return sortOrder === "asc" ? comparison : -comparison;
|
|
167
|
-
});
|
|
168
|
-
return result;
|
|
169
|
-
}
|
|
170
|
-
export async function mark_messages_as_viewed(messageIds, account) {
|
|
171
|
-
if (!messageIds || messageIds.length === 0) {
|
|
172
|
-
return 0;
|
|
173
|
-
}
|
|
174
|
-
const address = await Account.Instance().get_address(account);
|
|
175
|
-
if (!address) {
|
|
176
|
-
W_ERROR(WErrors.AccountNotFound, `mark_messages_as_viewed.account ${account}`);
|
|
177
|
-
}
|
|
178
|
-
const myAddress = address.toLowerCase();
|
|
179
|
-
const messageStorage = new MessageStorage(myAddress);
|
|
180
|
-
return messageStorage.updateMessagesViewed(messageIds);
|
|
181
|
-
}
|
|
182
|
-
export async function mark_conversation_as_viewed(peerAddress, account) {
|
|
183
|
-
const address = await Account.Instance().get_address(account);
|
|
184
|
-
if (!address) {
|
|
185
|
-
W_ERROR(WErrors.AccountNotFound, `mark_conversation_as_viewed.account ${account}`);
|
|
186
|
-
}
|
|
187
|
-
const myAddress = address.toLowerCase();
|
|
188
|
-
const peerAddr = await GetAccountOrMark_Address(peerAddress);
|
|
189
|
-
if (!peerAddr) {
|
|
190
|
-
W_ERROR(WErrors.AccountNotFound, `mark_conversation_as_viewed.peerAddress ${peerAddress} is not a valid account/address`);
|
|
191
|
-
}
|
|
192
|
-
const peerAddrLower = peerAddr.toLowerCase();
|
|
193
|
-
const messageStorage = new MessageStorage(myAddress);
|
|
194
|
-
const sessionMessages = messageStorage.getMessagesBySession(myAddress, peerAddrLower);
|
|
195
|
-
const unviewedIds = sessionMessages
|
|
196
|
-
.filter((m) => m.direction === MessageDirection.RECEIVED &&
|
|
197
|
-
m.viewedAt === undefined)
|
|
198
|
-
.map((m) => m.messageId);
|
|
199
|
-
if (unviewedIds.length === 0) {
|
|
200
|
-
return 0;
|
|
201
|
-
}
|
|
202
|
-
return messageStorage.updateMessagesViewed(unviewedIds);
|
|
203
|
-
}
|
|
204
|
-
export async function send_message(from, to, content, options) {
|
|
205
|
-
const fromAddress = await Account.Instance().get_address(from);
|
|
206
|
-
if (!fromAddress) {
|
|
207
|
-
W_ERROR(WErrors.AccountNotFound, `send_message.from ${from}`);
|
|
208
|
-
}
|
|
209
|
-
const t = await GetAccountOrMark_Address(to);
|
|
210
|
-
if (!t) {
|
|
211
|
-
W_ERROR(WErrors.AccountNotFound, `send_message.to ${to} is not a valid account/address`);
|
|
212
|
-
}
|
|
213
|
-
if (options?.guardAddress != null && options?.passportAddress != null) {
|
|
214
|
-
[options.guardAddress, options.passportAddress] =
|
|
215
|
-
await LocalMark.Instance().get_many_address([
|
|
216
|
-
options.guardAddress,
|
|
217
|
-
options.passportAddress,
|
|
218
|
-
]);
|
|
219
|
-
if (!options.guardAddress || !options.passportAddress) {
|
|
220
|
-
W_ERROR(WErrors.AccountNotFound, `send_message.guardAddress or passportAddress not found`);
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
const manager = getMessengerManager();
|
|
224
|
-
if (!isInitialized) {
|
|
225
|
-
await manager.start();
|
|
226
|
-
}
|
|
227
|
-
return manager.send(fromAddress, t, content, options);
|
|
228
|
-
}
|
|
229
|
-
export async function send_file(from, to, filePath, options) {
|
|
230
|
-
const fromAddress = await Account.Instance().get_address(from);
|
|
231
|
-
if (!fromAddress) {
|
|
232
|
-
W_ERROR(WErrors.AccountNotFound, `send_file.from ${from}`);
|
|
233
|
-
}
|
|
234
|
-
const t = await GetAccountOrMark_Address(to);
|
|
235
|
-
if (!t) {
|
|
236
|
-
W_ERROR(WErrors.AccountNotFound, `send_file.to ${to} is not a valid account/address`);
|
|
237
|
-
}
|
|
238
|
-
if (options?.guardAddress != null && options?.passportAddress != null) {
|
|
239
|
-
[options.guardAddress, options.passportAddress] =
|
|
240
|
-
await LocalMark.Instance().get_many_address([
|
|
241
|
-
options.guardAddress,
|
|
242
|
-
options.passportAddress,
|
|
243
|
-
]);
|
|
244
|
-
if (!options.guardAddress || !options.passportAddress) {
|
|
245
|
-
W_ERROR(WErrors.AccountNotFound, `send_file.guardAddress or passportAddress not found`);
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
const manager = getMessengerManager();
|
|
249
|
-
if (!isInitialized) {
|
|
250
|
-
await manager.start();
|
|
251
|
-
}
|
|
252
|
-
return manager.send_file(fromAddress, t, filePath, options);
|
|
253
|
-
}
|
|
254
|
-
export async function watch_messages(filter) {
|
|
255
|
-
if (filter?.account !== undefined) {
|
|
256
|
-
filter.account = await Account.Instance().get_address(filter.account);
|
|
257
|
-
if (!filter.account) {
|
|
258
|
-
W_ERROR(WErrors.AccountNotFound, `watch_messages.account ${filter.account}`);
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
if (filter?.customListFilter?.includeAddresses != null) {
|
|
262
|
-
filter.customListFilter.includeAddresses = (await Account.Instance().get_many_address(filter.customListFilter.includeAddresses)).filter((v) => v != null);
|
|
263
|
-
}
|
|
264
|
-
if (filter?.customListFilter?.excludeAddresses != null) {
|
|
265
|
-
filter.customListFilter.excludeAddresses = (await Account.Instance().get_many_address(filter.customListFilter.excludeAddresses)).filter((v) => v != null);
|
|
266
|
-
}
|
|
267
|
-
const manager = getMessengerManager();
|
|
268
|
-
if (!isInitialized) {
|
|
269
|
-
await manager.start();
|
|
270
|
-
}
|
|
271
|
-
const messages = await manager.watch(filter);
|
|
272
|
-
const skipAutoMarkViewed = filter?.skipAutoMarkViewed ?? false;
|
|
273
|
-
if (!skipAutoMarkViewed && messages.length > 0 && filter?.account) {
|
|
274
|
-
const myAddress = filter.account.toLowerCase();
|
|
275
|
-
const messageStorage = new MessageStorage(myAddress);
|
|
276
|
-
const unviewedIds = messages
|
|
277
|
-
.filter((m) => m.direction === MessageDirection.RECEIVED &&
|
|
278
|
-
m.viewedAt === undefined)
|
|
279
|
-
.map((m) => m.messageId);
|
|
280
|
-
if (unviewedIds.length > 0) {
|
|
281
|
-
messageStorage.updateMessagesViewed(unviewedIds);
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
return messages;
|
|
285
|
-
}
|
|
286
|
-
export async function pull_messages(account, limit) {
|
|
287
|
-
const address = await Account.Instance().get_address(account);
|
|
288
|
-
if (!address) {
|
|
289
|
-
W_ERROR(WErrors.AccountNotFound, `pull_messages.account ${account}`);
|
|
290
|
-
}
|
|
291
|
-
const manager = getMessengerManager();
|
|
292
|
-
if (!isInitialized) {
|
|
293
|
-
await manager.start();
|
|
294
|
-
}
|
|
295
|
-
const accountInfo = await manager.ensureAccountReady(address);
|
|
296
|
-
const result = await accountInfo.messenger.pullMessages(limit);
|
|
297
|
-
return result.messages.map((dm) => dm);
|
|
298
|
-
}
|
|
299
|
-
async function extract_zip_message(message, outputDir) {
|
|
300
|
-
if (!message.zipMetadata) {
|
|
301
|
-
throw new MessengerError(MessengerErrorCode.INVALID_MESSAGE_TYPE, "Message is not a ZIP archive");
|
|
302
|
-
}
|
|
303
|
-
if (!message.plaintext) {
|
|
304
|
-
throw new MessengerError(MessengerErrorCode.MESSAGE_NOT_DECRYPTED, "Message plaintext not available");
|
|
305
|
-
}
|
|
306
|
-
const zipBase64 = message.plaintext;
|
|
307
|
-
const zipData = Buffer.from(zipBase64, "base64");
|
|
308
|
-
if (message.zipMetadata?.fileHash) {
|
|
309
|
-
const actualHash = createHash("sha256").update(zipData).digest("hex");
|
|
310
|
-
const expectedHash = message.zipMetadata.fileHash.replace("0x", "");
|
|
311
|
-
if (actualHash !== expectedHash) {
|
|
312
|
-
throw new MessengerError(MessengerErrorCode.HASH_MISMATCH, `ZIP file hash mismatch: expected ${expectedHash}, got ${actualHash}`);
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
const { ZipReader, BlobReader, BlobWriter } = await import("@zip.js/zip.js");
|
|
316
|
-
const zipReader = new ZipReader(new BlobReader(new Blob([zipData])));
|
|
317
|
-
const entries = await zipReader.getEntries();
|
|
318
|
-
if (!fs.existsSync(outputDir)) {
|
|
319
|
-
fs.mkdirSync(outputDir, { recursive: true });
|
|
320
|
-
}
|
|
321
|
-
const savedPaths = [];
|
|
322
|
-
for (const entry of entries) {
|
|
323
|
-
if (!entry.directory) {
|
|
324
|
-
const fileEntry = entry;
|
|
325
|
-
const writer = new BlobWriter();
|
|
326
|
-
const blob = await fileEntry.getData(writer);
|
|
327
|
-
const content = Buffer.from(await blob.arrayBuffer());
|
|
328
|
-
const outputPath = path.join(outputDir, entry.filename);
|
|
329
|
-
fs.writeFileSync(outputPath, content);
|
|
330
|
-
savedPaths.push(outputPath);
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
await zipReader.close();
|
|
334
|
-
if (savedPaths.length > 0 && message.zipMetadata) {
|
|
335
|
-
const updatedMetadata = {
|
|
336
|
-
fileName: message.zipMetadata.fileName,
|
|
337
|
-
fileSize: message.zipMetadata.fileSize,
|
|
338
|
-
fileHash: message.zipMetadata.fileHash,
|
|
339
|
-
contentType: message.zipMetadata.contentType,
|
|
340
|
-
localCachePath: savedPaths[0],
|
|
341
|
-
downloadedAt: Date.now(),
|
|
342
|
-
};
|
|
343
|
-
message.zipMetadata = updatedMetadata;
|
|
344
|
-
const userAddress = message.direction === "sent"
|
|
345
|
-
? message.fromAddress
|
|
346
|
-
: message.toAddress;
|
|
347
|
-
const messageStorage = new MessageStorage(userAddress);
|
|
348
|
-
messageStorage.saveMessage(message);
|
|
349
|
-
}
|
|
350
|
-
return savedPaths[0] || "";
|
|
351
|
-
}
|
|
352
|
-
export async function extract_zip_messages(account, messages, outputDir) {
|
|
353
|
-
const results = [];
|
|
354
|
-
const userAddress = await Account.Instance().get_address(account);
|
|
355
|
-
if (!userAddress) {
|
|
356
|
-
throw new MessengerError(MessengerErrorCode.INVALID_INPUT, "account is required when extracting by message IDs");
|
|
357
|
-
}
|
|
358
|
-
for (const item of messages) {
|
|
359
|
-
try {
|
|
360
|
-
let message;
|
|
361
|
-
if (typeof item === "string") {
|
|
362
|
-
const messageId = item;
|
|
363
|
-
const messageStorage = new MessageStorage(userAddress);
|
|
364
|
-
const storedMessage = messageStorage.getMessageById(messageId);
|
|
365
|
-
if (!storedMessage) {
|
|
366
|
-
console.error(`Message not found: ${messageId}`);
|
|
367
|
-
continue;
|
|
368
|
-
}
|
|
369
|
-
message = storedMessage;
|
|
370
|
-
}
|
|
371
|
-
else {
|
|
372
|
-
message = item;
|
|
373
|
-
}
|
|
374
|
-
if (!message.zipMetadata) {
|
|
375
|
-
console.error(`Message ${message.messageId} is not a ZIP archive`);
|
|
376
|
-
continue;
|
|
377
|
-
}
|
|
378
|
-
const filePath = await extract_zip_message(message, outputDir);
|
|
379
|
-
results.push(filePath);
|
|
380
|
-
}
|
|
381
|
-
catch (e) {
|
|
382
|
-
const id = typeof item === "string" ? item : item.messageId;
|
|
383
|
-
console.error(`Failed to extract message ${id}:`, e);
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
return results;
|
|
387
|
-
}
|
|
388
|
-
export async function generate_wts(params) {
|
|
389
|
-
const myAddress = await Account.Instance().get_address(params.myAccount);
|
|
390
|
-
if (!myAddress) {
|
|
391
|
-
W_ERROR(WErrors.AccountNotFound, `generate_wts.myAccount ${params.myAccount}`);
|
|
392
|
-
}
|
|
393
|
-
const peerAddress = await GetAccountOrMark_Address(params.peerAccount);
|
|
394
|
-
if (!peerAddress) {
|
|
395
|
-
W_ERROR(WErrors.AccountNotFound, `generate_wts.peerAccount ${params.peerAccount}`);
|
|
396
|
-
}
|
|
397
|
-
return getMessengerManager().generate_wts(params.outputDir, myAddress, peerAddress, params.range, params.excludePlaintext);
|
|
398
|
-
}
|
|
399
|
-
function load_wts(filePath) {
|
|
400
|
-
const content = fs.readFileSync(filePath, "utf-8");
|
|
401
|
-
return JSON.parse(content);
|
|
402
|
-
}
|
|
403
|
-
function save_wts(wtsFile, filePath) {
|
|
404
|
-
const dir = path.dirname(filePath);
|
|
405
|
-
if (!fs.existsSync(dir)) {
|
|
406
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
407
|
-
}
|
|
408
|
-
fs.writeFileSync(filePath, JSON.stringify(wtsFile, null, 2), "utf-8");
|
|
409
|
-
}
|
|
410
|
-
export async function verify_wts(wtsFilePath) {
|
|
411
|
-
try {
|
|
412
|
-
const wtsFile = load_wts(wtsFilePath);
|
|
413
|
-
if (!wtsFile.payload || !wtsFile.meta) {
|
|
414
|
-
return { valid: false, error: "Invalid WTS file structure" };
|
|
415
|
-
}
|
|
416
|
-
if (wtsFile.meta.type !== "wts") {
|
|
417
|
-
return {
|
|
418
|
-
valid: false,
|
|
419
|
-
error: `Invalid meta.type: ${wtsFile.meta.type}`,
|
|
420
|
-
};
|
|
421
|
-
}
|
|
422
|
-
const { payload, meta } = wtsFile;
|
|
423
|
-
const sortedMessages = [...payload.messages].sort((a, b) => {
|
|
424
|
-
if (a.leafIndex === undefined || b.leafIndex === undefined)
|
|
425
|
-
return 0;
|
|
426
|
-
return a.leafIndex - b.leafIndex;
|
|
427
|
-
});
|
|
428
|
-
for (let i = 0; i < sortedMessages.length; i++) {
|
|
429
|
-
const msg = sortedMessages[i];
|
|
430
|
-
if (!msg) {
|
|
431
|
-
return {
|
|
432
|
-
valid: false,
|
|
433
|
-
error: `Message ${i}: Message is null or undefined`,
|
|
434
|
-
};
|
|
435
|
-
}
|
|
436
|
-
if (!msg.prevRoot) {
|
|
437
|
-
return {
|
|
438
|
-
valid: false,
|
|
439
|
-
error: `Message ${i}: Missing prevRoot`,
|
|
440
|
-
};
|
|
441
|
-
}
|
|
442
|
-
if (!msg.merkleRoot) {
|
|
443
|
-
return {
|
|
444
|
-
valid: false,
|
|
445
|
-
error: `Message ${i}: Missing merkleRoot`,
|
|
446
|
-
};
|
|
447
|
-
}
|
|
448
|
-
if (!msg.plaintextHash) {
|
|
449
|
-
return {
|
|
450
|
-
valid: false,
|
|
451
|
-
error: `Message ${i}: Missing plaintextHash`,
|
|
452
|
-
};
|
|
453
|
-
}
|
|
454
|
-
if (msg.timestamp === undefined || msg.timestamp === null) {
|
|
455
|
-
return {
|
|
456
|
-
valid: false,
|
|
457
|
-
error: `Message ${i}: Missing timestamp`,
|
|
458
|
-
};
|
|
459
|
-
}
|
|
460
|
-
if (msg.leafIndex === undefined || msg.leafIndex === null) {
|
|
461
|
-
return {
|
|
462
|
-
valid: false,
|
|
463
|
-
error: `Message ${i}: Missing leafIndex`,
|
|
464
|
-
};
|
|
465
|
-
}
|
|
466
|
-
const result = verifySingleMerkleRoot(msg.prevRoot, msg.merkleRoot, msg.plaintextHash, msg.timestamp, msg.leafIndex);
|
|
467
|
-
if (!result.valid) {
|
|
468
|
-
return {
|
|
469
|
-
valid: false,
|
|
470
|
-
error: `${result.error} at message ${i}, leafIndex ${msg.leafIndex}`,
|
|
471
|
-
};
|
|
472
|
-
}
|
|
473
|
-
if (i > 0) {
|
|
474
|
-
const prevMsg = sortedMessages[i - 1];
|
|
475
|
-
if (msg.leafIndex !== prevMsg.leafIndex + 1) {
|
|
476
|
-
return {
|
|
477
|
-
valid: false,
|
|
478
|
-
error: `Merkle chain discontinuity: leafIndex ${prevMsg.leafIndex} -> ${msg.leafIndex} (expected ${prevMsg.leafIndex + 1})`,
|
|
479
|
-
};
|
|
480
|
-
}
|
|
481
|
-
if (msg.prevRoot.toLowerCase() !==
|
|
482
|
-
prevMsg.merkleRoot.toLowerCase()) {
|
|
483
|
-
return {
|
|
484
|
-
valid: false,
|
|
485
|
-
error: `Merkle root mismatch at leafIndex ${msg.leafIndex}: expected prevRoot=${prevMsg.merkleRoot}, got ${msg.prevRoot}`,
|
|
486
|
-
};
|
|
487
|
-
}
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
for (let i = 0; i < payload.messages.length; i++) {
|
|
491
|
-
const msg = payload.messages[i];
|
|
492
|
-
if (!msg) {
|
|
493
|
-
return {
|
|
494
|
-
valid: false,
|
|
495
|
-
error: `Message ${i}: Message is null or undefined`,
|
|
496
|
-
};
|
|
497
|
-
}
|
|
498
|
-
const isNonTextMsg = !!msg.zipMetadata;
|
|
499
|
-
if (!isNonTextMsg) {
|
|
500
|
-
if (!msg.plaintextHash.startsWith("0x") ||
|
|
501
|
-
msg.plaintextHash.length !== 66) {
|
|
502
|
-
return {
|
|
503
|
-
valid: false,
|
|
504
|
-
error: `Message ${i}: Invalid plaintextHash format`,
|
|
505
|
-
};
|
|
506
|
-
}
|
|
507
|
-
if (msg.plaintext) {
|
|
508
|
-
const computedHash = hashPlaintext(msg.plaintext, msg.clientTimestamp, msg.guardAddress, msg.passportAddress, msg.lastReceivedLeafIndex);
|
|
509
|
-
if (computedHash.toLowerCase() !==
|
|
510
|
-
msg.plaintextHash.toLowerCase()) {
|
|
511
|
-
return {
|
|
512
|
-
valid: false,
|
|
513
|
-
error: `Message ${i}: Plaintext hash mismatch`,
|
|
514
|
-
};
|
|
515
|
-
}
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
if (msg.serverSignature && msg.serverPublicKey) {
|
|
519
|
-
if (!msg.timestamp) {
|
|
520
|
-
return {
|
|
521
|
-
valid: false,
|
|
522
|
-
error: `Message ${i}: Missing timestamp for signature verification`,
|
|
523
|
-
};
|
|
524
|
-
}
|
|
525
|
-
if (!msg.merkleRoot) {
|
|
526
|
-
return {
|
|
527
|
-
valid: false,
|
|
528
|
-
error: `Message ${i}: Missing merkleRoot for signature verification`,
|
|
529
|
-
};
|
|
530
|
-
}
|
|
531
|
-
if (!msg.prevRoot) {
|
|
532
|
-
return {
|
|
533
|
-
valid: false,
|
|
534
|
-
error: `Message ${i}: Missing prevRoot for signature verification`,
|
|
535
|
-
};
|
|
536
|
-
}
|
|
537
|
-
const signData = `${msg.prevRoot}:${msg.merkleRoot}:${msg.timestamp}:${msg.serverPublicKey}`;
|
|
538
|
-
const signatureValid = verifyEd25519Signature(msg.serverPublicKey, signData, msg.serverSignature);
|
|
539
|
-
if (!signatureValid) {
|
|
540
|
-
return {
|
|
541
|
-
valid: false,
|
|
542
|
-
error: `Message ${i}: Server signature verification failed`,
|
|
543
|
-
};
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
const { sha256 } = await import("@noble/hashes/sha256");
|
|
548
|
-
const { bytesToHex } = await import("@noble/hashes/utils");
|
|
549
|
-
const canonicalPayload = canonicalizeJson(payload);
|
|
550
|
-
const computedHash = "sha256:" +
|
|
551
|
-
bytesToHex(sha256(new TextEncoder().encode(canonicalPayload)));
|
|
552
|
-
if (computedHash !== meta.hash) {
|
|
553
|
-
return {
|
|
554
|
-
valid: false,
|
|
555
|
-
error: "Hash mismatch - content has been tampered",
|
|
556
|
-
hashValid: false,
|
|
557
|
-
hasSignature: !!meta.signature,
|
|
558
|
-
};
|
|
559
|
-
}
|
|
560
|
-
const signatures = [];
|
|
561
|
-
let signatureValid;
|
|
562
|
-
if (meta.signature) {
|
|
563
|
-
const { Ed25519PublicKey } = await import("../../keypairs/ed25519/publickey.js");
|
|
564
|
-
const sigArray = Array.isArray(meta.signature)
|
|
565
|
-
? meta.signature
|
|
566
|
-
: [meta.signature];
|
|
567
|
-
let allValid = true;
|
|
568
|
-
for (const sig of sigArray) {
|
|
569
|
-
let pkToUse;
|
|
570
|
-
const pk = sig.publicKey;
|
|
571
|
-
if (pk.startsWith("0x")) {
|
|
572
|
-
const buffer = Buffer.from(pk.slice(2), "hex");
|
|
573
|
-
if (buffer.length === 33) {
|
|
574
|
-
pkToUse = buffer.slice(1).toString("base64");
|
|
575
|
-
}
|
|
576
|
-
else if (buffer.length === 32) {
|
|
577
|
-
pkToUse = buffer.toString("base64");
|
|
578
|
-
}
|
|
579
|
-
else {
|
|
580
|
-
let address;
|
|
581
|
-
try {
|
|
582
|
-
const pubKey = new Ed25519PublicKey(pk.slice(2));
|
|
583
|
-
address = pubKey.toWAddress();
|
|
584
|
-
}
|
|
585
|
-
catch {
|
|
586
|
-
}
|
|
587
|
-
signatures.push({
|
|
588
|
-
publicKey: pk,
|
|
589
|
-
address,
|
|
590
|
-
valid: false,
|
|
591
|
-
});
|
|
592
|
-
allValid = false;
|
|
593
|
-
continue;
|
|
594
|
-
}
|
|
595
|
-
}
|
|
596
|
-
else {
|
|
597
|
-
try {
|
|
598
|
-
const buffer = Buffer.from(pk, "base64");
|
|
599
|
-
if (buffer.length === 33) {
|
|
600
|
-
pkToUse = buffer.slice(1).toString("base64");
|
|
601
|
-
}
|
|
602
|
-
else if (buffer.length === 32) {
|
|
603
|
-
pkToUse = buffer.toString("base64");
|
|
604
|
-
}
|
|
605
|
-
else {
|
|
606
|
-
let address;
|
|
607
|
-
try {
|
|
608
|
-
const pubKey = new Ed25519PublicKey(pk);
|
|
609
|
-
address = pubKey.toWAddress();
|
|
610
|
-
}
|
|
611
|
-
catch {
|
|
612
|
-
}
|
|
613
|
-
signatures.push({
|
|
614
|
-
publicKey: pk,
|
|
615
|
-
address,
|
|
616
|
-
valid: false,
|
|
617
|
-
});
|
|
618
|
-
allValid = false;
|
|
619
|
-
continue;
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
catch {
|
|
623
|
-
pkToUse = pk;
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
try {
|
|
627
|
-
const pubKey = new Ed25519PublicKey(pkToUse);
|
|
628
|
-
const signatureBytes = Uint8Array.from(Buffer.from(sig.value, "base64"));
|
|
629
|
-
const signValid = await pubKey.verify(new TextEncoder().encode(meta.hash), signatureBytes);
|
|
630
|
-
let address;
|
|
631
|
-
try {
|
|
632
|
-
address = pubKey.toWAddress();
|
|
633
|
-
}
|
|
634
|
-
catch {
|
|
635
|
-
}
|
|
636
|
-
signatures.push({
|
|
637
|
-
publicKey: pk,
|
|
638
|
-
address,
|
|
639
|
-
valid: signValid,
|
|
640
|
-
});
|
|
641
|
-
if (!signValid) {
|
|
642
|
-
allValid = false;
|
|
643
|
-
}
|
|
644
|
-
}
|
|
645
|
-
catch {
|
|
646
|
-
let address;
|
|
647
|
-
try {
|
|
648
|
-
const pubKey = new Ed25519PublicKey(pkToUse);
|
|
649
|
-
address = pubKey.toWAddress();
|
|
650
|
-
}
|
|
651
|
-
catch {
|
|
652
|
-
}
|
|
653
|
-
signatures.push({ publicKey: pk, address, valid: false });
|
|
654
|
-
allValid = false;
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
signatureValid = allValid;
|
|
658
|
-
if (!signatureValid) {
|
|
659
|
-
const failedAddresses = signatures
|
|
660
|
-
.filter((s) => !s.valid && s.address)
|
|
661
|
-
.map((s) => s.address);
|
|
662
|
-
return {
|
|
663
|
-
valid: false,
|
|
664
|
-
error: `Signatures from the following addresses are invalid: ${failedAddresses.join(", ")}`,
|
|
665
|
-
hashValid: true,
|
|
666
|
-
hasSignature: true,
|
|
667
|
-
signatureValid: false,
|
|
668
|
-
signatures,
|
|
669
|
-
};
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
return {
|
|
673
|
-
valid: true,
|
|
674
|
-
hashValid: true,
|
|
675
|
-
hasSignature: !!meta.signature,
|
|
676
|
-
signatureValid,
|
|
677
|
-
signatures: signatures.length > 0 ? signatures : undefined,
|
|
678
|
-
};
|
|
679
|
-
}
|
|
680
|
-
catch (error) {
|
|
681
|
-
return {
|
|
682
|
-
valid: false,
|
|
683
|
-
error: `Verification error: ${error}`,
|
|
684
|
-
hashValid: false,
|
|
685
|
-
hasSignature: false,
|
|
686
|
-
};
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
export async function sign_wts(wtsFilePath, account, outputPath) {
|
|
690
|
-
const verifyResult = await verify_wts(wtsFilePath);
|
|
691
|
-
if (!verifyResult.valid) {
|
|
692
|
-
throw new MessengerError(MessengerErrorCode.INVALID_INPUT, `WTS file verification failed: ${verifyResult.error}`);
|
|
693
|
-
}
|
|
694
|
-
const wtsFile = load_wts(wtsFilePath);
|
|
695
|
-
const address = await Account.Instance().get_address(account);
|
|
696
|
-
if (!address) {
|
|
697
|
-
W_ERROR(WErrors.AccountNotFound, `sign_wts.account ${account}`);
|
|
698
|
-
}
|
|
699
|
-
const signResult = await Account.Instance().signData(address, wtsFile.meta.hash);
|
|
700
|
-
let publicKeyBase64;
|
|
701
|
-
const pk = signResult.publicKey;
|
|
702
|
-
if (pk.startsWith("0x")) {
|
|
703
|
-
const buffer = Buffer.from(pk.slice(2), "hex");
|
|
704
|
-
if (buffer.length === 33) {
|
|
705
|
-
publicKeyBase64 = buffer.slice(1).toString("base64");
|
|
706
|
-
}
|
|
707
|
-
else if (buffer.length === 32) {
|
|
708
|
-
publicKeyBase64 = buffer.toString("base64");
|
|
709
|
-
}
|
|
710
|
-
else {
|
|
711
|
-
throw new MessengerError(MessengerErrorCode.INVALID_INPUT, `Invalid public key length: ${buffer.length}, expected 32 or 33 bytes`);
|
|
712
|
-
}
|
|
713
|
-
}
|
|
714
|
-
else {
|
|
715
|
-
publicKeyBase64 = pk;
|
|
716
|
-
}
|
|
717
|
-
const newSignature = {
|
|
718
|
-
value: Buffer.from(signResult.signature.slice(2), "hex").toString("base64"),
|
|
719
|
-
publicKey: publicKeyBase64,
|
|
720
|
-
algorithm: "Ed25519",
|
|
721
|
-
address: signResult.address,
|
|
722
|
-
};
|
|
723
|
-
let signatures;
|
|
724
|
-
if (wtsFile.meta.signature) {
|
|
725
|
-
const existingSigs = Array.isArray(wtsFile.meta.signature)
|
|
726
|
-
? [...wtsFile.meta.signature]
|
|
727
|
-
: [wtsFile.meta.signature];
|
|
728
|
-
const existingIndex = existingSigs.findIndex((sig) => sig.publicKey === publicKeyBase64);
|
|
729
|
-
if (existingIndex >= 0) {
|
|
730
|
-
existingSigs[existingIndex] = newSignature;
|
|
731
|
-
signatures = existingSigs;
|
|
732
|
-
}
|
|
733
|
-
else {
|
|
734
|
-
signatures = [...existingSigs, newSignature];
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
else {
|
|
738
|
-
signatures = [newSignature];
|
|
739
|
-
}
|
|
740
|
-
const signedWtsFile = {
|
|
741
|
-
...wtsFile,
|
|
742
|
-
meta: {
|
|
743
|
-
...wtsFile.meta,
|
|
744
|
-
signature: signatures,
|
|
745
|
-
},
|
|
746
|
-
};
|
|
747
|
-
let savePath;
|
|
748
|
-
if (outputPath) {
|
|
749
|
-
savePath = outputPath;
|
|
750
|
-
}
|
|
751
|
-
else {
|
|
752
|
-
const dir = path.dirname(wtsFilePath);
|
|
753
|
-
const ext = path.extname(wtsFilePath);
|
|
754
|
-
const baseName = path.basename(wtsFilePath, ext);
|
|
755
|
-
savePath = path.join(dir, `signed_${baseName}${ext}`);
|
|
756
|
-
}
|
|
757
|
-
save_wts(signedWtsFile, savePath);
|
|
758
|
-
return savePath;
|
|
759
|
-
}
|
|
760
|
-
export async function wts2html(wtsPath, options = {}) {
|
|
761
|
-
const fs = await import("fs");
|
|
762
|
-
const path = await import("path");
|
|
763
|
-
const stats = fs.statSync(wtsPath);
|
|
764
|
-
if (stats.isDirectory()) {
|
|
765
|
-
const files = fs.readdirSync(wtsPath);
|
|
766
|
-
const wtsFiles = files.filter((f) => f.endsWith(".wts"));
|
|
767
|
-
if (wtsFiles.length === 0) {
|
|
768
|
-
throw new MessengerError(MessengerErrorCode.INVALID_INPUT, `No .wts files found in directory: ${wtsPath}`);
|
|
769
|
-
}
|
|
770
|
-
const results = [];
|
|
771
|
-
for (const file of wtsFiles) {
|
|
772
|
-
const filePath = path.join(wtsPath, file);
|
|
773
|
-
const html = await convertWtsToHtml(filePath, options);
|
|
774
|
-
const outputFileName = file.replace(".wts", ".html");
|
|
775
|
-
const outputFilePath = options.outputPath
|
|
776
|
-
? path.join(options.outputPath, outputFileName)
|
|
777
|
-
: path.join(wtsPath, outputFileName);
|
|
778
|
-
const outputDir = path.dirname(outputFilePath);
|
|
779
|
-
if (!fs.existsSync(outputDir)) {
|
|
780
|
-
fs.mkdirSync(outputDir, { recursive: true });
|
|
781
|
-
}
|
|
782
|
-
fs.writeFileSync(outputFilePath, html, "utf-8");
|
|
783
|
-
results.push(outputFilePath);
|
|
784
|
-
}
|
|
785
|
-
return results;
|
|
786
|
-
}
|
|
787
|
-
const html = await convertWtsToHtml(wtsPath, options);
|
|
788
|
-
if (options.outputPath) {
|
|
789
|
-
const outputFileName = path.basename(wtsPath).replace(".wts", ".html");
|
|
790
|
-
const outputFilePath = path.join(options.outputPath, outputFileName);
|
|
791
|
-
const outputDir = path.dirname(outputFilePath);
|
|
792
|
-
if (!fs.existsSync(outputDir)) {
|
|
793
|
-
fs.mkdirSync(outputDir, { recursive: true });
|
|
794
|
-
}
|
|
795
|
-
fs.writeFileSync(outputFilePath, html, "utf-8");
|
|
796
|
-
return outputFilePath;
|
|
797
|
-
}
|
|
798
|
-
return html;
|
|
799
|
-
}
|
|
800
|
-
async function convertWtsToHtml(wtsFilePath, options = {}) {
|
|
801
|
-
const { title = "WTS Document", theme = "light" } = options;
|
|
802
|
-
const verifyResult = await verify_wts(wtsFilePath);
|
|
803
|
-
const wtsFile = load_wts(wtsFilePath);
|
|
804
|
-
const { payload, meta } = wtsFile;
|
|
805
|
-
const { bgColor, textColor, borderColor } = getThemeColors(theme);
|
|
806
|
-
const myAddress = meta.creator;
|
|
807
|
-
let maxLastReceivedLeafIndex = -1;
|
|
808
|
-
for (const msg of payload.messages) {
|
|
809
|
-
if (msg.to.toLowerCase() === myAddress.toLowerCase()) {
|
|
810
|
-
if (msg.lastReceivedLeafIndex !== undefined &&
|
|
811
|
-
msg.lastReceivedLeafIndex >= 0) {
|
|
812
|
-
if (msg.lastReceivedLeafIndex > maxLastReceivedLeafIndex) {
|
|
813
|
-
maxLastReceivedLeafIndex = msg.lastReceivedLeafIndex;
|
|
814
|
-
}
|
|
815
|
-
}
|
|
816
|
-
}
|
|
817
|
-
}
|
|
818
|
-
return generateHtmlPage({
|
|
819
|
-
title,
|
|
820
|
-
theme,
|
|
821
|
-
bgColor,
|
|
822
|
-
textColor,
|
|
823
|
-
borderColor,
|
|
824
|
-
meta,
|
|
825
|
-
payload,
|
|
826
|
-
verifyResult,
|
|
827
|
-
maxLastReceivedLeafIndex,
|
|
828
|
-
myAddress,
|
|
829
|
-
});
|
|
830
|
-
}
|
|
831
|
-
export async function proof_message(account, messageId, network) {
|
|
832
|
-
const address = await Account.Instance().get_address(account);
|
|
833
|
-
if (!address) {
|
|
834
|
-
W_ERROR(WErrors.AccountNotFound, `proof_message.account ${account}`);
|
|
835
|
-
}
|
|
836
|
-
const messageStorage = new MessageStorage(address);
|
|
837
|
-
const message = messageStorage.getMessageById(messageId);
|
|
838
|
-
if (!message) {
|
|
839
|
-
throw new MessengerError(MessengerErrorCode.INVALID_INPUT, `Message not found: ${messageId}`);
|
|
840
|
-
}
|
|
841
|
-
if (message.fromAddress.toLowerCase() !== address.toLowerCase() &&
|
|
842
|
-
message.toAddress.toLowerCase() !== address.toLowerCase()) {
|
|
843
|
-
throw new MessengerError(MessengerErrorCode.INVALID_INPUT, `Message does not belong to account ${address}`);
|
|
844
|
-
}
|
|
845
|
-
if (!message.serverSignature) {
|
|
846
|
-
throw new MessengerError(MessengerErrorCode.INVALID_PROOF, `Message does not have server signature`);
|
|
847
|
-
}
|
|
848
|
-
if (!message.serverPublicKey) {
|
|
849
|
-
throw new MessengerError(MessengerErrorCode.INVALID_PROOF, `Message does not have server public key`);
|
|
850
|
-
}
|
|
851
|
-
if (!message.plaintext) {
|
|
852
|
-
throw new MessengerError(MessengerErrorCode.INVALID_PROOF, `Message does not have plaintext`);
|
|
853
|
-
}
|
|
854
|
-
const { verifyMessage } = await import("./crypto.js");
|
|
855
|
-
const verifyParams = {
|
|
856
|
-
messageId: message.messageId,
|
|
857
|
-
plaintext: message.plaintext,
|
|
858
|
-
plaintextHash: message.plaintextHash,
|
|
859
|
-
createdAt: message.createdAt,
|
|
860
|
-
guardAddress: message.guardAddress,
|
|
861
|
-
passportAddress: message.passportAddress,
|
|
862
|
-
lastReceivedLeafIndex: message.lastReceivedLeafIndex,
|
|
863
|
-
serverSignature: message.serverSignature,
|
|
864
|
-
serverPublicKey: message.serverPublicKey,
|
|
865
|
-
};
|
|
866
|
-
if (message.newRoot && message.leafIndex !== undefined) {
|
|
867
|
-
if (!message.serverTimestamp) {
|
|
868
|
-
throw new MessengerError(MessengerErrorCode.INVALID_PROOF, `Message ${message.messageId} missing server timestamp for verification`);
|
|
869
|
-
}
|
|
870
|
-
verifyParams.merkleMetadata = {
|
|
871
|
-
newRoot: message.newRoot,
|
|
872
|
-
prevRoot: message.prevRoot,
|
|
873
|
-
leafIndex: message.leafIndex,
|
|
874
|
-
serverTimestamp: message.serverTimestamp,
|
|
875
|
-
};
|
|
876
|
-
}
|
|
877
|
-
const verifyResult = verifyMessage(verifyParams);
|
|
878
|
-
if (!verifyResult.valid) {
|
|
879
|
-
throw new MessengerError(MessengerErrorCode.INVALID_PROOF, `Message verification failed: ${verifyResult.error}`);
|
|
880
|
-
}
|
|
881
|
-
if (!message.serverPublicKey) {
|
|
882
|
-
throw new MessengerError(MessengerErrorCode.INVALID_PROOF, `Message does not have server public key`);
|
|
883
|
-
}
|
|
884
|
-
const { CallProof } = await import("../call/proof.js");
|
|
885
|
-
const callProof = new CallProof({
|
|
886
|
-
proof: message.newRoot,
|
|
887
|
-
server_pubkey: message.serverPublicKey,
|
|
888
|
-
server_signature: message.serverSignature,
|
|
889
|
-
proof_type: CHAIN_PROOF_TYPE,
|
|
890
|
-
description: `Message proof for ${messageId}`,
|
|
891
|
-
item_count: message.leafIndex ?? 1,
|
|
892
|
-
about_address: message.fromAddress.toLowerCase() === address.toLowerCase()
|
|
893
|
-
? message.toAddress
|
|
894
|
-
: message.fromAddress,
|
|
895
|
-
});
|
|
896
|
-
const env = {
|
|
897
|
-
network,
|
|
898
|
-
account: address,
|
|
899
|
-
};
|
|
900
|
-
const result = await callProof.call(env);
|
|
901
|
-
const { ResponseData: extractResponseData } = await import("../call/base.js");
|
|
902
|
-
const responseData = extractResponseData(result);
|
|
903
|
-
const proofResult = responseData.find((item) => item.type === "Proof");
|
|
904
|
-
if (!proofResult || !proofResult.object) {
|
|
905
|
-
throw new MessengerError(MessengerErrorCode.INVALID_PROOF, `Failed to get proof address from transaction result`);
|
|
906
|
-
}
|
|
907
|
-
message.proof = proofResult.object;
|
|
908
|
-
messageStorage.saveMessage(message);
|
|
909
|
-
return { proofAddress: proofResult.object };
|
|
910
|
-
}
|
|
911
|
-
const MIN_PASSPORT_VALIDITY = 10;
|
|
912
|
-
const MAX_PASSPORT_VALIDITY = 10 * 365 * 24 * 60 * 60;
|
|
913
|
-
const MAX_BLACKLIST_SIZE_ONCE = 100;
|
|
914
|
-
const MAX_FRIENDS_SIZE_ONCE = 100;
|
|
915
|
-
const MAX_GUARDS_SIZE_ONCE = 10;
|
|
916
|
-
export async function blacklist(request) {
|
|
917
|
-
const acc = await Account.Instance().get_address(request.account);
|
|
918
|
-
if (!acc) {
|
|
919
|
-
W_ERROR(WErrors.AccountNotFound, `blacklist.account ${request.account}`);
|
|
920
|
-
}
|
|
921
|
-
const manager = getMessengerManager();
|
|
922
|
-
if (!isInitialized) {
|
|
923
|
-
await manager.start();
|
|
924
|
-
}
|
|
925
|
-
await manager.ensureAccountReady(acc);
|
|
926
|
-
switch (request.op) {
|
|
927
|
-
case "add": {
|
|
928
|
-
let addresses = await GetManyAccountOrMark_Address(request.users);
|
|
929
|
-
if (addresses.length === 0) {
|
|
930
|
-
W_ERROR(WErrors.InvalidParam, `blacklist.add.users ${request.users} have not valid addresses`);
|
|
931
|
-
}
|
|
932
|
-
addresses = [...new Set(addresses.map((a) => a.toLowerCase()))];
|
|
933
|
-
if (addresses.length > MAX_BLACKLIST_SIZE_ONCE) {
|
|
934
|
-
W_ERROR(WErrors.InvalidParam, `blacklist.add.users ${request.users} have too many addresses, max ${MAX_BLACKLIST_SIZE_ONCE}`);
|
|
935
|
-
}
|
|
936
|
-
const result = await manager.addToBlacklist(acc, addresses);
|
|
937
|
-
return { op: "add", result };
|
|
938
|
-
}
|
|
939
|
-
case "remove": {
|
|
940
|
-
let addresses = await GetManyAccountOrMark_Address(request.users);
|
|
941
|
-
if (addresses.length === 0) {
|
|
942
|
-
W_ERROR(WErrors.InvalidParam, `blacklist.remove.users ${request.users} have not valid addresses`);
|
|
943
|
-
}
|
|
944
|
-
addresses = [...new Set(addresses.map((a) => a.toLowerCase()))];
|
|
945
|
-
if (addresses.length > MAX_BLACKLIST_SIZE_ONCE) {
|
|
946
|
-
W_ERROR(WErrors.InvalidParam, `blacklist.remove.users ${request.users} have too many addresses, max ${MAX_BLACKLIST_SIZE_ONCE}`);
|
|
947
|
-
}
|
|
948
|
-
const result = await manager.removeFromBlacklist(acc, addresses);
|
|
949
|
-
return { op: "remove", result };
|
|
950
|
-
}
|
|
951
|
-
case "clear": {
|
|
952
|
-
const result = await manager.clearBlacklist(acc);
|
|
953
|
-
return { op: "clear", result };
|
|
954
|
-
}
|
|
955
|
-
case "get": {
|
|
956
|
-
const result = await manager.getBlacklist(acc);
|
|
957
|
-
return { op: "get", result };
|
|
958
|
-
}
|
|
959
|
-
case "exist": {
|
|
960
|
-
let addresses = await GetManyAccountOrMark_Address(request.users);
|
|
961
|
-
if (addresses.length === 0) {
|
|
962
|
-
W_ERROR(WErrors.InvalidParam, `blacklist.exist.users ${request.users} have not valid addresses`);
|
|
963
|
-
}
|
|
964
|
-
addresses = [...new Set(addresses.map((a) => a.toLowerCase()))];
|
|
965
|
-
if (addresses.length > MAX_BLACKLIST_SIZE_ONCE) {
|
|
966
|
-
W_ERROR(WErrors.InvalidParam, `blacklist.exist.users ${request.users} have too many addresses, max ${MAX_BLACKLIST_SIZE_ONCE}`);
|
|
967
|
-
}
|
|
968
|
-
const result = await manager.existInBlacklist(acc, addresses);
|
|
969
|
-
return { op: "exist", result };
|
|
970
|
-
}
|
|
971
|
-
default:
|
|
972
|
-
throw new MessengerError(MessengerErrorCode.INVALID_INPUT, `blacklist.unknown op: ${request}`);
|
|
973
|
-
}
|
|
974
|
-
}
|
|
975
|
-
export async function friendslist(request) {
|
|
976
|
-
const acc = await Account.Instance().get_address(request.account);
|
|
977
|
-
if (!acc) {
|
|
978
|
-
W_ERROR(WErrors.AccountNotFound, `friendslist.account ${request.account}`);
|
|
979
|
-
}
|
|
980
|
-
const manager = getMessengerManager();
|
|
981
|
-
if (!isInitialized) {
|
|
982
|
-
await manager.start();
|
|
983
|
-
}
|
|
984
|
-
await manager.ensureAccountReady(acc);
|
|
985
|
-
switch (request.op) {
|
|
986
|
-
case "add": {
|
|
987
|
-
let addresses = await GetManyAccountOrMark_Address(request.users);
|
|
988
|
-
if (addresses.length === 0) {
|
|
989
|
-
W_ERROR(WErrors.InvalidParam, `friendslist.add.users ${request.users} have not valid addresses`);
|
|
990
|
-
}
|
|
991
|
-
addresses = [...new Set(addresses.map((a) => a.toLowerCase()))];
|
|
992
|
-
const result = await manager.addToFriendsList(acc, addresses);
|
|
993
|
-
return { op: "add", result };
|
|
994
|
-
}
|
|
995
|
-
case "remove": {
|
|
996
|
-
let addresses = await GetManyAccountOrMark_Address(request.users);
|
|
997
|
-
if (addresses.length === 0) {
|
|
998
|
-
W_ERROR(WErrors.InvalidParam, `friendslist.remove.users ${request.users} have not valid addresses`);
|
|
999
|
-
}
|
|
1000
|
-
addresses = [...new Set(addresses.map((a) => a.toLowerCase()))];
|
|
1001
|
-
if (addresses.length > MAX_FRIENDS_SIZE_ONCE) {
|
|
1002
|
-
W_ERROR(WErrors.InvalidParam, `friendslist.remove.users ${request.users} have too many addresses, max ${MAX_FRIENDS_SIZE_ONCE}`);
|
|
1003
|
-
}
|
|
1004
|
-
const result = await manager.removeFromFriendsList(acc, addresses);
|
|
1005
|
-
return { op: "remove", result };
|
|
1006
|
-
}
|
|
1007
|
-
case "clear": {
|
|
1008
|
-
const result = await manager.clearFriendsList(acc);
|
|
1009
|
-
return { op: "clear", result };
|
|
1010
|
-
}
|
|
1011
|
-
case "get": {
|
|
1012
|
-
const result = await manager.getFriendsList(acc);
|
|
1013
|
-
return { op: "get", result };
|
|
1014
|
-
}
|
|
1015
|
-
case "exist": {
|
|
1016
|
-
let addresses = await GetManyAccountOrMark_Address(request.users);
|
|
1017
|
-
if (addresses.length === 0) {
|
|
1018
|
-
W_ERROR(WErrors.InvalidParam, `friendslist.exist.users ${request.users} have not valid addresses`);
|
|
1019
|
-
}
|
|
1020
|
-
addresses = [...new Set(addresses.map((a) => a.toLowerCase()))];
|
|
1021
|
-
if (addresses.length > MAX_FRIENDS_SIZE_ONCE) {
|
|
1022
|
-
W_ERROR(WErrors.InvalidParam, `friendslist.exist.users ${request.users} have too many addresses, max ${MAX_FRIENDS_SIZE_ONCE}`);
|
|
1023
|
-
}
|
|
1024
|
-
const result = await manager.existInFriendsList(acc, addresses);
|
|
1025
|
-
return { op: "exist", result };
|
|
1026
|
-
}
|
|
1027
|
-
default:
|
|
1028
|
-
throw new MessengerError(MessengerErrorCode.INVALID_INPUT, `friendslist.unknown op: ${request}`);
|
|
1029
|
-
}
|
|
1030
|
-
}
|
|
1031
|
-
export async function guardlist(request) {
|
|
1032
|
-
const acc = await Account.Instance().get_address(request.account);
|
|
1033
|
-
if (!acc) {
|
|
1034
|
-
W_ERROR(WErrors.AccountNotFound, `guardlist.account ${request.account}`);
|
|
1035
|
-
}
|
|
1036
|
-
const manager = getMessengerManager();
|
|
1037
|
-
if (!isInitialized) {
|
|
1038
|
-
await manager.start();
|
|
1039
|
-
}
|
|
1040
|
-
await manager.ensureAccountReady(acc);
|
|
1041
|
-
switch (request.op) {
|
|
1042
|
-
case "add": {
|
|
1043
|
-
const uniqueGuardsMap = new Map();
|
|
1044
|
-
for (const g of request.guards) {
|
|
1045
|
-
uniqueGuardsMap.set(g.guard.toLowerCase(), g);
|
|
1046
|
-
}
|
|
1047
|
-
const guards = Array.from(uniqueGuardsMap.values());
|
|
1048
|
-
if (guards.length === 0) {
|
|
1049
|
-
W_ERROR(WErrors.InvalidParam, `guardlist.add.guards ${request.guards} have not valid guards`);
|
|
1050
|
-
}
|
|
1051
|
-
if (guards.length > MAX_GUARDS_SIZE_ONCE) {
|
|
1052
|
-
W_ERROR(WErrors.InvalidParam, `guardlist.add.guards ${request.guards} have too many guards, max ${MAX_GUARDS_SIZE_ONCE}`);
|
|
1053
|
-
}
|
|
1054
|
-
for (const g of guards) {
|
|
1055
|
-
if (!isValidU64(g.passportValiditySeconds) ||
|
|
1056
|
-
g.passportValiditySeconds < MIN_PASSPORT_VALIDITY ||
|
|
1057
|
-
g.passportValiditySeconds > MAX_PASSPORT_VALIDITY) {
|
|
1058
|
-
W_ERROR(WErrors.InvalidParam, `Guard ${g.guard}: passport validity ${g.passportValiditySeconds} must be between ${MIN_PASSPORT_VALIDITY} and ${MAX_PASSPORT_VALIDITY} seconds`);
|
|
1059
|
-
}
|
|
1060
|
-
}
|
|
1061
|
-
const addresses = await LocalMark.Instance().get_many_address(guards.map((g) => g.guard));
|
|
1062
|
-
if (addresses.length !== guards.length) {
|
|
1063
|
-
const foundAddresses = new Set(addresses);
|
|
1064
|
-
const missingGuards = [];
|
|
1065
|
-
for (const g of guards) {
|
|
1066
|
-
if (!foundAddresses.has(g.guard) &&
|
|
1067
|
-
!g.guard.startsWith("0x")) {
|
|
1068
|
-
missingGuards.push(g.guard);
|
|
1069
|
-
}
|
|
1070
|
-
}
|
|
1071
|
-
W_ERROR(WErrors.InvalidParam, `Guard not found: ${missingGuards.join(", ")}`);
|
|
1072
|
-
}
|
|
1073
|
-
const objs = await query_objects({
|
|
1074
|
-
objects: addresses,
|
|
1075
|
-
no_cache: false,
|
|
1076
|
-
network: manager.getConfig().network,
|
|
1077
|
-
});
|
|
1078
|
-
if (!objs || !objs.objects || objs.objects.length === 0) {
|
|
1079
|
-
W_ERROR(WErrors.InvalidParam, `Guard not found: ${guards.map((g) => g.guard).join(", ")}`);
|
|
1080
|
-
}
|
|
1081
|
-
objs.objects.forEach((obj) => {
|
|
1082
|
-
if (obj.type !== "Guard") {
|
|
1083
|
-
W_ERROR(WErrors.InvalidParam, `Guard ${obj.object} is not a Guard`);
|
|
1084
|
-
}
|
|
1085
|
-
});
|
|
1086
|
-
const guardListItems = guards.map((g, index) => ({
|
|
1087
|
-
guardAddress: addresses[index],
|
|
1088
|
-
passportValiditySeconds: g.passportValiditySeconds,
|
|
1089
|
-
}));
|
|
1090
|
-
const result = await manager.addToGuardList(acc, guardListItems);
|
|
1091
|
-
return { op: "add", result };
|
|
1092
|
-
}
|
|
1093
|
-
case "remove": {
|
|
1094
|
-
const guards = [
|
|
1095
|
-
...new Set(request.guards.map((g) => g.toLowerCase())),
|
|
1096
|
-
];
|
|
1097
|
-
if (guards.length === 0) {
|
|
1098
|
-
W_ERROR(WErrors.InvalidParam, `guardlist.remove.guards ${request.guards} have not valid guards`);
|
|
1099
|
-
}
|
|
1100
|
-
if (guards.length > MAX_GUARDS_SIZE_ONCE) {
|
|
1101
|
-
W_ERROR(WErrors.InvalidParam, `guardlist.remove.guards ${request.guards} have too many guards, max ${MAX_GUARDS_SIZE_ONCE}`);
|
|
1102
|
-
}
|
|
1103
|
-
const addresses = await LocalMark.Instance().get_many_address(guards);
|
|
1104
|
-
if (addresses.length !== guards.length) {
|
|
1105
|
-
const foundAddresses = new Set(addresses);
|
|
1106
|
-
const missingGuards = [];
|
|
1107
|
-
for (const g of guards) {
|
|
1108
|
-
if (!foundAddresses.has(g) && !g.startsWith("0x")) {
|
|
1109
|
-
missingGuards.push(g);
|
|
1110
|
-
}
|
|
1111
|
-
}
|
|
1112
|
-
W_ERROR(WErrors.InvalidParam, `Guard not found: ${missingGuards.join(", ")}`);
|
|
1113
|
-
}
|
|
1114
|
-
const result = await manager.removeFromGuardList(acc, addresses);
|
|
1115
|
-
return { op: "remove", result };
|
|
1116
|
-
}
|
|
1117
|
-
case "get": {
|
|
1118
|
-
const result = await manager.getGuardList(acc);
|
|
1119
|
-
return { op: "get", result };
|
|
1120
|
-
}
|
|
1121
|
-
default:
|
|
1122
|
-
throw new MessengerError(MessengerErrorCode.INVALID_INPUT, `guardlist.unknown op: ${request}`);
|
|
1123
|
-
}
|
|
1124
|
-
}
|
|
1125
|
-
export async function settings(request) {
|
|
1126
|
-
const acc = await Account.Instance().get_address(request.account);
|
|
1127
|
-
if (!acc) {
|
|
1128
|
-
W_ERROR(WErrors.AccountNotFound, `settings.account ${request.account}`);
|
|
1129
|
-
}
|
|
1130
|
-
const manager = getMessengerManager();
|
|
1131
|
-
if (!isInitialized) {
|
|
1132
|
-
await manager.start();
|
|
1133
|
-
}
|
|
1134
|
-
await manager.ensureAccountReady(acc);
|
|
1135
|
-
switch (request.op) {
|
|
1136
|
-
case "get": {
|
|
1137
|
-
const result = await manager.getSettings(acc);
|
|
1138
|
-
return { op: "get", result };
|
|
1139
|
-
}
|
|
1140
|
-
case "set": {
|
|
1141
|
-
const settings = {};
|
|
1142
|
-
if (request.allowStrangerMessages !== undefined) {
|
|
1143
|
-
settings.allowStrangerMessages = request.allowStrangerMessages;
|
|
1144
|
-
}
|
|
1145
|
-
if (request.maxInboxSize !== undefined) {
|
|
1146
|
-
settings.maxInboxSize = request.maxInboxSize;
|
|
1147
|
-
}
|
|
1148
|
-
const result = await manager.setSettings(acc, settings);
|
|
1149
|
-
return { op: "set", result };
|
|
1150
|
-
}
|
|
1151
|
-
default:
|
|
1152
|
-
throw new MessengerError(MessengerErrorCode.INVALID_INPUT, `settings.unknown op: ${request}`);
|
|
1153
|
-
}
|
|
1154
|
-
}
|
|
1
|
+
import{MessengerManager}from'./messenger-manager.js';import{Account}from'../local/account.js';import{W_ERROR,WErrors}from'../exception.js';import{LocalMark}from'../local/local.js';import{MessageStorage}from'./storage.js';import{MessengerError,MessengerErrorCode,CHAIN_PROOF_TYPE,MessageDirection}from'./types.js';import{createHash}from'crypto';import*as a181a from'fs';import*as a181b from'path';import{isValidU64}from'../common.js';import{verifySingleMerkleRoot,hashPlaintext,verifyEd25519Signature}from'./crypto.js';import{canonicalizeJson}from'./utils.js';import{generateHtmlPage,getThemeColors}from'./templates/wts-html-template.js';import{GetAccountOrMark_Address,GetManyAccountOrMark_Address}from'../local/index.js';import{query_objects}from'../query/object.js';import{Messenger}from'./messenger.js';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['m'])continue;try{const c=new Messenger(b['address']);await c['initialize']();}catch(d){console['error']('Failed\x20to\x20initialize\x20account\x20'+b['address']+':',d);}}}export function getMessengerManager(){return!managerInstance&&(managerInstance=new MessengerManager()),!isInitialized&&(isInitialized=!![],autoRegisterMessengerAccounts()['catch'](a=>{console['error']('Failed\x20to\x20auto-register\x20messenger\x20accounts:',a);}),managerInstance['start']()['catch'](a=>{console['error']('Failed\x20to\x20auto-start\x20messenger\x20manager:',a);})),managerInstance;}function registerCleanupHandler(){const a=()=>{backgroundTimer&&(clearInterval(backgroundTimer),backgroundTimer=null),managerInstance&&managerInstance['stop']();};process['on']('exit',a),process['on']('SIGINT',()=>{a(),process['exit']();}),process['on']('SIGTERM',()=>{a(),process['exit']();});}registerCleanupHandler();export async function watch_conversations(a){const b=await Account['Instance']()['get_address'](a?.['account']);!b&&W_ERROR(WErrors['AccountNotFound'],'watch_conversations.account\x20'+a?.['account']);const c=b['toLowerCase'](),d=getMessengerManager();!isInitialized&&await d['start']();const e=await d['ensureAccountReady'](b);await e['messenger']['pullMessages']();const f=new MessageStorage(c),g=f['getAllMessages'](c),h=new Map(),i=a?.['previewMessageCount']??0x2,j=a?.['skipAutoMarkViewed']??![];for(const n of g){const o=n['fromAddress']['toLowerCase']()===c?n['toAddress']:n['fromAddress'];!h['has'](o)&&h['set'](o,{'peerAddress':o,'lastMessageAt':n['createdAt'],'messageCount':0x0,'unreadCount':0x0,'lastMessagePreview':n['plaintext'],'messages':[]});const p=h['get'](o);p['messages']['push'](n),p['messageCount']++,n['createdAt']>p['lastMessageAt']&&(p['lastMessageAt']=n['createdAt'],p['lastMessagePreview']=n['plaintext']),n['direction']===MessageDirection['RECEIVED']&&n['viewedAt']===undefined&&p['unreadCount']++;}const k=[];for(const [,q]of h){if(a?.['startTime']!==undefined&&q['lastMessageAt']<a['startTime'])continue;if(a?.['endTime']!==undefined&&q['lastMessageAt']>a['endTime'])continue;if(a?.['unreadOnly']&&q['unreadCount']===0x0)continue;const r=[];if(i>0x0){const s=q['messages']['sort']((u,v)=>v['createdAt']-u['createdAt']),t=s['slice'](0x0,i);r['push'](...t['reverse']());if(!j){const u=t['filter'](v=>v['direction']===MessageDirection['RECEIVED']&&v['viewedAt']===undefined)['map'](v=>v['messageId']);u['length']>0x0&&f['updateMessagesViewed'](u);}}k['push']({'peerAddress':q['peerAddress'],'lastMessageAt':q['lastMessageAt'],'messageCount':q['messageCount'],'unreadCount':q['unreadCount'],'lastMessagePreview':q['lastMessagePreview'],...i>0x0&&{'previewMessages':r}});}const l=a?.['sortBy']??'lastMessageAt',m=a?.['sortOrder']??'desc';return k['sort']((v,w)=>{let x=0x0;switch(l){case'lastMessageAt':x=v['lastMessageAt']-w['lastMessageAt'];break;case'unreadCount':x=v['unreadCount']-w['unreadCount'];break;case'messageCount':x=v['messageCount']-w['messageCount'];break;}return m==='asc'?x:-x;}),k;}export async function mark_messages_as_viewed(a,b){if(!a||a['length']===0x0)return 0x0;const c=await Account['Instance']()['get_address'](b);!c&&W_ERROR(WErrors['AccountNotFound'],'mark_messages_as_viewed.account\x20'+b);const d=c['toLowerCase'](),e=new MessageStorage(d);return e['updateMessagesViewed'](a);}export async function mark_conversation_as_viewed(a,b){const c=await Account['Instance']()['get_address'](b);!c&&W_ERROR(WErrors['AccountNotFound'],'mark_conversation_as_viewed.account\x20'+b);const d=c['toLowerCase'](),e=await GetAccountOrMark_Address(a);!e&&W_ERROR(WErrors['AccountNotFound'],'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),i=h['filter'](j=>j['direction']===MessageDirection['RECEIVED']&&j['viewedAt']===undefined)['map'](j=>j['messageId']);if(i['length']===0x0)return 0x0;return g['updateMessagesViewed'](i);}export async function send_message(a,b,c,d){const e=await Account['Instance']()['get_address'](a);!e&&W_ERROR(WErrors['AccountNotFound'],'send_message.from\x20'+a);const f=await GetAccountOrMark_Address(b);!f&&W_ERROR(WErrors['AccountNotFound'],'send_message.to\x20'+b+'\x20is\x20not\x20a\x20valid\x20account/address');d?.['guardAddress']!=null&&d?.['passportAddress']!=null&&([d['guardAddress'],d['passportAddress']]=await LocalMark['Instance']()['get_many_address']([d['guardAddress'],d['passportAddress']]),(!d['guardAddress']||!d['passportAddress'])&&W_ERROR(WErrors['AccountNotFound'],'send_message.guardAddress\x20or\x20passportAddress\x20not\x20found'));const g=getMessengerManager();return!isInitialized&&await g['start'](),g['send'](e,f,c,d);}export async function send_file(a,b,c,d){const e=await Account['Instance']()['get_address'](a);!e&&W_ERROR(WErrors['AccountNotFound'],'send_file.from\x20'+a);const f=await GetAccountOrMark_Address(b);!f&&W_ERROR(WErrors['AccountNotFound'],'send_file.to\x20'+b+'\x20is\x20not\x20a\x20valid\x20account/address');d?.['guardAddress']!=null&&d?.['passportAddress']!=null&&([d['guardAddress'],d['passportAddress']]=await LocalMark['Instance']()['get_many_address']([d['guardAddress'],d['passportAddress']]),(!d['guardAddress']||!d['passportAddress'])&&W_ERROR(WErrors['AccountNotFound'],'send_file.guardAddress\x20or\x20passportAddress\x20not\x20found'));const g=getMessengerManager();return!isInitialized&&await g['start'](),g['send_file'](e,f,c,d);}export async function watch_messages(a){a?.['account']!==undefined&&(a['account']=await Account['Instance']()['get_address'](a['account']),!a['account']&&W_ERROR(WErrors['AccountNotFound'],'watch_messages.account\x20'+a['account']));a?.['customListFilter']?.['includeAddresses']!=null&&(a['customListFilter']['includeAddresses']=(await Account['Instance']()['get_many_address'](a['customListFilter']['includeAddresses']))['filter'](e=>e!=null));a?.['customListFilter']?.['excludeAddresses']!=null&&(a['customListFilter']['excludeAddresses']=(await Account['Instance']()['get_many_address'](a['customListFilter']['excludeAddresses']))['filter'](e=>e!=null));const b=getMessengerManager();!isInitialized&&await b['start']();const c=await b['watch'](a),d=a?.['skipAutoMarkViewed']??![];if(!d&&c['length']>0x0&&a?.['account']){const e=a['account']['toLowerCase'](),f=new MessageStorage(e),g=c['filter'](h=>h['direction']===MessageDirection['RECEIVED']&&h['viewedAt']===undefined)['map'](h=>h['messageId']);g['length']>0x0&&f['updateMessagesViewed'](g);}return c;}export async function pull_messages(a,b){const c=await Account['Instance']()['get_address'](a);!c&&W_ERROR(WErrors['AccountNotFound'],'pull_messages.account\x20'+a);const d=getMessengerManager();!isInitialized&&await d['start']();const e=await d['ensureAccountReady'](c),f=await e['messenger']['pullMessages'](b);return f['messages']['map'](g=>g);}async function extract_zip_message(a,b){if(!a['zipMetadata'])throw new MessengerError(MessengerErrorCode['INVALID_MESSAGE_TYPE'],'Message\x20is\x20not\x20a\x20ZIP\x20archive');if(!a['plaintext'])throw new MessengerError(MessengerErrorCode['MESSAGE_NOT_DECRYPTED'],'Message\x20plaintext\x20not\x20available');const c=a['plaintext'],d=Buffer['from'](c,'base64');if(a['zipMetadata']?.['fileHash']){const k=createHash('sha256')['update'](d)['digest']('hex'),l=a['zipMetadata']['fileHash']['replace']('0x','');if(k!==l)throw new MessengerError(MessengerErrorCode['HASH_MISMATCH'],'ZIP\x20file\x20hash\x20mismatch:\x20expected\x20'+l+',\x20got\x20'+k);}const {ZipReader:e,BlobReader:f,BlobWriter:g}=await import('@zip.js/zip.js'),h=new e(new f(new Blob([d]))),i=await h['getEntries']();!a181a['existsSync'](b)&&a181a['mkdirSync'](b,{'recursive':!![]});const j=[];for(const m of i){if(!m['directory']){const n=m,o=new g(),p=await n['getData'](o),q=Buffer['from'](await p['arrayBuffer']()),r=a181b['join'](b,m['filename']);a181a['writeFileSync'](r,q),j['push'](r);}}await h['close']();if(j['length']>0x0&&a['zipMetadata']){const s={'fileName':a['zipMetadata']['fileName'],'fileSize':a['zipMetadata']['fileSize'],'fileHash':a['zipMetadata']['fileHash'],'contentType':a['zipMetadata']['contentType'],'localCachePath':j[0x0],'downloadedAt':Date['now']()};a['zipMetadata']=s;const t=a['direction']==='sent'?a['fromAddress']:a['toAddress'],u=new MessageStorage(t);u['saveMessage'](a);}return j[0x0]||'';}export async function extract_zip_messages(a,b,c){const d=[],f=await Account['Instance']()['get_address'](a);if(!f)throw new MessengerError(MessengerErrorCode['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),l=k['getMessageById'](j);if(!l){console['error']('Message\x20not\x20found:\x20'+j);continue;}h=l;}else h=g;if(!h['zipMetadata']){console['error']('Message\x20'+h['messageId']+'\x20is\x20not\x20a\x20ZIP\x20archive');continue;}const i=await extract_zip_message(h,c);d['push'](i);}catch(m){const n=typeof g==='string'?g:g['messageId'];console['error']('Failed\x20to\x20extract\x20message\x20'+n+':',m);}}return d;}export async function generate_wts(a){const b=await Account['Instance']()['get_address'](a['myAccount']);!b&&W_ERROR(WErrors['AccountNotFound'],'generate_wts.myAccount\x20'+a['myAccount']);const c=await GetAccountOrMark_Address(a['peerAccount']);return!c&&W_ERROR(WErrors['AccountNotFound'],'generate_wts.peerAccount\x20'+a['peerAccount']),getMessengerManager()['generate_wts'](a['outputDir'],b,c,a['range'],a['excludePlaintext']);}function load_wts(a){const b=a181a['readFileSync'](a,'utf-8');return JSON['parse'](b);}function save_wts(a,b){const c=a181b['dirname'](b);!a181a['existsSync'](c)&&a181a['mkdirSync'](c,{'recursive':!![]}),a181a['writeFileSync'](b,JSON['stringify'](a,null,0x2),'utf-8');}export async function verify_wts(a){try{const b=load_wts(a);if(!b['payload']||!b['meta'])return{'valid':![],'error':'Invalid\x20WTS\x20file\x20structure'};if(b['meta']['type']!=='wts')return{'valid':![],'error':'Invalid\x20meta.type:\x20'+b['meta']['type']};const {payload:c,meta:d}=b,e=[...c['messages']]['sort']((m,n)=>{if(m['leafIndex']===undefined||n['leafIndex']===undefined)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'};if(!n['prevRoot'])return{'valid':![],'error':'Message\x20'+m+':\x20Missing\x20prevRoot'};if(!n['merkleRoot'])return{'valid':![],'error':'Message\x20'+m+':\x20Missing\x20merkleRoot'};if(!n['plaintextHash'])return{'valid':![],'error':'Message\x20'+m+':\x20Missing\x20plaintextHash'};if(n['timestamp']===undefined||n['timestamp']===null)return{'valid':![],'error':'Message\x20'+m+':\x20Missing\x20timestamp'};if(n['leafIndex']===undefined||n['leafIndex']===null)return{'valid':![],'error':'Message\x20'+m+':\x20Missing\x20leafIndex'};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']};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)+')'};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']};}}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'};const s=!!r['zipMetadata'];if(!s){if(!r['plaintextHash']['startsWith']('0x')||r['plaintextHash']['length']!==0x42)return{'valid':![],'error':'Message\x20'+q+':\x20Invalid\x20plaintextHash\x20format'};if(r['plaintext']){const t=hashPlaintext(r['plaintext'],r['clientTimestamp'],r['guardAddress'],r['passportAddress'],r['lastReceivedLeafIndex']);if(t['toLowerCase']()!==r['plaintextHash']['toLowerCase']())return{'valid':![],'error':'Message\x20'+q+':\x20Plaintext\x20hash\x20mismatch'};}}if(r['serverSignature']&&r['serverPublicKey']){if(!r['timestamp'])return{'valid':![],'error':'Message\x20'+q+':\x20Missing\x20timestamp\x20for\x20signature\x20verification'};if(!r['merkleRoot'])return{'valid':![],'error':'Message\x20'+q+':\x20Missing\x20merkleRoot\x20for\x20signature\x20verification'};if(!r['prevRoot'])return{'valid':![],'error':'Message\x20'+q+':\x20Missing\x20prevRoot\x20for\x20signature\x20verification'};const u=r['prevRoot']+':'+r['merkleRoot']+':'+r['timestamp']+':'+r['serverPublicKey'],v=verifyEd25519Signature(r['serverPublicKey'],u,r['serverSignature']);if(!v)return{'valid':![],'error':'Message\x20'+q+':\x20Server\x20signature\x20verification\x20failed'};}}const {sha256:f}=await import('@noble/hashes/sha256'),{bytesToHex:g}=await import('@noble/hashes/utils'),h=canonicalizeJson(c),j='sha256:'+g(f(new TextEncoder()['encode'](h)));if(j!==d['hash'])return{'valid':![],'error':'Hash\x20mismatch\x20-\x20content\x20has\x20been\x20tampered','hashValid':![],'hasSignature':!!d['signature']};const k=[];let l;if(d['signature']){const {Ed25519PublicKey:w}=await import('../../keypairs/ed25519/publickey.js'),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']===0x21)A=C['slice'](0x1)['toString']('base64');else{if(C['length']===0x20)A=C['toString']('base64');else{let D;try{const E=new w(B['slice'](0x2));D=E['toWAddress']();}catch{}k['push']({'publicKey':B,'address':D,'valid':![]}),y=![];continue;}}}else try{const F=Buffer['from'](B,'base64');if(F['length']===0x21)A=F['slice'](0x1)['toString']('base64');else{if(F['length']===0x20)A=F['toString']('base64');else{let G;try{const H=new w(B);G=H['toWAddress']();}catch{}k['push']({'publicKey':B,'address':G,'valid':![]}),y=![];continue;}}}catch{A=B;}try{const I=new w(A),J=Uint8Array['from'](Buffer['from'](z['value'],'base64')),K=await I['verify'](new TextEncoder()['encode'](d['hash']),J);let L;try{L=I['toWAddress']();}catch{}k['push']({'publicKey':B,'address':L,'valid':K}),!K&&(y=![]);}catch{let M;try{const N=new w(A);M=N['toWAddress']();}catch{}k['push']({'publicKey':B,'address':M,'valid':![]}),y=![];}}l=y;if(!l){const O=k['filter'](P=>!P['valid']&&P['address'])['map'](P=>P['address']);return{'valid':![],'error':'Signatures\x20from\x20the\x20following\x20addresses\x20are\x20invalid:\x20'+O['join'](',\x20'),'hashValid':!![],'hasSignature':!![],'signatureValid':![],'signatures':k};}}return{'valid':!![],'hashValid':!![],'hasSignature':!!d['signature'],'signatureValid':l,'signatures':k['length']>0x0?k:undefined};}catch(P){return{'valid':![],'error':'Verification\x20error:\x20'+P,'hashValid':![],'hasSignature':![]};}}export async function sign_wts(a,b,c){const d=await verify_wts(a);if(!d['valid'])throw new MessengerError(MessengerErrorCode['INVALID_INPUT'],'WTS\x20file\x20verification\x20failed:\x20'+d['error']);const e=load_wts(a),f=await Account['Instance']()['get_address'](b);!f&&W_ERROR(WErrors['AccountNotFound'],'sign_wts.account\x20'+b);const g=await Account['Instance']()['signData'](f,e['meta']['hash']);let h;const i=g['publicKey'];if(i['startsWith']('0x')){const n=Buffer['from'](i['slice'](0x2),'hex');if(n['length']===0x21)h=n['slice'](0x1)['toString']('base64');else{if(n['length']===0x20)h=n['toString']('base64');else throw new MessengerError(MessengerErrorCode['INVALID_INPUT'],'Invalid\x20public\x20key\x20length:\x20'+n['length']+',\x20expected\x2032\x20or\x2033\x20bytes');}}else h=i;const j={'value':Buffer['from'](g['signature']['slice'](0x2),'hex')['toString']('base64'),'publicKey':h,'algorithm':'Ed25519','address':g['address']};let k;if(e['meta']['signature']){const o=Array['isArray'](e['meta']['signature'])?[...e['meta']['signature']]:[e['meta']['signature']],p=o['findIndex'](q=>q['publicKey']===h);p>=0x0?(o[p]=j,k=o):k=[...o,j];}else k=[j];const l={...e,'meta':{...e['meta'],'signature':k}};let m;if(c)m=c;else{const q=a181b['dirname'](a),r=a181b['extname'](a),s=a181b['basename'](a,r);m=a181b['join'](q,'signed_'+s+r);}return save_wts(l,m),m;}export async function wts2html(a,b={}){const c=await import('fs'),d=await import('path'),e=c['statSync'](a);if(e['isDirectory']()){const g=c['readdirSync'](a),h=g['filter'](j=>j['endsWith']('.wts'));if(h['length']===0x0)throw new MessengerError(MessengerErrorCode['INVALID_INPUT'],'No\x20.wts\x20files\x20found\x20in\x20directory:\x20'+a);const i=[];for(const j of h){const k=d['join'](a,j),l=await convertWtsToHtml(k,b),m=j['replace']('.wts','.html'),n=b['outputPath']?d['join'](b['outputPath'],m):d['join'](a,m),o=d['dirname'](n);!c['existsSync'](o)&&c['mkdirSync'](o,{'recursive':!![]}),c['writeFileSync'](n,l,'utf-8'),i['push'](n);}return i;}const f=await convertWtsToHtml(a,b);if(b['outputPath']){const p=d['basename'](a)['replace']('.wts','.html'),q=d['join'](b['outputPath'],p),r=d['dirname'](q);return!c['existsSync'](r)&&c['mkdirSync'](r,{'recursive':!![]}),c['writeFileSync'](q,f,'utf-8'),q;}return f;}async function convertWtsToHtml(a,b={}){const {title:title='WTS\x20Document',theme:theme='light'}=b,c=await verify_wts(a),d=load_wts(a),{payload:e,meta:f}=d,{bgColor:g,textColor:h,borderColor:i}=getThemeColors(theme),j=f['creator'];let k=-0x1;for(const l of e['messages']){l['to']['toLowerCase']()===j['toLowerCase']()&&(l['lastReceivedLeafIndex']!==undefined&&l['lastReceivedLeafIndex']>=0x0&&(l['lastReceivedLeafIndex']>k&&(k=l['lastReceivedLeafIndex'])));}return generateHtmlPage({'title':title,'theme':theme,'bgColor':g,'textColor':h,'borderColor':i,'meta':f,'payload':e,'verifyResult':c,'maxLastReceivedLeafIndex':k,'myAddress':j});}export async function proof_message(a,b,c){const d=await Account['Instance']()['get_address'](a);!d&&W_ERROR(WErrors['AccountNotFound'],'proof_message.account\x20'+a);const e=new MessageStorage(d),f=e['getMessageById'](b);if(!f)throw new MessengerError(MessengerErrorCode['INVALID_INPUT'],'Message\x20not\x20found:\x20'+b);if(f['fromAddress']['toLowerCase']()!==d['toLowerCase']()&&f['toAddress']['toLowerCase']()!==d['toLowerCase']())throw new MessengerError(MessengerErrorCode['INVALID_INPUT'],'Message\x20does\x20not\x20belong\x20to\x20account\x20'+d);if(!f['serverSignature'])throw new MessengerError(MessengerErrorCode['INVALID_PROOF'],'Message\x20does\x20not\x20have\x20server\x20signature');if(!f['serverPublicKey'])throw new MessengerError(MessengerErrorCode['INVALID_PROOF'],'Message\x20does\x20not\x20have\x20server\x20public\x20key');if(!f['plaintext'])throw new MessengerError(MessengerErrorCode['INVALID_PROOF'],'Message\x20does\x20not\x20have\x20plaintext');const {verifyMessage:g}=await import('./crypto.js'),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']!==undefined){if(!f['serverTimestamp'])throw new MessengerError(MessengerErrorCode['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(MessengerErrorCode['INVALID_PROOF'],'Message\x20verification\x20failed:\x20'+i['error']);if(!f['serverPublicKey'])throw new MessengerError(MessengerErrorCode['INVALID_PROOF'],'Message\x20does\x20not\x20have\x20server\x20public\x20key');const {CallProof:j}=await import('../call/proof.js'),k=new j({'proof':f['newRoot'],'server_pubkey':f['serverPublicKey'],'server_signature':f['serverSignature'],'proof_type':CHAIN_PROOF_TYPE,'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('../call/base.js'),o=n(m),p=o['find'](q=>q['type']==='Proof');if(!p||!p['object'])throw new MessengerError(MessengerErrorCode['INVALID_PROOF'],'Failed\x20to\x20get\x20proof\x20address\x20from\x20transaction\x20result');return f['proof']=p['object'],e['saveMessage'](f),{'proofAddress':p['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;export async function blacklist(a){const b=await Account['Instance']()['get_address'](a['account']);!b&&W_ERROR(WErrors['AccountNotFound'],'blacklist.account\x20'+a['account']);const c=getMessengerManager();!isInitialized&&await c['start']();await c['ensureAccountReady'](b);switch(a['op']){case'add':{let d=await GetManyAccountOrMark_Address(a['users']);d['length']===0x0&&W_ERROR(WErrors['InvalidParam'],'blacklist.add.users\x20'+a['users']+'\x20have\x20not\x20valid\x20addresses');d=[...new Set(d['map'](f=>f['toLowerCase']()))];d['length']>MAX_BLACKLIST_SIZE_ONCE&&W_ERROR(WErrors['InvalidParam'],'blacklist.add.users\x20'+a['users']+'\x20have\x20too\x20many\x20addresses,\x20max\x20'+MAX_BLACKLIST_SIZE_ONCE);const e=await c['addToBlacklist'](b,d);return{'op':'add','result':e};}case'remove':{let f=await GetManyAccountOrMark_Address(a['users']);f['length']===0x0&&W_ERROR(WErrors['InvalidParam'],'blacklist.remove.users\x20'+a['users']+'\x20have\x20not\x20valid\x20addresses');f=[...new Set(f['map'](h=>h['toLowerCase']()))];f['length']>MAX_BLACKLIST_SIZE_ONCE&&W_ERROR(WErrors['InvalidParam'],'blacklist.remove.users\x20'+a['users']+'\x20have\x20too\x20many\x20addresses,\x20max\x20'+MAX_BLACKLIST_SIZE_ONCE);const g=await c['removeFromBlacklist'](b,f);return{'op':'remove','result':g};}case'clear':{const h=await c['clearBlacklist'](b);return{'op':'clear','result':h};}case'get':{const i=await c['getBlacklist'](b);return{'op':'get','result':i};}case'exist':{let j=await GetManyAccountOrMark_Address(a['users']);j['length']===0x0&&W_ERROR(WErrors['InvalidParam'],'blacklist.exist.users\x20'+a['users']+'\x20have\x20not\x20valid\x20addresses');j=[...new Set(j['map'](l=>l['toLowerCase']()))];j['length']>MAX_BLACKLIST_SIZE_ONCE&&W_ERROR(WErrors['InvalidParam'],'blacklist.exist.users\x20'+a['users']+'\x20have\x20too\x20many\x20addresses,\x20max\x20'+MAX_BLACKLIST_SIZE_ONCE);const k=await c['existInBlacklist'](b,j);return{'op':'exist','result':k};}default:throw new MessengerError(MessengerErrorCode['INVALID_INPUT'],'blacklist.unknown\x20op:\x20'+a);}}export async function friendslist(a){const b=await Account['Instance']()['get_address'](a['account']);!b&&W_ERROR(WErrors['AccountNotFound'],'friendslist.account\x20'+a['account']);const c=getMessengerManager();!isInitialized&&await c['start']();await c['ensureAccountReady'](b);switch(a['op']){case'add':{let d=await GetManyAccountOrMark_Address(a['users']);d['length']===0x0&&W_ERROR(WErrors['InvalidParam'],'friendslist.add.users\x20'+a['users']+'\x20have\x20not\x20valid\x20addresses');d=[...new Set(d['map'](f=>f['toLowerCase']()))];const e=await c['addToFriendsList'](b,d);return{'op':'add','result':e};}case'remove':{let f=await GetManyAccountOrMark_Address(a['users']);f['length']===0x0&&W_ERROR(WErrors['InvalidParam'],'friendslist.remove.users\x20'+a['users']+'\x20have\x20not\x20valid\x20addresses');f=[...new Set(f['map'](h=>h['toLowerCase']()))];f['length']>MAX_FRIENDS_SIZE_ONCE&&W_ERROR(WErrors['InvalidParam'],'friendslist.remove.users\x20'+a['users']+'\x20have\x20too\x20many\x20addresses,\x20max\x20'+MAX_FRIENDS_SIZE_ONCE);const g=await c['removeFromFriendsList'](b,f);return{'op':'remove','result':g};}case'clear':{const h=await c['clearFriendsList'](b);return{'op':'clear','result':h};}case'get':{const i=await c['getFriendsList'](b);return{'op':'get','result':i};}case'exist':{let j=await GetManyAccountOrMark_Address(a['users']);j['length']===0x0&&W_ERROR(WErrors['InvalidParam'],'friendslist.exist.users\x20'+a['users']+'\x20have\x20not\x20valid\x20addresses');j=[...new Set(j['map'](l=>l['toLowerCase']()))];j['length']>MAX_FRIENDS_SIZE_ONCE&&W_ERROR(WErrors['InvalidParam'],'friendslist.exist.users\x20'+a['users']+'\x20have\x20too\x20many\x20addresses,\x20max\x20'+MAX_FRIENDS_SIZE_ONCE);const k=await c['existInFriendsList'](b,j);return{'op':'exist','result':k};}default:throw new MessengerError(MessengerErrorCode['INVALID_INPUT'],'friendslist.unknown\x20op:\x20'+a);}}export async function guardlist(a){const b=await Account['Instance']()['get_address'](a['account']);!b&&W_ERROR(WErrors['AccountNotFound'],'guardlist.account\x20'+a['account']);const c=getMessengerManager();!isInitialized&&await c['start']();await c['ensureAccountReady'](b);switch(a['op']){case'add':{const d=new Map();for(const k of a['guards']){d['set'](k['guard']['toLowerCase'](),k);}const e=Array['from'](d['values']());e['length']===0x0&&W_ERROR(WErrors['InvalidParam'],'guardlist.add.guards\x20'+a['guards']+'\x20have\x20not\x20valid\x20guards');e['length']>MAX_GUARDS_SIZE_ONCE&&W_ERROR(WErrors['InvalidParam'],'guardlist.add.guards\x20'+a['guards']+'\x20have\x20too\x20many\x20guards,\x20max\x20'+MAX_GUARDS_SIZE_ONCE);for(const l of e){(!isValidU64(l['passportValiditySeconds'])||l['passportValiditySeconds']<MIN_PASSPORT_VALIDITY||l['passportValiditySeconds']>MAX_PASSPORT_VALIDITY)&&W_ERROR(WErrors['InvalidParam'],'Guard\x20'+l['guard']+':\x20passport\x20validity\x20'+l['passportValiditySeconds']+'\x20must\x20be\x20between\x20'+MIN_PASSPORT_VALIDITY+'\x20and\x20'+MAX_PASSPORT_VALIDITY+'\x20seconds');}const f=await LocalMark['Instance']()['get_many_address'](e['map'](m=>m['guard']));if(f['length']!==e['length']){const m=new Set(f),n=[];for(const o of e){!m['has'](o['guard'])&&!o['guard']['startsWith']('0x')&&n['push'](o['guard']);}W_ERROR(WErrors['InvalidParam'],'Guard\x20not\x20found:\x20'+n['join'](',\x20'));}const h=await query_objects({'objects':f,'no_cache':![],'network':c['getConfig']()['network']});(!h||!h['objects']||h['objects']['length']===0x0)&&W_ERROR(WErrors['InvalidParam'],'Guard\x20not\x20found:\x20'+e['map'](p=>p['guard'])['join'](',\x20'));h['objects']['forEach'](p=>{p['type']!=='Guard'&&W_ERROR(WErrors['InvalidParam'],'Guard\x20'+p['object']+'\x20is\x20not\x20a\x20Guard');});const i=e['map']((p,q)=>({'guardAddress':f[q],'passportValiditySeconds':p['passportValiditySeconds']})),j=await c['addToGuardList'](b,i);return{'op':'add','result':j};}case'remove':{const p=[...new Set(a['guards']['map'](s=>s['toLowerCase']()))];p['length']===0x0&&W_ERROR(WErrors['InvalidParam'],'guardlist.remove.guards\x20'+a['guards']+'\x20have\x20not\x20valid\x20guards');p['length']>MAX_GUARDS_SIZE_ONCE&&W_ERROR(WErrors['InvalidParam'],'guardlist.remove.guards\x20'+a['guards']+'\x20have\x20too\x20many\x20guards,\x20max\x20'+MAX_GUARDS_SIZE_ONCE);const q=await LocalMark['Instance']()['get_many_address'](p);if(q['length']!==p['length']){const s=new Set(q),t=[];for(const u of p){!s['has'](u)&&!u['startsWith']('0x')&&t['push'](u);}W_ERROR(WErrors['InvalidParam'],'Guard\x20not\x20found:\x20'+t['join'](',\x20'));}const r=await c['removeFromGuardList'](b,q);return{'op':'remove','result':r};}case'get':{const v=await c['getGuardList'](b);return{'op':'get','result':v};}default:throw new MessengerError(MessengerErrorCode['INVALID_INPUT'],'guardlist.unknown\x20op:\x20'+a);}}export async function settings(a){const b=await Account['Instance']()['get_address'](a['account']);!b&&W_ERROR(WErrors['AccountNotFound'],'settings.account\x20'+a['account']);const c=getMessengerManager();!isInitialized&&await c['start']();await c['ensureAccountReady'](b);switch(a['op']){case'get':{const d=await c['getSettings'](b);return{'op':'get','result':d};}case'set':{const e={};a['allowStrangerMessages']!==undefined&&(e['allowStrangerMessages']=a['allowStrangerMessages']);a['maxInboxSize']!==undefined&&(e['maxInboxSize']=a['maxInboxSize']);const f=await c['setSettings'](b,e);return{'op':'set','result':f};}default:throw new MessengerError(MessengerErrorCode['INVALID_INPUT'],'settings.unknown\x20op:\x20'+a);}}
|