30#include <dhtnet/multiplexed_socket.h>
31#include <opendht/dhtrunner.h>
32#include <opendht/thread_pool.h>
48 std::string deviceName,
49 std::unique_ptr<AccountCredentials> credentials,
54 JAMI_WARNING(
"[Account {}] [Auth] starting authentication with scheme '{}'",
57 auto ctx = std::make_shared<AuthContext>();
61 ctx->deviceName = std::move(deviceName);
63 ctx->onSuccess = std::move(onSuccess);
64 ctx->onFailure = std::move(onFailure);
66 if (
not ctx->credentials) {
72 if (
ctx->credentials->scheme ==
"p2p") {
73 JAMI_DEBUG(
"[LinkDevice] Importing account via p2p scheme.");
74 startLoadArchiveFromDevice(
ctx);
78 dht::ThreadPool::computation().run([
ctx = std::move(
ctx),
wthis = weak()] {
83 if (
ctx->credentials->scheme ==
"file") {
85 this_->loadFromFile(*ctx);
88 bool hasArchive = not ctx->credentials->uri.empty()
89 and std::filesystem::is_regular_file(ctx->credentials->uri);
92 if (ctx->credentials->updateIdentity.first
93 and ctx->credentials->updateIdentity.second
94 and needsMigration(this_->accountId_, ctx->credentials->updateIdentity)) {
95 this_->migrateAccount(*ctx);
97 this_->loadFromFile(*ctx);
99 }
else if (
ctx->credentials->updateIdentity.first
100 and ctx->credentials->updateIdentity.second) {
101 auto future_keypair = dht::ThreadPool::computation().get<dev::KeyPair>(
102 &dev::KeyPair::create);
104 JAMI_WARNING(
"[Account {}] [Auth] Converting certificate from old account {}",
106 ctx->credentials->updateIdentity.first->getPublicKey()
109 a.id = std::move(ctx->credentials->updateIdentity);
111 a.ca_key = std::make_shared<dht::crypto::PrivateKey>(
112 fileutils::loadFile(
"ca.key", this_->path_));
115 this_->updateCertificates(
a,
ctx->credentials->updateIdentity);
117 this_->onArchiveLoaded(*
ctx, std::move(
a),
false);
122 }
catch (
const std::exception&
e) {
123 ctx->onFailure(AuthError::UNKNOWN,
e.what());
129ArchiveAccountManager::updateCertificates(AccountArchive& archive, dht::crypto::Identity& device)
131 JAMI_WARNING(
"[Account {}] [Auth] Updating certificates", accountId_);
132 using Certificate = dht::crypto::Certificate;
135 if (not archive.id.first or not *archive.id.first or not archive.id.second or not archive.ca_key
136 or not *archive.ca_key)
140 bool updated =
false;
142 auto& cert = archive.id.second;
143 auto ca = cert->issuer;
145 if (not ca or (not ca->issuer and (not ca->isCA() or ca->getExpiration() < clock::now()))) {
146 ca = std::make_shared<Certificate>(
147 Certificate::generate(*archive.ca_key,
"Jami CA", {},
true));
149 JAMI_LOG(
"[Account {}] [Auth] CA certificate re-generated", accountId_);
153 if (updated or not cert->isCA() or cert->getExpiration() < clock::now()) {
154 cert = std::make_shared<Certificate>(
155 Certificate::generate(*archive.id.first,
157 dht::crypto::Identity {archive.ca_key, ca},
160 JAMI_LOG(
"[Account {}] [Auth] Account certificate for {} re-generated",
165 if (updated and device.first and *device.first) {
167 device.second = std::make_shared<Certificate>(
168 Certificate::generate(*device.first,
"Jami device", archive.id));
169 JAMI_LOG(
"[Account {}] [Auth] Device certificate re-generated", accountId_);
176ArchiveAccountManager::setValidity(std::string_view scheme,
177 const std::string& password,
178 dht::crypto::Identity& device,
179 const dht::InfoHash&
id,
182 auto archive = readArchive(scheme, password);
184 if (not archive.id.first or not *archive.id.first or not archive.id.second or not archive.ca_key
185 or not *archive.ca_key)
188 auto updated =
false;
191 JAMI_WARNING(
"[Account {}] [Auth] Updating validity for certificate with id: {}",
195 JAMI_WARNING(
"[Account {}] [Auth] Updating validity for certificates", accountId_);
197 auto& cert = archive.id.second;
198 auto ca = cert->issuer;
204 if (not
id or ca->getId() ==
id) {
205 ca->setValidity(*archive.ca_key, validity);
207 JAMI_LOG(
"[Account {}] [Auth] CA certificate re-generated", accountId_);
211 if (updated or not
id or cert->getId() ==
id) {
212 cert->setValidity(dht::crypto::Identity {archive.ca_key, ca}, validity);
213 device.second->issuer = cert;
215 JAMI_LOG(
"[Account {}] [Auth] Jami certificate re-generated", accountId_);
219 archive.save(fileutils::getFullPath(path_, archivePath_), scheme, password);
222 if (updated or not
id or device.second->getId() ==
id) {
224 device.second->setValidity(archive.id, validity);
232ArchiveAccountManager::createAccount(AuthContext&
ctx)
235 auto ca = dht::crypto::generateIdentity(
"Jami CA");
236 if (!ca.first || !ca.second) {
237 throw std::runtime_error(
"Unable to generate CA for this account.");
239 a.
id = dht::crypto::generateIdentity(
"Jami", ca, 4096,
true);
240 if (!a.
id.first || !a.
id.second) {
241 throw std::runtime_error(
"Unable to generate identity for this account.");
243 JAMI_WARNING(
"[Account {}] [Auth] New account: CA: {}, ID: {}",
246 a.
id.second->getId());
249 a.
eth_key = keypair.secret().makeInsecure().asBytes();
250 onArchiveLoaded(ctx, std::move(a),
false);
254ArchiveAccountManager::loadFromFile(AuthContext& ctx)
256 JAMI_WARNING(
"[Account {}] [Auth] Loading archive from: {}",
258 ctx.credentials->uri.c_str());
259 AccountArchive archive;
261 archive = AccountArchive(ctx.credentials->uri,
262 ctx.credentials->password_scheme,
263 ctx.credentials->password);
264 }
catch (
const std::exception& ex) {
265 JAMI_WARNING(
"[Account {}] [Auth] Unable to read archive file: {}", accountId_, ex.what());
266 ctx.onFailure(AuthError::INVALID_ARGUMENTS, ex.what());
269 onArchiveLoaded(ctx, std::move(archive),
false);
276 std::pair<bool, bool> stateOld {
false,
true};
277 std::pair<bool, bool> stateNew {
false,
true};
295static constexpr std::string_view
299 case AuthDecodingState::HANDSHAKE:
300 return "HANDSHAKE"sv;
301 case AuthDecodingState::EST:
303 case AuthDecodingState::AUTH:
305 case AuthDecodingState::DATA:
307 case AuthDecodingState::AUTH_ERROR:
308 return "AUTH_ERROR"sv;
309 case AuthDecodingState::DONE:
311 case AuthDecodingState::TIMEOUT:
313 case AuthDecodingState::CANCELED:
315 case AuthDecodingState::ERR:
321namespace PayloadKey {
332 uint8_t schemeId {0};
334 MSGPACK_DEFINE_MAP(schemeId, payload)
336 void set(
std::string_view key,
std::string_view value) {
337 payload.emplace(std::string(key), std::string(value));
340 auto find(std::string_view key)
const {
return payload.find(std::string(key)); }
342 auto at(std::string_view key)
const {
return payload.at(std::string(key)); }
347 std::string logStr =
"=========\n";
348 logStr += fmt::format(
"scheme: {}\n", schemeId);
349 for (
const auto& [msgKey, msgVal] : payload) {
350 logStr += fmt::format(
" - {}: {}\n", msgKey, msgVal);
352 logStr +=
"=========";
358 timeoutMsg.
set(PayloadKey::stateMsg,
toString(AuthDecodingState::TIMEOUT));
366 static constexpr auto token =
"token"sv;
367 static constexpr auto error =
"error"sv;
368 static constexpr auto auth_scheme =
"auth_scheme"sv;
369 static constexpr auto peer_id =
"peer_id"sv;
370 static constexpr auto auth_error =
"auth_error"sv;
371 static constexpr auto peer_address =
"peer_address"sv;
376 using Map = std::map<std::string, std::string>;
386 void set(std::string_view key, std::string_view value) {
387 emplace(std::string(key), std::string(value));
400 case Error::AUTH_ERROR:
401 errStr =
"auth_error";
403 case Error::CANCELED:
422 bool authEnabled {
false};
423 bool archiveTransferredWithoutFailure {
false};
428 , state(initialState)
435 auto stateMsgIt = msg.
find(PayloadKey::stateMsg);
436 if (stateMsgIt != msg.
payload.end()) {
437 if (stateMsgIt->second ==
toString(AuthDecodingState::TIMEOUT)) {
438 this->state = AuthDecodingState::TIMEOUT;
447 auto stateMsgIt = msg.
find(PayloadKey::stateMsg);
448 if (stateMsgIt != msg.
payload.end()) {
449 if (stateMsgIt->second ==
toString(AuthDecodingState::CANCELED)) {
450 this->state = AuthDecodingState::CANCELED;
459 if (state == AuthDecodingState::AUTH_ERROR) {
460 return DeviceAuthInfo::Error::AUTH_ERROR;
461 }
else if (state == AuthDecodingState::TIMEOUT) {
462 return DeviceAuthInfo::Error::TIMEOUT;
463 }
else if (state == AuthDecodingState::CANCELED) {
464 return DeviceAuthInfo::Error::CANCELED;
465 }
else if (state == AuthDecodingState::ERR) {
466 return DeviceAuthInfo::Error::UNKNOWN;
467 }
else if (archiveTransferredWithoutFailure) {
468 return DeviceAuthInfo::Error::NONE;
470 return DeviceAuthInfo::Error::NETWORK;
475 return state == AuthDecodingState::DONE || state == AuthDecodingState::ERR
476 || state == AuthDecodingState::AUTH_ERROR || state == AuthDecodingState::TIMEOUT
477 || state == AuthDecodingState::CANCELED;
485 unsigned numOpenChannels {0};
486 unsigned maxOpenChannels {1};
487 std::shared_ptr<dhtnet::ChannelSocket>
channel;
488 msgpack::unpacker pac {[](msgpack::type::object_type, std::size_t,
void*) {
return true; },
491 std::string authScheme {fileutils::ARCHIVE_AUTH_SCHEME_NONE};
492 std::string credentialsFromUser {
""};
496 , tmpId(
std::move(id))
503 unsigned numTries {0};
504 unsigned maxTries {3};
505 std::shared_ptr<dhtnet::ChannelSocket>
channel;
511 , channel(
std::move(c))
517 timeoutMsg.
set(PayloadKey::stateMsg,
toString(AuthDecodingState::CANCELED));
523ArchiveAccountManager::provideAccountAuthentication(
const std::string& key,
524 const std::string& scheme)
526 if (scheme != fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD) {
527 JAMI_ERROR(
"[LinkDevice] Unsupported account authentication scheme attempted.");
536 if (
ctx->linkDevCtx->state != AuthDecodingState::AUTH) {
537 JAMI_WARNING(
"[LinkDevice] Invalid state for providing account authentication.");
541 ctx->linkDevCtx->authScheme = scheme;
542 ctx->linkDevCtx->credentialsFromUser = key;
544 ctx->linkDevCtx->state = AuthDecodingState::DATA;
545 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
546 ctx->accountId,
static_cast<uint8_t
>(DeviceAuthState::IN_PROGRESS),
DeviceAuthInfo {});
548 dht::ThreadPool::io().run([key = std::move(key), scheme,
ctx]()
mutable {
550 toSend.
set(PayloadKey::password, std::move(key));
551 msgpack::sbuffer buffer(UINT16_MAX);
553 msgpack::pack(buffer, toSend);
556 ctx->linkDevCtx->channel->write(
reinterpret_cast<const unsigned char*
>(buffer.data()),
559 }
catch (
const std::exception& e) {
560 JAMI_WARNING(
"[LinkDevice] Failed to send password over auth ChannelSocket. Channel "
570 msgpack::unpacker pac {[](msgpack::type::object_type, std::size_t,
void*) {
return true; },
577ArchiveAccountManager::startLoadArchiveFromDevice(
const std::shared_ptr<AuthContext>&
ctx)
580 JAMI_WARNING(
"[LinkDevice] Already loading archive from device.");
581 ctx->onFailure(AuthError::INVALID_ARGUMENTS,
"Already loading archive from device.");
584 JAMI_DEBUG(
"[LinkDevice] Starting load archive from device {} {}.",
589 dht::ThreadPool::computation().run([ctx, wthis = weak()] {
590 auto ca = dht::crypto::generateEcIdentity(
"Jami Temporary CA");
591 if (!ca.first || !ca.second) {
592 throw std::runtime_error(
"[LinkDevice] Can't generate CA for this account.");
595 auto user = dht::crypto::generateIdentity(
"Jami Temporary User", ca, 4096,
true);
596 if (!user.first || !user.second) {
597 throw std::runtime_error(
"[LinkDevice] Can't generate identity for this account.");
600 auto this_ = wthis.lock();
602 JAMI_WARNING(
"[LinkDevice] Failed to get the ArchiveAccountManager.");
607 ctx->linkDevCtx = std::make_shared<LinkDeviceContext>(
608 dht::crypto::generateIdentity(
"Jami Temporary device", user));
609 JAMI_LOG(
"[LinkDevice] Established linkDevCtx. {} {} {}.",
612 fmt::ptr(ctx->linkDevCtx));
615 auto gen = Manager::instance().getSeededRandomEngine();
616 ctx->linkDevCtx->opId = std::uniform_int_distribution<uint64_t>(100000, 999999)(gen);
618 ctx->linkDevCtx->tempConnMgr.oniOSConnected(
619 [&](
const std::string& connType, dht::InfoHash peer_h) {
return false; });
621 ctx->linkDevCtx->tempConnMgr.onDhtConnected(ctx->linkDevCtx->tmpId.second->getPublicKey());
623 auto accountScheme = fmt::format(
"{}{}/{}",
625 ctx->linkDevCtx->tmpId.second->getId(),
626 ctx->linkDevCtx->opId);
627 JAMI_LOG(
"[LinkDevice] auth scheme will be: {}", accountScheme);
630 info.set(DeviceAuthInfo::token, accountScheme);
632 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
633 ctx->accountId,
static_cast<uint8_t
>(DeviceAuthState::TOKEN_AVAILABLE), info);
635 ctx->linkDevCtx->tempConnMgr.onICERequest(
636 [wctx = std::weak_ptr(ctx)](
const DeviceId& deviceId) {
637 if (
auto ctx = wctx.lock()) {
638 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
640 static_cast<uint8_t>(DeviceAuthState::CONNECTING),
647 ctx->linkDevCtx->tempConnMgr.onChannelRequest(
648 [wthis, ctx](
const std::shared_ptr<dht::crypto::Certificate>& cert,
649 const std::string& name) {
650 std::string_view url(name);
651 if (!starts_with(url, CHANNEL_SCHEME)) {
653 "[LinkDevice] Temporary connection manager received invalid scheme: {}",
660 if (ctx->linkDevCtx->opId == parsedOpId
661 && ctx->linkDevCtx->numOpenChannels < ctx->linkDevCtx->maxOpenChannels) {
662 ctx->linkDevCtx->numOpenChannels++;
663 JAMI_DEBUG(
"[LinkDevice] Opening channel ({}/{}): {}",
664 ctx->linkDevCtx->numOpenChannels,
665 ctx->linkDevCtx->maxOpenChannels,
672 ctx->linkDevCtx->tempConnMgr.onConnectionReady([ctx,
674 wthis](
const DeviceId& deviceId,
675 const std::string& name,
676 std::shared_ptr<dhtnet::ChannelSocket> socket) {
678 JAMI_WARNING(
"[LinkDevice] Temporary connection manager received invalid socket.");
680 ctx->timeout->cancel();
681 ctx->timeout.reset();
682 ctx->linkDevCtx->numOpenChannels--;
683 if (
auto sthis = wthis.lock())
684 sthis->authCtx_.reset();
685 ctx->linkDevCtx->state = AuthDecodingState::ERR;
686 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
688 static_cast<uint8_t
>(DeviceAuthState::DONE),
689 DeviceAuthInfo::createError(DeviceAuthInfo::Error::NETWORK));
692 ctx->linkDevCtx->channel = socket;
694 ctx->timeout = std::make_unique<asio::steady_timer>(*Manager::instance().ioContext());
695 ctx->timeout->expires_after(OP_TIMEOUT);
696 ctx->timeout->async_wait([c = std::weak_ptr(ctx), socket](
const std::error_code& ec) {
700 if (
auto ctx = c.lock()) {
701 if (!ctx->linkDevCtx->isCompleted()) {
702 ctx->linkDevCtx->state = AuthDecodingState::TIMEOUT;
703 JAMI_WARNING(
"[LinkDevice] timeout: {}", socket->name());
706 msgpack::sbuffer buffer(UINT16_MAX);
707 msgpack::pack(buffer, AuthMsg::timeout());
709 socket->write(reinterpret_cast<const unsigned char*>(buffer.data()),
717 socket->onShutdown([ctx, name, wthis]() {
718 JAMI_WARNING(
"[LinkDevice] Temporary connection manager closing socket: {}", name);
720 ctx->timeout->cancel();
721 ctx->timeout.reset();
722 ctx->linkDevCtx->numOpenChannels--;
723 ctx->linkDevCtx->channel.reset();
724 if (
auto sthis = wthis.lock())
725 sthis->authCtx_.reset();
727 DeviceAuthInfo::Error error = ctx->linkDevCtx->getErrorState();
728 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
730 static_cast<uint8_t
>(DeviceAuthState::DONE),
731 DeviceAuthInfo::createError(error));
734 socket->setOnRecv([ctx,
735 decodingCtx = std::make_shared<DecodingContext>(),
736 wthis](
const uint8_t* buf,
size_t len) {
741 decodingCtx->pac.reserve_buffer(len);
742 std::copy_n(buf, len, decodingCtx->pac.buffer());
743 decodingCtx->pac.buffer_consumed(len);
746 msgpack::object_handle oh;
747 if (decodingCtx->pac.next(oh)) {
748 JAMI_DEBUG(
"[LinkDevice] NEW: Unpacking message.");
749 oh.get().convert(toRecv);
753 }
catch (
const std::exception& e) {
754 ctx->linkDevCtx->state = AuthDecodingState::ERR;
755 JAMI_ERROR(
"[LinkDevice] Error unpacking message from source device: {}", e.what());
759 JAMI_DEBUG(
"[LinkDevice] NEW: Successfully unpacked message from source\n{}",
761 JAMI_DEBUG(
"[LinkDevice] NEW: State is {}:{}",
762 ctx->linkDevCtx->scheme,
763 ctx->linkDevCtx->formattedAuthState());
766 if (toRecv.schemeId != 0) {
767 JAMI_WARNING(
"[LinkDevice] NEW: Unsupported scheme received from source");
768 ctx->linkDevCtx->state = AuthDecodingState::ERR;
773 if (ctx->linkDevCtx->handleCanceledMessage(toRecv)) {
778 bool shouldShutdown =
false;
779 auto accDataIt = toRecv.find(PayloadKey::accData);
780 bool shouldLoadArchive = accDataIt != toRecv.payload.end();
782 if (ctx->linkDevCtx->state == AuthDecodingState::HANDSHAKE) {
783 auto peerCert = ctx->linkDevCtx->channel->peerCertificate();
784 auto authScheme = toRecv.at(PayloadKey::authScheme);
786 != fileutils::ARCHIVE_AUTH_SCHEME_NONE;
788 JAMI_DEBUG(
"[LinkDevice] NEW: Auth scheme from payload is '{}'", authScheme);
789 ctx->linkDevCtx->state = AuthDecodingState::AUTH;
791 info.set(DeviceAuthInfo::auth_scheme, authScheme);
792 info.set(DeviceAuthInfo::peer_id, peerCert->issuer->getId().toString());
793 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
794 ctx->accountId,
static_cast<uint8_t
>(DeviceAuthState::AUTHENTICATING), info);
795 }
else if (ctx->linkDevCtx->state == AuthDecodingState::DATA) {
796 auto passwordCorrectIt = toRecv.find(PayloadKey::passwordCorrect);
797 auto canRetry = toRecv.find(PayloadKey::canRetry);
800 if (canRetry != toRecv.payload.end() &&
canRetry->second ==
"false") {
801 JAMI_DEBUG(
"[LinkDevice] Authentication failed: maximum retry attempts "
803 ctx->linkDevCtx->state = AuthDecodingState::AUTH_ERROR;
808 if (passwordCorrectIt != toRecv.payload.end()
809 && passwordCorrectIt->second ==
"false") {
810 ctx->linkDevCtx->state = AuthDecodingState::AUTH;
812 JAMI_DEBUG(
"[LinkDevice] NEW: Password incorrect.");
813 auto peerCert = ctx->linkDevCtx->channel->peerCertificate();
814 auto peer_id = peerCert->issuer->getId().toString();
817 auto authScheme = fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD;
820 info.set(DeviceAuthInfo::auth_scheme, authScheme);
821 info.set(DeviceAuthInfo::peer_id, peer_id);
822 info.set(DeviceAuthInfo::auth_error,
"invalid_credentials");
824 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
826 static_cast<uint8_t
>(DeviceAuthState::AUTHENTICATING),
831 if (!shouldLoadArchive) {
832 JAMI_DEBUG(
"[LinkDevice] NEW: no archive received.");
835 ctx->linkDevCtx->state = AuthDecodingState::ERR;
836 shouldShutdown =
true;
841 if (shouldLoadArchive) {
842 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
844 static_cast<uint8_t
>(DeviceAuthState::IN_PROGRESS),
847 auto archive = AccountArchive(std::string_view(accDataIt->second));
848 if (
auto this_ = wthis.lock()) {
849 JAMI_DEBUG(
"[LinkDevice] NEW: Reading archive from peer.");
850 this_->onArchiveLoaded(*ctx, std::move(archive),
true);
851 JAMI_DEBUG(
"[LinkDevice] NEW: Successfully loaded archive.");
852 ctx->linkDevCtx->archiveTransferredWithoutFailure =
true;
854 ctx->linkDevCtx->archiveTransferredWithoutFailure =
false;
855 JAMI_ERROR(
"[LinkDevice] NEW: Failed to load account because of "
856 "null ArchiveAccountManager!");
858 }
catch (
const std::exception& e) {
859 ctx->linkDevCtx->state = AuthDecodingState::ERR;
860 ctx->linkDevCtx->archiveTransferredWithoutFailure =
false;
861 JAMI_WARNING(
"[LinkDevice] NEW: Error reading archive.");
863 shouldShutdown =
true;
866 if (shouldShutdown) {
867 ctx->linkDevCtx->channel->shutdown();
873 ctx->linkDevCtx->state = AuthDecodingState::HANDSHAKE;
877 JAMI_DEBUG(
"[LinkDevice] NEW: Packing first message for SOURCE.\nCurrent state is: "
881 ctx->linkDevCtx->formattedAuthState());
882 msgpack::sbuffer buffer(UINT16_MAX);
883 msgpack::pack(buffer, toSend);
885 ctx->linkDevCtx->channel->write(
reinterpret_cast<const unsigned char*
>(buffer.data()),
889 JAMI_LOG(
"[LinkDevice {}] Generated temporary account.",
890 ctx->linkDevCtx->tmpId.second->getId());
893 JAMI_DEBUG(
"[LinkDevice] Starting load archive from device END {} {}.",
899ArchiveAccountManager::addDevice(
const std::string& uriProvided,
900 std::string_view auth_scheme,
904 JAMI_WARNING(
"[LinkDevice] addDevice: auth context already exists.");
905 return static_cast<int32_t
>(AccountManager::AddDeviceError::ALREADY_LINKING);
907 JAMI_LOG(
"[LinkDevice] ArchiveAccountManager::addDevice({}, {})", accountId_, uriProvided);
909 std::string_view url(uriProvided);
911 JAMI_ERROR(
"[LinkDevice] Invalid uri provided: {}", uriProvided);
912 return static_cast<int32_t
>(AccountManager::AddDeviceError::INVALID_URI);
915 auto peerCodeS = url.substr(
AUTH_URI_SCHEME.length() + peerTempAcc.length() + 1, 6);
916 JAMI_LOG(
"[LinkDevice] ======\n * tempAcc = {}\n * code = {}", peerTempAcc, peerCodeS);
918 auto gen = Manager::instance().getSeededRandomEngine();
919 std::uniform_int_distribution<int32_t> dist(1, INT32_MAX);
920 auto token = dist(gen);
921 JAMI_WARNING(
"[LinkDevice] SOURCE: Creating auth context, token: {}.", token);
922 auto ctx = std::make_shared<AuthContext>();
923 ctx->accountId = accountId_;
925 ctx->credentials = std::make_unique<ArchiveAccountCredentials>();
929 dht::InfoHash(peerTempAcc),
931 [wthis = weak(), auth_scheme,
ctx, accountId=accountId_](std::shared_ptr<dhtnet::ChannelSocket> socket,
932 const dht::InfoHash& infoHash) {
933 auto this_ = wthis.lock();
934 if (!socket || !this_) {
936 "[LinkDevice] Invalid socket event while AccountManager connecting.");
938 this_->authCtx_.reset();
939 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
942 static_cast<uint8_t
>(DeviceAuthState::DONE),
943 DeviceAuthInfo::createError(DeviceAuthInfo::Error::NETWORK));
945 if (!this_->doAddDevice(auth_scheme,
ctx, socket))
946 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
949 static_cast<uint8_t
>(DeviceAuthState::DONE),
950 DeviceAuthInfo::createError(DeviceAuthInfo::Error::UNKNOWN));
953 runOnMainThread([token,
id = accountId_] {
954 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
955 id, token,
static_cast<uint8_t
>(DeviceAuthState::CONNECTING),
DeviceAuthInfo {});
958 }
catch (
const std::exception& e) {
959 JAMI_ERROR(
"[LinkDevice] Parsing uri failed: {}", uriProvided);
960 return static_cast<int32_t
>(AccountManager::AddDeviceError::GENERIC);
965ArchiveAccountManager::doAddDevice(std::string_view scheme,
966 const std::shared_ptr<AuthContext>&
ctx,
967 const std::shared_ptr<dhtnet::ChannelSocket>& channel)
970 JAMI_WARNING(
"[LinkDevice] SOURCE: addDevice canceled.");
974 JAMI_DEBUG(
"[LinkDevice] Setting up addDevice logic on SOURCE device.");
975 JAMI_DEBUG(
"[LinkDevice] SOURCE: Creating addDeviceCtx.");
976 ctx->addDeviceCtx = std::make_unique<AddDeviceContext>(channel);
977 ctx->addDeviceCtx->authScheme = scheme;
978 ctx->addDeviceCtx->state = AuthDecodingState::HANDSHAKE;
980 ctx->timeout = std::make_unique<asio::steady_timer>(*Manager::instance().ioContext());
981 ctx->timeout->expires_after(OP_TIMEOUT);
982 ctx->timeout->async_wait(
983 [wthis = weak(), wctx = std::weak_ptr(ctx)](
const std::error_code& ec) {
987 if (
auto ctx = wctx.lock()) {
988 if (!ctx->addDeviceCtx->isCompleted()) {
989 if (auto this_ = wthis.lock()) {
990 ctx->addDeviceCtx->state = AuthDecodingState::TIMEOUT;
991 JAMI_WARNING(
"[LinkDevice] Timeout for addDevice.");
994 msgpack::sbuffer buffer(UINT16_MAX);
995 msgpack::pack(buffer, AuthMsg::timeout());
997 ctx->addDeviceCtx->channel->write(reinterpret_cast<const unsigned char*>(
1001 ctx->addDeviceCtx->channel->shutdown();
1007 JAMI_DEBUG(
"[LinkDevice] SOURCE: Creating callbacks.");
1008 channel->onShutdown([ctx, w = weak()]() {
1009 JAMI_DEBUG(
"[LinkDevice] SOURCE: Shutdown with state {}... xfer {}uccessful",
1010 ctx->addDeviceCtx->formattedAuthState(),
1011 ctx->addDeviceCtx->archiveTransferredWithoutFailure ?
"s" :
"uns");
1014 ctx->timeout->cancel();
1015 ctx->timeout.reset();
1017 if (
auto this_ = w.lock()) {
1018 this_->authCtx_.reset();
1021 DeviceAuthInfo::Error error = ctx->addDeviceCtx->getErrorState();
1022 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(ctx->accountId,
1024 static_cast<uint8_t
>(
1025 DeviceAuthState::DONE),
1026 DeviceAuthInfo::createError(
1032 JAMI_DEBUG(
"[LinkDevice] Setting up receiving logic callback.");
1033 channel->setOnRecv([ctx,
1035 decodeCtx = std::make_shared<ArchiveAccountManager::DecodingContext>()](
1036 const uint8_t* buf,
size_t len) {
1037 JAMI_DEBUG(
"[LinkDevice] Setting up receiver callback for communication logic on SOURCE "
1041 auto this_ = wthis.lock();
1043 JAMI_ERROR(
"[LinkDevice] Invalid state for ArchiveAccountManager.");
1052 if (ctx->canceled || ctx->addDeviceCtx->state == AuthDecodingState::ERR) {
1057 decodeCtx->pac.reserve_buffer(len);
1058 std::copy_n(buf, len, decodeCtx->pac.buffer());
1059 decodeCtx->pac.buffer_consumed(len);
1062 JAMI_DEBUG(
"[LinkDevice] SOURCE: addDevice: setOnRecv: handling msg from NEW");
1063 msgpack::object_handle oh;
1066 if (decodeCtx->pac.next(oh)) {
1067 oh.get().convert(toRecv);
1068 JAMI_DEBUG(
"[LinkDevice] SOURCE: Successfully unpacked message from NEW "
1069 "(NEW->SOURCE)\n{}",
1070 toRecv.formatMsg());
1074 }
catch (
const std::exception& e) {
1076 ctx->addDeviceCtx->state = AuthDecodingState::ERR;
1077 JAMI_ERROR(
"[LinkDevice] error unpacking message from new device: {}", e.what());
1080 JAMI_DEBUG(
"[LinkDevice] SOURCE: State is '{}'", ctx->addDeviceCtx->formattedAuthState());
1085 if (toRecv.schemeId != 0) {
1086 ctx->addDeviceCtx->state = AuthDecodingState::ERR;
1087 JAMI_WARNING(
"[LinkDevice] Unsupported scheme received from a connection.");
1090 if (ctx->addDeviceCtx->state == AuthDecodingState::ERR
1091 || ctx->addDeviceCtx->state == AuthDecodingState::AUTH_ERROR) {
1092 JAMI_WARNING(
"[LinkDevice] Undefined behavior encountered during a link auth session.");
1093 ctx->addDeviceCtx->channel->shutdown();
1096 if (ctx->addDeviceCtx->handleTimeoutMessage(toRecv)) {
1100 bool shouldSendMsg =
false;
1101 bool shouldShutdown =
false;
1102 bool shouldSendArchive =
false;
1105 if (ctx->addDeviceCtx->state == AuthDecodingState::AUTH) {
1108 JAMI_DEBUG(
"[LinkDevice] SOURCE: addDevice: setOnRecv: verifying sent "
1109 "credentials from NEW");
1110 shouldSendMsg =
true;
1111 const auto& passwordIt = toRecv.find(PayloadKey::password);
1112 if (passwordIt != toRecv.payload.end()) {
1115 JAMI_DEBUG(
"[LinkDevice] Injecting account archive into outbound message.");
1116 ctx->addDeviceCtx->accData
1118 ->readArchive(fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD,
1121 shouldSendArchive =
true;
1122 JAMI_DEBUG(
"[LinkDevice] Sending account archive.");
1123 }
catch (
const std::exception& e) {
1124 ctx->addDeviceCtx->state = AuthDecodingState::ERR;
1125 JAMI_DEBUG(
"[LinkDevice] Finished reading archive: FAILURE: {}", e.what());
1126 shouldSendArchive =
false;
1129 if (!shouldSendArchive) {
1131 if (ctx->addDeviceCtx->numTries < ctx->addDeviceCtx->maxTries) {
1133 ctx->addDeviceCtx->numTries++;
1134 JAMI_DEBUG(
"[LinkDevice] Incorrect password received. "
1135 "Attempt {} out of {}.",
1136 ctx->addDeviceCtx->numTries,
1137 ctx->addDeviceCtx->maxTries);
1138 toSend.set(PayloadKey::passwordCorrect,
"false");
1139 toSend.set(PayloadKey::canRetry,
"true");
1142 JAMI_WARNING(
"[LinkDevice] Incorrect password received, maximum attempts reached.");
1143 toSend.set(PayloadKey::canRetry,
"false");
1144 ctx->addDeviceCtx->state = AuthDecodingState::AUTH_ERROR;
1145 shouldShutdown =
true;
1150 if (shouldSendArchive) {
1151 JAMI_DEBUG(
"[LinkDevice] SOURCE: Archive in message has encryption scheme '{}'",
1152 ctx->addDeviceCtx->authScheme);
1153 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
1156 static_cast<uint8_t
>(DeviceAuthState::IN_PROGRESS),
1158 shouldShutdown =
true;
1159 shouldSendMsg =
true;
1160 ctx->addDeviceCtx->archiveTransferredWithoutFailure =
true;
1161 toSend.set(PayloadKey::accData, ctx->addDeviceCtx->accData);
1163 if (shouldSendMsg) {
1164 JAMI_DEBUG(
"[LinkDevice] SOURCE: Sending msg to NEW:\n{}", toSend.formatMsg());
1165 msgpack::sbuffer buffer(UINT16_MAX);
1166 msgpack::pack(buffer, toSend);
1168 ctx->addDeviceCtx->channel->write(
reinterpret_cast<const unsigned char*
>(buffer.data()),
1173 if (shouldShutdown) {
1174 ctx->addDeviceCtx->channel->shutdown();
1180 if (ctx->addDeviceCtx->state == AuthDecodingState::HANDSHAKE) {
1181 ctx->addDeviceCtx->state = AuthDecodingState::EST;
1182 DeviceAuthInfo info;
1183 info.set(DeviceAuthInfo::peer_address, channel->getRemoteAddress().toString(
true));
1184 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
1185 ctx->accountId, ctx->token,
static_cast<uint8_t
>(DeviceAuthState::AUTHENTICATING), info);
1192ArchiveAccountManager::cancelAddDevice(uint32_t token)
1194 if (
auto ctx = authCtx_) {
1195 if (
ctx->token == token) {
1196 ctx->canceled =
true;
1197 if (
ctx->addDeviceCtx) {
1198 ctx->addDeviceCtx->state = AuthDecodingState::CANCELED;
1199 if (
ctx->addDeviceCtx->channel) {
1201 auto canceledMsg =
ctx->addDeviceCtx->createCanceledMsg();
1202 msgpack::sbuffer buffer(UINT16_MAX);
1203 msgpack::pack(buffer, canceledMsg);
1205 ctx->addDeviceCtx->channel->write(
reinterpret_cast<const unsigned char*
>(
1209 ctx->addDeviceCtx->channel->shutdown();
1213 ctx->onFailure(AuthError::UNKNOWN,
"");
1222ArchiveAccountManager::confirmAddDevice(uint32_t token)
1224 if (
auto ctx = authCtx_) {
1225 if (
ctx->token == token &&
ctx->addDeviceCtx
1226 &&
ctx->addDeviceCtx->state == AuthDecodingState::EST) {
1227 dht::ThreadPool::io().run([
ctx] {
1228 ctx->addDeviceCtx->state = AuthDecodingState::AUTH;
1230 JAMI_DEBUG(
"[LinkDevice] SOURCE: Packing first message for NEW and switching to "
1232 ctx->addDeviceCtx->formattedAuthState());
1233 toSend.
set(PayloadKey::authScheme,
ctx->addDeviceCtx->authScheme);
1234 msgpack::sbuffer buffer(UINT16_MAX);
1235 msgpack::pack(buffer, toSend);
1237 ctx->addDeviceCtx->channel->write(
reinterpret_cast<const unsigned char*
>(
1249ArchiveAccountManager::loadFromDHT(
const std::shared_ptr<AuthContext>&
ctx)
1251 ctx->dhtContext = std::make_unique<DhtLoadContext>();
1252 ctx->dhtContext->dht.run(
ctx->credentials->dhtPort, {},
true);
1253 for (
const auto& bootstrap :
ctx->credentials->dhtBootstrap) {
1254 ctx->dhtContext->dht.bootstrap(bootstrap);
1255 auto searchEnded = [
ctx, accountId = accountId_]() {
1256 if (not
ctx->dhtContext or
ctx->dhtContext->found) {
1259 auto& s = *ctx->dhtContext;
1260 if (s.stateOld.first && s.stateNew.first) {
1261 dht::ThreadPool::computation().run(
1263 network_error = !s.stateOld.second && !s.stateNew.second,
1264 accountId = std::move(accountId)] {
1265 ctx->dhtContext.reset();
1266 JAMI_WARNING(
"[Account {}] [Auth] Failure looking for archive on DHT: {}",
1268 network_error ?
"network error" :
"not found");
1269 ctx->onFailure(network_error ? AuthError::NETWORK : AuthError::UNKNOWN,
"");
1274 auto search = [ctx, searchEnded, w = weak()](
bool previous) {
1275 std::vector<uint8_t> key;
1277 auto& s = previous ? ctx->dhtContext->stateOld : ctx->dhtContext->stateNew;
1281 std::tie(key, loc) = computeKeys(ctx->credentials->password,
1282 ctx->credentials->uri,
1284 JAMI_LOG(
"[Auth] Attempting to load account from DHT with {:s} at {:s}",
1285 ctx->credentials->uri,
1287 if (not ctx->dhtContext or ctx->dhtContext->found) {
1290 ctx->dhtContext->dht.get(
1292 [ctx, key = std::move(key), w](
const std::shared_ptr<dht::Value>& val) {
1293 std::vector<uint8_t> decrypted;
1295 decrypted = archiver::decompress(
1296 dht::crypto::aesDecrypt(val->data, key));
1297 }
catch (
const std::exception& ex) {
1300 JAMI_DBG(
"[Auth] Found archive on the DHT");
1301 ctx->dhtContext->found =
true;
1302 dht::ThreadPool::computation().run(
1303 [ctx, decrypted = std::move(decrypted), w] {
1305 auto archive = AccountArchive(decrypted);
1306 if (
auto sthis = w.lock()) {
1307 if (ctx->dhtContext) {
1308 ctx->dhtContext->dht.join();
1309 ctx->dhtContext.reset();
1311 sthis->onArchiveLoaded(*ctx, std::move(archive),
false);
1313 }
catch (
const std::exception& e) {
1314 ctx->onFailure(AuthError::UNKNOWN,
"");
1317 return not ctx->dhtContext->found;
1320 JAMI_LOG(
"[Auth] DHT archive search ended at {}", loc.toString());
1325 }
catch (
const std::exception& e) {
1333 dht::ThreadPool::computation().run(std::bind(search,
true));
1334 dht::ThreadPool::computation().run(std::bind(search,
false));
1339ArchiveAccountManager::migrateAccount(AuthContext& ctx)
1341 JAMI_WARN(
"[Auth] Account migration needed");
1342 AccountArchive archive;
1344 archive =
readArchive(ctx.credentials->password_scheme, ctx.credentials->password);
1346 JAMI_DBG(
"[Auth] Unable to load archive");
1347 ctx.onFailure(AuthError::INVALID_ARGUMENTS,
"");
1351 updateArchive(archive);
1353 if (updateCertificates(archive, ctx.credentials->updateIdentity)) {
1356 onArchiveLoaded(ctx, std::move(archive),
false);
1358 ctx.onFailure(AuthError::UNKNOWN,
"");
1363ArchiveAccountManager::onArchiveLoaded(AuthContext& ctx, AccountArchive&& a,
bool isLinkDevProtocol)
1366 dhtnet::fileutils::check_dir(path_, 0700);
1368 if (isLinkDevProtocol) {
1370 ctx.linkDevCtx->authScheme.empty() ? FALSE_STR : TRUE_STR;
1372 a.
save(fileutils::getFullPath(path_, archivePath_),
1373 ctx.linkDevCtx->authScheme,
1374 ctx.linkDevCtx->credentialsFromUser);
1377 ctx.credentials->password_scheme.empty() ? FALSE_STR : TRUE_STR;
1379 a.
save(fileutils::getFullPath(path_, archivePath_),
1380 ctx.credentials ? ctx.credentials->password_scheme :
"",
1381 ctx.credentials ? ctx.credentials->
password :
"");
1384 if (not a.
id.second->isCA()) {
1385 JAMI_ERROR(
"[Account {}] [Auth] Attempting to sign a certificate with a non-CA.",
1389 std::shared_ptr<dht::crypto::Certificate> deviceCertificate;
1390 std::unique_ptr<ContactList> contacts;
1391 auto usePreviousIdentity =
false;
1393 if (
auto oldId = ctx.credentials->updateIdentity.second) {
1394 contacts = std::make_unique<ContactList>(ctx.accountId, oldId, path_, onChange_);
1395 if (contacts->isValidAccountDevice(*oldId) && ctx.credentials->updateIdentity.first) {
1396 deviceCertificate = oldId;
1397 usePreviousIdentity =
true;
1398 JAMI_WARNING(
"[Account {}] [Auth] Using previously generated device certificate {}",
1400 deviceCertificate->getLongId());
1407 if (!deviceCertificate) {
1408 JAMI_WARNING(
"[Account {}] [Auth] Creating new device certificate", accountId_);
1409 auto request = ctx.request.get();
1410 if (not request->verify()) {
1411 JAMI_ERROR(
"[Account {}] [Auth] Invalid certificate request.", accountId_);
1412 ctx.onFailure(AuthError::INVALID_ARGUMENTS,
"");
1415 deviceCertificate = std::make_shared<dht::crypto::Certificate>(
1416 dht::crypto::Certificate::generate(*request, a.
id));
1417 JAMI_WARNING(
"[Account {}] [Auth] Created new device: {}",
1419 deviceCertificate->getLongId());
1422 auto receipt = makeReceipt(a.
id, *deviceCertificate, ethAccount);
1423 auto receiptSignature = a.
id.first->sign({receipt.first.begin(), receipt.first.end()});
1425 auto info = std::make_unique<AccountInfo>();
1426 auto pk = usePreviousIdentity ? ctx.credentials->updateIdentity.first : ctx.key.get();
1427 auto sharedPk = pk->getSharedPublicKey();
1428 info->identity.first = pk;
1429 info->identity.second = deviceCertificate;
1430 info->accountId = a.
id.second->getId().toString();
1431 info->devicePk = sharedPk;
1432 info->deviceId = info->devicePk->getLongId().toString();
1433 if (ctx.deviceName.empty())
1434 ctx.deviceName = info->deviceId.substr(8);
1437 contacts = std::make_unique<ContactList>(ctx.accountId, a.
id.second, path_, onChange_);
1439 info->contacts = std::move(contacts);
1440 info->contacts->setContacts(a.
contacts);
1441 info->contacts->foundAccountDevice(deviceCertificate, ctx.deviceName, clock::now());
1442 info->ethAccount = ethAccount;
1443 info->announce = std::move(receipt.second);
1444 ConversationModule::saveConvInfosToPath(path_, a.
conversations);
1446 info_ = std::move(info);
1448 ctx.onSuccess(*info_,
1450 std::move(receipt.first),
1451 std::move(receiptSignature));
1454std::pair<std::vector<uint8_t>, dht::InfoHash>
1455ArchiveAccountManager::computeKeys(
const std::string& password,
1456 const std::string& pin,
1460 auto now = std::chrono::duration_cast<std::chrono::seconds>(clock::now().time_since_epoch());
1461 auto tseed = now.count() / std::chrono::seconds(EXPORT_KEY_RENEWAL_TIME).count();
1464 std::ostringstream ss;
1465 ss << std::hex << tseed;
1466 auto tseed_str = ss.str();
1469 std::vector<uint8_t> salt_key;
1470 salt_key.reserve(pin.size() + tseed_str.size());
1471 salt_key.insert(salt_key.end(), pin.begin(), pin.end());
1472 salt_key.insert(salt_key.end(), tseed_str.begin(), tseed_str.end());
1473 auto key = dht::crypto::stretchKey(password, salt_key, 256 / 8);
1476 auto loc = dht::InfoHash::get(key);
1481std::pair<std::string, std::shared_ptr<dht::Value>>
1482ArchiveAccountManager::makeReceipt(
const dht::crypto::Identity&
id,
1483 const dht::crypto::Certificate& device,
1484 const std::string& ethAccount)
1486 JAMI_LOG(
"[Account {}] [Auth] Signing receipt for device {}", accountId_, device.getLongId());
1487 auto devId = device.getId();
1488 DeviceAnnouncement announcement;
1489 announcement.dev = devId;
1490 announcement.pk = device.getSharedPublicKey();
1491 dht::Value ann_val {announcement};
1492 ann_val.sign(*
id.first);
1494 auto packedAnnoucement = ann_val.getPacked();
1495 JAMI_LOG(
"[Account {}] [Auth] Device announcement size: {}",
1497 packedAnnoucement.size());
1499 std::ostringstream is;
1500 is <<
"{\"id\":\"" <<
id.second->getId() <<
"\",\"dev\":\"" << devId <<
"\",\"eth\":\""
1501 << ethAccount <<
"\",\"announce\":\"" << base64::encode(packedAnnoucement) <<
"\"}";
1504 return {is.str(), std::make_shared<dht::Value>(std::move(ann_val))};
1508ArchiveAccountManager::needsMigration(
const std::string& accountId,
const dht::crypto::Identity&
id)
1512 auto cert =
id.second->issuer;
1514 if (not cert->isCA()) {
1515 JAMI_WARNING(
"[Account {}] [Auth] certificate {} is not a CA, needs update.",
1520 if (cert->getExpiration() < clock::now()) {
1521 JAMI_WARNING(
"[Account {}] [Auth] certificate {} is expired, needs update.",
1526 cert = cert->issuer;
1532ArchiveAccountManager::syncDevices()
1534 if (not dht_ or not dht_->isRunning()) {
1535 JAMI_WARNING(
"[Account {}] Not syncing devices: DHT is not running", accountId_);
1538 JAMI_LOG(
"[Account {}] Building device sync from {}", accountId_, info_->deviceId);
1539 auto sync_data = info_->contacts->getSyncData();
1541 for (
const auto&
dev : getKnownDevices()) {
1543 if (
dev.first.toString() == info_->deviceId) {
1546 if (!
dev.second.certificate) {
1547 JAMI_WARNING(
"[Account {}] Unable to find certificate for {}", accountId_,
dev.first);
1550 auto pk =
dev.second.certificate->getSharedPublicKey();
1551 JAMI_LOG(
"[Account {}] Sending device sync to {} {}",
1554 dev.first.toString());
1555 auto syncDeviceKey = dht::InfoHash::get(
"inbox:" + pk->getId().toString());
1556 dht_->putEncrypted(syncDeviceKey, pk, sync_data);
1563 bool publishPresence)
1565 AccountManager::startSync(std::move(cb), std::move(dcb), publishPresence);
1568 dht::InfoHash::get(
"inbox:" + info_->devicePk->getId().toString()),
1574 [
this, sync](
const std::shared_ptr<dht::crypto::Certificate>& cert)
mutable {
1575 if (!cert or cert->getId() != sync.from) {
1576 JAMI_WARNING(
"[Account {}] Unable to find certificate for device {}",
1578 sync.from.toString());
1581 if (not foundAccountDevice(cert))
1583 onSyncData(std::move(sync));
1591ArchiveAccountManager::readArchive(std::string_view scheme,
const std::string& pwd)
const
1593 JAMI_LOG(
"[Account {}] [Auth] Reading account archive", accountId_);
1594 return AccountArchive(fileutils::getFullPath(path_, archivePath_), scheme, pwd);
1598ArchiveAccountManager::updateArchive(AccountArchive& archive)
const
1603 static const auto filtered_keys = {Ringtone::PATH,
1607 Conf::CONFIG_DHT_PORT,
1615 static const auto encoded_keys = {TLS::CA_LIST_FILE,
1616 TLS::CERTIFICATE_FILE,
1617 TLS::PRIVATE_KEY_FILE};
1619 JAMI_LOG(
"[Account {}] [Auth] Building account archive", accountId_);
1620 for (
const auto& it : onExportConfig_()) {
1622 if (std::any_of(std::begin(filtered_keys), std::end(filtered_keys), [&](
const auto& key) {
1623 return key == it.first;
1628 if (std::any_of(std::begin(encoded_keys), std::end(encoded_keys), [&](
const auto& key) {
1629 return key == it.first;
1632 archive.config.emplace(it.first, base64::encode(fileutils::loadFile(it.second)));
1636 archive.config[it.first] = it.second;
1640 archive.contacts = info_->contacts->getContacts();
1642 archive.conversations = ConversationModule::convInfosFromPath(path_);
1643 archive.conversationsRequests = ConversationModule::convRequestsFromPath(path_);
1648ArchiveAccountManager::saveArchive(AccountArchive& archive,
1649 std::string_view scheme,
1650 const std::string& pwd)
1653 updateArchive(archive);
1654 if (archivePath_.empty())
1655 archivePath_ =
"export.gz";
1656 archive.save(fileutils::getFullPath(path_, archivePath_), scheme, pwd);
1657 }
catch (
const std::runtime_error& ex) {
1658 JAMI_ERROR(
"[Account {}] [Auth] Unable to export archive: {}", accountId_, ex.what());
1664ArchiveAccountManager::changePassword(
const std::string& password_old,
1665 const std::string& password_new)
1668 auto path = fileutils::getFullPath(path_, archivePath_);
1669 AccountArchive(path, fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD, password_old)
1670 .
save(path, fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD, password_new);
1672 }
catch (
const std::exception&) {
1678ArchiveAccountManager::getPasswordKey(
const std::string& password)
1681 auto data = dhtnet::fileutils::loadFile(fileutils::getFullPath(path_, archivePath_));
1683 auto key = dht::crypto::aesGetKey(data, password);
1684 auto decrypted = dht::crypto::aesDecrypt(dht::crypto::aesGetEncrypted(data), key);
1686 }
catch (
const std::exception& e) {
1687 JAMI_ERROR(
"[Account {}] Error loading archive: {}", accountId_, e.what());
1693ArchiveAccountManager::revokeDevice(
const std::string& device,
1694 std::string_view scheme,
1695 const std::string& password,
1698 auto fa = dht::ThreadPool::computation().getShared<
AccountArchive>(
1699 [
this, scheme = std::string(scheme), password] {
return readArchive(scheme, password); });
1701 [fa = std::move(fa),
1702 scheme = std::string(scheme),
1707 const std::shared_ptr<dht::crypto::Certificate>& crt)
mutable {
1709 cb(RevokeDeviceResult::ERROR_NETWORK);
1712 auto this_ = w.lock();
1715 this_->info_->contacts->foundAccountDevice(crt);
1720 cb(RevokeDeviceResult::ERROR_CREDENTIALS);
1725 a.
revoked = std::make_shared<
decltype(a.
revoked)::element_type>();
1729 this_->certStore().pinRevocationList(a.
id.second->getId().toString(),
1731 this_->certStore().loadRevocations(*a.
id.second);
1734 auto h = a.
id.second->getId();
1735 this_->dht_->put(h, a.
revoked, dht::DoneCallback {}, {},
true);
1737 this_->saveArchive(a, scheme, password);
1738 this_->info_->contacts->removeAccountDevice(crt->getLongId());
1739 cb(RevokeDeviceResult::SUCCESS);
1740 this_->syncDevices();
1746ArchiveAccountManager::exportArchive(
const std::string& destinationPath,
1747 std::string_view scheme,
1748 const std::string& password)
1753 updateArchive(archive);
1754 auto archivePath = fileutils::getFullPath(path_, archivePath_);
1755 if (!archive.
save(archivePath, scheme, password))
1760 std::filesystem::copy_file(archivePath,
1762 std::filesystem::copy_options::overwrite_existing,
1765 }
catch (
const std::runtime_error& ex) {
1766 JAMI_ERR(
"[Auth] Unable to export archive: %s", ex.what());
1769 JAMI_ERR(
"[Auth] Unable to export archive: Unable to read archive");
1775ArchiveAccountManager::isPasswordValid(
const std::string& password)
1778 readArchive(fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD, password);
1787ArchiveAccountManager::registerName(
const std::string& name,
1788 std::string_view scheme,
1789 const std::string& password,
1790 RegistrationCallback cb)
1792 std::string signedName;
1793 auto nameLowercase {name};
1794 std::transform(nameLowercase.begin(), nameLowercase.end(), nameLowercase.begin(), ::tolower);
1795 std::string publickey;
1796 std::string accountId;
1797 std::string ethAccount;
1800 auto archive = readArchive(scheme, password);
1801 auto privateKey = archive.id.first;
1802 const auto& pk = privateKey->getPublicKey();
1803 publickey = pk.toString();
1804 accountId = pk.getId().toString();
1805 signedName = base64::encode(
1806 privateKey->sign(std::vector<uint8_t>(nameLowercase.begin(), nameLowercase.end())));
1808 }
catch (
const std::exception& e) {
1810 cb(NameDirectory::RegistrationResponse::invalidCredentials, name);
1814 nameDir_.get().registerName(accountId, nameLowercase, ethAccount, cb, signedName, publickey);
Account specific keys/constants that must be shared in daemon and clients.
Simple class that represents a "key pair".
static KeyPair create()
Create a new, randomly generated object.
Address const & address() const
Retrieve the associated address of the public key.
std::function< void(const std::shared_ptr< dht::crypto::Certificate > &)> OnNewDeviceCb
const std::string accountId_
OnChangeCallback onChange_
CertRequest buildRequest(PrivateKey fDeviceKey)
std::function< void()> OnDeviceAnnouncedCb
std::shared_future< std::shared_ptr< dht::crypto::PrivateKey > > PrivateKey
std::function< void(RevokeDeviceResult)> RevokeDeviceCallback
std::function< void(AuthError error, const std::string &message)> AuthFailureCallback
std::function< void(const AccountInfo &info, const std::map< std::string, std::string > &config, std::string &&receipt, std::vector< uint8_t > &&receipt_signature)> AuthSuccessCallback
void initAuthentication(PrivateKey request, std::string deviceName, std::unique_ptr< AccountCredentials > credentials, AuthSuccessCallback onSuccess, AuthFailureCallback onFailure, const OnChangeCallback &onChange) override
Manages channels for syncing informations.
void connect(const DeviceId &deviceId, const std::string &name, ConnectCb &&cb, const std::string &connectionType="", bool forceNewConnection=false) override
Ask for a new sync channel.
#define JAMI_ERROR(formatstr,...)
#define JAMI_DEBUG(formatstr,...)
#define JAMI_WARNING(formatstr,...)
#define JAMI_LOG(formatstr,...)
static constexpr auto stateMsg
static constexpr auto accData
static constexpr auto password
static constexpr auto passwordCorrect
static constexpr auto canRetry
static constexpr auto authScheme
ArchiveStorageData readArchive(const std::filesystem::path &path, std::string_view scheme, const std::string &pwd)
static constexpr std::string_view toString(AuthDecodingState state)
void emitSignal(Args... args)
constexpr auto CHANNEL_SCHEME
const constexpr auto EXPORT_KEY_RENEWAL_TIME
constexpr auto AUTH_URI_SCHEME
constexpr auto OP_TIMEOUT
static constexpr const char ARCHIVE_HAS_PASSWORD[]
Crypto material contained in the archive, not persisted in the account configuration.
bool save(const std::filesystem::path &path, std::string_view scheme, const std::string &password) const
Save archive to file, optionally encrypted with provided password.
std::map< dht::InfoHash, Contact > contacts
Contacts.
std::map< std::string, ConversationRequest > conversationsRequests
std::shared_ptr< dht::crypto::RevocationList > revoked
Revoked devices.
std::shared_ptr< dht::crypto::PrivateKey > ca_key
Generated CA key (for self-signed certificates)
dht::crypto::Identity id
Account main private key and certificate chain.
std::map< std::string, ConvInfo > conversations
std::vector< uint8_t > eth_key
Ethereum private key.
std::map< std::string, std::string > config
Account configuration.
AuthMsg createCanceledMsg() const
std::string_view authScheme
AddDeviceContext(std::shared_ptr< dhtnet::ChannelSocket > c)
std::shared_ptr< dhtnet::ChannelSocket > channel
void set(std::string_view key, std::string_view value)
std::map< std::string, std::string > payload
auto at(std::string_view key) const
auto find(std::string_view key) const
std::map< std::string, std::string > Map
static DeviceAuthInfo createError(Error err)
DeviceAuthInfo(const Map &map)
void set(std::string_view key, std::string_view value)
DeviceAuthInfo(Map &&map)
constexpr std::string_view formattedAuthState() const
DeviceAuthInfo::Error getErrorState() const
bool handleTimeoutMessage(const AuthMsg &msg)
bool handleCanceledMessage(const AuthMsg &msg)
DeviceContextBase(uint64_t operationId, AuthDecodingState initialState)
LinkDeviceContext(dht::crypto::Identity id)
dht::crypto::Identity tmpId
dhtnet::ConnectionManager tempConnMgr
std::shared_ptr< dhtnet::ChannelSocket > channel