Ring Daemon 16.0.0
Loading...
Searching...
No Matches
archive_account_manager.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2004-2025 Savoir-faire Linux Inc.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
18#include "accountarchive.h"
19#include "fileutils.h"
20#include "libdevcrypto/Common.h"
21#include "archiver.h"
22#include "base64.h"
23#include "jami/account_const.h"
24#include "account_schema.h"
26#include "manager.h"
28#include "client/ring_signal.h"
29
30#include <dhtnet/multiplexed_socket.h>
31#include <opendht/dhtrunner.h>
32#include <opendht/thread_pool.h>
33
34#include <memory>
35#include <fstream>
36
37#include "config/yamlparser.h"
38
39namespace jami {
40
41const constexpr auto EXPORT_KEY_RENEWAL_TIME = std::chrono::minutes(20);
42constexpr auto AUTH_URI_SCHEME = "jami-auth://"sv;
43constexpr auto CHANNEL_SCHEME = "auth:"sv;
44constexpr auto OP_TIMEOUT = 5min;
45
46void
48 std::string deviceName,
49 std::unique_ptr<AccountCredentials> credentials,
50 AuthSuccessCallback onSuccess,
51 AuthFailureCallback onFailure,
53{
54 JAMI_WARNING("[Account {}] [Auth] starting authentication with scheme '{}'",
56 credentials->scheme);
57 auto ctx = std::make_shared<AuthContext>();
58 ctx->accountId = accountId_;
59 ctx->key = key;
60 ctx->request = buildRequest(key);
61 ctx->deviceName = std::move(deviceName);
62 ctx->credentials = dynamic_unique_cast<ArchiveAccountCredentials>(std::move(credentials));
63 ctx->onSuccess = std::move(onSuccess);
64 ctx->onFailure = std::move(onFailure);
65
66 if (not ctx->credentials) {
67 ctx->onFailure(AuthError::INVALID_ARGUMENTS, "invalid credentials");
68 return;
69 }
70 onChange_ = std::move(onChange);
71
72 if (ctx->credentials->scheme == "p2p") {
73 JAMI_DEBUG("[LinkDevice] Importing account via p2p scheme.");
74 startLoadArchiveFromDevice(ctx);
75 return;
76 }
77
78 dht::ThreadPool::computation().run([ctx = std::move(ctx), wthis = weak()] {
79 auto this_ = wthis.lock();
80 if (not this_)
81 return;
82 try {
83 if (ctx->credentials->scheme == "file") {
84 // Import from external archive
85 this_->loadFromFile(*ctx);
86 } else {
87 // Create/migrate local account
88 bool hasArchive = not ctx->credentials->uri.empty()
89 and std::filesystem::is_regular_file(ctx->credentials->uri);
90 if (hasArchive) {
91 // Create/migrate from local archive
92 if (ctx->credentials->updateIdentity.first
93 and ctx->credentials->updateIdentity.second
94 and needsMigration(this_->accountId_, ctx->credentials->updateIdentity)) {
95 this_->migrateAccount(*ctx);
96 } else {
97 this_->loadFromFile(*ctx);
98 }
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);
103 AccountArchive a;
104 JAMI_WARNING("[Account {}] [Auth] Converting certificate from old account {}",
105 this_->accountId_,
106 ctx->credentials->updateIdentity.first->getPublicKey()
107 .getId()
108 .to_view());
109 a.id = std::move(ctx->credentials->updateIdentity);
110 try {
111 a.ca_key = std::make_shared<dht::crypto::PrivateKey>(
112 fileutils::loadFile("ca.key", this_->path_));
113 } catch (...) {
114 }
115 this_->updateCertificates(a, ctx->credentials->updateIdentity);
116 a.eth_key = future_keypair.get().secret().makeInsecure().asBytes();
117 this_->onArchiveLoaded(*ctx, std::move(a), false);
118 } else {
119 this_->createAccount(*ctx);
120 }
121 }
122 } catch (const std::exception& e) {
123 ctx->onFailure(AuthError::UNKNOWN, e.what());
124 }
125 });
126}
127
128bool
129ArchiveAccountManager::updateCertificates(AccountArchive& archive, dht::crypto::Identity& device)
130{
131 JAMI_WARNING("[Account {}] [Auth] Updating certificates", accountId_);
132 using Certificate = dht::crypto::Certificate;
133
134 // We need the CA key to resign certificates
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)
137 return false;
138
139 // Currently set the CA flag and update expiration dates
140 bool updated = false;
141
142 auto& cert = archive.id.second;
143 auto ca = cert->issuer;
144 // Update CA if possible and relevant
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));
148 updated = true;
149 JAMI_LOG("[Account {}] [Auth] CA certificate re-generated", accountId_);
150 }
151
152 // Update certificate
153 if (updated or not cert->isCA() or cert->getExpiration() < clock::now()) {
154 cert = std::make_shared<Certificate>(
155 Certificate::generate(*archive.id.first,
156 "Jami",
157 dht::crypto::Identity {archive.ca_key, ca},
158 true));
159 updated = true;
160 JAMI_LOG("[Account {}] [Auth] Account certificate for {} re-generated",
161 accountId_,
162 cert->getId());
163 }
164
165 if (updated and device.first and *device.first) {
166 // update device certificate
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_);
170 }
171
172 return updated;
173}
174
175bool
176ArchiveAccountManager::setValidity(std::string_view scheme,
177 const std::string& password,
178 dht::crypto::Identity& device,
179 const dht::InfoHash& id,
180 int64_t validity)
181{
182 auto archive = readArchive(scheme, password);
183 // We need the CA key to resign certificates
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)
186 return false;
187
188 auto updated = false;
189
190 if (id)
191 JAMI_WARNING("[Account {}] [Auth] Updating validity for certificate with id: {}",
192 accountId_,
193 id);
194 else
195 JAMI_WARNING("[Account {}] [Auth] Updating validity for certificates", accountId_);
196
197 auto& cert = archive.id.second;
198 auto ca = cert->issuer;
199 if (not ca)
200 return false;
201
202 // using Certificate = dht::crypto::Certificate;
203 // Update CA if possible and relevant
204 if (not id or ca->getId() == id) {
205 ca->setValidity(*archive.ca_key, validity);
206 updated = true;
207 JAMI_LOG("[Account {}] [Auth] CA certificate re-generated", accountId_);
208 }
209
210 // Update certificate
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;
214 updated = true;
215 JAMI_LOG("[Account {}] [Auth] Jami certificate re-generated", accountId_);
216 }
217
218 if (updated) {
219 archive.save(fileutils::getFullPath(path_, archivePath_), scheme, password);
220 }
221
222 if (updated or not id or device.second->getId() == id) {
223 // update device certificate
224 device.second->setValidity(archive.id, validity);
225 updated = true;
226 }
227
228 return updated;
229}
230
231void
232ArchiveAccountManager::createAccount(AuthContext& ctx)
233{
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.");
238 }
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.");
242 }
243 JAMI_WARNING("[Account {}] [Auth] New account: CA: {}, ID: {}",
244 accountId_,
245 ca.second->getId(),
246 a.id.second->getId());
247 a.ca_key = ca.first;
248 auto keypair = dev::KeyPair::create();
249 a.eth_key = keypair.secret().makeInsecure().asBytes();
250 onArchiveLoaded(ctx, std::move(a), false);
251}
252
253void
254ArchiveAccountManager::loadFromFile(AuthContext& ctx)
255{
256 JAMI_WARNING("[Account {}] [Auth] Loading archive from: {}",
257 accountId_,
258 ctx.credentials->uri.c_str());
259 AccountArchive archive;
260 try {
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());
267 return;
268 }
269 onArchiveLoaded(ctx, std::move(archive), false);
270}
271
272// TODO remove?
274{
275 dht::DhtRunner dht;
276 std::pair<bool, bool> stateOld {false, true};
277 std::pair<bool, bool> stateNew {false, true};
278 bool found {false};
279};
280
281// this enum is for the states of add device TLS protocol
282// used for LinkDeviceProtocolStateChanged = AddDeviceStateChanged
283enum class AuthDecodingState : uint8_t {
284 HANDSHAKE = 0,
285 EST,
286 AUTH,
287 DATA,
288 ERR,
290 DONE,
291 TIMEOUT,
293};
294
295static constexpr std::string_view
297{
298 switch (state) {
299 case AuthDecodingState::HANDSHAKE:
300 return "HANDSHAKE"sv;
301 case AuthDecodingState::EST:
302 return "EST"sv;
303 case AuthDecodingState::AUTH:
304 return "AUTH"sv;
305 case AuthDecodingState::DATA:
306 return "DATA"sv;
307 case AuthDecodingState::AUTH_ERROR:
308 return "AUTH_ERROR"sv;
309 case AuthDecodingState::DONE:
310 return "DONE"sv;
311 case AuthDecodingState::TIMEOUT:
312 return "TIMEOUT"sv;
313 case AuthDecodingState::CANCELED:
314 return "CANCELED"sv;
315 case AuthDecodingState::ERR:
316 default:
317 return "ERR"sv;
318 }
319}
320
321namespace PayloadKey {
322static constexpr auto passwordCorrect = "passwordCorrect"sv;
323static constexpr auto canRetry = "canRetry"sv;
324static constexpr auto accData = "accData"sv;
325static constexpr auto authScheme = "authScheme"sv;
326static constexpr auto password = "password"sv;
327static constexpr auto stateMsg = "stateMsg"sv;
328}
329
331{
332 uint8_t schemeId {0};
333 std::map<std::string, std::string> payload;
334 MSGPACK_DEFINE_MAP(schemeId, payload)
335
336 void set(std::string_view key, std::string_view value) {
337 payload.emplace(std::string(key), std::string(value));
338 }
339
340 auto find(std::string_view key) const { return payload.find(std::string(key)); }
341
342 auto at(std::string_view key) const { return payload.at(std::string(key)); }
343
344 void logMsg() { JAMI_DEBUG("[LinkDevice]\nLinkDevice::logMsg:\n{}", formatMsg()); }
345
346 std::string formatMsg() {
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);
351 }
352 logStr += "=========";
353 return logStr;
354 }
355
356 static AuthMsg timeout() {
357 AuthMsg timeoutMsg;
358 timeoutMsg.set(PayloadKey::stateMsg, toString(AuthDecodingState::TIMEOUT));
359 return timeoutMsg;
360 }
361};
362
363struct ArchiveAccountManager::DeviceAuthInfo : public std::map<std::string, std::string>
364{
365 // Static key definitions
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;
372
373 // Add error enum
374 enum class Error { NETWORK, TIMEOUT, AUTH_ERROR, CANCELED, UNKNOWN, NONE };
375
376 using Map = std::map<std::string, std::string>;
377
378 DeviceAuthInfo() = default;
379 DeviceAuthInfo(const Map& map)
380 : Map(map)
381 {}
383 : Map(std::move(map))
384 {}
385
386 void set(std::string_view key, std::string_view value) {
387 emplace(std::string(key), std::string(value));
388 }
389
391 {
392 std::string errStr;
393 switch (err) {
394 case Error::NETWORK:
395 errStr = "network";
396 break;
397 case Error::TIMEOUT:
398 errStr = "timeout";
399 break;
400 case Error::AUTH_ERROR:
401 errStr = "auth_error";
402 break;
403 case Error::CANCELED:
404 errStr = "canceled";
405 break;
406 case Error::UNKNOWN:
407 errStr = "unknown";
408 break;
409 case Error::NONE:
410 errStr = "";
411 break;
412 }
413 return DeviceAuthInfo {Map {{std::string(error), errStr}}};
414 }
415};
416
418{
419 uint64_t opId;
420 AuthDecodingState state {AuthDecodingState::EST};
421 std::string scheme;
422 bool authEnabled {false};
423 bool archiveTransferredWithoutFailure {false};
424 std::string accData;
425
426 DeviceContextBase(uint64_t operationId, AuthDecodingState initialState)
427 : opId(operationId)
428 , state(initialState)
429 {}
430
431 constexpr std::string_view formattedAuthState() const { return toString(state); }
432
434 {
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;
439 return true;
440 }
441 }
442 return false;
443 }
444
446 {
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;
451 return true;
452 }
453 }
454 return false;
455 }
456
458 {
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;
469 }
470 return DeviceAuthInfo::Error::NETWORK;
471 }
472
473 bool isCompleted() const
474 {
475 return state == AuthDecodingState::DONE || state == AuthDecodingState::ERR
476 || state == AuthDecodingState::AUTH_ERROR || state == AuthDecodingState::TIMEOUT
477 || state == AuthDecodingState::CANCELED;
478 }
479};
480
482{
483 dht::crypto::Identity tmpId;
484 dhtnet::ConnectionManager tempConnMgr;
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; },
489 nullptr,
490 512};
491 std::string authScheme {fileutils::ARCHIVE_AUTH_SCHEME_NONE};
492 std::string credentialsFromUser {""};
493
494 LinkDeviceContext(dht::crypto::Identity id)
496 , tmpId(std::move(id))
497 , tempConnMgr(tmpId)
498 {}
499};
500
502{
503 unsigned numTries {0};
504 unsigned maxTries {3};
505 std::shared_ptr<dhtnet::ChannelSocket> channel;
506 std::string_view authScheme;
507 std::string credentials;
508
509 AddDeviceContext(std::shared_ptr<dhtnet::ChannelSocket> c)
511 , channel(std::move(c))
512 {}
513
515 {
516 AuthMsg timeoutMsg;
517 timeoutMsg.set(PayloadKey::stateMsg, toString(AuthDecodingState::CANCELED));
518 return timeoutMsg;
519 }
520};
521
522bool
523ArchiveAccountManager::provideAccountAuthentication(const std::string& key,
524 const std::string& scheme)
525{
526 if (scheme != fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD) {
527 JAMI_ERROR("[LinkDevice] Unsupported account authentication scheme attempted.");
528 return false;
529 }
530 auto ctx = authCtx_;
531 if (!ctx) {
532 JAMI_WARNING("[LinkDevice] No auth context found.");
533 return false;
534 }
535
536 if (ctx->linkDevCtx->state != AuthDecodingState::AUTH) {
537 JAMI_WARNING("[LinkDevice] Invalid state for providing account authentication.");
538 return false;
539 }
540 // After authentication, the next step is to receive the account archive from the exporting device
541 ctx->linkDevCtx->state = AuthDecodingState::DATA;
542 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
543 ctx->accountId, static_cast<uint8_t>(DeviceAuthState::IN_PROGRESS), DeviceAuthInfo {});
544
545 dht::ThreadPool::io().run([key = std::move(key), scheme, ctx]() mutable {
546 AuthMsg toSend;
547 toSend.set(PayloadKey::password, std::move(key));
548 msgpack::sbuffer buffer(UINT16_MAX);
549 toSend.logMsg();
550 msgpack::pack(buffer, toSend);
551 std::error_code ec;
552 try {
553 ctx->linkDevCtx->channel->write(reinterpret_cast<const unsigned char*>(buffer.data()),
554 buffer.size(),
555 ec);
556 } catch (const std::exception& e) {
557 JAMI_WARNING("[LinkDevice] Failed to send password over auth ChannelSocket. Channel "
558 "may be invalid.");
559 }
560 });
561
562 return true;
563}
564
566{
567 msgpack::unpacker pac {[](msgpack::type::object_type, std::size_t, void*) { return true; },
568 nullptr,
569 512};
570};
571
572// link device: newDev: creates a new temporary account on the DHT for establishing a TLS connection
573void
574ArchiveAccountManager::startLoadArchiveFromDevice(const std::shared_ptr<AuthContext>& ctx)
575{
576 if (authCtx_) {
577 JAMI_WARNING("[LinkDevice] Already loading archive from device.");
578 ctx->onFailure(AuthError::INVALID_ARGUMENTS, "Already loading archive from device.");
579 return;
580 }
581 JAMI_DEBUG("[LinkDevice] Starting load archive from device {} {}.",
582 fmt::ptr(this),
583 fmt::ptr(ctx));
584 authCtx_ = ctx;
585 // move the account creation to another thread
586 dht::ThreadPool::computation().run([ctx, wthis = weak()] {
587 auto ca = dht::crypto::generateEcIdentity("Jami Temporary CA");
588 if (!ca.first || !ca.second) {
589 throw std::runtime_error("[LinkDevice] Can't generate CA for this account.");
590 }
591 // temporary user for bootstrapping p2p connection is created here
592 auto user = dht::crypto::generateIdentity("Jami Temporary User", ca, 4096, true);
593 if (!user.first || !user.second) {
594 throw std::runtime_error("[LinkDevice] Can't generate identity for this account.");
595 }
596
597 auto this_ = wthis.lock();
598 if (!this_) {
599 JAMI_WARNING("[LinkDevice] Failed to get the ArchiveAccountManager.");
600 return;
601 }
602
603 // establish linkDevCtx
604 ctx->linkDevCtx = std::make_shared<LinkDeviceContext>(
605 dht::crypto::generateIdentity("Jami Temporary device", user));
606 JAMI_LOG("[LinkDevice] Established linkDevCtx. {} {} {}.",
607 fmt::ptr(this_),
608 fmt::ptr(ctx),
609 fmt::ptr(ctx->linkDevCtx));
610
611 // set up auth channel code and also use it as opId
612 auto gen = Manager::instance().getSeededRandomEngine();
613 ctx->linkDevCtx->opId = std::uniform_int_distribution<uint64_t>(100000, 999999)(gen);
614#if TARGET_OS_IOS
615 ctx->linkDevCtx->tempConnMgr.oniOSConnected(
616 [&](const std::string& connType, dht::InfoHash peer_h) { return false; });
617#endif
618 ctx->linkDevCtx->tempConnMgr.onDhtConnected(ctx->linkDevCtx->tmpId.second->getPublicKey());
619
620 auto accountScheme = fmt::format("{}{}/{}",
621 AUTH_URI_SCHEME,
622 ctx->linkDevCtx->tmpId.second->getId(),
623 ctx->linkDevCtx->opId);
624 JAMI_LOG("[LinkDevice] auth scheme will be: {}", accountScheme);
625
626 DeviceAuthInfo info;
627 info.set(DeviceAuthInfo::token, accountScheme);
628
629 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
630 ctx->accountId, static_cast<uint8_t>(DeviceAuthState::TOKEN_AVAILABLE), info);
631
632 ctx->linkDevCtx->tempConnMgr.onICERequest(
633 [wctx = std::weak_ptr(ctx)](const DeviceId& deviceId) {
634 if (auto ctx = wctx.lock()) {
635 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
636 ctx->accountId,
637 static_cast<uint8_t>(DeviceAuthState::CONNECTING),
638 DeviceAuthInfo {});
639 return true;
640 }
641 return false;
642 });
643
644 ctx->linkDevCtx->tempConnMgr.onChannelRequest(
645 [wthis, ctx](const std::shared_ptr<dht::crypto::Certificate>& cert,
646 const std::string& name) {
647 std::string_view url(name);
648 if (!starts_with(url, CHANNEL_SCHEME)) {
650 "[LinkDevice] Temporary connection manager received invalid scheme: {}",
651 name);
652 return false;
653 }
654 auto opStr = url.substr(CHANNEL_SCHEME.size());
655 auto parsedOpId = jami::to_int<uint64_t>(opStr);
656
657 if (ctx->linkDevCtx->opId == parsedOpId
658 && ctx->linkDevCtx->numOpenChannels < ctx->linkDevCtx->maxOpenChannels) {
659 ctx->linkDevCtx->numOpenChannels++;
660 JAMI_DEBUG("[LinkDevice] Opening channel ({}/{}): {}",
661 ctx->linkDevCtx->numOpenChannels,
662 ctx->linkDevCtx->maxOpenChannels,
663 name);
664 return true;
665 }
666 return false;
667 });
668
669 ctx->linkDevCtx->tempConnMgr.onConnectionReady([ctx,
670 accountScheme,
671 wthis](const DeviceId& deviceId,
672 const std::string& name,
673 std::shared_ptr<dhtnet::ChannelSocket> socket) {
674 if (!socket) {
675 JAMI_WARNING("[LinkDevice] Temporary connection manager received invalid socket.");
676 if (ctx->timeout)
677 ctx->timeout->cancel();
678 ctx->timeout.reset();
679 ctx->linkDevCtx->numOpenChannels--;
680 if (auto sthis = wthis.lock())
681 sthis->authCtx_.reset();
682 ctx->linkDevCtx->state = AuthDecodingState::ERR;
683 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
684 ctx->accountId,
685 static_cast<uint8_t>(DeviceAuthState::DONE),
686 DeviceAuthInfo::createError(DeviceAuthInfo::Error::NETWORK));
687 return;
688 }
689 ctx->linkDevCtx->channel = socket;
690
691 ctx->timeout = std::make_unique<asio::steady_timer>(*Manager::instance().ioContext());
692 ctx->timeout->expires_from_now(OP_TIMEOUT);
693 ctx->timeout->async_wait([c = std::weak_ptr(ctx), socket](const std::error_code& ec) {
694 if (ec) {
695 return;
696 }
697 if (auto ctx = c.lock()) {
698 if (!ctx->linkDevCtx->isCompleted()) {
699 ctx->linkDevCtx->state = AuthDecodingState::TIMEOUT;
700 JAMI_WARNING("[LinkDevice] timeout: {}", socket->name());
701
702 // Create and send timeout message
703 msgpack::sbuffer buffer(UINT16_MAX);
704 msgpack::pack(buffer, AuthMsg::timeout());
705 std::error_code ec;
706 socket->write(reinterpret_cast<const unsigned char*>(buffer.data()),
707 buffer.size(),
708 ec);
709 socket->shutdown();
710 }
711 }
712 });
713
714 socket->onShutdown([ctx, name, wthis]() {
715 JAMI_WARNING("[LinkDevice] Temporary connection manager closing socket: {}", name);
716 if (ctx->timeout)
717 ctx->timeout->cancel();
718 ctx->timeout.reset();
719 ctx->linkDevCtx->numOpenChannels--;
720 ctx->linkDevCtx->channel.reset();
721 if (auto sthis = wthis.lock())
722 sthis->authCtx_.reset();
723
724 DeviceAuthInfo::Error error = ctx->linkDevCtx->getErrorState();
725 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
726 ctx->accountId,
727 static_cast<uint8_t>(DeviceAuthState::DONE),
728 DeviceAuthInfo::createError(error));
729 });
730
731 socket->setOnRecv([ctx,
732 decodingCtx = std::make_shared<DecodingContext>(),
733 wthis](const uint8_t* buf, size_t len) {
734 if (!buf) {
735 return len;
736 }
737
738 decodingCtx->pac.reserve_buffer(len);
739 std::copy_n(buf, len, decodingCtx->pac.buffer());
740 decodingCtx->pac.buffer_consumed(len);
741 AuthMsg toRecv;
742 try {
743 msgpack::object_handle oh;
744 if (decodingCtx->pac.next(oh)) {
745 JAMI_DEBUG("[LinkDevice] NEW: Unpacking message.");
746 oh.get().convert(toRecv);
747 } else {
748 return len;
749 }
750 } catch (const std::exception& e) {
751 ctx->linkDevCtx->state = AuthDecodingState::ERR;
752 JAMI_ERROR("[LinkDevice] Error unpacking message from source device: {}", e.what());
753 return len;
754 }
755
756 JAMI_DEBUG("[LinkDevice] NEW: Successfully unpacked message from source\n{}",
757 toRecv.formatMsg());
758 JAMI_DEBUG("[LinkDevice] NEW: State is {}:{}",
759 ctx->linkDevCtx->scheme,
760 ctx->linkDevCtx->formattedAuthState());
761
762 // check if scheme is supported
763 if (toRecv.schemeId != 0) {
764 JAMI_WARNING("[LinkDevice] NEW: Unsupported scheme received from source");
765 ctx->linkDevCtx->state = AuthDecodingState::ERR;
766 return len;
767 }
768
769 // handle the protocol logic
770 if (ctx->linkDevCtx->handleCanceledMessage(toRecv)) {
771 // import canceled. Will be handeled onShutdown
772 return len;
773 }
774 AuthMsg toSend;
775 bool shouldShutdown = false;
776 auto accDataIt = toRecv.find(PayloadKey::accData);
777 bool shouldLoadArchive = accDataIt != toRecv.payload.end();
778
779 if (ctx->linkDevCtx->state == AuthDecodingState::HANDSHAKE) {
780 auto peerCert = ctx->linkDevCtx->channel->peerCertificate();
781 auto authScheme = toRecv.at(PayloadKey::authScheme);
782 ctx->linkDevCtx->authEnabled = authScheme
783 != fileutils::ARCHIVE_AUTH_SCHEME_NONE;
784
785 JAMI_DEBUG("[LinkDevice] NEW: Auth scheme from payload is '{}'", authScheme);
786 ctx->linkDevCtx->state = AuthDecodingState::AUTH;
787 DeviceAuthInfo info;
788 info.set(DeviceAuthInfo::auth_scheme, authScheme);
789 info.set(DeviceAuthInfo::peer_id, peerCert->issuer->getId().toString());
790 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
791 ctx->accountId, static_cast<uint8_t>(DeviceAuthState::AUTHENTICATING), info);
792 } else if (ctx->linkDevCtx->state == AuthDecodingState::DATA) {
793 auto passwordCorrectIt = toRecv.find(PayloadKey::passwordCorrect);
794 auto canRetry = toRecv.find(PayloadKey::canRetry);
795
796 // If we've reached the maximum number of retry attempts
797 if (canRetry != toRecv.payload.end() && canRetry->second == "false") {
798 JAMI_DEBUG("[LinkDevice] Authentication failed: maximum retry attempts "
799 "reached");
800 ctx->linkDevCtx->state = AuthDecodingState::AUTH_ERROR;
801 return len;
802 }
803
804 // If the password was incorrect but we can still retry
805 if (passwordCorrectIt != toRecv.payload.end()
806 && passwordCorrectIt->second == "false") {
807 ctx->linkDevCtx->state = AuthDecodingState::AUTH;
808
809 JAMI_DEBUG("[LinkDevice] NEW: Password incorrect.");
810 auto peerCert = ctx->linkDevCtx->channel->peerCertificate();
811 auto peer_id = peerCert->issuer->getId().toString();
812 // We received a password incorrect response, so we know we're using
813 // password authentication
814 auto authScheme = fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD;
815
816 DeviceAuthInfo info;
817 info.set(DeviceAuthInfo::auth_scheme, authScheme);
818 info.set(DeviceAuthInfo::peer_id, peer_id);
819 info.set(DeviceAuthInfo::auth_error, "invalid_credentials");
820
821 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
822 ctx->accountId,
823 static_cast<uint8_t>(DeviceAuthState::AUTHENTICATING),
824 info);
825 return len;
826 }
827
828 if (!shouldLoadArchive) {
829 JAMI_DEBUG("[LinkDevice] NEW: no archive received.");
830 // at this point we suppose to have archive. If not, export failed.
831 // Update state and signal will be handeled onShutdown
832 ctx->linkDevCtx->state = AuthDecodingState::ERR;
833 shouldShutdown = true;
834 }
835 }
836
837 // check if an account archive is ready to be loaded
838 if (shouldLoadArchive) {
839 emitSignal<libjami::ConfigurationSignal::DeviceAuthStateChanged>(
840 ctx->accountId,
841 static_cast<uint8_t>(DeviceAuthState::IN_PROGRESS),
842 DeviceAuthInfo {});
843 try {
844 auto archive = AccountArchive(std::string_view(accDataIt->second));
845 if (auto this_ = wthis.lock()) {
846 JAMI_DEBUG("[LinkDevice] NEW: Reading archive from peer.");
847 this_->onArchiveLoaded(*ctx, std::move(archive), true);
848 JAMI_DEBUG("[LinkDevice] NEW: Successfully loaded archive.");
849 ctx->linkDevCtx->archiveTransferredWithoutFailure = true;
850 } else {
851 ctx->linkDevCtx->archiveTransferredWithoutFailure = false;
852 JAMI_ERROR("[LinkDevice] NEW: Failed to load account because of "
853 "null ArchiveAccountManager!");
854 }
855 } catch (const std::exception& e) {
856 ctx->linkDevCtx->state = AuthDecodingState::ERR;
857 ctx->linkDevCtx->archiveTransferredWithoutFailure = false;
858 JAMI_WARNING("[LinkDevice] NEW: Error reading archive.");
859 }
860 shouldShutdown = true;
861 }
862
863 if (shouldShutdown) {
864 ctx->linkDevCtx->channel->shutdown();
865 }
866
867 return len;
868 }); // !onConnectionReady // TODO emit AuthStateChanged+"connection ready" signal
869
870 ctx->linkDevCtx->state = AuthDecodingState::HANDSHAKE;
871 // send first message to establish scheme
872 AuthMsg toSend;
873 toSend.schemeId = 0; // set latest scheme here
874 JAMI_DEBUG("[LinkDevice] NEW: Packing first message for SOURCE.\nCurrent state is: "
875 "\n\tauth "
876 "state = {}:{}",
877 toSend.schemeId,
878 ctx->linkDevCtx->formattedAuthState());
879 msgpack::sbuffer buffer(UINT16_MAX);
880 msgpack::pack(buffer, toSend);
881 std::error_code ec;
882 ctx->linkDevCtx->channel->write(reinterpret_cast<const unsigned char*>(buffer.data()),
883 buffer.size(),
884 ec);
885
886 JAMI_LOG("[LinkDevice {}] Generated temporary account.",
887 ctx->linkDevCtx->tmpId.second->getId());
888 });
889 });
890 JAMI_DEBUG("[LinkDevice] Starting load archive from device END {} {}.",
891 fmt::ptr(this),
892 fmt::ptr(ctx));
893}
894
895int32_t
896ArchiveAccountManager::addDevice(const std::string& uriProvided,
897 std::string_view auth_scheme,
898 AuthChannelHandler* channelHandler)
899{
900 if (authCtx_) {
901 JAMI_WARNING("[LinkDevice] addDevice: auth context already exists.");
902 return static_cast<int32_t>(AccountManager::AddDeviceError::ALREADY_LINKING);
903 }
904 JAMI_LOG("[LinkDevice] ArchiveAccountManager::addDevice({}, {})", accountId_, uriProvided);
905 try {
906 std::string_view url(uriProvided);
907 if (!starts_with(url, AUTH_URI_SCHEME)) {
908 JAMI_ERROR("[LinkDevice] Invalid uri provided: {}", uriProvided);
909 return static_cast<int32_t>(AccountManager::AddDeviceError::INVALID_URI);
910 }
911 auto peerTempAcc = url.substr(AUTH_URI_SCHEME.length(), 40);
912 auto peerCodeS = url.substr(AUTH_URI_SCHEME.length() + peerTempAcc.length() + 1, 6);
913 JAMI_LOG("[LinkDevice] ======\n * tempAcc = {}\n * code = {}", peerTempAcc, peerCodeS);
914
915 auto gen = Manager::instance().getSeededRandomEngine();
916 std::uniform_int_distribution<int32_t> dist(1, INT32_MAX);
917 auto token = dist(gen);
918 JAMI_WARNING("[LinkDevice] SOURCE: Creating auth context, token: {}.", token);
919 auto ctx = std::make_shared<AuthContext>();
920 ctx->accountId = accountId_;
921 ctx->token = token;
922 ctx->credentials = std::make_unique<ArchiveAccountCredentials>();
923 authCtx_ = ctx;
924
925 channelHandler->connect(
926 dht::InfoHash(peerTempAcc),
927 fmt::format("{}{}", CHANNEL_SCHEME, peerCodeS),
928 [wthis = weak(), auth_scheme, ctx, accountId=accountId_](std::shared_ptr<dhtnet::ChannelSocket> socket,
929 const dht::InfoHash& infoHash) {
930 auto this_ = wthis.lock();
931 if (!socket || !this_) {
933 "[LinkDevice] Invalid socket event while AccountManager connecting.");
934 if (this_)
935 this_->authCtx_.reset();
936 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
937 accountId,
938 ctx->token,
939 static_cast<uint8_t>(DeviceAuthState::DONE),
940 DeviceAuthInfo::createError(DeviceAuthInfo::Error::NETWORK));
941 } else {
942 if (!this_->doAddDevice(auth_scheme, ctx, socket))
943 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
944 accountId,
945 ctx->token,
946 static_cast<uint8_t>(DeviceAuthState::DONE),
947 DeviceAuthInfo::createError(DeviceAuthInfo::Error::UNKNOWN));
948 }
949 });
950 runOnMainThread([token, id = accountId_] {
951 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
952 id, token, static_cast<uint8_t>(DeviceAuthState::CONNECTING), DeviceAuthInfo {});
953 });
954 return token;
955 } catch (const std::exception& e) {
956 JAMI_ERROR("[LinkDevice] Parsing uri failed: {}", uriProvided);
957 return static_cast<int32_t>(AccountManager::AddDeviceError::GENERIC);
958 }
959}
960
961bool
962ArchiveAccountManager::doAddDevice(std::string_view scheme,
963 const std::shared_ptr<AuthContext>& ctx,
964 const std::shared_ptr<dhtnet::ChannelSocket>& channel)
965{
966 if (ctx->canceled) {
967 JAMI_WARNING("[LinkDevice] SOURCE: addDevice canceled.");
968 channel->shutdown();
969 return false;
970 }
971 JAMI_DEBUG("[LinkDevice] Setting up addDevice logic on SOURCE device.");
972 JAMI_DEBUG("[LinkDevice] SOURCE: Creating addDeviceCtx.");
973 ctx->addDeviceCtx = std::make_unique<AddDeviceContext>(channel);
974 ctx->addDeviceCtx->authScheme = scheme;
975 ctx->addDeviceCtx->state = AuthDecodingState::HANDSHAKE;
976
977 ctx->timeout = std::make_unique<asio::steady_timer>(*Manager::instance().ioContext());
978 ctx->timeout->expires_from_now(OP_TIMEOUT);
979 ctx->timeout->async_wait(
980 [wthis = weak(), wctx = std::weak_ptr(ctx)](const std::error_code& ec) {
981 if (ec) {
982 return;
983 }
984 if (auto ctx = wctx.lock()) {
985 if (!ctx->addDeviceCtx->isCompleted()) {
986 if (auto this_ = wthis.lock()) {
987 ctx->addDeviceCtx->state = AuthDecodingState::TIMEOUT;
988 JAMI_WARNING("[LinkDevice] Timeout for addDevice.");
989
990 // Create and send timeout message
991 msgpack::sbuffer buffer(UINT16_MAX);
992 msgpack::pack(buffer, AuthMsg::timeout());
993 std::error_code ec;
994 ctx->addDeviceCtx->channel->write(reinterpret_cast<const unsigned char*>(
995 buffer.data()),
996 buffer.size(),
997 ec);
998 ctx->addDeviceCtx->channel->shutdown();
999 }
1000 }
1001 }
1002 });
1003
1004 JAMI_DEBUG("[LinkDevice] SOURCE: Creating callbacks.");
1005 channel->onShutdown([ctx, w = weak()]() {
1006 JAMI_DEBUG("[LinkDevice] SOURCE: Shutdown with state {}... xfer {}uccessful",
1007 ctx->addDeviceCtx->formattedAuthState(),
1008 ctx->addDeviceCtx->archiveTransferredWithoutFailure ? "s" : "uns");
1009 // check if the archive was successfully loaded and emitSignal
1010 if (ctx->timeout)
1011 ctx->timeout->cancel();
1012 ctx->timeout.reset();
1013
1014 if (auto this_ = w.lock()) {
1015 this_->authCtx_.reset();
1016 }
1017
1018 DeviceAuthInfo::Error error = ctx->addDeviceCtx->getErrorState();
1019 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(ctx->accountId,
1020 ctx->token,
1021 static_cast<uint8_t>(
1022 DeviceAuthState::DONE),
1023 DeviceAuthInfo::createError(
1024 error));
1025 });
1026
1027 // for now we only have one valid protocol (version is AuthMsg::scheme = 0) but can later
1028 // add in more schemes inside this callback function
1029 JAMI_DEBUG("[LinkDevice] Setting up receiving logic callback.");
1030 channel->setOnRecv([ctx,
1031 wthis = weak(),
1032 decodeCtx = std::make_shared<ArchiveAccountManager::DecodingContext>()](
1033 const uint8_t* buf, size_t len) {
1034 JAMI_DEBUG("[LinkDevice] Setting up receiver callback for communication logic on SOURCE "
1035 "device.");
1036 // when archive is sent to newDev we will get back a success or fail response before the
1037 // connection closes and we need to handle this and pass it to the shutdown callback
1038 auto this_ = wthis.lock();
1039 if (!this_) {
1040 JAMI_ERROR("[LinkDevice] Invalid state for ArchiveAccountManager.");
1041 return (size_t) 0;
1042 }
1043
1044 if (!buf) {
1045 JAMI_ERROR("[LinkDevice] Invalid buffer.");
1046 return (size_t) 0;
1047 }
1048
1049 if (ctx->canceled || ctx->addDeviceCtx->state == AuthDecodingState::ERR) {
1050 JAMI_ERROR("[LinkDevice] Error.");
1051 return (size_t) 0;
1052 }
1053
1054 decodeCtx->pac.reserve_buffer(len);
1055 std::copy_n(buf, len, decodeCtx->pac.buffer());
1056 decodeCtx->pac.buffer_consumed(len);
1057
1058 // handle unpacking the data from the peer
1059 JAMI_DEBUG("[LinkDevice] SOURCE: addDevice: setOnRecv: handling msg from NEW");
1060 msgpack::object_handle oh;
1061 AuthMsg toRecv;
1062 try {
1063 if (decodeCtx->pac.next(oh)) {
1064 oh.get().convert(toRecv);
1065 JAMI_DEBUG("[LinkDevice] SOURCE: Successfully unpacked message from NEW "
1066 "(NEW->SOURCE)\n{}",
1067 toRecv.formatMsg());
1068 } else {
1069 return len;
1070 }
1071 } catch (const std::exception& e) {
1072 // set the generic error state in the context
1073 ctx->addDeviceCtx->state = AuthDecodingState::ERR;
1074 JAMI_ERROR("[LinkDevice] error unpacking message from new device: {}", e.what()); // also warn in logs
1075 }
1076
1077 JAMI_DEBUG("[LinkDevice] SOURCE: State is '{}'", ctx->addDeviceCtx->formattedAuthState());
1078
1079 // It's possible to start handling different protocol scheme numbers here
1080 // one possibility is for multi-account xfer in the future
1081 // validate the scheme
1082 if (toRecv.schemeId != 0) {
1083 ctx->addDeviceCtx->state = AuthDecodingState::ERR;
1084 JAMI_WARNING("[LinkDevice] Unsupported scheme received from a connection.");
1085 }
1086
1087 if (ctx->addDeviceCtx->state == AuthDecodingState::ERR
1088 || ctx->addDeviceCtx->state == AuthDecodingState::AUTH_ERROR) {
1089 JAMI_WARNING("[LinkDevice] Undefined behavior encountered during a link auth session.");
1090 ctx->addDeviceCtx->channel->shutdown();
1091 }
1092 // Check for timeout message
1093 if (ctx->addDeviceCtx->handleTimeoutMessage(toRecv)) {
1094 return len;
1095 }
1096 AuthMsg toSend;
1097 bool shouldSendMsg = false;
1098 bool shouldShutdown = false;
1099 bool shouldSendArchive = false;
1100
1101 // we expect to be receiving credentials in this state and we know the archive is encrypted
1102 if (ctx->addDeviceCtx->state == AuthDecodingState::AUTH) {
1103 // receive the incoming password, check if the password is right, and send back the
1104 // archive if it is correct
1105 JAMI_DEBUG("[LinkDevice] SOURCE: addDevice: setOnRecv: verifying sent "
1106 "credentials from NEW");
1107 shouldSendMsg = true;
1108 const auto& passwordIt = toRecv.find(PayloadKey::password);
1109 if (passwordIt != toRecv.payload.end()) {
1110 // try and decompress archive for xfer
1111 try {
1112 JAMI_DEBUG("[LinkDevice] Injecting account archive into outbound message.");
1113 ctx->addDeviceCtx->accData
1114 = this_
1115 ->readArchive(fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD,
1116 passwordIt->second)
1117 .serialize();
1118 shouldSendArchive = true;
1119 JAMI_DEBUG("[LinkDevice] Sending account archive.");
1120 } catch (const std::exception& e) {
1121 ctx->addDeviceCtx->state = AuthDecodingState::ERR;
1122 JAMI_DEBUG("[LinkDevice] Finished reading archive: FAILURE: {}", e.what());
1123 shouldSendArchive = false;
1124 }
1125 }
1126 if (!shouldSendArchive) {
1127 // pass is not valid
1128 if (ctx->addDeviceCtx->numTries < ctx->addDeviceCtx->maxTries) {
1129 // can retry auth
1130 ctx->addDeviceCtx->numTries++;
1131 JAMI_DEBUG("[LinkDevice] Incorrect password received. "
1132 "Attempt {} out of {}.",
1133 ctx->addDeviceCtx->numTries,
1134 ctx->addDeviceCtx->maxTries);
1135 toSend.set(PayloadKey::passwordCorrect, "false");
1136 toSend.set(PayloadKey::canRetry, "true");
1137 } else {
1138 // cannot retry auth
1139 JAMI_WARNING("[LinkDevice] Incorrect password received, maximum attempts reached.");
1140 toSend.set(PayloadKey::canRetry, "false");
1141 ctx->addDeviceCtx->state = AuthDecodingState::AUTH_ERROR;
1142 shouldShutdown = true;
1143 }
1144 }
1145 }
1146
1147 if (shouldSendArchive) {
1148 JAMI_DEBUG("[LinkDevice] SOURCE: Archive in message has encryption scheme '{}'",
1149 ctx->addDeviceCtx->authScheme);
1150 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
1151 ctx->accountId,
1152 ctx->token,
1153 static_cast<uint8_t>(DeviceAuthState::IN_PROGRESS),
1154 DeviceAuthInfo {});
1155 shouldShutdown = true;
1156 shouldSendMsg = true;
1157 ctx->addDeviceCtx->archiveTransferredWithoutFailure = true;
1158 toSend.set(PayloadKey::accData, ctx->addDeviceCtx->accData);
1159 }
1160 if (shouldSendMsg) {
1161 JAMI_DEBUG("[LinkDevice] SOURCE: Sending msg to NEW:\n{}", toSend.formatMsg());
1162 msgpack::sbuffer buffer(UINT16_MAX);
1163 msgpack::pack(buffer, toSend);
1164 std::error_code ec;
1165 ctx->addDeviceCtx->channel->write(reinterpret_cast<const unsigned char*>(buffer.data()),
1166 buffer.size(),
1167 ec);
1168 }
1169
1170 if (shouldShutdown) {
1171 ctx->addDeviceCtx->channel->shutdown();
1172 }
1173
1174 return len;
1175 }); // !channel onRecv closure
1176
1177 if (ctx->addDeviceCtx->state == AuthDecodingState::HANDSHAKE) {
1178 ctx->addDeviceCtx->state = AuthDecodingState::EST;
1179 DeviceAuthInfo info;
1180 info.set(DeviceAuthInfo::peer_address, channel->getRemoteAddress().toString(true));
1181 emitSignal<libjami::ConfigurationSignal::AddDeviceStateChanged>(
1182 ctx->accountId, ctx->token, static_cast<uint8_t>(DeviceAuthState::AUTHENTICATING), info);
1183 }
1184
1185 return true;
1186}
1187
1188bool
1189ArchiveAccountManager::cancelAddDevice(uint32_t token)
1190{
1191 if (auto ctx = authCtx_) {
1192 if (ctx->token == token) {
1193 ctx->canceled = true;
1194 if (ctx->addDeviceCtx) {
1195 ctx->addDeviceCtx->state = AuthDecodingState::CANCELED;
1196 if (ctx->addDeviceCtx->channel) {
1197 // Create and send canceled message
1198 auto canceledMsg = ctx->addDeviceCtx->createCanceledMsg();
1199 msgpack::sbuffer buffer(UINT16_MAX);
1200 msgpack::pack(buffer, canceledMsg);
1201 std::error_code ec;
1202 ctx->addDeviceCtx->channel->write(reinterpret_cast<const unsigned char*>(
1203 buffer.data()),
1204 buffer.size(),
1205 ec);
1206 ctx->addDeviceCtx->channel->shutdown();
1207 }
1208 }
1209 if (ctx->onFailure)
1210 ctx->onFailure(AuthError::UNKNOWN, "");
1211 authCtx_.reset();
1212 return true;
1213 }
1214 }
1215 return false;
1216}
1217
1218bool
1219ArchiveAccountManager::confirmAddDevice(uint32_t token)
1220{
1221 if (auto ctx = authCtx_) {
1222 if (ctx->token == token && ctx->addDeviceCtx
1223 && ctx->addDeviceCtx->state == AuthDecodingState::EST) {
1224 dht::ThreadPool::io().run([ctx] {
1225 ctx->addDeviceCtx->state = AuthDecodingState::AUTH;
1226 AuthMsg toSend;
1227 JAMI_DEBUG("[LinkDevice] SOURCE: Packing first message for NEW and switching to "
1228 "state: {}",
1229 ctx->addDeviceCtx->formattedAuthState());
1230 toSend.set(PayloadKey::authScheme, ctx->addDeviceCtx->authScheme);
1231 msgpack::sbuffer buffer(UINT16_MAX);
1232 msgpack::pack(buffer, toSend);
1233 std::error_code ec;
1234 ctx->addDeviceCtx->channel->write(reinterpret_cast<const unsigned char*>(
1235 buffer.data()),
1236 buffer.size(),
1237 ec);
1238 });
1239 return true;
1240 }
1241 }
1242 return false;
1243}
1244
1245void
1246ArchiveAccountManager::loadFromDHT(const std::shared_ptr<AuthContext>& ctx)
1247{
1248 ctx->dhtContext = std::make_unique<DhtLoadContext>();
1249 ctx->dhtContext->dht.run(ctx->credentials->dhtPort, {}, true);
1250 for (const auto& bootstrap : ctx->credentials->dhtBootstrap) {
1251 ctx->dhtContext->dht.bootstrap(bootstrap);
1252 auto searchEnded = [ctx, accountId = accountId_]() {
1253 if (not ctx->dhtContext or ctx->dhtContext->found) {
1254 return;
1255 }
1256 auto& s = *ctx->dhtContext;
1257 if (s.stateOld.first && s.stateNew.first) {
1258 dht::ThreadPool::computation().run(
1259 [ctx,
1260 network_error = !s.stateOld.second && !s.stateNew.second,
1261 accountId = std::move(accountId)] {
1262 ctx->dhtContext.reset();
1263 JAMI_WARNING("[Account {}] [Auth] Failure looking for archive on DHT: {}",
1264 accountId,
1265 network_error ? "network error" : "not found");
1266 ctx->onFailure(network_error ? AuthError::NETWORK : AuthError::UNKNOWN, "");
1267 });
1268 }
1269 };
1270
1271 auto search = [ctx, searchEnded, w = weak()](bool previous) {
1272 std::vector<uint8_t> key;
1273 dht::InfoHash loc;
1274 auto& s = previous ? ctx->dhtContext->stateOld : ctx->dhtContext->stateNew;
1275
1276 // compute archive location and decryption keys
1277 try {
1278 std::tie(key, loc) = computeKeys(ctx->credentials->password,
1279 ctx->credentials->uri,
1280 previous);
1281 JAMI_LOG("[Auth] Attempting to load account from DHT with {:s} at {:s}",
1282 ctx->credentials->uri,
1283 loc.toString());
1284 if (not ctx->dhtContext or ctx->dhtContext->found) {
1285 return;
1286 }
1287 ctx->dhtContext->dht.get(
1288 loc,
1289 [ctx, key = std::move(key), w](const std::shared_ptr<dht::Value>& val) {
1290 std::vector<uint8_t> decrypted;
1291 try {
1292 decrypted = archiver::decompress(
1293 dht::crypto::aesDecrypt(val->data, key));
1294 } catch (const std::exception& ex) {
1295 return true;
1296 }
1297 JAMI_DBG("[Auth] Found archive on the DHT");
1298 ctx->dhtContext->found = true;
1299 dht::ThreadPool::computation().run(
1300 [ctx, decrypted = std::move(decrypted), w] {
1301 try {
1302 auto archive = AccountArchive(decrypted);
1303 if (auto sthis = w.lock()) {
1304 if (ctx->dhtContext) {
1305 ctx->dhtContext->dht.join();
1306 ctx->dhtContext.reset();
1307 }
1308 sthis->onArchiveLoaded(*ctx, std::move(archive), false);
1309 }
1310 } catch (const std::exception& e) {
1311 ctx->onFailure(AuthError::UNKNOWN, "");
1312 }
1313 });
1314 return not ctx->dhtContext->found;
1315 },
1316 [=, &s](bool ok) {
1317 JAMI_LOG("[Auth] DHT archive search ended at {}", loc.toString());
1318 s.first = true;
1319 s.second = ok;
1320 searchEnded();
1321 });
1322 } catch (const std::exception& e) {
1323 // JAMI_ERROR("Error computing keys: {}", e.what());
1324 s.first = true;
1325 s.second = true;
1326 searchEnded();
1327 return;
1328 }
1329 };
1330 dht::ThreadPool::computation().run(std::bind(search, true));
1331 dht::ThreadPool::computation().run(std::bind(search, false));
1332 }
1333}
1334
1335void
1336ArchiveAccountManager::migrateAccount(AuthContext& ctx)
1337{
1338 JAMI_WARN("[Auth] Account migration needed");
1339 AccountArchive archive;
1340 try {
1341 archive = readArchive(ctx.credentials->password_scheme, ctx.credentials->password);
1342 } catch (...) {
1343 JAMI_DBG("[Auth] Unable to load archive");
1344 ctx.onFailure(AuthError::INVALID_ARGUMENTS, "");
1345 return;
1346 }
1347
1348 updateArchive(archive);
1349
1350 if (updateCertificates(archive, ctx.credentials->updateIdentity)) {
1351 // because updateCertificates already regenerate a device, we do not need to
1352 // regenerate one in onArchiveLoaded
1353 onArchiveLoaded(ctx, std::move(archive), false);
1354 } else {
1355 ctx.onFailure(AuthError::UNKNOWN, "");
1356 }
1357}
1358
1359void
1360ArchiveAccountManager::onArchiveLoaded(AuthContext& ctx, AccountArchive&& a, bool isLinkDevProtocol)
1361{
1362 auto ethAccount = dev::KeyPair(dev::Secret(a.eth_key)).address().hex();
1363 dhtnet::fileutils::check_dir(path_, 0700);
1364
1365 if (isLinkDevProtocol) {
1366 a.save(fileutils::getFullPath(path_, archivePath_),
1367 ctx.linkDevCtx->authScheme,
1368 ctx.linkDevCtx->credentialsFromUser);
1369 } else {
1370 a.save(fileutils::getFullPath(path_, archivePath_),
1371 ctx.credentials ? ctx.credentials->password_scheme : "",
1372 ctx.credentials ? ctx.credentials->password : "");
1373 }
1374
1375 if (not a.id.second->isCA()) {
1376 JAMI_ERROR("[Account {}] [Auth] Attempting to sign a certificate with a non-CA.",
1377 accountId_);
1378 }
1379
1380 std::shared_ptr<dht::crypto::Certificate> deviceCertificate;
1381 std::unique_ptr<ContactList> contacts;
1382 auto usePreviousIdentity = false;
1383 // If updateIdentity got a valid certificate, there is no need for a new cert
1384 if (auto oldId = ctx.credentials->updateIdentity.second) {
1385 contacts = std::make_unique<ContactList>(ctx.accountId, oldId, path_, onChange_);
1386 if (contacts->isValidAccountDevice(*oldId) && ctx.credentials->updateIdentity.first) {
1387 deviceCertificate = oldId;
1388 usePreviousIdentity = true;
1389 JAMI_WARNING("[Account {}] [Auth] Using previously generated device certificate {}",
1390 accountId_,
1391 deviceCertificate->getLongId());
1392 } else {
1393 contacts.reset();
1394 }
1395 }
1396
1397 // Generate a new device if needed
1398 if (!deviceCertificate) {
1399 JAMI_WARNING("[Account {}] [Auth] Creating new device certificate", accountId_);
1400 auto request = ctx.request.get();
1401 if (not request->verify()) {
1402 JAMI_ERROR("[Account {}] [Auth] Invalid certificate request.", accountId_);
1403 ctx.onFailure(AuthError::INVALID_ARGUMENTS, "");
1404 return;
1405 }
1406 deviceCertificate = std::make_shared<dht::crypto::Certificate>(
1407 dht::crypto::Certificate::generate(*request, a.id));
1408 JAMI_WARNING("[Account {}] [Auth] Created new device: {}",
1409 accountId_,
1410 deviceCertificate->getLongId());
1411 }
1412
1413 auto receipt = makeReceipt(a.id, *deviceCertificate, ethAccount);
1414 auto receiptSignature = a.id.first->sign({receipt.first.begin(), receipt.first.end()});
1415
1416 auto info = std::make_unique<AccountInfo>();
1417 auto pk = usePreviousIdentity ? ctx.credentials->updateIdentity.first : ctx.key.get();
1418 auto sharedPk = pk->getSharedPublicKey();
1419 info->identity.first = pk;
1420 info->identity.second = deviceCertificate;
1421 info->accountId = a.id.second->getId().toString();
1422 info->devicePk = sharedPk;
1423 info->deviceId = info->devicePk->getLongId().toString();
1424 if (ctx.deviceName.empty())
1425 ctx.deviceName = info->deviceId.substr(8);
1426
1427 if (!contacts) {
1428 contacts = std::make_unique<ContactList>(ctx.accountId, a.id.second, path_, onChange_);
1429 }
1430 info->contacts = std::move(contacts);
1431 info->contacts->setContacts(a.contacts);
1432 info->contacts->foundAccountDevice(deviceCertificate, ctx.deviceName, clock::now());
1433 info->ethAccount = ethAccount;
1434 info->announce = std::move(receipt.second);
1435 ConversationModule::saveConvInfosToPath(path_, a.conversations);
1436 ConversationModule::saveConvRequestsToPath(path_, a.conversationsRequests);
1437 info_ = std::move(info);
1438
1439 ctx.onSuccess(*info_,
1440 std::move(a.config),
1441 std::move(receipt.first),
1442 std::move(receiptSignature));
1443}
1444
1445std::pair<std::vector<uint8_t>, dht::InfoHash>
1446ArchiveAccountManager::computeKeys(const std::string& password,
1447 const std::string& pin,
1448 bool previous)
1449{
1450 // Compute time seed
1451 auto now = std::chrono::duration_cast<std::chrono::seconds>(clock::now().time_since_epoch());
1452 auto tseed = now.count() / std::chrono::seconds(EXPORT_KEY_RENEWAL_TIME).count();
1453 if (previous)
1454 tseed--;
1455 std::ostringstream ss;
1456 ss << std::hex << tseed;
1457 auto tseed_str = ss.str();
1458
1459 // Generate key for archive encryption, using PIN as the salt
1460 std::vector<uint8_t> salt_key;
1461 salt_key.reserve(pin.size() + tseed_str.size());
1462 salt_key.insert(salt_key.end(), pin.begin(), pin.end());
1463 salt_key.insert(salt_key.end(), tseed_str.begin(), tseed_str.end());
1464 auto key = dht::crypto::stretchKey(password, salt_key, 256 / 8);
1465
1466 // Generate public storage location as SHA1(key).
1467 auto loc = dht::InfoHash::get(key);
1468
1469 return {key, loc};
1470}
1471
1472std::pair<std::string, std::shared_ptr<dht::Value>>
1473ArchiveAccountManager::makeReceipt(const dht::crypto::Identity& id,
1474 const dht::crypto::Certificate& device,
1475 const std::string& ethAccount)
1476{
1477 JAMI_LOG("[Account {}] [Auth] Signing receipt for device {}", accountId_, device.getLongId());
1478 auto devId = device.getId();
1479 DeviceAnnouncement announcement;
1480 announcement.dev = devId;
1481 announcement.pk = device.getSharedPublicKey();
1482 dht::Value ann_val {announcement};
1483 ann_val.sign(*id.first);
1484
1485 auto packedAnnoucement = ann_val.getPacked();
1486 JAMI_LOG("[Account {}] [Auth] Device announcement size: {}",
1487 accountId_,
1488 packedAnnoucement.size());
1489
1490 std::ostringstream is;
1491 is << "{\"id\":\"" << id.second->getId() << "\",\"dev\":\"" << devId << "\",\"eth\":\""
1492 << ethAccount << "\",\"announce\":\"" << base64::encode(packedAnnoucement) << "\"}";
1493
1494 // auto announce_ = ;
1495 return {is.str(), std::make_shared<dht::Value>(std::move(ann_val))};
1496}
1497
1498bool
1499ArchiveAccountManager::needsMigration(const std::string& accountId, const dht::crypto::Identity& id)
1500{
1501 if (not id.second)
1502 return true;
1503 auto cert = id.second->issuer;
1504 while (cert) {
1505 if (not cert->isCA()) {
1506 JAMI_WARNING("[Account {}] [Auth] certificate {} is not a CA, needs update.",
1507 accountId,
1508 cert->getId());
1509 return true;
1510 }
1511 if (cert->getExpiration() < clock::now()) {
1512 JAMI_WARNING("[Account {}] [Auth] certificate {} is expired, needs update.",
1513 accountId,
1514 cert->getId());
1515 return true;
1516 }
1517 cert = cert->issuer;
1518 }
1519 return false;
1520}
1521
1522void
1523ArchiveAccountManager::syncDevices()
1524{
1525 if (not dht_ or not dht_->isRunning()) {
1526 JAMI_WARNING("[Account {}] Not syncing devices: DHT is not running", accountId_);
1527 return;
1528 }
1529 JAMI_LOG("[Account {}] Building device sync from {}", accountId_, info_->deviceId);
1530 auto sync_data = info_->contacts->getSyncData();
1531
1532 for (const auto& dev : getKnownDevices()) {
1533 // don't send sync data to ourself
1534 if (dev.first.toString() == info_->deviceId) {
1535 continue;
1536 }
1537 if (!dev.second.certificate) {
1538 JAMI_WARNING("[Account {}] Unable to find certificate for {}", accountId_, dev.first);
1539 continue;
1540 }
1541 auto pk = dev.second.certificate->getSharedPublicKey();
1542 JAMI_LOG("[Account {}] Sending device sync to {} {}",
1543 accountId_,
1544 dev.second.name,
1545 dev.first.toString());
1546 auto syncDeviceKey = dht::InfoHash::get("inbox:" + pk->getId().toString());
1547 dht_->putEncrypted(syncDeviceKey, pk, sync_data);
1548 }
1549}
1550
1551void
1552ArchiveAccountManager::startSync(const OnNewDeviceCb& cb,
1553 const OnDeviceAnnouncedCb& dcb,
1554 bool publishPresence)
1555{
1556 AccountManager::startSync(std::move(cb), std::move(dcb), publishPresence);
1557
1558 dht_->listen<DeviceSync>(
1559 dht::InfoHash::get("inbox:" + info_->devicePk->getId().toString()),
1560 [this](DeviceSync&& sync) {
1561 // Received device sync data.
1562 // check device certificate
1563 findCertificate(
1564 sync.from,
1565 [this, sync](const std::shared_ptr<dht::crypto::Certificate>& cert) mutable {
1566 if (!cert or cert->getId() != sync.from) {
1567 JAMI_WARNING("[Account {}] Unable to find certificate for device {}",
1568 accountId_,
1569 sync.from.toString());
1570 return;
1571 }
1572 if (not foundAccountDevice(cert))
1573 return;
1574 onSyncData(std::move(sync));
1575 });
1576
1577 return true;
1578 });
1579}
1580
1581AccountArchive
1582ArchiveAccountManager::readArchive(std::string_view scheme, const std::string& pwd) const
1583{
1584 JAMI_LOG("[Account {}] [Auth] Reading account archive", accountId_);
1585 return AccountArchive(fileutils::getFullPath(path_, archivePath_), scheme, pwd);
1586}
1587
1588void
1589ArchiveAccountManager::updateArchive(AccountArchive& archive) const
1590{
1591 using namespace libjami::Account::ConfProperties;
1592
1593 // Keys not exported to archive
1594 static const auto filtered_keys = {Ringtone::PATH,
1595 ARCHIVE_PATH,
1596 DEVICE_ID,
1597 DEVICE_NAME,
1598 Conf::CONFIG_DHT_PORT,
1599 DHT_PROXY_LIST_URL,
1600 AUTOANSWER,
1601 PROXY_ENABLED,
1602 PROXY_SERVER,
1603 PROXY_PUSH_TOKEN};
1604
1605 // Keys with meaning of file path where the contents has to be exported in base64
1606 static const auto encoded_keys = {TLS::CA_LIST_FILE,
1607 TLS::CERTIFICATE_FILE,
1608 TLS::PRIVATE_KEY_FILE};
1609
1610 JAMI_LOG("[Account {}] [Auth] Building account archive", accountId_);
1611 for (const auto& it : onExportConfig_()) {
1612 // filter-out?
1613 if (std::any_of(std::begin(filtered_keys), std::end(filtered_keys), [&](const auto& key) {
1614 return key == it.first;
1615 }))
1616 continue;
1617
1618 // file contents?
1619 if (std::any_of(std::begin(encoded_keys), std::end(encoded_keys), [&](const auto& key) {
1620 return key == it.first;
1621 })) {
1622 try {
1623 archive.config.emplace(it.first, base64::encode(fileutils::loadFile(it.second)));
1624 } catch (...) {
1625 }
1626 } else
1627 archive.config[it.first] = it.second;
1628 }
1629 if (info_) {
1630 // If migrating from same archive, info_ will be null
1631 archive.contacts = info_->contacts->getContacts();
1632 // Note we do not know accountID_ here, use path
1633 archive.conversations = ConversationModule::convInfosFromPath(path_);
1634 archive.conversationsRequests = ConversationModule::convRequestsFromPath(path_);
1635 }
1636}
1637
1638void
1639ArchiveAccountManager::saveArchive(AccountArchive& archive,
1640 std::string_view scheme,
1641 const std::string& pwd)
1642{
1643 try {
1644 updateArchive(archive);
1645 if (archivePath_.empty())
1646 archivePath_ = "export.gz";
1647 archive.save(fileutils::getFullPath(path_, archivePath_), scheme, pwd);
1648 } catch (const std::runtime_error& ex) {
1649 JAMI_ERROR("[Account {}] [Auth] Unable to export archive: {}", accountId_, ex.what());
1650 return;
1651 }
1652}
1653
1654bool
1655ArchiveAccountManager::changePassword(const std::string& password_old,
1656 const std::string& password_new)
1657{
1658 try {
1659 auto path = fileutils::getFullPath(path_, archivePath_);
1660 AccountArchive(path, fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD, password_old)
1661 .save(path, fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD, password_new);
1662 return true;
1663 } catch (const std::exception&) {
1664 return false;
1665 }
1666}
1667
1668std::vector<uint8_t>
1669ArchiveAccountManager::getPasswordKey(const std::string& password)
1670{
1671 try {
1672 auto data = dhtnet::fileutils::loadFile(fileutils::getFullPath(path_, archivePath_));
1673 // Try to decrypt to check if password is valid
1674 auto key = dht::crypto::aesGetKey(data, password);
1675 auto decrypted = dht::crypto::aesDecrypt(dht::crypto::aesGetEncrypted(data), key);
1676 return key;
1677 } catch (const std::exception& e) {
1678 JAMI_ERROR("[Account {}] Error loading archive: {}", accountId_, e.what());
1679 }
1680 return {};
1681}
1682
1683bool
1684ArchiveAccountManager::revokeDevice(const std::string& device,
1685 std::string_view scheme,
1686 const std::string& password,
1688{
1689 auto fa = dht::ThreadPool::computation().getShared<AccountArchive>(
1690 [this, scheme = std::string(scheme), password] { return readArchive(scheme, password); });
1691 findCertificate(DeviceId(device),
1692 [fa = std::move(fa),
1693 scheme = std::string(scheme),
1694 password,
1695 device,
1696 cb,
1697 w = weak()](
1698 const std::shared_ptr<dht::crypto::Certificate>& crt) mutable {
1699 if (not crt) {
1700 cb(RevokeDeviceResult::ERROR_NETWORK);
1701 return;
1702 }
1703 auto this_ = w.lock();
1704 if (not this_)
1705 return;
1706 this_->info_->contacts->foundAccountDevice(crt);
1708 try {
1709 a = fa.get();
1710 } catch (...) {
1711 cb(RevokeDeviceResult::ERROR_CREDENTIALS);
1712 return;
1713 }
1714 // Add revoked device to the revocation list and resign it
1715 if (not a.revoked)
1716 a.revoked = std::make_shared<decltype(a.revoked)::element_type>();
1717 a.revoked->revoke(*crt);
1718 a.revoked->sign(a.id);
1719 // add to CRL cache
1720 this_->certStore().pinRevocationList(a.id.second->getId().toString(),
1721 a.revoked);
1722 this_->certStore().loadRevocations(*a.id.second);
1723
1724 // Announce CRL immediately
1725 auto h = a.id.second->getId();
1726 this_->dht_->put(h, a.revoked, dht::DoneCallback {}, {}, true);
1727
1728 this_->saveArchive(a, scheme, password);
1729 this_->info_->contacts->removeAccountDevice(crt->getLongId());
1730 cb(RevokeDeviceResult::SUCCESS);
1731 this_->syncDevices();
1732 });
1733 return false;
1734}
1735
1736bool
1737ArchiveAccountManager::exportArchive(const std::string& destinationPath,
1738 std::string_view scheme,
1739 const std::string& password)
1740{
1741 try {
1742 // Save contacts if possible before exporting
1743 AccountArchive archive = readArchive(scheme, password);
1744 updateArchive(archive);
1745 auto archivePath = fileutils::getFullPath(path_, archivePath_);
1746 if (!archive.save(archivePath, scheme, password))
1747 return false;
1748
1749 // Export the file
1750 std::error_code ec;
1751 std::filesystem::copy_file(archivePath,
1752 destinationPath,
1753 std::filesystem::copy_options::overwrite_existing,
1754 ec);
1755 return !ec;
1756 } catch (const std::runtime_error& ex) {
1757 JAMI_ERR("[Auth] Unable to export archive: %s", ex.what());
1758 return false;
1759 } catch (...) {
1760 JAMI_ERR("[Auth] Unable to export archive: Unable to read archive");
1761 return false;
1762 }
1763}
1764
1765bool
1766ArchiveAccountManager::isPasswordValid(const std::string& password)
1767{
1768 try {
1769 readArchive(fileutils::ARCHIVE_AUTH_SCHEME_PASSWORD, password);
1770 return true;
1771 } catch (...) {
1772 return false;
1773 }
1774}
1775
1776#if HAVE_RINGNS
1777void
1778ArchiveAccountManager::registerName(const std::string& name,
1779 std::string_view scheme,
1780 const std::string& password,
1781 RegistrationCallback cb)
1782{
1783 std::string signedName;
1784 auto nameLowercase {name};
1785 std::transform(nameLowercase.begin(), nameLowercase.end(), nameLowercase.begin(), ::tolower);
1786 std::string publickey;
1787 std::string accountId;
1788 std::string ethAccount;
1789
1790 try {
1791 auto archive = readArchive(scheme, password);
1792 auto privateKey = archive.id.first;
1793 const auto& pk = privateKey->getPublicKey();
1794 publickey = pk.toString();
1795 accountId = pk.getId().toString();
1796 signedName = base64::encode(
1797 privateKey->sign(std::vector<uint8_t>(nameLowercase.begin(), nameLowercase.end())));
1798 ethAccount = dev::KeyPair(dev::Secret(archive.eth_key)).address().hex();
1799 } catch (const std::exception& e) {
1800 // JAMI_ERR("[Auth] Unable to export account: %s", e.what());
1801 cb(NameDirectory::RegistrationResponse::invalidCredentials, name);
1802 return;
1803 }
1804
1805 nameDir_.get().registerName(accountId, nameLowercase, ethAccount, cb, signedName, publickey);
1806}
1807#endif
1808
1809} // namespace jami
Account specific keys/constants that must be shared in daemon and clients.
std::string hex() const
Definition FixedHash.h:206
Simple class that represents a "key pair".
static KeyPair create()
Create a new, randomly generated object.
Definition Common.cpp:99
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_ERR(...)
Definition logger.h:218
#define JAMI_ERROR(formatstr,...)
Definition logger.h:228
#define JAMI_DBG(...)
Definition logger.h:216
#define JAMI_DEBUG(formatstr,...)
Definition logger.h:226
#define JAMI_WARN(...)
Definition logger.h:217
#define JAMI_WARNING(formatstr,...)
Definition logger.h:227
#define JAMI_LOG(formatstr,...)
Definition logger.h:225
Definition Address.h:25
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)
dht::PkId DeviceId
static constexpr std::string_view toString(AuthDecodingState state)
void emitSignal(Args... args)
Definition ring_signal.h:64
constexpr auto CHANNEL_SCHEME
const constexpr auto EXPORT_KEY_RENEWAL_TIME
constexpr auto AUTH_URI_SCHEME
constexpr auto OP_TIMEOUT
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.
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
void set(std::string_view key, std::string_view value)
DeviceContextBase(uint64_t operationId, AuthDecodingState initialState)
std::shared_ptr< dhtnet::ChannelSocket > channel