Implement private KDE integration and optional release-cycle path

This commit is contained in:
Pavel Isaev 2026-11-06 20:59:41 +03:00
parent ec148aefe6
commit ce27ecfb50
7 changed files with 233 additions and 20 deletions

View file

@ -166,6 +166,8 @@ systemd-nspawn --settings=no --register=no --private-network --resolv-conf=off \
config=/usr/lib/archipelago/mkinitcpio-core.conf
if [[ -f /usr/lib/archipelago/mkinitcpio-gnome.conf ]]; then
config=/usr/lib/archipelago/mkinitcpio-gnome.conf
elif [[ -f /usr/lib/archipelago/mkinitcpio-kde.conf ]]; then
config=/usr/lib/archipelago/mkinitcpio-kde.conf
fi
mkinitcpio --nocolor -c "$config" -k "$kernel" -g "$modules/initramfs.img"
done

View file

@ -1,6 +1,7 @@
[[ $EUID == 0 ]] || { echo 'Run as root' >&2; exit 1; }
[[ -e /run/ostree-booted ]] || { echo 'Not an installed OSTree deployment' >&2; exit 1; }
[[ ! -e /usr/lib/archipelago/gnome-firstboot ]] || { echo 'This deployment uses GNOME Initial Setup through GDM' >&2; exit 1; }
[[ ! -e /usr/lib/archipelago/kde-firstboot ]] || { echo 'This deployment uses Plasma Setup' >&2; exit 1; }
exec 9>/run/archipelago-provision.lock
state=/etc/archipelago
mkdir -p "$state"

View file

