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);
286static constexpr std::string_view
290 case AuthDecodingState::HANDSHAKE:
291 return "HANDSHAKE"sv;
292 case AuthDecodingState::EST:
294 case AuthDecodingState::AUTH:
296 case AuthDecodingState::DATA:
298 case AuthDecodingState::AUTH_ERROR:
299 return "AUTH_ERROR"sv;
300 case AuthDecodingState::DONE:
302 case AuthDecodingState::TIMEOUT:
304 case AuthDecodingState::CANCELED:
306 case AuthDecodingState::ERR:
312namespace PayloadKey {
323 uint8_t schemeId {0};
325 MSGPACK_DEFINE_MAP(schemeId, payload)
327 void set(
std::string_view key,
std::string_view value) {
328 payload.emplace(std::string(key), std::string(value));
331 auto find(std::string_view key)
const {
return payload.find(std::string(key)); }
333 auto at(std::string_view key)
const {
return payload.at(std::string(key)); }
338 std::string logStr = fmt::format(
"=========\nscheme: {}\n", schemeId);
339 for (
const auto& [msgKey, msgVal] : payload) {
340 logStr += fmt::format(
" - {}: {}\n", msgKey, msgVal);
342 logStr +=
"=========";
348 timeoutMsg.
set(PayloadKey::stateMsg,
toString(AuthDecodingState::TIMEOUT));
356 static constexpr auto token =
"token"sv;
357 static constexpr auto error =
"error"sv;
358 static constexpr auto auth_scheme =
"auth_scheme"sv;
359 static constexpr auto peer_id =
"peer_id"sv;
360 static constexpr auto auth_error =
"auth_error"sv;
361 static constexpr auto peer_address =
"peer_address"sv;
366 using Map = std::map<std::string, std::string>;
376 void set(std::string_view key, std::string_view value) {
377 emplace(std::string(key), std::string(value));
390 case Error::AUTH_ERROR:
391 errStr =
"auth_error";
393 case Error::CANCELED:
412 bool authEnabled {
false};
413 bool archiveTransferredWithoutFailure {
false};
418 , state(initialState)
425 auto stateMsgIt = msg.
find(PayloadKey::stateMsg);
426 if (stateMsgIt != msg.
payload.end()) {
427 if (stateMsgIt->second ==
toString(AuthDecodingState::TIMEOUT)) {
428 this->state = AuthDecodingState::TIMEOUT;
437 auto stateMsgIt = msg.
find(PayloadKey::stateMsg);
438 if (stateMsgIt != msg.
payload.end()) {
439 if (stateMsgIt->second ==
toString(AuthDecodingState::CANCELED)) {
440 this->state = AuthDecodingState::CANCELED;
449 if (state == AuthDecodingState::AUTH_ERROR) {
450 return DeviceAuthInfo::Error::AUTH_ERROR;
451 }
else if (state == AuthDecodingState::TIMEOUT) {
452 return DeviceAuthInfo::Error::TIMEOUT;
453 }
else if (state == AuthDecodingState::CANCELED) {
454 return DeviceAuthInfo::Error::CANCELED;
455 }
else if (state == AuthDecodingState::ERR) {
456 return DeviceAuthInfo::Error::UNKNOWN;
457 }
else if (archiveTransferredWithoutFailure) {
458 return DeviceAuthInfo::Error::NONE;
460 return DeviceAuthInfo::Error::NETWORK;
465 return state == AuthDecodingState::DONE || state == AuthDecodingState::ERR
466 || state == AuthDecodingState::AUTH_ERROR || state == AuthDecodingState::TIMEOUT
467 || state == AuthDecodingState::CANCELED;
475 unsigned numOpenChannels {0};
476 unsigned maxOpenChannels {1};
477 std::shared_ptr<dhtnet::ChannelSocket>
channel;
478 msgpack::unpacker pac {[](msgpack::type::object_type, std::size_t,
void*) {
return true; },
481 std::string authScheme {fileutils::ARCHIVE_AUTH_SCHEME_NONE};
482 std::string credentialsFromUser {
""};
486 , tmpId(
std::move(id))
493 unsigned numTries {0};
494 unsigned maxTries {3};
495 std::shared_ptr<dhtnet::ChannelSocket>
channel;
501 , channel(
std::move(c))
507 timeoutMsg.
set(PayloadKey::stateMsg,
toString(AuthDecodingState::CANCELED));
513ArchiveAccountManager::provideAccountAuthentication(
const std::string& key,
514 const std::string& scheme)
516 if (scheme != fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD) {
517 JAMI_ERROR(
"[LinkDevice] Unsupported account authentication scheme attempted.");
526 if (
ctx->linkDevCtx->state != AuthDecodingState::AUTH) {
527 JAMI_WARNING(
"[LinkDevice] Invalid state for providing account authentication.");
531 ctx->linkDevCtx->authScheme = scheme;
532 ctx->linkDevCtx->credentialsFromUser = key;
534 ctx->linkDevCtx->state = AuthDecodingState::DATA;
535 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
536 ctx->accountId,
static_cast<uint8_t
>(DeviceAuthState::IN_PROGRESS),
DeviceAuthInfo {});
538 dht::ThreadPool::io().run([key = std::move(key), scheme,
ctx]()
mutable {
540 toSend.
set(PayloadKey::password, std::move(key));
541 msgpack::sbuffer buffer(UINT16_MAX);
543 msgpack::pack(buffer, toSend);
546 ctx->linkDevCtx->channel->write(
reinterpret_cast<const unsigned char*
>(buffer.data()),
549 }
catch (
const std::exception& e) {
550 JAMI_WARNING(
"[LinkDevice] Failed to send password over auth ChannelSocket. Channel "
560 msgpack::unpacker pac {[](msgpack::type::object_type, std::size_t,
void*) {
return true; },
567ArchiveAccountManager::startLoadArchiveFromDevice(
const std::shared_ptr<AuthContext>&
ctx)
570 JAMI_WARNING(
"[LinkDevice] Already loading archive from device.");
571 ctx->onFailure(AuthError::INVALID_ARGUMENTS,
"Already loading archive from device.");
574 JAMI_DEBUG(
"[LinkDevice] Starting load archive from device {} {}.",
579 dht::ThreadPool::computation().run([ctx, wthis = weak()] {
580 auto ca = dht::crypto::generateEcIdentity(
"Jami Temporary CA");
581 if (!ca.first || !ca.second) {
582 throw std::runtime_error(
"[LinkDevice] Can't generate CA for this account.");
585 auto user = dht::crypto::generateIdentity(
"Jami Temporary User", ca, 4096,
true);
586 if (!user.first || !user.second) {
587 throw std::runtime_error(
"[LinkDevice] Can't generate identity for this account.");
590 auto this_ = wthis.lock();
592 JAMI_WARNING(
"[LinkDevice] Failed to get the ArchiveAccountManager.");
597 ctx->linkDevCtx = std::make_shared<LinkDeviceContext>(
598 dht::crypto::generateIdentity(
"Jami Temporary device", user));
599 JAMI_LOG(
"[LinkDevice] Established linkDevCtx. {} {} {}.",
602 fmt::ptr(ctx->linkDevCtx));
605 auto gen = Manager::instance().getSeededRandomEngine();
606 ctx->linkDevCtx->opId = std::uniform_int_distribution<uint64_t>(100000, 999999)(gen);
608 ctx->linkDevCtx->tempConnMgr.oniOSConnected(
609 [&](
const std::string& connType, dht::InfoHash peer_h) {
return false; });
611 ctx->linkDevCtx->tempConnMgr.onDhtConnected(ctx->linkDevCtx->tmpId.second->getPublicKey());
613 auto accountScheme = fmt::format(
"{}{}/{}",
615 ctx->linkDevCtx->tmpId.second->getId(),
616 ctx->linkDevCtx->opId);
617 JAMI_LOG(
"[LinkDevice] auth scheme will be: {}", accountScheme);
620 info.set(DeviceAuthInfo::token, accountScheme);
622 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
623 ctx->accountId,
static_cast<uint8_t
>(DeviceAuthState::TOKEN_AVAILABLE), info);
625 ctx->linkDevCtx->tempConnMgr.onICERequest(
626 [wctx = std::weak_ptr(ctx)](
const DeviceId& deviceId) {
627 if (
auto ctx = wctx.lock()) {
628 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
630 static_cast<uint8_t>(DeviceAuthState::CONNECTING),
637 ctx->linkDevCtx->tempConnMgr.onChannelRequest(
638 [wthis, ctx](
const std::shared_ptr<dht::crypto::Certificate>& cert,
639 const std::string& name) {
640 std::string_view url(name);
641 if (!starts_with(url, CHANNEL_SCHEME)) {
643 "[LinkDevice] Temporary connection manager received invalid scheme: {}",
650 if (ctx->linkDevCtx->opId == parsedOpId
651 && ctx->linkDevCtx->numOpenChannels < ctx->linkDevCtx->maxOpenChannels) {
652 ctx->linkDevCtx->numOpenChannels++;
653 JAMI_DEBUG(
"[LinkDevice] Opening channel ({}/{}): {}",
654 ctx->linkDevCtx->numOpenChannels,
655 ctx->linkDevCtx->maxOpenChannels,
662 ctx->linkDevCtx->tempConnMgr.onConnectionReady([ctx,
664 wthis](
const DeviceId& deviceId,
665 const std::string& name,
666 std::shared_ptr<dhtnet::ChannelSocket> socket) {
668 JAMI_WARNING(
"[LinkDevice] Temporary connection manager received invalid socket.");
670 ctx->timeout->cancel();
671 ctx->timeout.reset();
672 ctx->linkDevCtx->numOpenChannels--;
673 if (
auto sthis = wthis.lock())
674 sthis->authCtx_.reset();
675 ctx->linkDevCtx->state = AuthDecodingState::ERR;
676 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
678 static_cast<uint8_t
>(DeviceAuthState::DONE),
679 DeviceAuthInfo::createError(DeviceAuthInfo::Error::NETWORK));
682 ctx->linkDevCtx->channel = socket;
684 ctx->timeout = std::make_unique<asio::steady_timer>(*Manager::instance().ioContext());
685 ctx->timeout->expires_after(OP_TIMEOUT);
686 ctx->timeout->async_wait([c = std::weak_ptr(ctx), socket](
const std::error_code& ec) {
690 if (
auto ctx = c.lock()) {
691 if (!ctx->linkDevCtx->isCompleted()) {
692 ctx->linkDevCtx->state = AuthDecodingState::TIMEOUT;
693 JAMI_WARNING(
"[LinkDevice] timeout: {}", socket->name());
696 msgpack::sbuffer buffer(UINT16_MAX);
697 msgpack::pack(buffer, AuthMsg::timeout());
699 socket->write(reinterpret_cast<const unsigned char*>(buffer.data()),
707 socket->onShutdown([ctx, name, wthis]() {
708 JAMI_WARNING(
"[LinkDevice] Temporary connection manager closing socket: {}", name);
710 ctx->timeout->cancel();
711 ctx->timeout.reset();
712 ctx->linkDevCtx->numOpenChannels--;
713 ctx->linkDevCtx->channel.reset();
714 if (
auto sthis = wthis.lock())
715 sthis->authCtx_.reset();
717 DeviceAuthInfo::Error error = ctx->linkDevCtx->getErrorState();
718 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
720 static_cast<uint8_t
>(DeviceAuthState::DONE),
721 DeviceAuthInfo::createError(error));
724 socket->setOnRecv([ctx,
725 decodingCtx = std::make_shared<DecodingContext>(),
726 wthis](
const uint8_t* buf,
size_t len) {
731 decodingCtx->pac.reserve_buffer(len);
732 std::copy_n(buf, len, decodingCtx->pac.buffer());
733 decodingCtx->pac.buffer_consumed(len);
736 msgpack::object_handle oh;
737 if (decodingCtx->pac.next(oh)) {
738 JAMI_DEBUG(
"[LinkDevice] NEW: Unpacking message.");
739 oh.get().convert(toRecv);
743 }
catch (
const std::exception& e) {
744 ctx->linkDevCtx->state = AuthDecodingState::ERR;
745 JAMI_ERROR(
"[LinkDevice] Error unpacking message from source device: {}", e.what());
749 JAMI_DEBUG(
"[LinkDevice] NEW: Successfully unpacked message from source\n{}",
751 JAMI_DEBUG(
"[LinkDevice] NEW: State is {}:{}",
752 ctx->linkDevCtx->scheme,
753 ctx->linkDevCtx->formattedAuthState());
756 if (toRecv.schemeId != 0) {
757 JAMI_WARNING(
"[LinkDevice] NEW: Unsupported scheme received from source");
758 ctx->linkDevCtx->state = AuthDecodingState::ERR;
763 if (ctx->linkDevCtx->handleCanceledMessage(toRecv)) {
768 bool shouldShutdown =
false;
769 auto accDataIt = toRecv.find(PayloadKey::accData);
770 bool shouldLoadArchive = accDataIt != toRecv.payload.end();
772 if (ctx->linkDevCtx->state == AuthDecodingState::HANDSHAKE) {
773 auto peerCert = ctx->linkDevCtx->channel->peerCertificate();
774 auto authScheme = toRecv.at(PayloadKey::authScheme);
776 != fileutils::ARCHIVE_AUTH_SCHEME_NONE;
778 JAMI_DEBUG(
"[LinkDevice] NEW: Auth scheme from payload is '{}'", authScheme);
779 ctx->linkDevCtx->state = AuthDecodingState::AUTH;
781 info.set(DeviceAuthInfo::auth_scheme, authScheme);
782 info.set(DeviceAuthInfo::peer_id, peerCert->issuer->getId().toString());
783 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
784 ctx->accountId,
static_cast<uint8_t
>(DeviceAuthState::AUTHENTICATING), info);
785 }
else if (ctx->linkDevCtx->state == AuthDecodingState::DATA) {
786 auto passwordCorrectIt = toRecv.find(PayloadKey::passwordCorrect);
787 auto canRetry = toRecv.find(PayloadKey::canRetry);
790 if (canRetry != toRecv.payload.end() &&
canRetry->second ==
"false") {
791 JAMI_DEBUG(
"[LinkDevice] Authentication failed: maximum retry attempts "
793 ctx->linkDevCtx->state = AuthDecodingState::AUTH_ERROR;
798 if (passwordCorrectIt != toRecv.payload.end()
799 && passwordCorrectIt->second ==
"false") {
800 ctx->linkDevCtx->state = AuthDecodingState::AUTH;
802 JAMI_DEBUG(
"[LinkDevice] NEW: Password incorrect.");
803 auto peerCert = ctx->linkDevCtx->channel->peerCertificate();
804 auto peer_id = peerCert->issuer->getId().toString();
807 auto authScheme = fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD;
810 info.set(DeviceAuthInfo::auth_scheme, authScheme);
811 info.set(DeviceAuthInfo::peer_id, peer_id);
812 info.set(DeviceAuthInfo::auth_error,
"invalid_credentials");
814 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
816 static_cast<uint8_t
>(DeviceAuthState::AUTHENTICATING),
821 if (!shouldLoadArchive) {
822 JAMI_DEBUG(
"[LinkDevice] NEW: no archive received.");
825 ctx->linkDevCtx->state = AuthDecodingState::ERR;
826 shouldShutdown =
true;
831 if (shouldLoadArchive) {
832 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
834 static_cast<uint8_t
>(DeviceAuthState::IN_PROGRESS),
837 auto archive = AccountArchive(std::string_view(accDataIt->second));
838 if (
auto this_ = wthis.lock()) {
839 JAMI_DEBUG(
"[LinkDevice] NEW: Reading archive from peer.");
840 this_->onArchiveLoaded(*ctx, std::move(archive),
true);
841 JAMI_DEBUG(
"[LinkDevice] NEW: Successfully loaded archive.");
842 ctx->linkDevCtx->archiveTransferredWithoutFailure =
true;
844 ctx->linkDevCtx->archiveTransferredWithoutFailure =
false;
845 JAMI_ERROR(
"[LinkDevice] NEW: Failed to load account because of "
846 "null ArchiveAccountManager!");
848 }
catch (
const std::exception& e) {
849 ctx->linkDevCtx->state = AuthDecodingState::ERR;
850 ctx->linkDevCtx->archiveTransferredWithoutFailure =
false;
851 JAMI_WARNING(
"[LinkDevice] NEW: Error reading archive.");
853 shouldShutdown =
true;
856 if (shouldShutdown) {
857 ctx->linkDevCtx->channel->shutdown();
863 ctx->linkDevCtx->state = AuthDecodingState::HANDSHAKE;
867 JAMI_DEBUG(
"[LinkDevice] NEW: Packing first message for SOURCE.\nCurrent state is: "
871 ctx->linkDevCtx->formattedAuthState());
872 msgpack::sbuffer buffer(UINT16_MAX);
873 msgpack::pack(buffer, toSend);
875 ctx->linkDevCtx->channel->write(
reinterpret_cast<const unsigned char*
>(buffer.data()),
879 JAMI_LOG(
"[LinkDevice {}] Generated temporary account.",
880 ctx->linkDevCtx->tmpId.second->getId());
883 JAMI_DEBUG(
"[LinkDevice] Starting load archive from device END {} {}.",
889ArchiveAccountManager::addDevice(
const std::string& uriProvided,
890 std::string_view auth_scheme,
894 JAMI_WARNING(
"[LinkDevice] addDevice: auth context already exists.");
895 return static_cast<int32_t
>(AccountManager::AddDeviceError::ALREADY_LINKING);
897 JAMI_LOG(
"[LinkDevice] ArchiveAccountManager::addDevice({}, {})", accountId_, uriProvided);
899 std::string_view url(uriProvided);
901 JAMI_ERROR(
"[LinkDevice] Invalid uri provided: {}", uriProvided);
902 return static_cast<int32_t
>(AccountManager::AddDeviceError::INVALID_URI);
905 auto peerCodeS = url.substr(
AUTH_URI_SCHEME.length() + peerTempAcc.length() + 1, 6);
906 JAMI_LOG(
"[LinkDevice] ======\n * tempAcc = {}\n * code = {}", peerTempAcc, peerCodeS);
908 auto gen = Manager::instance().getSeededRandomEngine();
909 std::uniform_int_distribution<int32_t> dist(1, INT32_MAX);
910 auto token = dist(gen);
911 JAMI_WARNING(
"[LinkDevice] SOURCE: Creating auth context, token: {}.", token);
912 auto ctx = std::make_shared<AuthContext>();
913 ctx->accountId = accountId_;
915 ctx->credentials = std::make_unique<ArchiveAccountCredentials>();
919 dht::InfoHash(peerTempAcc),
921 [wthis = weak(), auth_scheme,
ctx, accountId=accountId_](std::shared_ptr<dhtnet::ChannelSocket> socket,
922 const dht::InfoHash& infoHash) {
923 auto this_ = wthis.lock();
924 if (!socket || !this_) {
925 JAMI_WARNING(
"[LinkDevice] Invalid socket event while AccountManager connecting.");
927 this_->authCtx_.reset();
928 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
931 static_cast<uint8_t
>(DeviceAuthState::DONE),
932 DeviceAuthInfo::createError(DeviceAuthInfo::Error::NETWORK));
934 if (!this_->doAddDevice(auth_scheme,
ctx, socket))
935 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
938 static_cast<uint8_t
>(DeviceAuthState::DONE),
939 DeviceAuthInfo::createError(DeviceAuthInfo::Error::UNKNOWN));
942 runOnMainThread([token,
id = accountId_] {
943 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
944 id, token,
static_cast<uint8_t
>(DeviceAuthState::CONNECTING),
DeviceAuthInfo {});
947 }
catch (
const std::exception& e) {
948 JAMI_ERROR(
"[LinkDevice] Parsing uri failed: {}", uriProvided);
949 return static_cast<int32_t
>(AccountManager::AddDeviceError::GENERIC);
954ArchiveAccountManager::doAddDevice(std::string_view scheme,
955 const std::shared_ptr<AuthContext>&
ctx,
956 const std::shared_ptr<dhtnet::ChannelSocket>& channel)
959 JAMI_WARNING(
"[LinkDevice] SOURCE: addDevice canceled.");
963 JAMI_DEBUG(
"[LinkDevice] Setting up addDevice logic on SOURCE device.");
964 JAMI_DEBUG(
"[LinkDevice] SOURCE: Creating addDeviceCtx.");
965 ctx->addDeviceCtx = std::make_unique<AddDeviceContext>(channel);
966 ctx->addDeviceCtx->authScheme = scheme;
967 ctx->addDeviceCtx->state = AuthDecodingState::HANDSHAKE;
969 ctx->timeout = std::make_unique<asio::steady_timer>(*Manager::instance().ioContext());
970 ctx->timeout->expires_after(OP_TIMEOUT);
971 ctx->timeout->async_wait(
972 [wthis = weak(), wctx = std::weak_ptr(ctx)](
const std::error_code& ec) {
976 if (
auto ctx = wctx.lock()) {
977 if (!ctx->addDeviceCtx->isCompleted()) {
978 if (auto this_ = wthis.lock()) {
979 ctx->addDeviceCtx->state = AuthDecodingState::TIMEOUT;
980 JAMI_WARNING(
"[LinkDevice] Timeout for addDevice.");
983 msgpack::sbuffer buffer(UINT16_MAX);
984 msgpack::pack(buffer, AuthMsg::timeout());
986 ctx->addDeviceCtx->channel->write(reinterpret_cast<const unsigned char*>(
990 ctx->addDeviceCtx->channel->shutdown();
996 JAMI_DEBUG(
"[LinkDevice] SOURCE: Creating callbacks.");
997 channel->onShutdown([ctx, w = weak()]() {
998 JAMI_DEBUG(
"[LinkDevice] SOURCE: Shutdown with state {}... xfer {}uccessful",
999 ctx->addDeviceCtx->formattedAuthState(),
1000 ctx->addDeviceCtx->archiveTransferredWithoutFailure ?
"s" :
"uns");
1003 ctx->timeout->cancel();
1004 ctx->timeout.reset();
1006 if (
auto this_ = w.lock()) {
1007 this_->authCtx_.reset();
1010 DeviceAuthInfo::Error error = ctx->addDeviceCtx->getErrorState();
1011 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(ctx->accountId,
1013 static_cast<uint8_t
>(
1014 DeviceAuthState::DONE),
1015 DeviceAuthInfo::createError(
1021 JAMI_DEBUG(
"[LinkDevice] Setting up receiving logic callback.");
1022 channel->setOnRecv([ctx,
1024 decodeCtx = std::make_shared<ArchiveAccountManager::DecodingContext>()](
1025 const uint8_t* buf,
size_t len) {
1026 JAMI_DEBUG(
"[LinkDevice] Setting up receiver callback for communication logic on SOURCE "
1030 auto this_ = wthis.lock();
1032 JAMI_ERROR(
"[LinkDevice] Invalid state for ArchiveAccountManager.");
1041 if (ctx->canceled || ctx->addDeviceCtx->state == AuthDecodingState::ERR) {
1046 decodeCtx->pac.reserve_buffer(len);
1047 std::copy_n(buf, len, decodeCtx->pac.buffer());
1048 decodeCtx->pac.buffer_consumed(len);
1051 JAMI_DEBUG(
"[LinkDevice] SOURCE: addDevice: setOnRecv: handling msg from NEW");
1052 msgpack::object_handle oh;
1055 if (decodeCtx->pac.next(oh)) {
1056 oh.get().convert(toRecv);
1057 JAMI_DEBUG(
"[LinkDevice] SOURCE: Successfully unpacked message from NEW "
1058 "(NEW->SOURCE)\n{}",
1059 toRecv.formatMsg());
1063 }
catch (
const std::exception& e) {
1065 ctx->addDeviceCtx->state = AuthDecodingState::ERR;
1066 JAMI_ERROR(
"[LinkDevice] error unpacking message from new device: {}", e.what());
1069 JAMI_DEBUG(
"[LinkDevice] SOURCE: State is '{}'", ctx->addDeviceCtx->formattedAuthState());
1074 if (toRecv.schemeId != 0) {
1075 ctx->addDeviceCtx->state = AuthDecodingState::ERR;
1076 JAMI_WARNING(
"[LinkDevice] Unsupported scheme received from a connection.");
1079 if (ctx->addDeviceCtx->state == AuthDecodingState::ERR
1080 || ctx->addDeviceCtx->state == AuthDecodingState::AUTH_ERROR) {
1081 JAMI_WARNING(
"[LinkDevice] Undefined behavior encountered during a link auth session.");
1082 ctx->addDeviceCtx->channel->shutdown();
1085 if (ctx->addDeviceCtx->handleTimeoutMessage(toRecv)) {
1089 bool shouldSendMsg =
false;
1090 bool shouldShutdown =
false;
1091 bool shouldSendArchive =
false;
1094 if (ctx->addDeviceCtx->state == AuthDecodingState::AUTH) {
1097 JAMI_DEBUG(
"[LinkDevice] SOURCE: addDevice: setOnRecv: verifying sent "
1098 "credentials from NEW");
1099 shouldSendMsg =
true;
1100 const auto& passwordIt = toRecv.find(PayloadKey::password);
1101 if (passwordIt != toRecv.payload.end()) {
1104 JAMI_DEBUG(
"[LinkDevice] Injecting account archive into outbound message.");
1105 ctx->addDeviceCtx->accData
1107 ->readArchive(fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD,
1110 shouldSendArchive =
true;
1111 JAMI_DEBUG(
"[LinkDevice] Sending account archive.");
1112 }
catch (
const std::exception& e) {
1113 ctx->addDeviceCtx->state = AuthDecodingState::ERR;
1114 JAMI_DEBUG(
"[LinkDevice] Finished reading archive: FAILURE: {}", e.what());
1115 shouldSendArchive =
false;
1118 if (!shouldSendArchive) {
1120 if (ctx->addDeviceCtx->numTries < ctx->addDeviceCtx->maxTries) {
1122 ctx->addDeviceCtx->numTries++;
1123 JAMI_DEBUG(
"[LinkDevice] Incorrect password received. "
1124 "Attempt {} out of {}.",
1125 ctx->addDeviceCtx->numTries,
1126 ctx->addDeviceCtx->maxTries);
1127 toSend.set(PayloadKey::passwordCorrect,
"false");
1128 toSend.set(PayloadKey::canRetry,
"true");
1131 JAMI_WARNING(
"[LinkDevice] Incorrect password received, maximum attempts reached.");
1132 toSend.set(PayloadKey::canRetry,
"false");
1133 ctx->addDeviceCtx->state = AuthDecodingState::AUTH_ERROR;
1134 shouldShutdown =
true;
1139 if (shouldSendArchive) {
1140 JAMI_DEBUG(
"[LinkDevice] SOURCE: Archive in message has encryption scheme '{}'",
1141 ctx->addDeviceCtx->authScheme);
1142 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
1145 static_cast<uint8_t
>(DeviceAuthState::IN_PROGRESS),
1147 shouldShutdown =
true;
1148 shouldSendMsg =
true;
1149 ctx->addDeviceCtx->archiveTransferredWithoutFailure =
true;
1150 toSend.set(PayloadKey::accData, ctx->addDeviceCtx->accData);
1152 if (shouldSendMsg) {
1153 JAMI_DEBUG(
"[LinkDevice] SOURCE: Sending msg to NEW:\n{}", toSend.formatMsg());
1154 msgpack::sbuffer buffer(UINT16_MAX);
1155 msgpack::pack(buffer, toSend);
1157 ctx->addDeviceCtx->channel->write(
reinterpret_cast<const unsigned char*
>(buffer.data()),
1162 if (shouldShutdown) {
1163 ctx->addDeviceCtx->channel->shutdown();
1169 if (ctx->addDeviceCtx->state == AuthDecodingState::HANDSHAKE) {
1170 ctx->addDeviceCtx->state = AuthDecodingState::EST;
1171 DeviceAuthInfo info;
1172 info.set(DeviceAuthInfo::peer_address, channel->getRemoteAddress().toString(
true));
1173 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
1174 ctx->accountId, ctx->token,
static_cast<uint8_t
>(DeviceAuthState::AUTHENTICATING), info);
1181ArchiveAccountManager::cancelAddDevice(uint32_t token)
1183 if (
auto ctx = authCtx_) {
1184 if (
ctx->token == token) {
1185 ctx->canceled =
true;
1186 if (
ctx->addDeviceCtx) {
1187 ctx->addDeviceCtx->state = AuthDecodingState::CANCELED;
1188 if (
ctx->addDeviceCtx->channel) {
1190 auto canceledMsg =
ctx->addDeviceCtx->createCanceledMsg();
1191 msgpack::sbuffer buffer(UINT16_MAX);
1192 msgpack::pack(buffer, canceledMsg);
1194 ctx->addDeviceCtx->channel->write(
reinterpret_cast<const unsigned char*
>(
1198 ctx->addDeviceCtx->channel->shutdown();
1202 ctx->onFailure(AuthError::UNKNOWN,
"");
1211ArchiveAccountManager::confirmAddDevice(uint32_t token)
1213 if (
auto ctx = authCtx_) {
1214 if (
ctx->token == token &&
ctx->addDeviceCtx
1215 &&
ctx->addDeviceCtx->state == AuthDecodingState::EST) {
1216 dht::ThreadPool::io().run([
ctx] {
1217 ctx->addDeviceCtx->state = AuthDecodingState::AUTH;
1219 JAMI_DEBUG(
"[LinkDevice] SOURCE: Packing first message for NEW and switching to "
1221 ctx->addDeviceCtx->formattedAuthState());
1222 toSend.
set(PayloadKey::authScheme,
ctx->addDeviceCtx->authScheme);
1223 msgpack::sbuffer buffer(UINT16_MAX);
1224 msgpack::pack(buffer, toSend);
1226 ctx->addDeviceCtx->channel->write(
reinterpret_cast<const unsigned char*
>(
1238ArchiveAccountManager::migrateAccount(AuthContext&
ctx)
1240 JAMI_WARN(
"[Auth] Account migration needed");
1243 archive = readArchive(
ctx.credentials->password_scheme,
ctx.credentials->password);
1245 JAMI_DBG(
"[Auth] Unable to load archive");
1246 ctx.onFailure(AuthError::INVALID_ARGUMENTS,
"");
1250 updateArchive(archive);
1252 if (updateCertificates(archive, ctx.credentials->updateIdentity)) {
1255 onArchiveLoaded(ctx, std::move(archive),
false);
1257 ctx.onFailure(AuthError::UNKNOWN,
"");
1262ArchiveAccountManager::onArchiveLoaded(AuthContext& ctx, AccountArchive&& a,
bool isLinkDevProtocol)
1265 dhtnet::fileutils::check_dir(path_, 0700);
1267 if (isLinkDevProtocol) {
1269 ctx.linkDevCtx->authScheme.empty() ? FALSE_STR : TRUE_STR;
1271 a.
save(fileutils::getFullPath(path_, archivePath_),
1272 ctx.linkDevCtx->authScheme,
1273 ctx.linkDevCtx->credentialsFromUser);
1276 ctx.credentials->password_scheme.empty() ? FALSE_STR : TRUE_STR;
1278 a.
save(fileutils::getFullPath(path_, archivePath_),
1279 ctx.credentials ? ctx.credentials->password_scheme :
"",
1280 ctx.credentials ? ctx.credentials->
password :
"");
1283 if (not a.
id.second->isCA()) {
1284 JAMI_ERROR(
"[Account {}] [Auth] Attempting to sign a certificate with a non-CA.",
1288 std::shared_ptr<dht::crypto::Certificate> deviceCertificate;
1289 std::unique_ptr<ContactList> contacts;
1290 auto usePreviousIdentity =
false;
1292 if (
auto oldId = ctx.credentials->updateIdentity.second) {
1293 contacts = std::make_unique<ContactList>(ctx.accountId, oldId, path_, onChange_);
1294 if (contacts->isValidAccountDevice(*oldId) && ctx.credentials->updateIdentity.first) {
1295 deviceCertificate = oldId;
1296 usePreviousIdentity =
true;
1297 JAMI_WARNING(
"[Account {}] [Auth] Using previously generated device certificate {}",
1299 deviceCertificate->getLongId());
1306 if (!deviceCertificate) {
1307 JAMI_WARNING(
"[Account {}] [Auth] Creating new device certificate", accountId_);
1308 auto request = ctx.request.get();
1309 if (not request->verify()) {
1310 JAMI_ERROR(
"[Account {}] [Auth] Invalid certificate request.", accountId_);
1311 ctx.onFailure(AuthError::INVALID_ARGUMENTS,
"");
1314 deviceCertificate = std::make_shared<dht::crypto::Certificate>(
1315 dht::crypto::Certificate::generate(*request, a.
id));
1316 JAMI_WARNING(
"[Account {}] [Auth] Created new device: {}",
1318 deviceCertificate->getLongId());
1321 auto receipt = makeReceipt(a.
id, *deviceCertificate, ethAccount);
1322 auto receiptSignature = a.
id.first->sign({receipt.first.begin(), receipt.first.end()});
1324 auto info = std::make_unique<AccountInfo>();
1325 auto pk = usePreviousIdentity ? ctx.credentials->updateIdentity.first : ctx.key.get();
1326 auto sharedPk = pk->getSharedPublicKey();
1327 info->identity.first = pk;
1328 info->identity.second = deviceCertificate;
1329 info->accountId = a.
id.second->getId().toString();
1330 info->devicePk = sharedPk;
1331 info->deviceId = info->devicePk->getLongId().toString();
1332 if (ctx.deviceName.empty())
1333 ctx.deviceName = info->deviceId.substr(8);
1336 contacts = std::make_unique<ContactList>(ctx.accountId, a.
id.second, path_, onChange_);
1338 info->contacts = std::move(contacts);
1339 info->contacts->setContacts(a.
contacts);
1340 info->contacts->foundAccountDevice(deviceCertificate, ctx.deviceName, clock::now());
1341 info->ethAccount = ethAccount;
1342 info->announce = std::move(receipt.second);
1343 ConversationModule::saveConvInfosToPath(path_, a.
conversations);
1345 info_ = std::move(info);
1347 ctx.onSuccess(*info_,
1349 std::move(receipt.first),
1350 std::move(receiptSignature));
1353std::pair<std::vector<uint8_t>, dht::InfoHash>
1354ArchiveAccountManager::computeKeys(
const std::string& password,
1355 const std::string& pin,
1359 auto now = std::chrono::duration_cast<std::chrono::seconds>(clock::now().time_since_epoch());
1360 auto tseed = now.count() / std::chrono::seconds(EXPORT_KEY_RENEWAL_TIME).count();
1363 std::ostringstream ss;
1364 ss << std::hex << tseed;
1365 auto tseed_str = ss.str();
1368 std::vector<uint8_t> salt_key;
1369 salt_key.reserve(pin.size() + tseed_str.size());
1370 salt_key.insert(salt_key.end(), pin.begin(), pin.end());
1371 salt_key.insert(salt_key.end(), tseed_str.begin(), tseed_str.end());
1372 auto key = dht::crypto::stretchKey(password, salt_key, 256 / 8);
1375 auto loc = dht::InfoHash::get(key);
1380std::pair<std::string, std::shared_ptr<dht::Value>>
1381ArchiveAccountManager::makeReceipt(
const dht::crypto::Identity&
id,
1382 const dht::crypto::Certificate& device,
1383 const std::string& ethAccount)
1385 JAMI_LOG(
"[Account {}] [Auth] Signing receipt for device {}", accountId_, device.getLongId());
1386 auto devId = device.getId();
1387 DeviceAnnouncement announcement;
1388 announcement.dev = devId;
1389 announcement.pk = device.getSharedPublicKey();
1390 dht::Value ann_val {announcement};
1391 ann_val.sign(*
id.first);
1393 auto packedAnnoucement = ann_val.getPacked();
1394 JAMI_LOG(
"[Account {}] [Auth] Device announcement size: {}",
1396 packedAnnoucement.size());
1398 std::ostringstream is;
1399 is <<
"{\"id\":\"" <<
id.second->getId() <<
"\",\"dev\":\"" << devId <<
"\",\"eth\":\""
1400 << ethAccount <<
"\",\"announce\":\"" << base64::encode(packedAnnoucement) <<
"\"}";
1403 return {is.str(), std::make_shared<dht::Value>(std::move(ann_val))};
1407ArchiveAccountManager::needsMigration(
const std::string& accountId,
const dht::crypto::Identity&
id)
1411 auto cert =
id.second->issuer;
1413 if (not cert->isCA()) {
1414 JAMI_WARNING(
"[Account {}] [Auth] certificate {} is not a CA, needs update.",
1419 if (cert->getExpiration() < clock::now()) {
1420 JAMI_WARNING(
"[Account {}] [Auth] certificate {} is expired, needs update.",
1425 cert = cert->issuer;
1431ArchiveAccountManager::syncDevices()
1433 JAMI_LOG(
"[Account {}] Building device sync from {}", accountId_, info_->deviceId);
1434 onSyncData_(info_->contacts->getSyncData());
1440 bool publishPresence)
1442 AccountManager::startSync(std::move(cb), std::move(dcb), publishPresence);
1445 dht::InfoHash::get(
"inbox:" + info_->devicePk->getId().toString()),
1451 [
this, sync](
const std::shared_ptr<dht::crypto::Certificate>& cert)
mutable {
1452 if (!cert or cert->getId() != sync.from) {
1453 JAMI_WARNING(
"[Account {}] Unable to find certificate for device {}",
1455 sync.from.toString());
1458 if (not foundAccountDevice(cert))
1460 onSyncData(std::move(sync));
1468ArchiveAccountManager::readArchive(std::string_view scheme,
const std::string& pwd)
const
1470 JAMI_LOG(
"[Account {}] [Auth] Reading account archive", accountId_);
1471 return AccountArchive(fileutils::getFullPath(path_, archivePath_), scheme, pwd);
1475ArchiveAccountManager::updateArchive(AccountArchive& archive)
const
1480 static const auto filtered_keys = {Ringtone::PATH,
1484 Conf::CONFIG_DHT_PORT,
1492 static const auto encoded_keys = {TLS::CA_LIST_FILE,
1493 TLS::CERTIFICATE_FILE,
1494 TLS::PRIVATE_KEY_FILE};
1496 JAMI_LOG(
"[Account {}] [Auth] Building account archive", accountId_);
1497 for (
const auto& it : onExportConfig_()) {
1499 if (std::any_of(std::begin(filtered_keys), std::end(filtered_keys), [&](
const auto& key) {
1500 return key == it.first;
1505 if (std::any_of(std::begin(encoded_keys), std::end(encoded_keys), [&](
const auto& key) {
1506 return key == it.first;
1509 archive.config.emplace(it.first, base64::encode(fileutils::loadFile(it.second)));
1513 archive.config[it.first] = it.second;
1517 archive.contacts = info_->contacts->getContacts();
1519 archive.conversations = ConversationModule::convInfosFromPath(path_);
1520 archive.conversationsRequests = ConversationModule::convRequestsFromPath(path_);
1525ArchiveAccountManager::saveArchive(AccountArchive& archive,
1526 std::string_view scheme,
1527 const std::string& pwd)
1530 updateArchive(archive);
1531 if (archivePath_.empty())
1532 archivePath_ =
"export.gz";
1533 archive.save(fileutils::getFullPath(path_, archivePath_), scheme, pwd);
1534 }
catch (
const std::runtime_error& ex) {
1535 JAMI_ERROR(
"[Account {}] [Auth] Unable to export archive: {}", accountId_, ex.what());
1541ArchiveAccountManager::changePassword(
const std::string& password_old,
1542 const std::string& password_new)
1545 auto path = fileutils::getFullPath(path_, archivePath_);
1546 AccountArchive(path, fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD, password_old)
1547 .
save(path, fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD, password_new);
1549 }
catch (
const std::exception&) {
1555ArchiveAccountManager::getPasswordKey(
const std::string& password)
1558 auto data = dhtnet::fileutils::loadFile(fileutils::getFullPath(path_, archivePath_));
1560 auto key = dht::crypto::aesGetKey(data, password);
1561 auto decrypted = dht::crypto::aesDecrypt(dht::crypto::aesGetEncrypted(data), key);
1563 }
catch (
const std::exception& e) {
1564 JAMI_ERROR(
"[Account {}] Error loading archive: {}", accountId_, e.what());
1570ArchiveAccountManager::revokeDevice(
const std::string& device,
1571 std::string_view scheme,
1572 const std::string& password,
1575 auto fa = dht::ThreadPool::computation().getShared<
AccountArchive>(
1576 [
this, scheme = std::string(scheme), password] {
return readArchive(scheme, password); });
1578 [fa = std::move(fa),
1579 scheme = std::string(scheme),
1584 const std::shared_ptr<dht::crypto::Certificate>& crt)
mutable {
1586 cb(RevokeDeviceResult::ERROR_NETWORK);
1589 auto this_ = w.lock();
1592 this_->info_->contacts->foundAccountDevice(crt);
1597 cb(RevokeDeviceResult::ERROR_CREDENTIALS);
1602 a.
revoked = std::make_shared<
decltype(a.
revoked)::element_type>();
1606 this_->certStore().pinRevocationList(a.
id.second->getId().toString(),
1608 this_->certStore().loadRevocations(*a.
id.second);
1611 auto h = a.
id.second->getId();
1612 this_->dht_->put(h, a.
revoked, dht::DoneCallback {}, {},
true);
1614 this_->saveArchive(a, scheme, password);
1615 this_->info_->contacts->removeAccountDevice(crt->getLongId());
1616 cb(RevokeDeviceResult::SUCCESS);
1617 this_->syncDevices();
1623ArchiveAccountManager::exportArchive(
const std::string& destinationPath,
1624 std::string_view scheme,
1625 const std::string& password)
1630 updateArchive(archive);
1631 auto archivePath = fileutils::getFullPath(path_, archivePath_);
1632 if (!archive.
save(archivePath, scheme, password))
1637 std::filesystem::copy_file(archivePath,
1639 std::filesystem::copy_options::overwrite_existing,
1642 }
catch (
const std::runtime_error& ex) {
1643 JAMI_ERR(
"[Auth] Unable to export archive: %s", ex.what());
1646 JAMI_ERR(
"[Auth] Unable to export archive: Unable to read archive");
1652ArchiveAccountManager::isPasswordValid(
const std::string& password)
1655 readArchive(fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD, password);
1664ArchiveAccountManager::registerName(
const std::string& name,
1665 std::string_view scheme,
1666 const std::string& password,
1667 RegistrationCallback cb)
1669 std::string signedName;
1670 auto nameLowercase {name};
1671 std::transform(nameLowercase.begin(), nameLowercase.end(), nameLowercase.begin(), ::tolower);
1672 std::string publickey;
1673 std::string accountId;
1674 std::string ethAccount;
1677 auto archive = readArchive(scheme, password);
1678 auto privateKey = archive.id.first;
1679 const auto& pk = privateKey->getPublicKey();
1680 publickey = pk.toString();
1681 accountId = pk.getId().toString();
1682 signedName = base64::encode(privateKey->sign(std::vector<uint8_t>(nameLowercase.begin(), nameLowercase.end())));
1684 }
catch (
const std::exception& e) {
1686 cb(NameDirectory::RegistrationResponse::invalidCredentials, name);
1690 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
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