Skip to content

A native macOS / windows / Linux database IDE built with Swift and AppKit. Connect to PostgreSQL, MySQL, SQLite, and Redis from a single app with a fast, keyboard-driven interface.

C++

feat(linux): Sign in with ChatGPT (OAuth + provider client) (#60)

haidang181028399bc05106
diff --git a/linux/src/Core/Models/AI/ChatGPTTokenBundle.h b/linux/src/Core/Models/AI/ChatGPTTokenBundle.h
new file mode 100644
index 0000000..5ce05aa
--- /dev/null
+++ b/linux/src/Core/Models/AI/ChatGPTTokenBundle.h
@@ -0,0 +1,62 @@
+#pragma once
+
+// Persisted ChatGPT OAuth token bundle. Lives in SecretStore as a single
+// JSON blob keyed by provider id (or, in our simpler Linux model, a
+// process-wide "chatgpt" key).
+
+#include <chrono>
+#include <optional>
+#include <string>
+
+#include <nlohmann/json.hpp>
+
+namespace gridex {
+
+struct ChatGPTTokenBundle {
+ std::string accessToken;
+ std::string refreshToken;
+ std::string idToken;
+
+ // Decoded id_token claims (populated by ChatGPTOAuthService::applyClaims).
+ std::optional<std::string> email;
+ std::optional<std::string> accountId;
+ std::optional<std::string> planType;
+
+ // Wall-clock instant the bundle was created or refreshed.
+ std::chrono::system_clock::time_point obtainedAt =
+ std::chrono::system_clock::now();
+
+ [[nodiscard]] nlohmann::json toJson() const {
+ nlohmann::json j = {
+ {"accessToken", accessToken},
+ {"refreshToken", refreshToken},
+ {"idToken", idToken},
+ {"obtainedAt", std::chrono::duration_cast<std::chrono::seconds>(
+ obtainedAt.time_since_epoch()).count()},
+ };
+ if (email) j["email"] = *email;
+ if (accountId) j["accountId"] = *accountId;
+ if (planType) j["planType"] = *planType;
+ return j;
+ }
+
+ static std::optional<ChatGPTTokenBundle> fromJson(const nlohmann::json& j) {
+ if (!j.is_object() || !j.contains("accessToken") || !j.contains("refreshToken")) {
+ return std::nullopt;
+ }
+ ChatGPTTokenBundle b;
+ b.accessToken = j.value("accessToken", "");
+ b.refreshToken = j.value("refreshToken", "");
+ b.idToken = j.value("idToken", "");
+ if (j.contains("email")) b.email = j["email"].get<std::string>();
+ if (j.contains("accountId")) b.accountId = j["accountId"].get<std::string>();
+ if (j.contains("planType")) b.planType = j["planType"].get<std::string>();
+ if (j.contains("obtainedAt") && j["obtainedAt"].is_number_integer()) {
+ b.obtainedAt = std::chrono::system_clock::time_point(
+ std::chrono::seconds(j["obtainedAt"].get<std::int64_t>()));
+ }
+ return b;
+ }
+};
+
+} // namespace gridex
diff --git a/linux/src/Data/Keychain/SecretStore.h b/linux/src/Data/Keychain/SecretStore.h
index 9ba89ef..17589e5 100644
--- a/linux/src/Data/Keychain/SecretStore.h
+++ b/linux/src/Data/Keychain/SecretStore.h
@@ -53,6 +53,17 @@ public:
return load("ai.apikey." + std::string(provider));
}
+ // ChatGPT OAuth token bundle (JSON-serialized — see ChatGPTTokenBundle).
+ void saveChatGPTTokens(std::string_view providerKey, std::string_view tokensJson) {
+ save("ai.chatgpt.tokens." + std::string(providerKey), tokensJson);
+ }
+ std::optional<std::string> loadChatGPTTokens(std::string_view providerKey) {
+ return load("ai.chatgpt.tokens." + std::string(providerKey));
+ }
+ void deleteChatGPTTokens(std::string_view providerKey) {
+ remove("ai.chatgpt.tokens." + std::string(providerKey));
+ }
+
private:
std::string serviceName_;
};
diff --git a/linux/src/Presentation/Views/Settings/SettingsDialog.cpp b/linux/src/Presentation/Views/Settings/SettingsDialog.cpp
index 91cbed9..fdca3d8 100644
--- a/linux/src/Presentation/Views/Settings/SettingsDialog.cpp
+++ b/linux/src/Presentation/Views/Settings/SettingsDialog.cpp
@@ -1,6 +1,16 @@
#include "Presentation/Views/Settings/SettingsDialog.h"
+#include "Core/Models/AI/ChatGPTTokenBundle.h"
+#include "Services/AI/Auth/ChatGPTOAuthService.h"
+
+#include <nlohmann/json.hpp>
+
#include <QApplication>
+#include <QNetworkAccessManager>
+#include <QNetworkReply>
+#include <QNetworkRequest>
+#include <QUrl>
+#include <QUrlQuery>
#include <QComboBox>
#include <QFormLayout>
#include <QFrame>
@@ -11,7 +21,6 @@
#include <QListWidget>
#include <QMessageBox>
#include <QPointer>
-#include <QProgressBar>
#include <QPushButton>
#include <QSettings>
#include <QStackedWidget>
@@ -29,7 +38,7 @@ namespace gridex {
namespace {
-constexpr const char* kProviders[] = {"Anthropic", "OpenAI", "Ollama", "Gemini"};
+constexpr const char* kProviders[] = {"Anthropic", "OpenAI", "Ollama", "Gemini", "ChatGPT"};
QString endpointKey(const QString& provider) {
return QStringLiteral("ai/endpoint/") + provider;
@@ -49,6 +58,8 @@ QString endpointPlaceholder(const QString& provider) {
} // namespace
+SettingsDialog::~SettingsDialog() = default;
+
SettingsDialog::SettingsDialog(SecretStore* secretStore, QWidget* parent)
: QDialog(parent), secretStore_(secretStore) {
buildUi();
@@ -122,6 +133,7 @@ void SettingsDialog::buildAiPage(QWidget* page) {
form->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
form->setHorizontalSpacing(12);
form->setVerticalSpacing(10);
+ aiForm_ = form; // captured for runtime row-visibility toggling
// Provider
providerCombo_ = new QComboBox(page);
@@ -140,12 +152,26 @@ void SettingsDialog::buildAiPage(QWidget* page) {
connect(modelCombo_, &QComboBox::currentTextChanged,
this, &SettingsDialog::onModelChanged);
mrH->addWidget(modelCombo_, 1);
- modelSpinner_ = new QProgressBar(modelRow);
- modelSpinner_->setFixedSize(80, 16);
- modelSpinner_->setRange(0, 0); // indeterminate animation
- modelSpinner_->setTextVisible(false);
+ // Tiny Braille-glyph spinner — replaces the 80×16 QProgressBar bar with
+ // a single character that ticks at ~12fps next to the model combo.
+ modelSpinner_ = new QLabel(modelRow);
+ modelSpinner_->setFixedWidth(14);
+ modelSpinner_->setAlignment(Qt::AlignCenter);
+ modelSpinner_->setStyleSheet("color: #89b4fa; font-size: 14px; font-weight: 600;");
modelSpinner_->hide();
mrH->addWidget(modelSpinner_);
+ spinnerTimer_ = new QTimer(this);
+ spinnerTimer_->setInterval(80);
+ static const QStringList kFrames = {
+ QStringLiteral("⠋"), QStringLiteral("⠙"), QStringLiteral("⠹"),
+ QStringLiteral("⠸"), QStringLiteral("⠼"), QStringLiteral("⠴"),
+ QStringLiteral("⠦"), QStringLiteral("⠧"), QStringLiteral("⠇"),
+ QStringLiteral("⠏"),
+ };
+ connect(spinnerTimer_, &QTimer::timeout, this, [this]() {
+ modelSpinner_->setText(kFrames[spinnerFrame_]);
+ spinnerFrame_ = (spinnerFrame_ + 1) % kFrames.size();
+ });
modelStatus_ = new QLabel(modelRow);
modelStatus_->setForegroundRole(QPalette::PlaceholderText);
mrH->addWidget(modelStatus_);
@@ -178,11 +204,53 @@ void SettingsDialog::buildAiPage(QWidget* page) {
});
keyH->addWidget(eye);
form->addRow(tr("API Key:"), keyRow);
+ apiKeyRow_ = keyRow;
+ if (auto* lbl = qobject_cast<QLabel*>(form->labelForField(keyRow))) {
+ // Capture label so toggling visibility hides both halves of the row.
+ keyRow->setProperty("formLabel", QVariant::fromValue<QObject*>(lbl));
+ }
+
+ // ChatGPT OAuth — replaces API Key when provider == ChatGPT.
+ oauthRow_ = new QWidget(page);
+ auto* oauthH = new QHBoxLayout(oauthRow_);
+ oauthH->setContentsMargins(0, 0, 0, 0);
+ oauthH->setSpacing(8);
+ oauthStatus_ = new QLabel(oauthRow_);
+ oauthStatus_->setForegroundRole(QPalette::PlaceholderText);
+ signInBtn_ = new QPushButton(tr("Sign in with ChatGPT"), oauthRow_);
+ signInBtn_->setObjectName(QStringLiteral("primaryButton"));
+ signOutBtn_ = new QPushButton(tr("Sign out"), oauthRow_);
+ signOutBtn_->hide();
+ oauthH->addWidget(oauthStatus_, 1);
+ oauthH->addWidget(signInBtn_);
+ oauthH->addWidget(signOutBtn_);
+ form->addRow(tr("ChatGPT account:"), oauthRow_);
+ // Hide both label and field by default — onProviderChanged() flips them
+ // when the user picks ChatGPT.
+ if (auto* lbl = qobject_cast<QLabel*>(form->labelForField(oauthRow_))) lbl->hide();
+ oauthRow_->hide();
+ connect(signInBtn_, &QPushButton::clicked, this, &SettingsDialog::onOAuthSignInClicked);
+ connect(signOutBtn_, &QPushButton::clicked, this, &SettingsDialog::onOAuthSignOutClicked);
+
+ oauthService_ = std::make_unique<ChatGPTOAuthService>(secretStore_);
+ connect(oauthService_.get(), &ChatGPTOAuthService::signInCompleted,
+ this, [this](const QString&, const ChatGPTTokenBundle&) {
+ refreshOAuthStatus();
+ fetchChatGPTModels();
+ });
+ connect(oauthService_.get(), &ChatGPTOAuthService::signInFailed,
+ this, [this](const QString&, const QString& msg) {
+ signInBtn_->setEnabled(true);
+ signInBtn_->setText(tr("Sign in with ChatGPT"));
+ oauthStatus_->setText(QString("<span style='color:#f38ba8;'>%1</span>").arg(msg));
+ oauthStatus_->setTextFormat(Qt::RichText);
+ });
// Custom endpoint
endpointEdit_ = new QLineEdit(page);
endpointEdit_->setClearButtonEnabled(true);
form->addRow(tr("Custom endpoint:"), endpointEdit_);
+ endpointRow_ = endpointEdit_;
root->addLayout(form);
root->addStretch();
@@ -233,7 +301,7 @@ void SettingsDialog::onKeyEditTimeout() {
void SettingsDialog::fetchModels(const QString& provider, const QString& apiKey) {
// Show spinner + status while fetching.
- modelSpinner_->show();
+ modelSpinner_->show(); spinnerFrame_ = 0; spinnerTimer_->start();
modelStatus_->setText(tr("Loading models…"));
modelCombo_->setEnabled(false);
@@ -269,7 +337,7 @@ void SettingsDialog::fetchModels(const QString& provider, const QString& apiKey)
}
modelCombo_->blockSignals(false);
- modelSpinner_->hide();
+ spinnerTimer_->stop(); modelSpinner_->hide();
modelCombo_->setEnabled(true);
if (models.empty()) {
const bool hasKey = !apiKeyEdit_->text().trimmed().isEmpty();
@@ -293,7 +361,151 @@ void SettingsDialog::fetchModels(const QString& provider, const QString& apiKey)
}
void SettingsDialog::onProviderChanged(const QString& provider) {
- loadForProvider(provider);
+ const bool isChatGPT = (provider == QLatin1String("ChatGPT"));
+
+ // Toggle the API-key + custom-endpoint rows out of the form when the
+ // user picks the OAuth-based ChatGPT provider; show the OAuth row
+ // instead. Both halves of a QFormLayout row (label + field) need to be
+ // hidden together, hence the labelForField lookups.
+ if (aiForm_) {
+ auto setRowVisible = [&](QWidget* row, bool visible) {
+ if (!row) return;
+ if (auto* lbl = qobject_cast<QLabel*>(aiForm_->labelForField(row))) {
+ lbl->setVisible(visible);
+ }
+ row->setVisible(visible);
+ };
+ setRowVisible(apiKeyRow_, !isChatGPT);
+ setRowVisible(endpointRow_, !isChatGPT);
+ setRowVisible(oauthRow_, isChatGPT);
+ }
+
+ if (isChatGPT) {
+ refreshOAuthStatus();
+ if (oauthService_ && oauthService_->status().signedIn) {
+ fetchChatGPTModels();
+ } else {
+ modelCombo_->clear();
+ modelStatus_->setText(tr("Sign in to load models."));
+ }
+ } else {
+ loadForProvider(provider);
+ }
+}
+
+void SettingsDialog::fetchChatGPTModels() {
+ if (!oauthService_) return;
+ auto bundle = oauthService_->currentBundle();
+ if (!bundle) return;
+
+ modelSpinner_->show(); spinnerFrame_ = 0; spinnerTimer_->start();
+ modelStatus_->setText(tr("Loading models…"));
+ modelCombo_->setEnabled(false);
+ modelCombo_->clear();
+
+ QUrl url(QStringLiteral("https://chatgpt.com/backend-api/codex/models"));
+ QUrlQuery q;
+ q.addQueryItem("client_version", "1.0.0");
+ url.setQuery(q);
+
+ QNetworkRequest req(url);
+ req.setRawHeader("Authorization",
+ QByteArrayLiteral("Bearer ") + QByteArray::fromStdString(bundle->accessToken));
+ if (bundle->accountId) {
+ req.setRawHeader("ChatGPT-Account-ID",
+ QByteArray::fromStdString(*bundle->accountId));
+ }
+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
+ QNetworkRequest::NoLessSafeRedirectPolicy);
+
+ auto* nam = new QNetworkAccessManager(this);
+ auto* reply = nam->get(req);
+ connect(reply, &QNetworkReply::finished, this, [this, nam, reply]() {
+ reply->deleteLater();
+ nam->deleteLater();
+ spinnerTimer_->stop(); modelSpinner_->hide();
+ modelCombo_->setEnabled(true);
+
+ int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ if (status == 401 || status == 403) {
+ modelStatus_->setText(tr("Sign-in expired — sign in again."));
+ return;
+ }
+ if (status < 200 || status >= 300) {
+ modelStatus_->setText(tr("HTTP %1 on /models").arg(status));
+ return;
+ }
+ QByteArray data = reply->readAll();
+ try {
+ auto j = nlohmann::json::parse(data.toStdString());
+ if (!j.contains("models") || !j["models"].is_array()) {
+ modelStatus_->setText(tr("/models response missing 'models' array"));
+ return;
+ }
+ QSettings s;
+ const QString savedModel = s.value("ai/model").toString();
+ modelCombo_->blockSignals(true);
+ int count = 0;
+ for (const auto& m : j["models"]) {
+ if (!m.contains("slug") || !m["slug"].is_string()) continue;
+ bool supported = m.value("supported_in_api", true);
+ std::string vis = m.value("visibility", std::string("list"));
+ if (!supported || vis != "list") continue;
+ QString slug = QString::fromStdString(m["slug"].get<std::string>());
+ QString name = m.contains("name") && m["name"].is_string()
+ ? QString::fromStdString(m["name"].get<std::string>()) : slug;
+ modelCombo_->addItem(name, slug);
+ ++count;
+ }
+ if (!savedModel.isEmpty()) {
+ int idx = modelCombo_->findData(savedModel);
+ if (idx < 0) idx = modelCombo_->findText(savedModel);
+ if (idx >= 0) modelCombo_->setCurrentIndex(idx);
+ }
+ modelCombo_->blockSignals(false);
+ modelStatus_->setText(count == 0
+ ? tr("No models returned.")
+ : tr("%1 models").arg(count));
+ } catch (const std::exception& e) {
+ modelStatus_->setText(tr("Could not parse /models response: ") + e.what());
+ }
+ });
+}
+
+void SettingsDialog::refreshOAuthStatus() {
+ if (!oauthService_) return;
+ auto status = oauthService_->status();
+ if (status.signedIn) {
+ QString line = status.email.isEmpty() ? tr("Signed in") : status.email;
+ if (!status.planType.isEmpty()) {
+ line += QString(" <span style='color:#a6e3a1;'>(%1)</span>").arg(status.planType);
+ }
+ oauthStatus_->setText(QString("<span style='color:#a6e3a1;'>●</span> %1").arg(line));
+ oauthStatus_->setTextFormat(Qt::RichText);
+ signInBtn_->hide();
+ signOutBtn_->show();
+ } else {
+ oauthStatus_->setText(tr("Not signed in"));
+ oauthStatus_->setTextFormat(Qt::PlainText);
+ signInBtn_->show();
+ signInBtn_->setEnabled(true);
+ signInBtn_->setText(tr("Sign in with ChatGPT"));
+ signOutBtn_->hide();
+ }
+}
+
+void SettingsDialog::onOAuthSignInClicked() {
+ if (!oauthService_) return;
+ signInBtn_->setEnabled(false);
+ signInBtn_->setText(tr("Waiting for browser…"));
+ oauthStatus_->setText(tr("Browser opened — complete sign-in there."));
+ oauthService_->signIn();
+}
+
+void SettingsDialog::onOAuthSignOutClicked() {
+ if (!oauthService_) return;
+ oauthService_->signOut();
+ refreshOAuthStatus();
}
void SettingsDialog::onModelChanged(const QString& /*modelName*/) {
diff --git a/linux/src/Presentation/Views/Settings/SettingsDialog.h b/linux/src/Presentation/Views/Settings/SettingsDialog.h
index 4d46818..d35770c 100644
--- a/linux/src/Presentation/Views/Settings/SettingsDialog.h
+++ b/linux/src/Presentation/Views/Settings/SettingsDialog.h
@@ -1,6 +1,7 @@
#pragma once
#include <QDialog>
+#include <memory>
class QComboBox;
class QLabel;
@@ -8,17 +9,22 @@ class QLineEdit;
class QListWidget;
class QProgressBar;
class QPushButton;
+class QFormLayout;
class QStackedWidget;
class QTimer;
+class QWidget;
namespace gridex {
class SecretStore;
+class ChatGPTOAuthService;
+struct ChatGPTTokenBundle;
class SettingsDialog : public QDialog {
Q_OBJECT
public:
explicit SettingsDialog(SecretStore* secretStore, QWidget* parent = nullptr);
+ ~SettingsDialog() override;
private slots:
void onProviderChanged(const QString& provider);
@@ -43,11 +49,28 @@ private:
QComboBox* modelCombo_ = nullptr;
QLineEdit* apiKeyEdit_ = nullptr;
QLineEdit* endpointEdit_ = nullptr;
- QProgressBar* modelSpinner_ = nullptr;
+ QLabel* modelSpinner_ = nullptr; // small Braille-glyph spinner
QLabel* modelStatus_ = nullptr;
QPushButton* saveBtn_ = nullptr;
- QTimer* keyDebounce_ = nullptr;
+ QTimer* keyDebounce_ = nullptr;
+ QTimer* spinnerTimer_ = nullptr;
+ int spinnerFrame_ = 0;
+
+ // ChatGPT OAuth — replaces the API-key row when "ChatGPT" is selected.
+ QWidget* oauthRow_ = nullptr;
+ QLabel* oauthStatus_ = nullptr;
+ QPushButton* signInBtn_ = nullptr;
+ QPushButton* signOutBtn_ = nullptr;
+ QFormLayout* aiForm_ = nullptr; // owning form so we can hide rows
+ QWidget* apiKeyRow_ = nullptr; // captured to toggle visibility
+ QWidget* endpointRow_ = nullptr;
+ std::unique_ptr<ChatGPTOAuthService> oauthService_;
+
+ void refreshOAuthStatus();
+ void onOAuthSignInClicked();
+ void onOAuthSignOutClicked();
+ void fetchChatGPTModels();
// Appearance page controls.
QComboBox* themeCombo_ = nullptr;
diff --git a/linux/src/Services/AI/AIServiceFactory.cpp b/linux/src/Services/AI/AIServiceFactory.cpp
index 1f38b31..63e1ea0 100644
--- a/linux/src/Services/AI/AIServiceFactory.cpp
+++ b/linux/src/Services/AI/AIServiceFactory.cpp
@@ -3,6 +3,7 @@
#include <stdexcept>
#include "Services/AI/Providers/AnthropicProvider.h"
+#include "Services/AI/Providers/ChatGPTProvider.h"
#include "Services/AI/Providers/GeminiProvider.h"
#include "Services/AI/Providers/OllamaProvider.h"
#include "Services/AI/Providers/OpenAIProvider.h"
@@ -28,6 +29,11 @@ AIServiceFactory::createAIService(const std::string& providerName,
if (providerName == "Gemini") {
return std::make_unique<GeminiProvider>(apiKey, baseUrl);
}
+ if (providerName == "ChatGPT") {
+ // apiKey is unused — credentials live in libsecret as an OAuth bundle
+ // populated by the Sign in with ChatGPT flow.
+ return std::make_unique<ChatGPTProvider>(apiKey, baseUrl);
+ }
throw std::invalid_argument("AIServiceFactory: unknown provider '" + providerName + "'");
}
diff --git a/linux/src/Services/AI/Auth/ChatGPTOAuthConstants.h b/linux/src/Services/AI/Auth/ChatGPTOAuthConstants.h
new file mode 100644
index 0000000..dc6beee
--- /dev/null
+++ b/linux/src/Services/AI/Auth/ChatGPTOAuthConstants.h
@@ -0,0 +1,49 @@
+#pragma once
+
+// ChatGPTOAuthConstants — endpoints + parameter constants for the ChatGPT
+// OAuth flow. Mirrors the macOS / Windows ports verbatim so a single
+// origination signature is used across platforms.
+//
+// Reusing OpenAI's public Codex CLI client_id is a deliberate trade-off: the
+// authorize endpoint only accepts loopback redirects that were registered
+// for that client. OpenAI may revoke it at any time.
+
+#include <array>
+#include <cstdint>
+#include <string_view>
+
+namespace gridex::oauth {
+
+// Public Codex CLI client_id. Same value used by macOS + Windows ports.
+constexpr std::string_view kClientId = "app_EMoamEEZ73f0CkXaXp7hrann";
+
+constexpr std::string_view kIssuer = "https://auth.openai.com";
+constexpr std::string_view kAuthorizePath = "/oauth/authorize";
+constexpr std::string_view kTokenPath = "/oauth/token";
+
+// Backend used by signed-in callers. Distinct from api.openai.com/v1.
+constexpr std::string_view kChatGPTBackend = "https://chatgpt.com/backend-api/codex";
+
+// `offline_access` returns refresh_token; `api.connectors.*` lets the
+// access_token reach the chatgpt.com backend.
+constexpr std::string_view kScopes =
+ "openid profile email offline_access api.connectors.read api.connectors.invoke";
+
+// Sent as `originator` query param; informational, the auth server does not
+// gate behaviour on it.
+constexpr std::string_view kOriginator = "gridex_linux";
+
+// 3 min — long enough for password manager + 2FA, short enough to bound
+// the UI hang.
+constexpr int kCallbackTimeoutSeconds = 180;
+
+// Refresh slightly before access_token's `exp` so a request in flight at
+// `exp` doesn't get a 401.
+constexpr int kRefreshSkewSeconds = 30;
+
+// Loopback ports tried in order. Codex CLI default is 1455.
+constexpr std::array<std::uint16_t, 4> kPreferredPorts = {1455, 1456, 1457, 1458};
+
+constexpr std::string_view kCallbackPath = "/auth/callback";
+
+} // namespace gridex::oauth
diff --git a/linux/src/Services/AI/Auth/ChatGPTOAuthService.cpp b/linux/src/Services/AI/Auth/ChatGPTOAuthService.cpp
new file mode 100644
index 0000000..40cdce5
--- /dev/null
+++ b/linux/src/Services/AI/Auth/ChatGPTOAuthService.cpp
@@ -0,0 +1,313 @@
+#include "Services/AI/Auth/ChatGPTOAuthService.h"
+
+#include <QByteArray>
+#include <QNetworkAccessManager>
+#include <QProcess>
+#include <QStringList>
+#include <QNetworkReply>
+#include <QNetworkRequest>
+#include <QUrl>
+#include <QUrlQuery>
+
+#include <nlohmann/json.hpp>
+
+#include "Data/Keychain/SecretStore.h"
+#include "Services/AI/Auth/ChatGPTOAuthConstants.h"
+#include "Services/AI/Auth/JwtDecoder.h"
+#include "Services/AI/Auth/OAuthLoopbackServer.h"
+#include "Services/AI/Auth/PKCE.h"
+
+namespace gridex {
+
+namespace {
+
+QString sv(std::string_view s) {
+ return QString::fromUtf8(s.data(), static_cast<int>(s.size()));
+}
+
+QString parseErrorBody(const QByteArray& data) {
+ try {
+ auto j = nlohmann::json::parse(data.toStdString());
+ if (j.contains("error")) {
+ QString err = QString::fromStdString(j["error"].get<std::string>());
+ if (j.contains("error_description")) {
+ return err + ": " + QString::fromStdString(j["error_description"].get<std::string>());
+ }
+ return err;
+ }
+ if (j.contains("message")) {
+ return QString::fromStdString(j["message"].get<std::string>());
+ }
+ } catch (...) {}
+ return QString::fromUtf8(data).trimmed();
+}
+
+} // namespace
+
+ChatGPTOAuthService::ChatGPTOAuthService(SecretStore* secretStore, QObject* parent)
+ : QObject(parent),
+ secretStore_(secretStore),
+ nam_(std::make_unique<QNetworkAccessManager>()) {}
+
+ChatGPTOAuthService::~ChatGPTOAuthService() = default;
+
+void ChatGPTOAuthService::signIn(const QString& providerKey) {
+ using namespace oauth;
+
+ // Tear down any previous attempt's listener.
+ server_.reset(new OAuthLoopbackServer(this));
+ std::uint16_t port = server_->start();
+ if (port == 0) {
+ emit signInFailed(providerKey, tr("Could not bind any loopback port for OAuth callback"));
+ return;
+ }
+
+ QString verifier = PKCE::makeVerifier();
+ QString challenge = PKCE::challengeFor(verifier);
+ QString state = PKCE::makeState();
+ QString redirectUri =
+ QString("http://localhost:%1%2").arg(port).arg(sv(kCallbackPath));
+
+ QUrl authorize(sv(kIssuer) + sv(kAuthorizePath));
+ QUrlQuery q;
+ q.addQueryItem("response_type", "code");
+ q.addQueryItem("client_id", sv(kClientId));
+ q.addQueryItem("redirect_uri", redirectUri);
+ q.addQueryItem("scope", sv(kScopes));
+ q.addQueryItem("code_challenge", challenge);
+ q.addQueryItem("code_challenge_method", "S256");
+ q.addQueryItem("state", state);
+ q.addQueryItem("id_token_add_organizations", "true");
+ q.addQueryItem("codex_cli_simplified_flow", "true");
+ q.addQueryItem("originator", sv(kOriginator));
+ authorize.setQuery(q);
+
+ // Open the user's default browser via xdg-open. Avoids the Qt6::Gui
+ // dependency on this service library (services link Qt6::Network only).
+ if (!QProcess::startDetached("xdg-open", {authorize.toString(QUrl::FullyEncoded)})) {
+ emit signInFailed(providerKey, tr("Could not open browser (xdg-open failed)"));
+ server_.reset();
+ return;
+ }
+
+ server_->awaitCallback(
+ kCallbackTimeoutSeconds,
+ [this, providerKey, state, verifier, redirectUri](OAuthCallback cb) {
+ onCallbackSuccess(providerKey, state, verifier, redirectUri, cb.code, cb.state);
+ },
+ [this, providerKey](QString msg) {
+ onCallbackError(providerKey, msg);
+ });
+}
+
+void ChatGPTOAuthService::onCallbackSuccess(const QString& providerKey,
+ const QString& expectedState,
+ const QString& verifier,
+ const QString& redirectUri,
+ const QString& code,
+ const QString& callbackState) {
+ if (callbackState != expectedState) {
+ emit signInFailed(providerKey,
+ tr("OAuth state mismatch — sign-in aborted (possible CSRF)"));
+ return;
+ }
+ exchangeCodeForTokens(providerKey, code, verifier, redirectUri);
+}
+
+void ChatGPTOAuthService::onCallbackError(const QString& providerKey, const QString& message) {
+ emit signInFailed(providerKey, message);
+}
+
+void ChatGPTOAuthService::exchangeCodeForTokens(const QString& providerKey,
+ const QString& code,
+ const QString& verifier,
+ const QString& redirectUri) {
+ using namespace oauth;
+ QUrl tokenUrl(sv(kIssuer) + sv(kTokenPath));
+ QNetworkRequest req(tokenUrl);
+ req.setHeader(QNetworkRequest::ContentTypeHeader,
+ "application/x-www-form-urlencoded");
+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
+ QNetworkRequest::NoLessSafeRedirectPolicy);
+
+ QUrlQuery body;
+ body.addQueryItem("grant_type", "authorization_code");
+ body.addQueryItem("code", code);
+ body.addQueryItem("redirect_uri", redirectUri);
+ body.addQueryItem("client_id", sv(kClientId));
+ body.addQueryItem("code_verifier", verifier);
+ QByteArray payload = body.toString(QUrl::FullyEncoded).toUtf8();
+
+ QNetworkReply* reply = nam_->post(req, payload);
+ connect(reply, &QNetworkReply::finished, this, [this, reply, providerKey]() {
+ reply->deleteLater();
+ int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ QByteArray data = reply->readAll();
+ if (status < 200 || status >= 300) {
+ emit signInFailed(providerKey,
+ tr("Token exchange failed (HTTP %1): %2")
+ .arg(status).arg(parseErrorBody(data)));
+ return;
+ }
+ try {
+ auto j = nlohmann::json::parse(data.toStdString());
+ ChatGPTTokenBundle bundle;
+ bundle.accessToken = j.value("access_token", "");
+ bundle.refreshToken = j.value("refresh_token", "");
+ bundle.idToken = j.value("id_token", "");
+ if (bundle.accessToken.empty() || bundle.refreshToken.empty()) {
+ emit signInFailed(providerKey,
+ tr("Token exchange returned no access_token / refresh_token"));
+ return;
+ }
+ applyClaims(bundle);
+ persistBundle(providerKey, bundle);
+ emit signInCompleted(providerKey, bundle);
+ } catch (const std::exception& e) {
+ emit signInFailed(providerKey,
+ tr("Token exchange returned an unexpected payload: ") + e.what());
+ }
+ });
+}
+
+void ChatGPTOAuthService::requestFreshToken(const QString& providerKey) {
+ auto bundle = currentBundle(providerKey);
+ if (!bundle) {
+ emit signInFailed(providerKey, tr("Not signed in"));
+ return;
+ }
+ auto exp = oauth::JwtDecoder::expiration(QString::fromStdString(bundle->accessToken));
+ bool stale = !exp || (std::chrono::system_clock::now() +
+ std::chrono::seconds(oauth::kRefreshSkewSeconds) >= *exp);
+ if (!stale) {
+ emit tokenRefreshed(providerKey, *bundle);
+ return;
+ }
+ {
+ std::lock_guard lk(mu_);
+ if (refreshInFlight_) return; // coalesce; the in-flight call will emit
+ refreshInFlight_ = true;
+ }
+ performRefresh(providerKey, *bundle);
+}
+
+void ChatGPTOAuthService::performRefresh(const QString& providerKey,
+ ChatGPTTokenBundle bundle) {
+ using namespace oauth;
+ QUrl tokenUrl(sv(kIssuer) + sv(kTokenPath));
+ QNetworkRequest req(tokenUrl);
+ req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
+ QNetworkRequest::NoLessSafeRedirectPolicy);
+ nlohmann::json body = {
+ {"client_id", std::string(kClientId)},
+ {"grant_type", "refresh_token"},
+ {"refresh_token", bundle.refreshToken},
+ };
+ QByteArray payload = QByteArray::fromStdString(body.dump());
+
+ QNetworkReply* reply = nam_->post(req, payload);
+ connect(reply, &QNetworkReply::finished, this,
+ [this, reply, providerKey, bundle]() mutable {
+ reply->deleteLater();
+ {
+ std::lock_guard lk(mu_);
+ refreshInFlight_ = false;
+ }
+ int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ QByteArray data = reply->readAll();
+
+ if (status >= 200 && status < 300) {
+ try {
+ auto j = nlohmann::json::parse(data.toStdString());
+ bundle.accessToken = j.value("access_token", bundle.accessToken);
+ if (j.contains("refresh_token") && j["refresh_token"].is_string()) {
+ auto rt = j["refresh_token"].get<std::string>();
+ if (!rt.empty()) bundle.refreshToken = rt;
+ }
+ if (j.contains("id_token") && j["id_token"].is_string()) {
+ auto idt = j["id_token"].get<std::string>();
+ if (!idt.empty()) {
+ bundle.idToken = idt;
+ applyClaims(bundle);
+ }
+ }
+ bundle.obtainedAt = std::chrono::system_clock::now();
+ persistBundle(providerKey, bundle);
+ emit tokenRefreshed(providerKey, bundle);
+ } catch (...) {
+ emit signInFailed(providerKey,
+ tr("Refresh returned an unexpected payload"));
+ }
+ return;
+ }
+
+ // Refresh-token-rejected family: clear the bundle, prompt re-sign-in.
+ QString detail = parseErrorBody(data).toLower();
+ const QStringList dead = {"refresh_token_expired",
+ "refresh_token_reused",
+ "refresh_token_invalidated"};
+ for (const auto& d : dead) {
+ if (detail.contains(d)) {
+ if (secretStore_) secretStore_->deleteChatGPTTokens(providerKey.toStdString());
+ emit signInFailed(providerKey,
+ tr("Sign-in expired — please sign in with ChatGPT again"));
+ return;
+ }
+ }
+ emit signInFailed(providerKey,
+ tr("Refresh failed (HTTP %1): %2").arg(status).arg(parseErrorBody(data)));
+ });
+}
+
+void ChatGPTOAuthService::persistBundle(const QString& providerKey,
+ const ChatGPTTokenBundle& bundle) {
+ if (!secretStore_) return;
+ std::string raw = bundle.toJson().dump();
+ secretStore_->saveChatGPTTokens(providerKey.toStdString(), raw);
+}
+
+void ChatGPTOAuthService::applyClaims(ChatGPTTokenBundle& bundle) {
+ if (bundle.idToken.empty()) return;
+ try {
+ auto claims = oauth::JwtDecoder::payload(QString::fromStdString(bundle.idToken));
+ if (claims.contains("email") && claims["email"].is_string()) {
+ bundle.email = claims["email"].get<std::string>();
+ }
+ if (claims.contains("chatgpt_account_id") && claims["chatgpt_account_id"].is_string()) {
+ bundle.accountId = claims["chatgpt_account_id"].get<std::string>();
+ }
+ if (claims.contains("chatgpt_plan_type") && claims["chatgpt_plan_type"].is_string()) {
+ bundle.planType = claims["chatgpt_plan_type"].get<std::string>();
+ }
+ } catch (...) {}
+}
+
+std::optional<ChatGPTTokenBundle>
+ChatGPTOAuthService::currentBundle(const QString& providerKey) const {
+ if (!secretStore_) return std::nullopt;
+ auto raw = secretStore_->loadChatGPTTokens(providerKey.toStdString());
+ if (!raw) return std::nullopt;
+ try {
+ auto j = nlohmann::json::parse(*raw);
+ return ChatGPTTokenBundle::fromJson(j);
+ } catch (...) {
+ return std::nullopt;
+ }
+}
+
+void ChatGPTOAuthService::signOut(const QString& providerKey) {
+ if (secretStore_) secretStore_->deleteChatGPTTokens(providerKey.toStdString());
+}
+
+ChatGPTSignInStatus ChatGPTOAuthService::status(const QString& providerKey) const {
+ ChatGPTSignInStatus s;
+ auto b = currentBundle(providerKey);
+ if (!b) return s;
+ s.signedIn = true;
+ if (b->email) s.email = QString::fromStdString(*b->email);
+ if (b->planType) s.planType = QString::fromStdString(*b->planType);
+ return s;
+}
+
+} // namespace gridex
diff --git a/linux/src/Services/AI/Auth/ChatGPTOAuthService.h b/linux/src/Services/AI/Auth/ChatGPTOAuthService.h
new file mode 100644
index 0000000..b7b62a8
--- /dev/null
+++ b/linux/src/Services/AI/Auth/ChatGPTOAuthService.h
@@ -0,0 +1,102 @@
+#pragma once
+
+// ChatGPTOAuthService — orchestrates the PKCE-OAuth flow for OpenAI's
+// auth.openai.com tenant against the public Codex CLI client_id.
+//
+// signIn(): spins up the loopback listener, opens the browser, waits for
+// the callback (3-min timeout), exchanges the auth code for tokens,
+// persists the bundle in the keychain. Emits signInCompleted /
+// signInFailed when done.
+//
+// tokenBundle(): returns a usable bundle, refreshing via refresh_token
+// when access_token is within kRefreshSkewSeconds of expiring. Coalesces
+// concurrent refresh calls for the same providerKey.
+//
+// signOut(): forgets the persisted bundle; cheap, no server call.
+//
+// Status: a synchronous probe so the Settings UI can render the
+// "Signed in as ..." pill without a network round-trip.
+
+#include <memory>
+#include <mutex>
+#include <optional>
+#include <string>
+
+#include <QObject>
+#include <QString>
+
+#include "Core/Models/AI/ChatGPTTokenBundle.h"
+
+class QNetworkAccessManager;
+
+namespace gridex {
+
+class SecretStore;
+
+namespace oauth {
+class OAuthLoopbackServer;
+}
+
+struct ChatGPTSignInStatus {
+ bool signedIn = false;
+ QString email;
+ QString planType;
+};
+
+class ChatGPTOAuthService : public QObject {
+ Q_OBJECT
+public:
+ explicit ChatGPTOAuthService(SecretStore* secretStore, QObject* parent = nullptr);
+ ~ChatGPTOAuthService() override;
+
+ // Kicks off the browser-based sign-in flow. providerKey identifies which
+ // bundle slot in the keychain (single-account "chatgpt" by default).
+ // Emits signInCompleted on success, signInFailed otherwise.
+ void signIn(const QString& providerKey = QStringLiteral("chatgpt"));
+
+ // Synchronous accessor — returns nullopt if no valid bundle is stored.
+ std::optional<ChatGPTTokenBundle> currentBundle(
+ const QString& providerKey = QStringLiteral("chatgpt")) const;
+
+ // Returns a fresh access token, performing a refresh if needed.
+ // Emits tokenRefreshed on success, signInFailed if the refresh token
+ // was rejected (in which case the bundle is wiped — caller should
+ // prompt for a new sign-in).
+ void requestFreshToken(
+ const QString& providerKey = QStringLiteral("chatgpt"));
+
+ void signOut(const QString& providerKey = QStringLiteral("chatgpt"));
+
+ ChatGPTSignInStatus status(
+ const QString& providerKey = QStringLiteral("chatgpt")) const;
+
+signals:
+ void signInCompleted(const QString& providerKey, const ChatGPTTokenBundle& bundle);
+ void signInFailed(const QString& providerKey, const QString& message);
+ void tokenRefreshed(const QString& providerKey, const ChatGPTTokenBundle& bundle);
+
+private:
+ void onCallbackSuccess(const QString& providerKey,
+ const QString& expectedState,
+ const QString& verifier,
+ const QString& redirectUri,
+ const QString& code,
+ const QString& callbackState);
+ void onCallbackError(const QString& providerKey, const QString& message);
+ void exchangeCodeForTokens(const QString& providerKey,
+ const QString& code,
+ const QString& verifier,
+ const QString& redirectUri);
+ void performRefresh(const QString& providerKey, ChatGPTTokenBundle bundle);
+ void persistBundle(const QString& providerKey, const ChatGPTTokenBundle& bundle);
+ static void applyClaims(ChatGPTTokenBundle& bundle);
+
+ SecretStore* secretStore_;
+ std::unique_ptr<QNetworkAccessManager> nam_;
+ std::unique_ptr<oauth::OAuthLoopbackServer> server_;
+
+ mutable std::mutex mu_;
+ bool refreshInFlight_ = false;
+};
+
+} // namespace gridex
diff --git a/linux/src/Services/AI/Auth/JwtDecoder.cpp b/linux/src/Services/AI/Auth/JwtDecoder.cpp
new file mode 100644
index 0000000..17db749
--- /dev/null
+++ b/linux/src/Services/AI/Auth/JwtDecoder.cpp
@@ -0,0 +1,43 @@
+#include "Services/AI/Auth/JwtDecoder.h"
+
+#include <QStringList>
+#include <stdexcept>
+
+#include "Services/AI/Auth/PKCE.h"
+
+namespace gridex::oauth {
+
+nlohmann::json JwtDecoder::payload(const QString& jwt) {
+ auto parts = jwt.split('.');
+ if (parts.size() != 3) {
+ throw std::runtime_error("Malformed JWT: expected 3 segments, got " +
+ std::to_string(parts.size()));
+ }
+ QByteArray decoded = PKCE::base64UrlDecode(parts[1]);
+ if (decoded.isEmpty()) {
+ throw std::runtime_error("Malformed JWT: payload is not valid base64url");
+ }
+ auto j = nlohmann::json::parse(decoded.toStdString(), nullptr, /*allow_exceptions=*/false);
+ if (j.is_discarded() || !j.is_object()) {
+ throw std::runtime_error("Malformed JWT: payload is not a JSON object");
+ }
+ return j;
+}
+
+std::optional<std::chrono::system_clock::time_point>
+JwtDecoder::expiration(const QString& jwt) {
+ try {
+ auto claims = payload(jwt);
+ if (!claims.contains("exp")) return std::nullopt;
+ const auto& exp = claims["exp"];
+ std::int64_t epochSeconds = 0;
+ if (exp.is_number_integer()) epochSeconds = exp.get<std::int64_t>();
+ else if (exp.is_number_float()) epochSeconds = static_cast<std::int64_t>(exp.get<double>());
+ else return std::nullopt;
+ return std::chrono::system_clock::time_point(std::chrono::seconds(epochSeconds));
+ } catch (...) {
+ return std::nullopt;
+ }
+}
+
+} // namespace gridex::oauth
diff --git a/linux/src/Services/AI/Auth/JwtDecoder.h b/linux/src/Services/AI/Auth/JwtDecoder.h
new file mode 100644
index 0000000..74d85d7
--- /dev/null
+++ b/linux/src/Services/AI/Auth/JwtDecoder.h
@@ -0,0 +1,26 @@
+#pragma once
+
+// Minimal JWT payload decoder. Never verifies signature — issuer is
+// auth.openai.com over TLS, refresh failures are surfaced by the server.
+
+#include <chrono>
+#include <optional>
+
+#include <QString>
+#include <nlohmann/json.hpp>
+
+namespace gridex::oauth {
+
+class JwtDecoder {
+public:
+ // Decodes the second segment of a JWT into a JSON object.
+ // Throws std::runtime_error if the token isn't 3 segments or payload
+ // isn't a JSON object.
+ static nlohmann::json payload(const QString& jwt);
+
+ // Convenience: extract `exp` claim as system_clock time_point. Returns
+ // nullopt when missing/malformed → caller should treat as expired.
+ static std::optional<std::chrono::system_clock::time_point> expiration(const QString& jwt);
+};
+
+} // namespace gridex::oauth
diff --git a/linux/src/Services/AI/Auth/OAuthLoopbackServer.cpp b/linux/src/Services/AI/Auth/OAuthLoopbackServer.cpp
new file mode 100644
index 0000000..e12a545
--- /dev/null
+++ b/linux/src/Services/AI/Auth/OAuthLoopbackServer.cpp
@@ -0,0 +1,184 @@
+#include "Services/AI/Auth/OAuthLoopbackServer.h"
+
+#include <QHostAddress>
+#include <QTcpServer>
+#include <QTcpSocket>
+#include <QUrl>
+#include <QUrlQuery>
+
+#include "Services/AI/Auth/ChatGPTOAuthConstants.h"
+
+namespace gridex::oauth {
+
+namespace {
+
+constexpr const char* kSuccessPage = R"(<!doctype html><html><head><meta charset="utf-8">
+<title>Gridex sign-in</title>
+<style>body{font:14px system-ui;color:#cdd6f4;background:#1e1e2e;text-align:center;padding:80px}
+h2{color:#a6e3a1}</style></head><body>
+<h2>Sign-in complete</h2>
+<p>You can close this tab and return to Gridex.</p>
+<script>setTimeout(()=>window.close(),500)</script></body></html>)";
+
+constexpr const char* kErrorPage = R"(<!doctype html><html><head><meta charset="utf-8">
+<title>Gridex sign-in</title>
+<style>body{font:14px system-ui;color:#cdd6f4;background:#1e1e2e;text-align:center;padding:80px}
+h2{color:#f38ba8}</style></head><body>
+<h2>Sign-in failed</h2>
+<p>Return to Gridex for details. You can close this tab.</p></body></html>)";
+
+} // namespace
+
+OAuthLoopbackServer::OAuthLoopbackServer(QObject* parent)
+ : QObject(parent) {
+ timeout_.setSingleShot(true);
+ connect(&timeout_, &QTimer::timeout, this, [this] {
+ resolveError(tr("OAuth callback timed out"));
+ });
+}
+
+OAuthLoopbackServer::~OAuthLoopbackServer() { stop(); }
+
+std::uint16_t OAuthLoopbackServer::start() {
+ server_ = new QTcpServer(this);
+ connect(server_, &QTcpServer::newConnection, this,
+ &OAuthLoopbackServer::handleNewConnection);
+
+ for (auto p : kPreferredPorts) {
+ if (server_->listen(QHostAddress::LocalHost, p)) {
+ port_ = p;
+ return p;
+ }
+ }
+ // Last resort: kernel-assigned ephemeral port.
+ if (server_->listen(QHostAddress::LocalHost, 0)) {
+ port_ = static_cast<std::uint16_t>(server_->serverPort());
+ return port_;
+ }
+ delete server_;
+ server_ = nullptr;
+ return 0;
+}
+
+void OAuthLoopbackServer::awaitCallback(int timeoutSeconds,
+ SuccessFn onSuccess, ErrorFn onError) {
+ onSuccess_ = std::move(onSuccess);
+ onError_ = std::move(onError);
+ timeout_.start(timeoutSeconds * 1000);
+}
+
+void OAuthLoopbackServer::stop() {
+ timeout_.stop();
+ if (server_) {
+ server_->close();
+ server_->deleteLater();
+ server_ = nullptr;
+ }
+}
+
+void OAuthLoopbackServer::handleNewConnection() {
+ while (auto* sock = server_->nextPendingConnection()) {
+ connect(sock, &QTcpSocket::readyRead, this, [this, sock] {
+ handleClientReadyRead(sock);
+ });
+ connect(sock, &QTcpSocket::disconnected, sock, &QTcpSocket::deleteLater);
+ }
+}
+
+void OAuthLoopbackServer::handleClientReadyRead(QTcpSocket* sock) {
+ // Buffer the read on the socket itself — Qt keeps appended bytes
+ // available via `peek/readAll`. Stop reading once we have the
+ // request line (CRLF or LF).
+ QByteArray buf = sock->peek(8192);
+ int eol = buf.indexOf("\r\n");
+ if (eol < 0) eol = buf.indexOf('\n');
+ if (eol < 0) {
+ if (buf.size() > 16 * 1024) {
+ sendHtml(sock, 400, kErrorPage);
+ resolveError(tr("OAuth callback: headers exceed 16KB"));
+ }
+ return; // need more bytes
+ }
+ QString line = QString::fromUtf8(buf.left(eol));
+ sock->read(eol + 1); // consume request line — we don't read further
+ processRequestLine(sock, line);
+}
+
+void OAuthLoopbackServer::processRequestLine(QTcpSocket* sock, const QString& line) {
+ auto parts = line.split(' ');
+ if (parts.size() < 2) {
+ sendHtml(sock, 400, kErrorPage);
+ resolveError(tr("OAuth callback: malformed request line"));
+ return;
+ }
+ QString pathAndQuery = parts[1];
+ QUrl url(QStringLiteral("http://localhost") + pathAndQuery);
+ if (!url.isValid()) {
+ sendHtml(sock, 400, kErrorPage);
+ resolveError(tr("OAuth callback: could not parse path"));
+ return;
+ }
+
+ // /favicon.ico and stray probes — just send the error page and keep listening.
+ if (url.path() != QString::fromUtf8(kCallbackPath.data(),
+ static_cast<int>(kCallbackPath.size()))) {
+ sendHtml(sock, 404, kErrorPage);
+ return;
+ }
+
+ QUrlQuery q(url);
+ QString code = q.queryItemValue("code");
+ QString state = q.queryItemValue("state");
+ QString errCode = q.queryItemValue("error");
+ QString errDesc = q.queryItemValue("error_description");
+
+ if (!errCode.isEmpty()) {
+ sendHtml(sock, 400, kErrorPage);
+ resolveError(QString("Authorization server returned '%1': %2").arg(errCode, errDesc));
+ return;
+ }
+ if (code.isEmpty() || state.isEmpty()) {
+ sendHtml(sock, 400, kErrorPage);
+ resolveError(tr("OAuth callback: missing code or state"));
+ return;
+ }
+
+ sendHtml(sock, 200, kSuccessPage);
+ OAuthCallback cb{std::move(code), std::move(state)};
+ resolveSuccess(std::move(cb));
+}
+
+void OAuthLoopbackServer::sendHtml(QTcpSocket* sock, int status, const QString& body) {
+ QByteArray bytes = body.toUtf8();
+ QString head = QString(
+ "HTTP/1.1 %1 OK\r\n"
+ "Content-Type: text/html; charset=utf-8\r\n"
+ "Content-Length: %2\r\n"
+ "Connection: close\r\n\r\n").arg(status).arg(bytes.size());
+ sock->write(head.toUtf8());
+ sock->write(bytes);
+ sock->flush();
+ sock->disconnectFromHost();
+}
+
+void OAuthLoopbackServer::resolveSuccess(OAuthCallback cb) {
+ bool expected = false;
+ if (!resolved_.compare_exchange_strong(expected, true)) return;
+ timeout_.stop();
+ if (onSuccess_) onSuccess_(std::move(cb));
+ onSuccess_ = nullptr;
+ onError_ = nullptr;
+ QTimer::singleShot(0, this, &OAuthLoopbackServer::stop);
+}
+
+void OAuthLoopbackServer::resolveError(QString message) {
+ bool expected = false;
+ if (!resolved_.compare_exchange_strong(expected, true)) return;
+ timeout_.stop();
+ if (onError_) onError_(std::move(message));
+ onSuccess_ = nullptr;
+ onError_ = nullptr;
+ QTimer::singleShot(0, this, &OAuthLoopbackServer::stop);
+}
+
+} // namespace gridex::oauth
diff --git a/linux/src/Services/AI/Auth/OAuthLoopbackServer.h b/linux/src/Services/AI/Auth/OAuthLoopbackServer.h
new file mode 100644
index 0000000..b2c8c35
--- /dev/null
+++ b/linux/src/Services/AI/Auth/OAuthLoopbackServer.h
@@ -0,0 +1,64 @@
+#pragma once
+
+// Single-shot loopback HTTP listener for the ChatGPT OAuth callback.
+// Binds 127.0.0.1 (not 0.0.0.0) so LAN-side hijack is impossible.
+// Reuse-after-success is not supported — instantiate per sign-in attempt.
+
+#include <atomic>
+#include <cstdint>
+#include <functional>
+
+#include <QObject>
+#include <QString>
+#include <QTimer>
+
+class QTcpServer;
+class QTcpSocket;
+
+namespace gridex::oauth {
+
+struct OAuthCallback {
+ QString code;
+ QString state;
+};
+
+class OAuthLoopbackServer : public QObject {
+ Q_OBJECT
+public:
+ using SuccessFn = std::function<void(OAuthCallback)>;
+ using ErrorFn = std::function<void(QString)>;
+
+ explicit OAuthLoopbackServer(QObject* parent = nullptr);
+ ~OAuthLoopbackServer() override;
+
+ // Tries each preferred port in order, falling back to a kernel-assigned
+ // ephemeral port. Returns the bound port (0 on failure).
+ std::uint16_t start();
+
+ // Registers callbacks for the next callback / failure. Exactly one of
+ // them is invoked once. Calling start() again on a resolved server is
+ // not supported.
+ void awaitCallback(int timeoutSeconds, SuccessFn onSuccess, ErrorFn onError);
+
+ void stop();
+
+ std::uint16_t port() const noexcept { return port_; }
+
+private:
+ void handleNewConnection();
+ void handleClientReadyRead(QTcpSocket* sock);
+ void processRequestLine(QTcpSocket* sock, const QString& requestLine);
+ void sendHtml(QTcpSocket* sock, int status, const QString& body);
+ void resolveSuccess(OAuthCallback cb);
+ void resolveError(QString message);
+
+ QTcpServer* server_ = nullptr;
+ std::uint16_t port_ = 0;
+ QTimer timeout_;
+
+ SuccessFn onSuccess_;
+ ErrorFn onError_;
+ std::atomic<bool> resolved_{false};
+};
+
+} // namespace gridex::oauth
diff --git a/linux/src/Services/AI/Auth/PKCE.cpp b/linux/src/Services/AI/Auth/PKCE.cpp
new file mode 100644
index 0000000..53035fb
--- /dev/null
+++ b/linux/src/Services/AI/Auth/PKCE.cpp
@@ -0,0 +1,50 @@
+#include "Services/AI/Auth/PKCE.h"
+
+#include <QCryptographicHash>
+#include <QRandomGenerator>
+
+namespace gridex::oauth {
+
+namespace {
+
+QByteArray randomBytes(int count) {
+ // QRandomGenerator::system() wraps a CSPRNG (getrandom on Linux).
+ QByteArray out(count, '\0');
+ QRandomGenerator::system()->generate(reinterpret_cast<quint32*>(out.data()),
+ reinterpret_cast<quint32*>(out.data() + count));
+ return out;
+}
+
+} // namespace
+
+QString PKCE::base64UrlNoPad(const QByteArray& data) {
+ QByteArray b64 = data.toBase64();
+ b64.replace('+', '-');
+ b64.replace('/', '_');
+ while (b64.endsWith('=')) b64.chop(1);
+ return QString::fromLatin1(b64);
+}
+
+QByteArray PKCE::base64UrlDecode(const QString& s) {
+ QByteArray b = s.toLatin1();
+ b.replace('-', '+');
+ b.replace('_', '/');
+ int pad = b.size() % 4;
+ if (pad) b.append(4 - pad, '=');
+ return QByteArray::fromBase64(b);
+}
+
+QString PKCE::makeVerifier() {
+ return base64UrlNoPad(randomBytes(32));
+}
+
+QString PKCE::challengeFor(const QString& verifier) {
+ QByteArray hash = QCryptographicHash::hash(verifier.toUtf8(), QCryptographicHash::Sha256);
+ return base64UrlNoPad(hash);
+}
+
+QString PKCE::makeState() {
+ return base64UrlNoPad(randomBytes(32));
+}
+
+} // namespace gridex::oauth
diff --git a/linux/src/Services/AI/Auth/PKCE.h b/linux/src/Services/AI/Auth/PKCE.h
new file mode 100644
index 0000000..0a0d599
--- /dev/null
+++ b/linux/src/Services/AI/Auth/PKCE.h
@@ -0,0 +1,29 @@
+#pragma once
+
+// RFC 7636 PKCE primitives + base64url helpers. Pure functions.
+
+#include <QByteArray>
+#include <QString>
+
+namespace gridex::oauth {
+
+class PKCE {
+public:
+ // 32 random bytes → base64url-no-pad (43 chars). Suitable as code_verifier.
+ static QString makeVerifier();
+
+ // SHA256(verifier) → base64url-no-pad. Used as code_challenge with S256.
+ static QString challengeFor(const QString& verifier);
+
+ // 32 random bytes → base64url-no-pad. Used as the OAuth `state` param.
+ static QString makeState();
+
+ // Standard base64 → URL-safe variant (no padding).
+ static QString base64UrlNoPad(const QByteArray& data);
+
+ // base64url → bytes. Re-pads to a multiple of 4 with '=' and reverses
+ // URL-safe substitutions before decoding.
+ static QByteArray base64UrlDecode(const QString& s);
+};
+
+} // namespace gridex::oauth
diff --git a/linux/src/Services/AI/Providers/ChatGPTProvider.cpp b/linux/src/Services/AI/Providers/ChatGPTProvider.cpp
new file mode 100644
index 0000000..8963b37
--- /dev/null
+++ b/linux/src/Services/AI/Providers/ChatGPTProvider.cpp
@@ -0,0 +1,295 @@
+#include "Services/AI/Providers/ChatGPTProvider.h"
+
+#include <chrono>
+#include <stdexcept>
+
+#include <QByteArray>
+#include <QEventLoop>
+#include <QNetworkAccessManager>
+#include <QNetworkReply>
+#include <QNetworkRequest>
+#include <QString>
+#include <QUrl>
+#include <QUrlQuery>
+
+#include <nlohmann/json.hpp>
+
+#include "Core/Errors/GridexError.h"
+#include "Core/Models/AI/ChatGPTTokenBundle.h"
+#include "Data/Keychain/SecretStore.h"
+#include "Services/AI/Auth/ChatGPTOAuthConstants.h"
+#include "Services/AI/Auth/JwtDecoder.h"
+
+namespace gridex {
+
+namespace {
+
+constexpr const char* kProviderKey = "chatgpt";
+
+std::string trim(const std::string& s) {
+ auto b = s.find_first_not_of(" \t\r\n/");
+ if (b == std::string::npos) return "";
+ auto e = s.find_last_not_of(" \t\r\n/");
+ return s.substr(b, e - b + 1);
+}
+
+QByteArray httpPost(const QUrl& url,
+ const QByteArray& body,
+ const std::vector<std::pair<QByteArray, QByteArray>>& headers,
+ int* outStatus,
+ QString* outError) {
+ QNetworkAccessManager nam;
+ QNetworkRequest req(url);
+ for (const auto& [k, v] : headers) req.setRawHeader(k, v);
+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
+ QNetworkRequest::NoLessSafeRedirectPolicy);
+
+ QEventLoop loop;
+ QNetworkReply* reply = nam.post(req, body);
+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
+ loop.exec();
+ if (outStatus) *outStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ if (outError) *outError = reply->errorString();
+ QByteArray data = reply->readAll();
+ reply->deleteLater();
+ return data;
+}
+
+QByteArray httpGet(const QUrl& url,
+ const std::vector<std::pair<QByteArray, QByteArray>>& headers,
+ int* outStatus,
+ QString* outError) {
+ QNetworkAccessManager nam;
+ QNetworkRequest req(url);
+ for (const auto& [k, v] : headers) req.setRawHeader(k, v);
+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
+ QNetworkRequest::NoLessSafeRedirectPolicy);
+
+ QEventLoop loop;
+ QNetworkReply* reply = nam.get(req);
+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
+ loop.exec();
+ if (outStatus) *outStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+ if (outError) *outError = reply->errorString();
+ QByteArray data = reply->readAll();
+ reply->deleteLater();
+ return data;
+}
+
+// Loads the bundle, refreshes the access_token in-process if it's within
+// kRefreshSkewSeconds of expiring, persists the rotated bundle, and returns it.
+ChatGPTTokenBundle loadAndMaybeRefresh() {
+ SecretStore store;
+ auto raw = store.loadChatGPTTokens(kProviderKey);
+ if (!raw) throw AuthenticationError("ChatGPT: not signed in");
+ auto j = nlohmann::json::parse(*raw);
+ auto bundleOpt = ChatGPTTokenBundle::fromJson(j);
+ if (!bundleOpt) throw AuthenticationError("ChatGPT: stored token bundle is malformed");
+ ChatGPTTokenBundle bundle = *bundleOpt;
+
+ auto exp = oauth::JwtDecoder::expiration(QString::fromStdString(bundle.accessToken));
+ bool stale = !exp || (std::chrono::system_clock::now() +
+ std::chrono::seconds(oauth::kRefreshSkewSeconds) >= *exp);
+ if (!stale) return bundle;
+
+ // Refresh — POST application/json {client_id, grant_type, refresh_token}
+ QUrl tokenUrl(QString::fromUtf8(oauth::kIssuer.data(),
+ static_cast<int>(oauth::kIssuer.size())) +
+ QString::fromUtf8(oauth::kTokenPath.data(),
+ static_cast<int>(oauth::kTokenPath.size())));
+ nlohmann::json body = {
+ {"client_id", std::string(oauth::kClientId)},
+ {"grant_type", "refresh_token"},
+ {"refresh_token", bundle.refreshToken},
+ };
+ int status = 0;
+ QString err;
+ QByteArray data = httpPost(tokenUrl, QByteArray::fromStdString(body.dump()),
+ {{"Content-Type", "application/json"}}, &status, &err);
+ if (status < 200 || status >= 300) {
+ // Refresh-token-rejected family — wipe the bundle and surface
+ // AuthenticationError so the UI prompts re-sign-in.
+ try {
+ auto e = nlohmann::json::parse(data.toStdString());
+ std::string detail = e.value("error", std::string{});
+ if (detail == "refresh_token_expired" ||
+ detail == "refresh_token_reused" ||
+ detail == "refresh_token_invalidated") {
+ store.deleteChatGPTTokens(kProviderKey);
+ }
+ } catch (...) {}
+ throw AuthenticationError("ChatGPT refresh failed (HTTP " +
+ std::to_string(status) + "): " +
+ std::string(data.constData(), data.size()));
+ }
+ auto rj = nlohmann::json::parse(data.toStdString());
+ bundle.accessToken = rj.value("access_token", bundle.accessToken);
+ if (rj.contains("refresh_token") && rj["refresh_token"].is_string()) {
+ std::string rt = rj["refresh_token"].get<std::string>();
+ if (!rt.empty()) bundle.refreshToken = rt;
+ }
+ if (rj.contains("id_token") && rj["id_token"].is_string()) {
+ std::string idt = rj["id_token"].get<std::string>();
+ if (!idt.empty()) bundle.idToken = idt;
+ }
+ bundle.obtainedAt = std::chrono::system_clock::now();
+ store.saveChatGPTTokens(kProviderKey, bundle.toJson().dump());
+ return bundle;
+}
+
+std::string roleToRpc(LLMMessage::Role role) {
+ switch (role) {
+ case LLMMessage::Role::System: return "system";
+ case LLMMessage::Role::User: return "user";
+ case LLMMessage::Role::Assistant: return "assistant";
+ }
+ return "user";
+}
+
+// Walk SSE byte stream and concatenate `response.output_text.delta` payloads.
+std::string parseResponsesSse(const QByteArray& body) {
+ std::string out;
+ QList<QByteArray> lines = body.split('\n');
+ QByteArray currentEvent;
+ for (auto& raw : lines) {
+ QByteArray line = raw.endsWith('\r') ? raw.left(raw.size() - 1) : raw;
+ if (line.isEmpty()) { currentEvent.clear(); continue; }
+ if (line.startsWith(":")) continue; // SSE comment
+ if (line.startsWith("event: ")) {
+ currentEvent = line.mid(7);
+ continue;
+ }
+ if (!line.startsWith("data: ")) continue;
+ QByteArray payload = line.mid(6);
+ if (payload == "[DONE]") break;
+ if (currentEvent == "response.output_text.delta") {
+ try {
+ auto j = nlohmann::json::parse(payload.toStdString());
+ if (j.contains("delta") && j["delta"].is_string()) {
+ out += j["delta"].get<std::string>();
+ }
+ } catch (...) {}
+ } else if (currentEvent == "response.error") {
+ try {
+ auto j = nlohmann::json::parse(payload.toStdString());
+ std::string m;
+ if (j.contains("error") && j["error"].is_object() &&
+ j["error"].contains("message"))
+ m = j["error"]["message"].get<std::string>();
+ else if (j.contains("message"))
+ m = j["message"].get<std::string>();
+ else
+ m = payload.toStdString();
+ throw QueryError("ChatGPT response.error: " + m);
+ } catch (const QueryError&) {
+ throw;
+ } catch (...) {}
+ } else if (currentEvent == "response.completed") {
+ return out;
+ }
+ }
+ return out;
+}
+
+} // namespace
+
+ChatGPTProvider::ChatGPTProvider(const std::string& /*apiKey*/, const std::string& baseUrl) {
+ std::string base = trim(baseUrl);
+ baseUrl_ = base.empty() ? std::string(oauth::kChatGPTBackend) : base;
+ while (!baseUrl_.empty() && baseUrl_.back() == '/') baseUrl_.pop_back();
+}
+
+std::string ChatGPTProvider::sendMessage(const std::vector<LLMMessage>& messages,
+ const std::string& systemPrompt,
+ const std::string& model,
+ int /*maxTokens*/, double /*temperature*/) {
+ auto bundle = loadAndMaybeRefresh();
+
+ nlohmann::json input = nlohmann::json::array();
+ for (const auto& m : messages) {
+ if (m.role == LLMMessage::Role::System) continue; // → instructions field
+ std::string partType = (m.role == LLMMessage::Role::Assistant) ? "output_text" : "input_text";
+ input.push_back({
+ {"type", "message"},
+ {"role", roleToRpc(m.role)},
+ {"content", nlohmann::json::array({{ {"type", partType}, {"text", m.content} }})},
+ });
+ }
+ nlohmann::json body = {
+ {"model", model},
+ {"instructions", systemPrompt},
+ {"input", input},
+ {"stream", true},
+ {"store", false},
+ };
+
+ QUrl url(QString::fromStdString(baseUrl_ + "/responses"));
+ std::vector<std::pair<QByteArray, QByteArray>> headers = {
+ {"Content-Type", "application/json"},
+ {"Authorization", QByteArrayLiteral("Bearer ") + QByteArray::fromStdString(bundle.accessToken)},
+ {"OpenAI-Beta", "responses=v1"},
+ };
+ if (bundle.accountId) {
+ headers.push_back({"ChatGPT-Account-ID", QByteArray::fromStdString(*bundle.accountId)});
+ }
+
+ int status = 0;
+ QString err;
+ QByteArray data = httpPost(url, QByteArray::fromStdString(body.dump()), headers, &status, &err);
+ if (status == 401 || status == 403) {
+ SecretStore store;
+ store.deleteChatGPTTokens(kProviderKey);
+ throw AuthenticationError("ChatGPT sign-in expired — sign in again");
+ }
+ if (status < 200 || status >= 300) {
+ std::string snippet(data.constData(), std::min<int>(400, data.size()));
+ throw QueryError("ChatGPT /responses HTTP " + std::to_string(status) + ": " + snippet);
+ }
+ return parseResponsesSse(data);
+}
+
+std::vector<LLMModel> ChatGPTProvider::availableModels() {
+ auto bundle = loadAndMaybeRefresh();
+ QUrl url(QString::fromStdString(baseUrl_ + "/models"));
+ QUrlQuery q;
+ q.addQueryItem("client_version", "1.0.0");
+ url.setQuery(q);
+
+ std::vector<std::pair<QByteArray, QByteArray>> headers = {
+ {"Authorization", QByteArrayLiteral("Bearer ") + QByteArray::fromStdString(bundle.accessToken)},
+ };
+ if (bundle.accountId) {
+ headers.push_back({"ChatGPT-Account-ID", QByteArray::fromStdString(*bundle.accountId)});
+ }
+
+ int status = 0;
+ QString err;
+ QByteArray data = httpGet(url, headers, &status, &err);
+ if (status < 200 || status >= 300) return {};
+
+ std::vector<LLMModel> out;
+ try {
+ auto j = nlohmann::json::parse(data.toStdString());
+ if (!j.contains("models") || !j["models"].is_array()) return out;
+ for (const auto& m : j["models"]) {
+ if (!m.contains("slug") || !m["slug"].is_string()) continue;
+ bool supported = m.value("supported_in_api", true);
+ std::string vis = m.value("visibility", std::string("list"));
+ if (!supported || vis != "list") continue;
+ LLMModel mm;
+ mm.id = m["slug"].get<std::string>();
+ mm.name = m.value("name", mm.id);
+ mm.provider = "ChatGPT";
+ mm.contextWindow = m.value("context_window", 128000);
+ out.push_back(std::move(mm));
+ }
+ } catch (...) {}
+ return out;
+}
+
+bool ChatGPTProvider::validateAPIKey() {
+ SecretStore store;
+ return store.loadChatGPTTokens(kProviderKey).has_value();
+}
+
+} // namespace gridex
diff --git a/linux/src/Services/AI/Providers/ChatGPTProvider.h b/linux/src/Services/AI/Providers/ChatGPTProvider.h
new file mode 100644
index 0000000..a67bb38
--- /dev/null
+++ b/linux/src/Services/AI/Providers/ChatGPTProvider.h
@@ -0,0 +1,41 @@
+#pragma once
+
+// LLMService implementation backed by the ChatGPT subscription via the Codex
+// CLI OAuth flow. Talks to chatgpt.com/backend-api/codex/responses (the
+// Responses API), NOT api.openai.com/v1/chat/completions.
+//
+// Token refresh happens lazily inside each request so a refresh in one call
+// is visible to the next: load bundle from keychain → if access_token is
+// close to expiring, POST /oauth/token with refresh_token → write the
+// rotated bundle back → use access_token in the request.
+
+#include <string>
+#include <vector>
+
+#include "Core/Protocols/AI/ILLMService.h"
+
+namespace gridex {
+
+class ChatGPTProvider : public ILLMService {
+public:
+ // baseUrl defaults to https://chatgpt.com/backend-api/codex when empty.
+ // apiKey is unused; the OAuth bundle in libsecret is the credential.
+ ChatGPTProvider(const std::string& apiKey, const std::string& baseUrl);
+
+ std::string providerName() const override { return "ChatGPT"; }
+
+ std::string sendMessage(const std::vector<LLMMessage>& messages,
+ const std::string& systemPrompt,
+ const std::string& model,
+ int maxTokens = 4096,
+ double temperature = 0.7) override;
+
+ std::vector<LLMModel> availableModels() override;
+
+ bool validateAPIKey() override;
+
+private:
+ std::string baseUrl_;
+};
+
+} // namespace gridex
diff --git a/linux/src/Services/CMakeLists.txt b/linux/src/Services/CMakeLists.txt
index 52b69cb..a34b762 100644
--- a/linux/src/Services/CMakeLists.txt
+++ b/linux/src/Services/CMakeLists.txt
@@ -12,6 +12,11 @@ add_library(gridex-services STATIC
AI/Providers/OpenAIProvider.cpp
AI/Providers/OllamaProvider.cpp
AI/Providers/GeminiProvider.cpp
+ AI/Providers/ChatGPTProvider.cpp
+ AI/Auth/PKCE.cpp
+ AI/Auth/JwtDecoder.cpp
+ AI/Auth/OAuthLoopbackServer.cpp
+ AI/Auth/ChatGPTOAuthService.cpp
Export/ExportService.cpp
Export/DatabaseDumpRunner.cpp
MCP/MCPServer.cpp