@ -0,0 +1,168 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// One immutable OS transaction; package/runtime applications belong to other backends.
#include <resources/AbstractResourcesBackend.h>
#include <resources/StandardBackendUpdater.h>
#include <Transaction/Transaction.h>
#include <QDate>
#include <QFile>
#include <QJsonDocument>
#include <QProcess>
#include <QRegularExpression>
#include <QTimer>
class OSResource final : public AbstractResource
{
Q_OBJECT
public:
explicit OSResource(AbstractResourcesBackend *backend) : AbstractResource(backend) {}
QJsonObject record;
QString packageName() const override { return QStringLiteral("archipelago-os"); }
QString name() const override { return QStringLiteral("Archipelago KDE"); }
QString comment() override { return tr("Verified operating system image; activation requires a restart"); }
QVariant icon() const override { return QStringLiteral("distributor-logo"); }
bool canExecute() const override { return false; }
void invokeApplication() const override {}
bool isRemovable() const override { return false; }
State state() override { return record["state"] == "available" ? Upgradeable : Installed; }
bool hasCategory(const QString &category) const override { return category == "System"; }
Type type() const override { return System; }
quint64 size() override { return 0; } // The transport has not reported download size.
QString sizeDescription() override { return tr("Download size is determined by OSTree"); }
QJsonArray licenses() override { return {}; }
QString installedVersion() const override { return record["plan"].toObject()["base"].toString(); }
QString availableVersion() const override { return record["plan"].toObject()["target"].toString(); }
QString origin() const override { return QStringLiteral("Archipelago"); }
QString section() override { return QStringLiteral("System"); }
QString author() const override { return QStringLiteral("Archipelago"); }
QString sourceIcon() const override { return QStringLiteral("drive-harddisk"); }
QDate releaseDate() const override { return {}; }
QList<PackageState> addonsInformation() override { return {}; }
QString longDescription() override {
QString text = comment().toHtmlEscaped();
if (record["state"] == "pending") text += tr("<p>A deployment is staged. Restart when ready.</p>");
if (record["state"] == "error") text += "<p>" + record["error"].toString().toHtmlEscaped() + "</p>";
text += "<pre>" + record["support_description"].toString().toHtmlEscaped() + "</pre>";
text += "<ul>";
for (const auto &entry : record["plan"].toObject()["package_changes"].toArray()) {
const auto change = entry.toObject();
const QString before = change["old_version"].isString() ? change["old_version"].toString() : tr("not installed");
const QString after = change["new_version"].isString() ? change["new_version"].toString() : tr("will be removed");
text += "<li>" + change["name"].toString().toHtmlEscaped() + ": "
+ before.toHtmlEscaped() + QStringLiteral(" → ") + after.toHtmlEscaped() + "</li>";
}
return text + "</ul>";
}
void fetchChangelog() override { Q_EMIT changelogFetched(longDescription()); }
void reload() {
QFile file(QStringLiteral("/var/lib/archipelago/software/status.json"));
QJsonObject next;
if (file.open(QIODevice::ReadOnly)) next = QJsonDocument::fromJson(file.readAll()).object();
if (next["version"].toInt() != 1) next = {{"state", "error"}, {"error", tr("Update status unavailable; refresh to retrieve a verified plan.")}};
record = next;
Q_EMIT stateChanged();
Q_EMIT versionsChanged();
Q_EMIT longDescriptionChanged();
}
};
class OSTransaction final : public Transaction
{
Q_OBJECT
public:
explicit OSTransaction(OSResource *resource)
: Transaction(resource->backend(), resource, InstallRole, {}) {
setCancellable(false);
const QString id = resource->record["plan_id"].toString();
QTimer::singleShot(0, this, [this, resource, id] {
if (resource->state() != AbstractResource::Upgradeable ||
!QRegularExpression(QStringLiteral("^[a-f0-9]{64}$")).match(id).hasMatch()) {
Q_EMIT passiveMessage(tr("No valid update plan; refresh updates first."));
setStatus(DoneWithErrorStatus);
deleteLater();
return;
}
auto process = new QProcess(this);
setStatus(CommittingStatus);
connect(process, &QProcess::errorOccurred, this, [this, process](QProcess::ProcessError error) {
if (error != QProcess::FailedToStart) return;
Q_EMIT passiveMessage(process->errorString());
setStatus(DoneWithErrorStatus);
deleteLater();
});
connect(process, &QProcess::finished, this, [this, process, resource](int code, QProcess::ExitStatus status) {
resource->reload();
const bool success = code == 0 && status == QProcess::NormalExit;
if (!success) Q_EMIT passiveMessage(QString::fromUtf8(process->readAllStandardError()));
if (success) setProgress(100);
setStatus(success ? DoneStatus : DoneWithErrorStatus);
deleteLater();
});
process->start(QStringLiteral("/usr/bin/pkexec"), {QStringLiteral("/usr/lib/archipelago/software-helper"), QStringLiteral("apply"), id});
});
}
void cancel() override {} // The shared privileged operation continues independently of the GUI.
};
class ArchipelagoBackend final : public AbstractResourcesBackend
{
Q_OBJECT
public:
explicit ArchipelagoBackend(QObject *parent = nullptr) : AbstractResourcesBackend(parent) {
resource = new OSResource(this);
updater = new StandardBackendUpdater(this);
connect(resource, &AbstractResource::stateChanged, this, [this] {
updater->setNeedsReboot(resource->record["state"] == "pending");
Q_EMIT updatesCountChanged();
Q_EMIT resourcesChanged(resource, {"state", "installedVersion", "availableVersion", "longDescription"});
});
resource->reload();
auto timer = new QTimer(this);
connect(timer, &QTimer::timeout, resource, &OSResource::reload);
timer->start(30000);
}
bool isValid() const override {
QFile purpose(QStringLiteral("/usr/lib/archipelago/purpose"));
return QFile::exists(QStringLiteral("/run/ostree-booted")) && purpose.open(QIODevice::ReadOnly)
&& purpose.readAll().trimmed() == "purpose/desktop/kde";
}
QString displayName() const override { return QStringLiteral("Archipelago"); }
int updatesCount() const override { return resource->state() == AbstractResource::Upgradeable ? 1 : 0; }
AbstractBackendUpdater *backendUpdater() const override { return updater; }
AbstractReviewsBackend *reviewsBackend() const override { return nullptr; }
int fetchingUpdatesProgress() const override { return refreshing ? 0 : 100; }
ResultsStream *search(const Filters &filters) override {
QVector<StreamResult> found{StreamResult(resource)};
filters.filterJustInCase(found);
return new ResultsStream(QStringLiteral("Archipelago"), found);
}
Transaction *installApplication(AbstractResource *app, const AddonList &) override {
return app == resource ? new OSTransaction(resource) : nullptr;
}
Transaction *removeApplication(AbstractResource *) override {
Q_EMIT passiveMessage(tr("The operating system cannot be removed."));
return nullptr;
}
void checkForUpdates() override {
if (refreshing) return;
refreshing = true;
Q_EMIT fetchingUpdatesProgressChanged();
auto process = new QProcess(this);
const auto finished = [this, process](bool success) {
refreshing = false;
resource->reload();
if (!success) Q_EMIT passiveMessage(process->errorString() + QString::fromUtf8(process->readAllStandardError()));
Q_EMIT fetchingUpdatesProgressChanged();
process->deleteLater();
};
connect(process, &QProcess::finished, this, [finished](int code, QProcess::ExitStatus status) { finished(code == 0 && status == QProcess::NormalExit); });
connect(process, &QProcess::errorOccurred, this, [finished](QProcess::ProcessError error) { if (error == QProcess::FailedToStart) finished(false); });
process->start(QStringLiteral("/usr/bin/pkexec"), {QStringLiteral("/usr/lib/archipelago/software-helper"), QStringLiteral("refresh")});
}
private:
OSResource *resource;
StandardBackendUpdater *updater;
bool refreshing = false;
};
DISCOVER_BACKEND_PLUGIN(ArchipelagoBackend)
#include "ArchipelagoBackend.moc"

