feat: 优化客户端跨平台配置和运行态管理
This commit is contained in:
+85
-16
@@ -13,6 +13,7 @@
|
||||
#include <QMessageBox>
|
||||
#include <QSaveFile>
|
||||
#include <QSettings>
|
||||
#include <QStandardPaths>
|
||||
#include <QStringList>
|
||||
#include <QDebug>
|
||||
#include <string>
|
||||
@@ -46,6 +47,8 @@ const QString kRegistryImportedAtKey = QStringLiteral("imported_at_utc");
|
||||
const QString kEmbeddedServerConfigPath = QStringLiteral(":/simcae/server_config.json");
|
||||
const QString kApiBaseUrlKey = QStringLiteral("api_base_url");
|
||||
|
||||
// 需要提权写入时,子进程参数统一用 Base64Url 编码。
|
||||
// 这样可以避免 Windows 路径、中文、空格或换行在 ShellExecute 参数传递中被截断或误解析。
|
||||
QString encodeArgument(const QString& value)
|
||||
{
|
||||
return QString::fromLatin1(value.toUtf8().toBase64(
|
||||
@@ -173,9 +176,31 @@ bool writeConfigValueToFile(const QString& configPath, const QString& key,
|
||||
|
||||
bool isRegistryManagedConfigKey(const QString& key)
|
||||
{
|
||||
// 服务端地址是编译期 qrc 配置,不进入注册表。
|
||||
// 其他运行配置会在 Launcher 首次启动时导入注册表,之后以注册表为准。
|
||||
return key != kApiBaseUrlKey;
|
||||
}
|
||||
|
||||
bool isPathInsideDirectory(const QString& path, const QString& directory)
|
||||
{
|
||||
if (path.isEmpty() || directory.isEmpty())
|
||||
return false;
|
||||
|
||||
QString normalizedPath = QDir::cleanPath(QFileInfo(path).absoluteFilePath());
|
||||
QString normalizedDirectory = QDir::cleanPath(QFileInfo(directory).absoluteFilePath());
|
||||
#ifdef Q_OS_WIN
|
||||
normalizedPath = normalizedPath.toLower();
|
||||
normalizedDirectory = normalizedDirectory.toLower();
|
||||
#endif
|
||||
return normalizedPath == normalizedDirectory
|
||||
|| normalizedPath.startsWith(normalizedDirectory + QDir::separator());
|
||||
}
|
||||
|
||||
bool isUserDataPath(const QString& path)
|
||||
{
|
||||
return isPathInsideDirectory(path, ConfigHelper::instance().dataRoot());
|
||||
}
|
||||
|
||||
QJsonObject registryManagedConfigObject(const QJsonObject& source)
|
||||
{
|
||||
QJsonObject result;
|
||||
@@ -198,6 +223,8 @@ QString windowsErrorMessage(DWORD errorCode)
|
||||
bool runElevatedSelfCommand(const QStringList& arguments, const QString& targetPath,
|
||||
const QString& originalError, QString* errorMessage)
|
||||
{
|
||||
// 安装到 C:\Program Files 等目录时,普通用户不能直接修改配置或运行态文件。
|
||||
// 这里不让主进程一直以管理员运行,而是在确实需要写入时临时拉起自身完成单次写入。
|
||||
const QMessageBox::StandardButton choice = QMessageBox::question(
|
||||
nullptr,
|
||||
QCoreApplication::translate("ConfigHelper", "Administrator Permission Required"),
|
||||
@@ -397,6 +424,12 @@ bool ConfigHelper::writeFileWithElevationIfNeeded(const QString& path, const QBy
|
||||
}
|
||||
|
||||
#ifdef Q_OS_WIN
|
||||
if (isUserDataPath(path))
|
||||
{
|
||||
if (errorMessage)
|
||||
*errorMessage = localError;
|
||||
return false;
|
||||
}
|
||||
if (data.size() > 24 * 1024)
|
||||
{
|
||||
if (errorMessage)
|
||||
@@ -423,6 +456,12 @@ bool ConfigHelper::removeFileWithElevationIfNeeded(const QString& path, QString*
|
||||
}
|
||||
|
||||
#ifdef Q_OS_WIN
|
||||
if (isUserDataPath(path))
|
||||
{
|
||||
if (errorMessage)
|
||||
*errorMessage = localError;
|
||||
return false;
|
||||
}
|
||||
return removeFileWithElevation(path, localError, errorMessage);
|
||||
#else
|
||||
if (errorMessage)
|
||||
@@ -458,15 +497,44 @@ QString ConfigHelper::installRoot() const
|
||||
return QDir::cleanPath(QDir(runtimeRoot()).filePath(relativeRoot));
|
||||
}
|
||||
|
||||
QString ConfigHelper::runtimeRoot() const
|
||||
{
|
||||
return QDir::cleanPath(QApplication::applicationDirPath());
|
||||
}
|
||||
|
||||
QString ConfigHelper::updateRoot() const
|
||||
{
|
||||
return QDir(runtimeRoot()).filePath("update");
|
||||
}
|
||||
QString ConfigHelper::runtimeRoot() const
|
||||
{
|
||||
return QDir::cleanPath(QApplication::applicationDirPath());
|
||||
}
|
||||
|
||||
QString ConfigHelper::dataRoot() const
|
||||
{
|
||||
QString base = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
|
||||
if (base.isEmpty())
|
||||
base = QDir::homePath();
|
||||
return QDir::cleanPath(QDir(base).filePath(
|
||||
QStringLiteral("Marsco/UpdateClientSDK/installations/%1").arg(m_registryInstallId)));
|
||||
}
|
||||
|
||||
QString ConfigHelper::dataConfigDir() const
|
||||
{
|
||||
return QDir(dataRoot()).filePath(QStringLiteral("config"));
|
||||
}
|
||||
|
||||
QString ConfigHelper::clientIdentityPath() const
|
||||
{
|
||||
return QDir(dataConfigDir()).filePath(QStringLiteral("client_identity.dat"));
|
||||
}
|
||||
|
||||
QString ConfigHelper::policyPath() const
|
||||
{
|
||||
return QDir(dataConfigDir()).filePath(QStringLiteral("version_policy.dat"));
|
||||
}
|
||||
|
||||
QString ConfigHelper::localStatePath() const
|
||||
{
|
||||
return QDir(dataConfigDir()).filePath(QStringLiteral("local_state.json"));
|
||||
}
|
||||
|
||||
QString ConfigHelper::updateRoot() const
|
||||
{
|
||||
return QDir(dataRoot()).filePath("update");
|
||||
}
|
||||
|
||||
QString ConfigHelper::runtimeRelativePath() const
|
||||
{
|
||||
@@ -572,16 +640,15 @@ bool ConfigHelper::syncRegistryFromConfigFileIfChanged()
|
||||
|
||||
if (configChangedAfterPreviousImport)
|
||||
{
|
||||
const QString configDir = QFileInfo(m_configPath).absolutePath();
|
||||
const QStringList staleFiles{
|
||||
QDir(configDir).filePath(QStringLiteral("client_identity.dat")),
|
||||
QDir(configDir).filePath(QStringLiteral("version_policy.dat")),
|
||||
QDir(configDir).filePath(QStringLiteral("local_state.json"))
|
||||
clientIdentityPath(),
|
||||
policyPath(),
|
||||
localStatePath()
|
||||
};
|
||||
for (const QString& staleFile : staleFiles)
|
||||
{
|
||||
QString removeError;
|
||||
if (!ConfigHelper::removeFileWithElevationIfNeeded(staleFile, &removeError))
|
||||
if (!removeFile(staleFile, &removeError))
|
||||
{
|
||||
m_error = QStringLiteral("Cannot remove stale runtime file after config change: %1. %2")
|
||||
.arg(staleFile, removeError);
|
||||
@@ -608,9 +675,11 @@ bool ConfigHelper::sanitizeConfigFileAfterImport(QSettings& settings)
|
||||
QCryptographicHash::hash(normalizedEmptyConfig, QCryptographicHash::Sha256).toHex());
|
||||
|
||||
QString writeError;
|
||||
if (!ConfigHelper::writeFileWithElevationIfNeeded(m_configPath, emptyFileBytes, &writeError))
|
||||
if (!writeBytesToFile(m_configPath, emptyFileBytes, &writeError))
|
||||
{
|
||||
m_error = QStringLiteral("Cannot clear app_config.json after registry import: %1").arg(writeError);
|
||||
// 清空 app_config.json 只是为了减少明文配置暴露,不是启动必需步骤。
|
||||
// 如果安装目录或文件只读,不再为了清空源配置弹 UAC;运行配置已经写入 HKCU 注册表。
|
||||
m_error = QStringLiteral("Cannot clear app_config.json after registry import without elevation: %1").arg(writeError);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -17,9 +17,14 @@ public:
|
||||
QString getValue(const QString& section, const QString& key) const;
|
||||
bool setValue(const QString& section, const QString& key, const QString& value);
|
||||
QString configPath() const;
|
||||
QString installRoot() const;
|
||||
QString runtimeRoot() const;
|
||||
QString updateRoot() const;
|
||||
QString installRoot() const;
|
||||
QString runtimeRoot() const;
|
||||
QString dataRoot() const;
|
||||
QString dataConfigDir() const;
|
||||
QString clientIdentityPath() const;
|
||||
QString policyPath() const;
|
||||
QString localStatePath() const;
|
||||
QString updateRoot() const;
|
||||
QString runtimeRelativePath() const;
|
||||
QString lastError() const;
|
||||
|
||||
|
||||
+296
-43
@@ -1,48 +1,301 @@
|
||||
#include "DeviceIdentityHelper.h"
|
||||
#include "ConfigHelper.h"
|
||||
#include <QCryptographicHash>
|
||||
#include <QDateTime>
|
||||
#include <QDir>
|
||||
#include <QEventLoop>
|
||||
#include <QFile>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QNetworkAccessManager>
|
||||
#include "DeviceIdentityHelper.h"
|
||||
#include "ConfigHelper.h"
|
||||
|
||||
#include <QCoreApplication>
|
||||
#include <QCryptographicHash>
|
||||
#include <QDateTime>
|
||||
#include <QDir>
|
||||
#include <QEventLoop>
|
||||
#include <QFile>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QSysInfo>
|
||||
#include <QUuid>
|
||||
#include <QTimer>
|
||||
#ifdef HAVE_OPENSSL
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/pem.h>
|
||||
#endif
|
||||
DeviceIdentityHelper::DeviceIdentityHelper(const QString& dir):m_installDir(dir){}
|
||||
QString DeviceIdentityHelper::deviceId() const{return m_deviceId;}
|
||||
QString DeviceIdentityHelper::errorString() const{return m_error;}
|
||||
bool DeviceIdentityHelper::verifySignature(const QByteArray& payload,const QString& sig64){
|
||||
#ifndef HAVE_OPENSSL
|
||||
Q_UNUSED(payload);Q_UNUSED(sig64);m_error="OpenSSL unavailable";return false;
|
||||
#else
|
||||
QFile f(QDir(m_installDir).filePath("config/manifest_public_key.pem")); if(!f.open(QIODevice::ReadOnly)){m_error="device public key missing";return false;}
|
||||
QByteArray kd=f.readAll();BIO* b=BIO_new_mem_buf(kd.constData(),kd.size());EVP_PKEY* k=b?PEM_read_bio_PUBKEY(b,nullptr,nullptr,nullptr):nullptr;if(b)BIO_free(b);if(!k){m_error="device public key invalid";return false;}
|
||||
EVP_MD_CTX* c=EVP_MD_CTX_new();QByteArray sig=QByteArray::fromBase64(sig64.toUtf8());bool ok=c&&EVP_DigestVerifyInit(c,nullptr,EVP_sha256(),nullptr,k)==1&&EVP_DigestVerifyUpdate(c,payload.constData(),payload.size())==1&&EVP_DigestVerifyFinal(c,reinterpret_cast<const unsigned char*>(sig.constData()),sig.size())==1;if(c)EVP_MD_CTX_free(c);EVP_PKEY_free(k);if(!ok)m_error="device credential RSA signature invalid";return ok;
|
||||
#endif
|
||||
}
|
||||
bool DeviceIdentityHelper::loadAndVerify(const QString& appId,const QString& channel){
|
||||
QFile f(QDir(m_installDir).filePath("config/client_identity.dat"));if(!f.open(QIODevice::ReadOnly))return false;QJsonParseError e;auto d=QJsonDocument::fromJson(f.readAll(),&e);if(e.error!=QJsonParseError::NoError||!d.isObject()){m_error="device credential JSON invalid";return false;}auto w=d.object();QByteArray text=w.value("identity_text").toString().toUtf8();if(text.isEmpty()||!verifySignature(text,w.value("signature").toString()))return false;auto identity=QJsonDocument::fromJson(text).object();QDateTime expiry=QDateTime::fromString(identity.value("valid_until").toString(),Qt::ISODate);if(identity.value("app_id").toString()!=appId||identity.value("channel").toString()!=channel||identity.value("license_id").toString().isEmpty()||identity.value("installation_id").toString().isEmpty()||identity.value("device_id").toString().isEmpty()){m_error="device/license credential identity mismatch";return false;}if(!expiry.isValid()||expiry<=QDateTime::currentDateTimeUtc()){m_error="license expired";return false;}m_deviceId=identity.value("device_id").toString();return true;
|
||||
}
|
||||
bool DeviceIdentityHelper::verifyLocal(const QString& appId,const QString& channel){m_error.clear();return loadAndVerify(appId,channel);}
|
||||
bool DeviceIdentityHelper::ensureIssued(const QString& base,const QString& token,const QString& appId,const QString& channel,const QString& licenseKey){
|
||||
m_error.clear();if(loadAndVerify(appId,channel)){ConfigHelper::instance().setValue("Update","device_id",m_deviceId);return true;}
|
||||
const QString trimmedBase=base.trimmed();
|
||||
if(appId.trimmed().isEmpty()){m_error="app_id is empty in config/app_config.json";return false;}
|
||||
if(channel.trimmed().isEmpty()){m_error="channel is empty in config/app_config.json";return false;}
|
||||
if(trimmedBase.isEmpty()||trimmedBase.contains("YOUR_SERVER_IP",Qt::CaseInsensitive)){m_error="api_base_url is not configured. Set config/server_config.json before building the client, for example http://192.168.229.128:8000";return false;}
|
||||
if(token.trimmed().isEmpty()){m_error="client_token is empty in config/app_config.json";return false;}
|
||||
if(licenseKey.trimmed().isEmpty()){m_error="license_key is empty. Create a License in the admin page and paste the generated key into config/app_config.json";return false;}
|
||||
ConfigHelper& config=ConfigHelper::instance();
|
||||
QString installation=config.getValue("Device","installation_id");if(installation.isEmpty()){installation=QUuid::createUuid().toString(QUuid::WithoutBraces);if(!config.setValue("Device","installation_id",installation)){m_error=QString("cannot save installation id to %1: %2").arg(config.configPath(),config.lastError());return false;}}
|
||||
QByteArray machine=QSysInfo::machineUniqueId()+installation.toUtf8();QString mh=QString::fromLatin1(QCryptographicHash::hash(machine,QCryptographicHash::Sha256).toHex());QJsonObject body{{"app_id",appId},{"channel",channel},{"license_key",licenseKey},{"installation_id",installation},{"machine_hash",mh}};
|
||||
QNetworkAccessManager manager;QNetworkRequest req{QUrl(trimmedBase+"/api/v1/device/issue")};req.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");req.setRawHeader("X-Client-Token",token.toUtf8());QNetworkReply* reply=manager.post(req,QJsonDocument(body).toJson(QJsonDocument::Compact));QEventLoop loop;bool timeoutOk=false;int timeoutMs=ConfigHelper::instance().getValue("Update","request_timeout_ms").toInt(&timeoutOk);if(!timeoutOk||timeoutMs<1000)timeoutMs=5000;QTimer timer;timer.setSingleShot(true);QObject::connect(&timer,&QTimer::timeout,[&](){if(reply&&reply->isRunning())reply->abort();});QObject::connect(reply,&QNetworkReply::finished,&loop,&QEventLoop::quit);timer.start(timeoutMs);loop.exec();timer.stop();int status=reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();QByteArray raw=reply->readAll();reply->deleteLater();if(status!=200){m_error=QString("device issue failed (HTTP %1): %2").arg(status).arg(QString::fromUtf8(raw));return false;}auto response=QJsonDocument::fromJson(raw).object();QJsonObject wrapper{{"identity_text",response.value("identity_text")},{"signature",response.value("signature")}};QString path=QDir(m_installDir).filePath("config/client_identity.dat");QByteArray bytes=QJsonDocument(wrapper).toJson(QJsonDocument::Compact);QString writeError;if(!ConfigHelper::writeFileWithElevationIfNeeded(path,bytes,&writeError)){m_error=QString("cannot save device credential to %1: %2").arg(path,writeError);return false;}if(!loadAndVerify(appId,channel))return false;if(!config.setValue("Update","device_id",m_deviceId)){m_error=QString("cannot save server device id to %1: %2").arg(config.configPath(),config.lastError());return false;}return true;
|
||||
#include <QUuid>
|
||||
|
||||
#ifdef HAVE_OPENSSL
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/pem.h>
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
QString manifestPublicKeyPath(const QString &installDir)
|
||||
{
|
||||
return QDir(installDir).filePath(QStringLiteral("config/manifest_public_key.pem"));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
DeviceIdentityHelper::DeviceIdentityHelper(const QString &installDir)
|
||||
: m_installDir(installDir)
|
||||
{
|
||||
}
|
||||
|
||||
QString DeviceIdentityHelper::deviceId() const
|
||||
{
|
||||
return m_deviceId;
|
||||
}
|
||||
|
||||
QString DeviceIdentityHelper::errorString() const
|
||||
{
|
||||
return m_error;
|
||||
}
|
||||
|
||||
bool DeviceIdentityHelper::verifySignature(const QByteArray &payload, const QString &signatureBase64)
|
||||
{
|
||||
#ifndef HAVE_OPENSSL
|
||||
Q_UNUSED(payload);
|
||||
Q_UNUSED(signatureBase64);
|
||||
m_error = QCoreApplication::translate(
|
||||
"DeviceIdentityHelper",
|
||||
"OpenSSL is unavailable, so device credential signature cannot be verified.");
|
||||
return false;
|
||||
#else
|
||||
const QString keyPath = manifestPublicKeyPath(m_installDir);
|
||||
QFile keyFile(keyPath);
|
||||
if (!keyFile.open(QIODevice::ReadOnly)) {
|
||||
m_error = QCoreApplication::translate("DeviceIdentityHelper", "Device public key is missing: %1").arg(keyPath);
|
||||
return false;
|
||||
}
|
||||
|
||||
const QByteArray keyData = keyFile.readAll();
|
||||
BIO *bio = BIO_new_mem_buf(keyData.constData(), keyData.size());
|
||||
EVP_PKEY *publicKey = bio ? PEM_read_bio_PUBKEY(bio, nullptr, nullptr, nullptr) : nullptr;
|
||||
if (bio) {
|
||||
BIO_free(bio);
|
||||
}
|
||||
if (!publicKey) {
|
||||
m_error = QCoreApplication::translate("DeviceIdentityHelper", "Device public key is invalid: %1").arg(keyPath);
|
||||
return false;
|
||||
}
|
||||
|
||||
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
|
||||
const QByteArray signature = QByteArray::fromBase64(signatureBase64.toUtf8());
|
||||
const bool ok = ctx
|
||||
&& EVP_DigestVerifyInit(ctx, nullptr, EVP_sha256(), nullptr, publicKey) == 1
|
||||
&& EVP_DigestVerifyUpdate(ctx, payload.constData(), payload.size()) == 1
|
||||
&& EVP_DigestVerifyFinal(
|
||||
ctx,
|
||||
reinterpret_cast<const unsigned char *>(signature.constData()),
|
||||
signature.size()) == 1;
|
||||
|
||||
if (ctx) {
|
||||
EVP_MD_CTX_free(ctx);
|
||||
}
|
||||
EVP_PKEY_free(publicKey);
|
||||
|
||||
if (!ok) {
|
||||
m_error = QCoreApplication::translate(
|
||||
"DeviceIdentityHelper",
|
||||
"Device credential signature is invalid. The local identity file may not match this server.");
|
||||
}
|
||||
return ok;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool DeviceIdentityHelper::loadAndVerify(const QString &expectedAppId, const QString &expectedChannel)
|
||||
{
|
||||
// client_identity.dat 是服务端签发的本机设备凭证,不是用户可手写配置。
|
||||
// 本地启动时先用公钥校验签名,再校验 app/channel/license/installation/device 和有效期。
|
||||
QString credentialPath = ConfigHelper::instance().clientIdentityPath();
|
||||
if (!QFile::exists(credentialPath)) {
|
||||
credentialPath = QDir(m_installDir).filePath(QStringLiteral("config/client_identity.dat"));
|
||||
}
|
||||
|
||||
QFile credentialFile(credentialPath);
|
||||
if (!credentialFile.open(QIODevice::ReadOnly)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument wrapperDoc = QJsonDocument::fromJson(credentialFile.readAll(), &parseError);
|
||||
if (parseError.error != QJsonParseError::NoError || !wrapperDoc.isObject()) {
|
||||
m_error = QCoreApplication::translate("DeviceIdentityHelper", "Device credential file is not valid JSON: %1")
|
||||
.arg(credentialPath);
|
||||
return false;
|
||||
}
|
||||
|
||||
const QJsonObject wrapper = wrapperDoc.object();
|
||||
const QByteArray identityText = wrapper.value(QStringLiteral("identity_text")).toString().toUtf8();
|
||||
const QString signature = wrapper.value(QStringLiteral("signature")).toString();
|
||||
if (identityText.isEmpty() || !verifySignature(identityText, signature)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const QJsonDocument identityDoc = QJsonDocument::fromJson(identityText);
|
||||
const QJsonObject identity = identityDoc.object();
|
||||
const QDateTime expiry = QDateTime::fromString(
|
||||
identity.value(QStringLiteral("valid_until")).toString(),
|
||||
Qt::ISODate);
|
||||
|
||||
const bool identityMatches = identity.value(QStringLiteral("app_id")).toString() == expectedAppId
|
||||
&& identity.value(QStringLiteral("channel")).toString() == expectedChannel
|
||||
&& !identity.value(QStringLiteral("license_id")).toString().isEmpty()
|
||||
&& !identity.value(QStringLiteral("installation_id")).toString().isEmpty()
|
||||
&& !identity.value(QStringLiteral("device_id")).toString().isEmpty();
|
||||
if (!identityMatches) {
|
||||
m_error = QCoreApplication::translate(
|
||||
"DeviceIdentityHelper",
|
||||
"Device credential does not match this application, channel, license, installation or device.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!expiry.isValid() || expiry <= QDateTime::currentDateTimeUtc()) {
|
||||
m_error = QCoreApplication::translate(
|
||||
"DeviceIdentityHelper",
|
||||
"License has expired. Please ask the administrator to issue a new License.");
|
||||
return false;
|
||||
}
|
||||
|
||||
m_deviceId = identity.value(QStringLiteral("device_id")).toString();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DeviceIdentityHelper::verifyLocal(const QString &appId, const QString &channel)
|
||||
{
|
||||
m_error.clear();
|
||||
return loadAndVerify(appId, channel);
|
||||
}
|
||||
|
||||
bool DeviceIdentityHelper::ensureIssued(
|
||||
const QString &apiBaseUrl,
|
||||
const QString &clientToken,
|
||||
const QString &appId,
|
||||
const QString &channel,
|
||||
const QString &licenseKey)
|
||||
{
|
||||
// 首次启动或本地凭证失效时,Launcher 会拿 License 向服务端登记设备。
|
||||
// 服务端返回签名后的 identity_text,客户端保存为 client_identity.dat,并把真实 device_id 写入运行配置。
|
||||
m_error.clear();
|
||||
if (loadAndVerify(appId, channel)) {
|
||||
ConfigHelper::instance().setValue(QStringLiteral("Update"), QStringLiteral("device_id"), m_deviceId);
|
||||
return true;
|
||||
}
|
||||
|
||||
const QString trimmedBaseUrl = apiBaseUrl.trimmed();
|
||||
if (appId.trimmed().isEmpty()) {
|
||||
m_error = QCoreApplication::translate("DeviceIdentityHelper", "app_id is empty in app_config.json.");
|
||||
return false;
|
||||
}
|
||||
if (channel.trimmed().isEmpty()) {
|
||||
m_error = QCoreApplication::translate("DeviceIdentityHelper", "channel is empty in app_config.json.");
|
||||
return false;
|
||||
}
|
||||
if (trimmedBaseUrl.isEmpty() || trimmedBaseUrl.contains(QStringLiteral("YOUR_SERVER_IP"), Qt::CaseInsensitive)) {
|
||||
m_error = QCoreApplication::translate(
|
||||
"DeviceIdentityHelper",
|
||||
"Server address is not configured. Set config/server_config.json before building Launcher, for example: http://192.168.229.128:8000");
|
||||
return false;
|
||||
}
|
||||
if (clientToken.trimmed().isEmpty()) {
|
||||
m_error = QCoreApplication::translate(
|
||||
"DeviceIdentityHelper",
|
||||
"client_token is empty. Copy the client_token generated by the admin page into app_config.json.");
|
||||
return false;
|
||||
}
|
||||
if (licenseKey.trimmed().isEmpty()) {
|
||||
m_error = QCoreApplication::translate(
|
||||
"DeviceIdentityHelper",
|
||||
"License is empty. Create or select a License in the admin page, then copy the generated client configuration.");
|
||||
return false;
|
||||
}
|
||||
|
||||
ConfigHelper &config = ConfigHelper::instance();
|
||||
QString installationId = config.getValue(QStringLiteral("Device"), QStringLiteral("installation_id"));
|
||||
if (installationId.isEmpty()) {
|
||||
installationId = QUuid::createUuid().toString(QUuid::WithoutBraces);
|
||||
if (!config.setValue(QStringLiteral("Device"), QStringLiteral("installation_id"), installationId)) {
|
||||
m_error = QCoreApplication::translate("DeviceIdentityHelper", "Cannot save installation id to %1: %2")
|
||||
.arg(config.configPath(), config.lastError());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const QByteArray machine = QSysInfo::machineUniqueId() + installationId.toUtf8();
|
||||
const QString machineHash = QString::fromLatin1(
|
||||
QCryptographicHash::hash(machine, QCryptographicHash::Sha256).toHex());
|
||||
const QJsonObject body{
|
||||
{QStringLiteral("app_id"), appId},
|
||||
{QStringLiteral("channel"), channel},
|
||||
{QStringLiteral("license_key"), licenseKey},
|
||||
{QStringLiteral("installation_id"), installationId},
|
||||
{QStringLiteral("machine_hash"), machineHash},
|
||||
};
|
||||
|
||||
QNetworkAccessManager manager;
|
||||
QNetworkRequest request{QUrl(trimmedBaseUrl + QStringLiteral("/api/v1/device/issue"))};
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, QStringLiteral("application/json"));
|
||||
request.setRawHeader("X-Client-Token", clientToken.toUtf8());
|
||||
|
||||
QNetworkReply *reply = manager.post(request, QJsonDocument(body).toJson(QJsonDocument::Compact));
|
||||
QEventLoop loop;
|
||||
QTimer timer;
|
||||
timer.setSingleShot(true);
|
||||
|
||||
bool timeoutOk = false;
|
||||
int timeoutMs = ConfigHelper::instance()
|
||||
.getValue(QStringLiteral("Update"), QStringLiteral("request_timeout_ms"))
|
||||
.toInt(&timeoutOk);
|
||||
if (!timeoutOk || timeoutMs < 1000) {
|
||||
timeoutMs = 5000;
|
||||
}
|
||||
|
||||
QObject::connect(&timer, &QTimer::timeout, [&]() {
|
||||
if (reply && reply->isRunning()) {
|
||||
reply->abort();
|
||||
}
|
||||
});
|
||||
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
|
||||
|
||||
timer.start(timeoutMs);
|
||||
loop.exec();
|
||||
timer.stop();
|
||||
|
||||
const int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
const QByteArray raw = reply->readAll();
|
||||
reply->deleteLater();
|
||||
if (status != 200) {
|
||||
m_error = QCoreApplication::translate("DeviceIdentityHelper", "Device identity request failed (HTTP %1): %2")
|
||||
.arg(status)
|
||||
.arg(QString::fromUtf8(raw));
|
||||
return false;
|
||||
}
|
||||
|
||||
const QJsonDocument responseDoc = QJsonDocument::fromJson(raw);
|
||||
const QJsonObject response = responseDoc.object();
|
||||
if (response.value(QStringLiteral("identity_text")).toString().isEmpty()
|
||||
|| response.value(QStringLiteral("signature")).toString().isEmpty()) {
|
||||
m_error = QCoreApplication::translate(
|
||||
"DeviceIdentityHelper",
|
||||
"Server returned an invalid device identity response.");
|
||||
return false;
|
||||
}
|
||||
|
||||
const QJsonObject wrapper{
|
||||
{QStringLiteral("identity_text"), response.value(QStringLiteral("identity_text"))},
|
||||
{QStringLiteral("signature"), response.value(QStringLiteral("signature"))},
|
||||
};
|
||||
const QByteArray credentialBytes = QJsonDocument(wrapper).toJson(QJsonDocument::Compact);
|
||||
const QString credentialPath = config.clientIdentityPath();
|
||||
|
||||
QString writeError;
|
||||
if (!ConfigHelper::writeFileWithElevationIfNeeded(credentialPath, credentialBytes, &writeError)) {
|
||||
m_error = QCoreApplication::translate("DeviceIdentityHelper", "Cannot save device credential to %1: %2")
|
||||
.arg(credentialPath, writeError);
|
||||
return false;
|
||||
}
|
||||
if (!loadAndVerify(appId, channel)) {
|
||||
return false;
|
||||
}
|
||||
if (!config.setValue(QStringLiteral("Update"), QStringLiteral("device_id"), m_deviceId)) {
|
||||
m_error = QCoreApplication::translate("DeviceIdentityHelper", "Cannot save server device id to %1: %2")
|
||||
.arg(config.configPath(), config.lastError());
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,28 @@
|
||||
#pragma once
|
||||
#include <QString>
|
||||
class DeviceIdentityHelper {
|
||||
public:
|
||||
explicit DeviceIdentityHelper(const QString& installDir);
|
||||
bool ensureIssued(const QString& apiBaseUrl, const QString& clientToken, const QString& appId,
|
||||
const QString& channel, const QString& licenseKey);
|
||||
bool verifyLocal(const QString& appId, const QString& channel);
|
||||
QString deviceId() const;
|
||||
QString errorString() const;
|
||||
private:
|
||||
bool loadAndVerify(const QString& expectedAppId, const QString& expectedChannel);
|
||||
bool verifySignature(const QByteArray& payload, const QString& signatureBase64);
|
||||
QString m_installDir, m_deviceId, m_error;
|
||||
};
|
||||
#pragma once
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QString>
|
||||
|
||||
class DeviceIdentityHelper {
|
||||
public:
|
||||
explicit DeviceIdentityHelper(const QString &installDir);
|
||||
|
||||
bool ensureIssued(
|
||||
const QString &apiBaseUrl,
|
||||
const QString &clientToken,
|
||||
const QString &appId,
|
||||
const QString &channel,
|
||||
const QString &licenseKey);
|
||||
bool verifyLocal(const QString &appId, const QString &channel);
|
||||
|
||||
QString deviceId() const;
|
||||
QString errorString() const;
|
||||
|
||||
private:
|
||||
bool loadAndVerify(const QString &expectedAppId, const QString &expectedChannel);
|
||||
bool verifySignature(const QByteArray &payload, const QString &signatureBase64);
|
||||
|
||||
QString m_installDir;
|
||||
QString m_deviceId;
|
||||
QString m_error;
|
||||
};
|
||||
|
||||
@@ -17,7 +17,10 @@ void HttpHelper::postRequest(const QString& url, const QJsonObject& jsonBody,
|
||||
// Add auth token header
|
||||
QString token = ConfigHelper::instance().getValue("Server", "client_token");
|
||||
req.setRawHeader("X-Client-Token", token.toUtf8());
|
||||
QFile identity(QDir(QApplication::applicationDirPath()).filePath("config/client_identity.dat"));
|
||||
QString identityPath = ConfigHelper::instance().clientIdentityPath();
|
||||
if (!QFile::exists(identityPath))
|
||||
identityPath = QDir(QApplication::applicationDirPath()).filePath("config/client_identity.dat");
|
||||
QFile identity(identityPath);
|
||||
if (identity.open(QIODevice::ReadOnly))
|
||||
req.setRawHeader("X-Device-Credential", identity.readAll().toBase64());
|
||||
|
||||
@@ -64,4 +67,4 @@ void HttpHelper::postRequest(const QString& url, const QJsonObject& jsonBody,
|
||||
|
||||
reply->deleteLater();
|
||||
manager->deleteLater();
|
||||
}
|
||||
}
|
||||
|
||||
+16
-10
@@ -26,8 +26,10 @@ bool IntegrityHelper::safeRelativePath(const QString& path) const
|
||||
&& !clean.startsWith("../") && !clean.contains(":");
|
||||
}
|
||||
|
||||
bool IntegrityHelper::runtimeProtectedPath(const QString& path) const
|
||||
{
|
||||
bool IntegrityHelper::runtimeProtectedPath(const QString& path) const
|
||||
{
|
||||
// 这些文件属于 SDK 运行态,不参与业务版本文件的 Manifest 校验。
|
||||
// 例如 app_config.json、client_identity.dat 会随安装机器变化,不能要求它们和发布包 hash 完全一致。
|
||||
const QString p = QDir::fromNativeSeparators(path).toCaseFolded();
|
||||
QSet<QString> protectedPaths{
|
||||
"bootstrap", "bootstrap.exe", "client.ini", "config/app_config.json", "config/local_state.json",
|
||||
@@ -81,11 +83,13 @@ bool IntegrityHelper::verifySignature(const QByteArray& payload, const QString&
|
||||
#endif
|
||||
}
|
||||
|
||||
bool IntegrityHelper::verifyInstalledVersion(const QString& appId, const QString& channel,
|
||||
const QString& version)
|
||||
{
|
||||
m_error.clear();
|
||||
QString cachePath = QDir(ConfigHelper::instance().updateRoot()).filePath(
|
||||
bool IntegrityHelper::verifyInstalledVersion(const QString& appId, const QString& channel,
|
||||
const QString& version)
|
||||
{
|
||||
m_error.clear();
|
||||
// Manifest cache 来自服务端发布版本时生成的签名清单。
|
||||
// 客户端先验签 Manifest,再逐个校验文件 SHA256,防止升级文件被篡改或漏替换。
|
||||
QString cachePath = QDir(ConfigHelper::instance().updateRoot()).filePath(
|
||||
"manifest_cache/manifest_" + version + ".json");
|
||||
const QString legacyCachePath = QDir(m_installDir).filePath(
|
||||
"update/manifest_cache/manifest_" + version + ".json");
|
||||
@@ -132,9 +136,11 @@ bool IntegrityHelper::verifyInstalledVersion(const QString& appId, const QString
|
||||
if (suffix == "exe" || suffix == "dll") declaredExecutables.insert(path.toCaseFolded());
|
||||
}
|
||||
|
||||
QDir root(m_installDir);
|
||||
QDirIterator it(m_installDir, QDir::Files, QDirIterator::Subdirectories);
|
||||
while (it.hasNext()) {
|
||||
QDir root(m_installDir);
|
||||
QDirIterator it(m_installDir, QDir::Files, QDirIterator::Subdirectories);
|
||||
// 除了清单中声明的文件,还要拒绝额外出现的 exe/dll。
|
||||
// 这能降低被人偷偷塞插件或可执行文件的风险。
|
||||
while (it.hasNext()) {
|
||||
const QString fullPath = it.next();
|
||||
const QString relative = QDir::fromNativeSeparators(root.relativeFilePath(fullPath));
|
||||
const QString folded = relative.toCaseFolded();
|
||||
|
||||
@@ -1,17 +1,24 @@
|
||||
#include "LocalStateHelper.h"
|
||||
#include "ConfigHelper.h"
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QJsonDocument>
|
||||
|
||||
LocalStateHelper::LocalStateHelper(const QString& baseDir)
|
||||
: m_baseDir(baseDir)
|
||||
, m_filePath(baseDir + "/config/local_state.json")
|
||||
{
|
||||
}
|
||||
|
||||
bool LocalStateHelper::loadState(const QString& relativePath)
|
||||
{
|
||||
m_filePath = m_baseDir + "/" + relativePath;
|
||||
LocalStateHelper::LocalStateHelper(const QString& baseDir)
|
||||
: m_baseDir(baseDir)
|
||||
, m_filePath(ConfigHelper::instance().localStatePath())
|
||||
{
|
||||
}
|
||||
|
||||
bool LocalStateHelper::loadState(const QString& relativePath)
|
||||
{
|
||||
const QString defaultState = QStringLiteral("config/local_state.json");
|
||||
if (relativePath == defaultState)
|
||||
m_filePath = ConfigHelper::instance().localStatePath();
|
||||
else if (QDir::isAbsolutePath(relativePath))
|
||||
m_filePath = relativePath;
|
||||
else
|
||||
m_filePath = m_baseDir + "/" + relativePath;
|
||||
QFile file(m_filePath);
|
||||
if (!file.exists())
|
||||
{
|
||||
|
||||
+22
-7
@@ -2,6 +2,7 @@
|
||||
#include "ConfigHelper.h"
|
||||
#include <QApplication>
|
||||
#include <QDateTime>
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
@@ -11,12 +12,25 @@
|
||||
#include <openssl/pem.h>
|
||||
#endif
|
||||
|
||||
PolicyHelper::PolicyHelper(const QString& baseDir) : m_baseDir(baseDir) {}
|
||||
|
||||
bool PolicyHelper::loadPolicy(const QString& relativePath)
|
||||
{
|
||||
QFile file(m_baseDir + "/" + relativePath);
|
||||
if (!file.open(QIODevice::ReadOnly)) { m_error = "Cannot open policy file"; return false; }
|
||||
PolicyHelper::PolicyHelper(const QString& baseDir) : m_baseDir(baseDir) {}
|
||||
|
||||
static QString resolvePolicyPath(const QString& baseDir, const QString& relativePath, bool forWrite)
|
||||
{
|
||||
const QString defaultPolicy = QStringLiteral("config/version_policy.dat");
|
||||
if (relativePath == defaultPolicy) {
|
||||
const QString runtimePolicy = ConfigHelper::instance().policyPath();
|
||||
if (forWrite || QFile::exists(runtimePolicy))
|
||||
return runtimePolicy;
|
||||
}
|
||||
if (QDir::isAbsolutePath(relativePath))
|
||||
return relativePath;
|
||||
return baseDir + "/" + relativePath;
|
||||
}
|
||||
|
||||
bool PolicyHelper::loadPolicy(const QString& relativePath)
|
||||
{
|
||||
QFile file(resolvePolicyPath(m_baseDir, relativePath, false));
|
||||
if (!file.open(QIODevice::ReadOnly)) { m_error = "Cannot open policy file"; return false; }
|
||||
QJsonParseError error;
|
||||
const QJsonDocument doc = QJsonDocument::fromJson(file.readAll(), &error);
|
||||
if (error.error != QJsonParseError::NoError || !doc.isObject()) {
|
||||
@@ -35,7 +49,8 @@ bool PolicyHelper::savePolicy(const QString& relativePath) const
|
||||
{
|
||||
const QByteArray bytes = QJsonDocument(m_policy).toJson(QJsonDocument::Indented);
|
||||
QString writeError;
|
||||
if (!ConfigHelper::writeFileWithElevationIfNeeded(m_baseDir + "/" + relativePath, bytes, &writeError)) {
|
||||
const QString path = resolvePolicyPath(m_baseDir, relativePath, true);
|
||||
if (!ConfigHelper::writeFileWithElevationIfNeeded(path, bytes, &writeError)) {
|
||||
m_error = "Cannot save policy file: " + writeError;
|
||||
return false;
|
||||
}
|
||||
|
||||
+16
-12
@@ -10,17 +10,19 @@
|
||||
#include <QStandardPaths>
|
||||
#include <QUuid>
|
||||
|
||||
static QByteArray ticketMac(const QJsonObject& payload, const QString& secret)
|
||||
{
|
||||
static QByteArray ticketMac(const QJsonObject& payload, const QString& secret)
|
||||
{
|
||||
return QMessageAuthenticationCode::hash(
|
||||
QJsonDocument(payload).toJson(QJsonDocument::Compact), secret.toUtf8(), QCryptographicHash::Sha256).toHex();
|
||||
}
|
||||
|
||||
bool TicketHelper::createTicket(const QString& appId, const QString& deviceId,
|
||||
const QString& version, const QString& secret,
|
||||
QString* ticketPath, QString* errorMessage)
|
||||
{
|
||||
if (appId.isEmpty() || version.isEmpty() || secret.isEmpty()) {
|
||||
bool TicketHelper::createTicket(const QString& appId, const QString& deviceId,
|
||||
const QString& version, const QString& secret,
|
||||
QString* ticketPath, QString* errorMessage)
|
||||
{
|
||||
// Launcher 启动业务主程序前生成一次性 ticket。
|
||||
// ticket 只保存在临时目录、有效期 60 秒,并用 launch_token 做 HMAC,防止用户绕过 Launcher 直接启动主程序。
|
||||
if (appId.isEmpty() || version.isEmpty() || secret.isEmpty()) {
|
||||
if (errorMessage) *errorMessage = "ticket identity or secret is empty";
|
||||
return false;
|
||||
}
|
||||
@@ -47,11 +49,13 @@ bool TicketHelper::createTicket(const QString& appId, const QString& deviceId,
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TicketHelper::consumeAndVerify(const QString& ticketPath, const QString& expectedAppId,
|
||||
const QString& expectedDeviceId, const QString& expectedVersion,
|
||||
const QString& secret, QString* errorMessage)
|
||||
{
|
||||
const QString consumingPath = ticketPath + ".consuming."
|
||||
bool TicketHelper::consumeAndVerify(const QString& ticketPath, const QString& expectedAppId,
|
||||
const QString& expectedDeviceId, const QString& expectedVersion,
|
||||
const QString& secret, QString* errorMessage)
|
||||
{
|
||||
// 主程序启动后第一时间把 ticket 改名成 .consuming,再读取并删除。
|
||||
// 这样同一张 ticket 即使校验失败也不能被重复使用,避免重放启动。
|
||||
const QString consumingPath = ticketPath + ".consuming."
|
||||
+ QString::number(QCoreApplication::applicationPid());
|
||||
if (!QFile::rename(ticketPath, consumingPath)) {
|
||||
if (errorMessage) *errorMessage = "ticket missing or already consumed";
|
||||
|
||||
Reference in New Issue
Block a user