View file

@ -0,0 +1,4 @@
# Included inside the matching, checksum-pinned Discover source tree.
kcoreaddons_add_plugin(archipelago-backend SOURCES ArchipelagoBackend.cpp INSTALL_NAMESPACE "discover")
target_link_libraries(archipelago-backend Qt::Core KF6::CoreAddons Discover::Common)
set_target_properties(archipelago-backend PROPERTIES INSTALL_RPATH "/usr/lib/plasma-discover")

View file

@ -1,5 +1,5 @@
//! GNOME onboarding observation and first-install Flatpak defaults.
//! Upstream GNOME creates accounts; Flatpak owns application transactions.
//! Native desktop onboarding observation and first-install Flatpak defaults.
//! Upstream provisioners create accounts; Flatpak owns application transactions.
use serde_json::Value;
use std::{collections::BTreeMap, fs::{self, File}, os::unix::fs::MetadataExt,
path::Path, process::Command};
@ -20,8 +20,9 @@ fn call(program: &str, args: &[&str]) -> Result<()> {
fn target() -> Result<()> {
if output("/usr/bin/id", &["-u"])?.trim() != "0" { return Err("Run as root".into()); }
if !Path::new("/run/ostree-booted").exists() ||
fs::read_to_string("/usr/lib/archipelago/purpose").unwrap_or_default().trim() != "purpose/desktop/gnome" {
return Err("Requires an installed GNOME Purpose deployment".into());
!matches!(fs::read_to_string("/usr/lib/archipelago/purpose").unwrap_or_default().trim(),
"purpose/desktop/gnome" | "purpose/desktop/kde") {
return Err("Requires an installed GNOME or KDE Purpose deployment".into());
}
Ok(())
}
@ -73,6 +74,9 @@ pub fn reconcile() -> Result<()> {
target()?;
let _lock = lock("/run/archipelago-provision.lock")?;
if Path::new("/etc/archipelago/provisioned").exists() { return Ok(()); }
let kde = fs::read_to_string("/usr/lib/archipelago/purpose").map_err(|e| e.to_string())?.trim() == "purpose/desktop/kde";
if kde && !Path::new("/etc/plasma-setup-done").is_file() { return Ok(()); }
let login_service = if kde { "sddm" } else { "gdm-password" };
let sessions: Value = serde_json::from_str(&output("/usr/bin/loginctl", &["list-sessions", "--json=short"])?).map_err(|e| e.to_string())?;
for session in sessions.as_array().ok_or("Invalid session list")? {
let id = session["session"].as_str().ok_or("Missing session ID")?;
@ -81,7 +85,7 @@ pub fn reconcile() -> Result<()> {
"-p", "Class", "-p", "Type", "-p", "Service", "-p", "Active", "-p", "Remote"])?;
let fields: BTreeMap<_, _> = text.lines().filter_map(|line| line.split_once('=')).collect();
if fields.get("Active") != Some(&"yes") || fields.get("Remote") != Some(&"no") ||
fields.get("Class") != Some(&"user") || fields.get("Service") != Some(&"gdm-password") ||
fields.get("Class") != Some(&"user") || fields.get("Service") != Some(&login_service) ||
!matches!(fields.get("Type"), Some(&"wayland") | Some(&"x11")) { continue; }
let name = *fields.get("Name").ok_or("Missing user name")?;
username(name)?;
@ -102,24 +106,37 @@ pub fn reconcile() -> Result<()> {
return Err("Primary administrator is not in wheel".into());
}
call("/usr/bin/visudo", &["-c"])?;
// Native account creation must provide rootless-container identities before
// onboarding is complete. Never overwrite administrator-assigned ranges.
for database in ["/etc/subuid", "/etc/subgid"] {
let ranges = fs::read_to_string(database).map_err(|e| format!("{database}: {e}"))?;
let usable = ranges.lines().any(|line| {
let fields: Vec<_> = line.split(':').collect();
fields.len() == 3 && (fields[0] == name || fields[0] == uid.to_string()) &&
fields[1].parse::<u32>().is_ok_and(|start| start >= 65536) &&
fields[2].parse::<u32>().is_ok_and(|count| count >= 65536)
});
if !usable { return Err(format!("Primary user has no usable subordinate identity range in {database}")); }
}
fs::create_dir_all("/etc/archipelago").map_err(|e| e.to_string())?;
atomic(Path::new("/etc/archipelago/provisioned"), format!("{name}\n").as_bytes())?;
println!("GNOME onboarding observed after authenticated user login: {name}");
println!("Desktop onboarding observed after authenticated user login: {name}");
return Ok(());
}
// Pending is normal while GDM's native setup session is active.
// Pending is normal while the native setup session is active.
Ok(())
}
fn app_ref(value: &str) -> bool {
let parts: Vec<_> = value.split('/').collect();
parts.len() == 4 && parts[0] == "app" && parts[2] == "x86_64" && parts[3] == "stable" &&
parts[1].starts_with("org.gnome.") && parts[1].bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
(parts[1].starts_with("org.gnome.") || parts[1].starts_with("org.kde.")) &&
parts[1].bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
}
pub fn seed_flatpaks() -> Result<()> {
target()?;
if !Path::new("/etc/archipelago/provisioned").is_file() { return Err("Complete GNOME onboarding first".into()); }
if !Path::new("/etc/archipelago/provisioned").is_file() { return Err("Complete desktop onboarding first".into()); }
let _lock = lock("/run/archipelago-flatpak-defaults.lock")?;
let state = Path::new("/var/lib/archipelago/flatpak-defaults-v1");
fs::create_dir_all(state.join("completed")).map_err(|e| e.to_string())?;

View file

@ -1,4 +1,4 @@
//! Privileged, short-lived GNOME Software bridge to the shared update engine.
//! Privileged, short-lived desktop software bridge to the shared update engine.
use serde_json::{json, Value};
use std::{fs, path::Path, process::Command};
@ -20,18 +20,21 @@ pub fn refresh() -> Result<(), String> {
.open("/run/archipelago-software.lock").map_err(|e| e.to_string())?;
lock.try_lock().map_err(|e| format!("Software refresh busy: {e}"))?;
let state = crate::extensions::status()?;
let support = run(&["/usr/bin/archipelago", "status"])
.unwrap_or_else(|error| format!("Support status unavailable: {error}"));
if state["deployments"].as_array().ok_or("missing deployments")?.iter()
.any(|d| d["pending"] == true || d["staged"] == true) {
return save(&json!({"version":1,"state":"pending","deployments":state}));
return save(&json!({"version":1,"state":"pending","deployments":state,"support_description":support}));
}
match run(&["/usr/bin/archipelago", "update", "plan", "--json"]) {
Ok(text) => {
let mut record: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
record["version"] = json!(1);
record["support_description"] = json!(support);
record["state"] = json!(if record["plan"]["base"] == record["plan"]["target"] { "current" } else { "available" });
save(&record)
}
Err(error) => { save(&json!({"version":1,"state":"error","error":error}))?; Err(error) }
Err(error) => { save(&json!({"version":1,"state":"error","error":error,"support_description":support}))?; Err(error) }
}
}
pub fn request(operation: &str, plan: Option<&str>) -> Result<(), String> {

View file

@ -62,7 +62,7 @@ fn binding() -> Result<Value, String> {
let path = if local.exists() { local } else { Path::new("/usr/lib/archipelago/update.json") };
let profile: Value = serde_json::from_slice(&fs::read(path).map_err(|e| format!("update profile {}: {e}", path.display()))?).map_err(|e| e.to_string())?;
let url = profile["url"].as_str().ok_or("missing update URL")?;
let reference = profile["refs"][variant()].as_str().ok_or("missing variant ref")?;
let reference = profile["refs"][variant()?].as_str().ok_or("missing variant ref")?;
if profile["version"] != 1 || !(url.starts_with("https://") || url.starts_with("http://") || url.starts_with("file:///")) || url.chars().any(char::is_whitespace) {
return Err("unsupported update profile URL/version".into());
}
@ -101,8 +101,22 @@ fn summary_commit(summary: &str, reference: &str) -> Result<String, String> {
}
Err("signed summary does not contain the selected image track".into())
}
fn variant() -> &'static str {
if Path::new("/usr/lib/archipelago/gnome-firstboot").exists() { "gnome" } else { "core" }
fn purpose_variant(identity: &str) -> Result<&'static str, String> {
match identity.trim() {
"purpose/desktop/gnome" => Ok("gnome"),
"purpose/desktop/kde" => Ok("kde"),
other => Err(format!("unsupported Purpose identity: {other:?}")),
}
}
fn variant() -> Result<&'static str, String> {
match fs::read_to_string("/usr/lib/archipelago/purpose") {
Ok(identity) => purpose_variant(&identity),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
// Legacy images predate the explicit Purpose identity.
Ok(if Path::new("/usr/lib/archipelago/gnome-firstboot").exists() { "gnome" } else { "core" })
}
Err(e) => Err(format!("read Purpose identity: {e}")),
}
}
fn commit_date(repository: &str, commit: &str) -> Result<String, String> {
let text = output("ostree", &[&format!("--repo={repository}"), "show", commit])?;
@ -130,7 +144,7 @@ fn require_newer(base: &str, target: &str) -> Result<(), String> {
}
pub(crate) fn stage_deployment(commit: &str) -> Result<(), String> {
let mut args = vec!["admin", "deploy", "--stage", "--retain", "--os=archipelago"];
if variant() == "gnome" {
if matches!(variant()?, "gnome" | "kde") {
args.extend(["--karg=quiet", "--karg=splash", "--karg=plymouth.ignore-serial-consoles"]);
}
args.push(commit);
@ -176,7 +190,7 @@ fn plan_output(save: bool, json_output: bool, include_diff: bool) -> Result<(),
let reference = binding["reference"].as_str().ok_or("missing reference")?;
let target = summary_commit(&repo(&["remote", "summary", REMOTE])?, &reference)?;
require_newer(&base, &target)?;
let mut plan = json!({"version":3,"binding":binding,"variant":variant(),"reference":reference,
let mut plan = json!({"version":3,"binding":binding,"variant":variant()?,"reference":reference,
"target":target,"base":base,"requested":requested,"initial":state});
if include_diff {
let inventory = "/usr/lib/archipelago/packages.txt";
@ -217,7 +231,7 @@ pub fn apply(id: &str) -> Result<(), String> {
}
fn apply_plan(plan: &Value) -> Result<(), String> {
let binding = binding()?;
if plan["version"] != 3 || plan["binding"] != binding || plan["variant"] != variant() { return Err("unsupported plan or infrastructure binding changed; create a new plan".into()); }
if plan["version"] != 3 || plan["binding"] != binding || plan["variant"] != variant()? { return Err("unsupported plan or infrastructure binding changed; create a new plan".into()); }
let initial = crate::extensions::status()?;
booted(&initial)?;
if initial != plan["initial"] { return Err("deployment state changed; create a new plan".into()); }
@ -229,8 +243,12 @@ fn apply_plan(plan: &Value) -> Result<(), String> {
// verifies its commit signature without reinterpreting old build-local ref bindings.
repo(&["pull", "--depth=0", REMOTE, target])?;
let files = repo(&["ls", target, "/usr/lib/archipelago"])?;
let gnome = files.lines().any(|l| l.ends_with("/gnome-firstboot"));
if gnome != (variant() == "gnome") { return Err("candidate Purpose differs from booted Purpose".into()); }
let candidate = if files.lines().any(|l| l.ends_with("/purpose")) {
purpose_variant(&repo(&["cat", target, "/usr/lib/archipelago/purpose"])?)?
} else if files.lines().any(|l| l.ends_with("/gnome-firstboot")) {
"gnome"
} else { "core" };
if candidate != variant()? { return Err("candidate Purpose differs from booted Purpose".into()); }
if output("uname", &["-m"])?.trim() != "x86_64" { return Err("only x86_64 is implemented".into()); }
repo(&["cat", target, "/usr/lib/archipelago/snapshot"])?;
output("ostree", &["--repo=/sysroot/ostree/repo", "pull-local", &format!("{STATE}/repo"), target])?;