LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.
C cdebiandesktop-environmentebpffirewalllandlocklinuxlinux-distributionopen-sourceprivacyquickjsraspberry-pi-5reactsecuritywaylandwayland-compositor
Imager: lord.imager, the shared core and the first boot hook
Federico Pereirac55734f1f1f7
diff --git a/apps/imager/core/catalog.js b/apps/imager/core/catalog.jsnew file mode 100644index 0000000..e58db48--- /dev/null+++ b/apps/imager/core/catalog.js@@ -0,0 +1,64 @@+// catalog.js — what the LordOS Imager offers: devices, cooling, appearance and the defaults. Data+// only (labels are i18n keys); shared by the native and desktop apps. docs/IMAGER.md.++// Devices. Only the Raspberry Pi 5 is supported (docs/RASPBERRY.md); the others are listed so+// people see why their board isn't there. `pc` writes the amd64 live ISO to a USB stick.+export const DEVICES = [+ { id: 'rpi5', name: 'Raspberry Pi 5', kind: 'pi', supported: true, image: /^lordos-[0-9][\w.~+-]*-rpi5-arm64\.img\.xz$/, customise: true },+ { id: 'pc', kind: 'pc', supported: true, image: /^lordos-live-[0-9][\w.~+-]*-amd64\.iso$/, customise: false },+ { id: 'rpi500', name: 'Raspberry Pi 500 / CM5', kind: 'pi', supported: false },+ { id: 'rpi4', name: 'Raspberry Pi 4 / 400', kind: 'pi', supported: false },+ { id: 'rpi3', name: 'Raspberry Pi 3 / Zero 2', kind: 'pi', supported: false, never: true },+];+export const deviceById = (id) => DEVICES.find((d) => d.id === id) || null;++// RAM advice for the Pi 5 (docs/RASPBERRY.md, "Recommended equipment")+export const RAM_ADVICE = [+ { gb: 4, level: 'min' }, { gb: 8, level: 'comfortable' }, { gb: 16, level: 'max' },+];++export const LANGUAGES = [+ { id: 'en', name: 'English', locale: 'en_US.UTF-8' },+ { id: 'es', name: 'Español', locale: 'es_ES.UTF-8' },+ { id: 'pt', name: 'Português', locale: 'pt_BR.UTF-8' },+];++// Coolers and what each one allows (lordos-firstrun checks the same in C)+export const COOLERS = [+ { id: 'case-fan', fan: true }, // a case with a fan on the fan header (for example the Argon ONE V5)+ { id: 'active-cooler', fan: true }, // the official active cooler (heatsink + fan)+ { id: 'passive', fan: false }, // a passive heatsink case+ { id: 'none', fan: false }, // a bare board+];+export const coolerHasFan = (id) => !!COOLERS.find((c) => c.id === id && c.fan);+export function profilesFor(cooler) {+ if (coolerHasFan(cooler)) return ['balanced', 'performance', 'quiet'];+ if (cooler === 'none') return ['conservative', 'balanced'];+ return ['balanced', 'conservative'];+}+export const defaultProfile = (cooler) => (cooler === 'none' ? 'conservative' : 'balanced');+export const overclockAllowed = (cooler) => coolerHasFan(cooler);++export const THEMES = ['default', 'classic'];+export const MODES = ['light', 'dark'];+// Lord Default's accents (themes/default/tokens.js)+export const ACCENTS = [+ { id: 'azul', color: '#0a84ff' }, { id: 'violeta', color: '#bf5af2' }, { id: 'rosa', color: '#ff375f' },+ { id: 'naranja', color: '#ff9f0a' }, { id: 'verde', color: '#30d158' }, { id: 'grafito', color: '#8e8e93' },+];+// A few of the LordOS wallpapers (assets/wallpapers/index.json ids)+export const WALLPAPERS = ['lumo-celestial', 'crystal-crown', 'aurora'];++// What a new customisation starts with (the board's own defaults where nothing is chosen)+export function defaultConfig() {+ return {+ hostname: '', lang: 'en', timezone: '', keyboard: '', variant: '', wifiCountry: '',+ user: { name: '', fullname: '', autologin: false },+ wifi: { enabled: false, ssid: '', hidden: false, open: false },+ ssh: 'off', sshKeys: [],+ remote: false, bluetooth: true,+ theme: 'default', mode: 'dark', accent: 'azul', wallpaper: 'lumo-celestial',+ cooler: '', performance: '', overclock: false,+ autoUpdates: true,+ };+}diff --git a/apps/imager/core/firstrun.js b/apps/imager/core/firstrun.jsnew file mode 100644index 0000000..6625a38--- /dev/null+++ b/apps/imager/core/firstrun.js@@ -0,0 +1,101 @@+// firstrun.js — writes lordos-firstrun.txt, the file the Raspberry Pi applies on its first boot+// (lordos-firstrun, server/src/firstrun; format in docs/IMAGER.md, "The first-run file"). Shared+// by the native and desktop apps. Secrets never go in: the password arrives here already hashed+// (yescrypt or SHA-512 crypt) and the Wi-Fi password as its derived WPA2 key.+import * as v from './validate.js';+import { coolerHasFan } from './catalog.js';++export const FIRSTRUN_NAME = 'lordos-firstrun.txt';++// Checks a whole customisation; returns [] or a list of { field, key } problems (key = i18n key).+// secrets: { passwordHash, psk } (already derived) or { password, confirm, wifiPassword } (raw, in+// the form, to check before deriving).+export function check(cfg, secrets = {}) {+ const out = [];+ const add = (field, key) => key && out.push({ field, key });+ if (cfg.hostname) add('hostname', v.hostname(cfg.hostname));+ add('timezone', v.timezone(cfg.timezone));+ if (cfg.user?.name || cfg.user?.fullname) {+ add('user', v.username(cfg.user.name));+ add('fullname', v.fullname(cfg.user.fullname));+ if (!secrets.passwordHash) add('password', v.password(secrets.password, secrets.confirm));+ }+ if (cfg.wifi?.enabled) {+ add('ssid', v.ssid(cfg.wifi.ssid));+ if (!cfg.wifi.open && !secrets.psk) add('wifiPassword', secrets.wifiPassword ? v.wifiPassword(secrets.wifiPassword) : 'imager.err.wifiPassLength');+ }+ if (cfg.ssh !== 'off' && !cfg.user?.name) add('ssh', 'imager.err.sshNeedsUser');+ if (cfg.ssh === 'keys' && !(cfg.sshKeys || []).length) add('ssh', 'imager.err.sshNeedsKey');+ if (cfg.remote && !cfg.user?.name) add('remote', 'imager.err.remoteNeedsUser');+ if (cfg.overclock && !coolerHasFan(cfg.cooler)) add('overclock', 'imager.err.overclockNeedsFan');+ if ((cfg.performance === 'performance' || cfg.performance === 'quiet') && !coolerHasFan(cfg.cooler)) add('performance', 'imager.err.profileNeedsFan');+ return out;+}++// The file. Only what was chosen is written; everything else keeps the image's defaults.+export function build(cfg, { passwordHash, psk } = {}) {+ const L = ['# LordOS first-run settings, written by the LordOS Imager.',+ '# Read once on the first boot by lordos-firstrun and then deleted. docs/IMAGER.md', 'version=1'];+ const put = (k, val) => { if (val !== undefined && val !== null && val !== '') L.push(`${k}=${val}`); };+ const bool = (k, b) => L.push(`${k}=${b ? 1 : 0}`);+ put('hostname', cfg.hostname);+ put('lang', cfg.lang);+ put('timezone', cfg.timezone);+ if (cfg.keyboard) { put('keyboard', cfg.keyboard); L.push(`keyboard_variant=${cfg.variant || ''}`); }+ put('wifi_country', cfg.wifiCountry);+ const hasUser = !!cfg.user?.name;+ if (hasUser) {+ if (!passwordHash || !/^\$(6|y)\$/.test(passwordHash)) throw new Error('imager.err.passEmpty');+ put('user', cfg.user.name);+ put('fullname', cfg.user.fullname && cfg.user.fullname.trim());+ put('password_hash', passwordHash);+ bool('autologin', cfg.user.autologin);+ }+ if (cfg.wifi?.enabled && cfg.wifi.ssid) {+ put('wifi_ssid_hex', v.hex(v.utf8(cfg.wifi.ssid)));+ if (!cfg.wifi.open) {+ if (!/^[0-9a-f]{64}$/.test(psk || '')) throw new Error('imager.err.wifiPassLength');+ put('wifi_psk', psk);+ }+ bool('wifi_hidden', cfg.wifi.hidden);+ }+ if (hasUser) {+ put('ssh', cfg.ssh || 'off');+ if (cfg.ssh && cfg.ssh !== 'off') for (const k of cfg.sshKeys || []) put('ssh_key', k.line || k);+ bool('remote_desktop', cfg.remote);+ }+ bool('bluetooth', cfg.bluetooth !== false);+ put('theme', cfg.theme);+ put('mode', cfg.mode);+ put('accent', cfg.accent);+ put('wallpaper', cfg.wallpaper);+ if (cfg.cooler) {+ put('cooler', cfg.cooler);+ put('performance', cfg.performance);+ bool('overclock', cfg.overclock && coolerHasFan(cfg.cooler));+ }+ bool('auto_updates', cfg.autoUpdates !== false);+ return L.join('\n') + '\n';+}++// A saved profile: everything but secrets (no password, no hash, no Wi-Fi password or key).+const PROFILE_KEYS = ['hostname', 'lang', 'timezone', 'keyboard', 'variant', 'wifiCountry', 'ssh', 'remote', 'bluetooth', 'theme',+ 'mode', 'accent', 'wallpaper', 'cooler', 'performance', 'overclock', 'autoUpdates'];+export function toProfile(name, cfg) {+ const { user, wifi } = cfg;+ const rest = Object.fromEntries(PROFILE_KEYS.filter((k) => k in cfg).map((k) => [k, cfg[k]])); // a whitelist: nothing else gets in+ rest.sshKeys = (cfg.sshKeys || []).map((k) => k.line || k); // public keys only+ return {+ format: 'lordos-imager-profile', version: 1, name: String(name).slice(0, 64),+ config: { ...rest, user: { name: user?.name || '', fullname: user?.fullname || '', autologin: !!user?.autologin },+ wifi: { enabled: !!wifi?.enabled, ssid: wifi?.ssid || '', hidden: !!wifi?.hidden, open: !!wifi?.open } },+ };+}+export function fromProfile(p, base) {+ if (!p || p.format !== 'lordos-imager-profile' || p.version !== 1 || typeof p.config !== 'object') return null;+ const c = { ...base, ...p.config };+ c.user = { ...base.user, ...(p.config.user || {}) };+ c.wifi = { ...base.wifi, ...(p.config.wifi || {}) };+ c.sshKeys = (Array.isArray(p.config.sshKeys) ? p.config.sshKeys : []).map((k) => v.sshKey(k.line || k)).filter((k) => !k.error);+ return c;+}diff --git a/apps/imager/core/releases.js b/apps/imager/core/releases.jsnew file mode 100644index 0000000..0d0e563--- /dev/null+++ b/apps/imager/core/releases.js@@ -0,0 +1,48 @@+// releases.js — the LordOS releases, from the list GitHub publishes for lordbasex/LordOS+// (https://api.github.com/repos/lordbasex/LordOS/releases, the same list the Debian installer reads).+// Shared by the native and desktop apps. Only names and sizes are taken from it: what is written is+// trusted only after SHA256SUMS.sig verifies with the release key (docs/IMAGER.md).+import { deviceById } from './catalog.js';++export const REPO = 'lordbasex/LordOS';+export const RELEASES_URL = `https://api.github.com/repos/${REPO}/releases?per_page=10`;+export const downloadUrl = (tag, name) => `https://github.com/${REPO}/releases/download/${tag}/${name}`;+// The fingerprint docs/SIGNING.md publishes (SHA-256 of the DER public key)+export const RELEASE_KEY_FINGERPRINT = 'c7155b8e6bbbb180f907381994d06af76d333016cd6f3facf67cadd053ea108e';++const TAG = /^v[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}(-[a-z0-9.]+)?$/;+const NAME = /^[A-Za-z0-9][A-Za-z0-9._+~-]{0,127}$/;++// [{ tag, version, date, prerelease, image: {name,size}, sums: {name,size}, sig: {name,size} }],+// newest first, only releases that have an image for the device and both signature files.+export function parseReleases(json, deviceId) {+ let list;+ try { list = typeof json === 'string' ? JSON.parse(json) : json; } catch { return []; }+ if (!Array.isArray(list)) return [];+ const dev = deviceById(deviceId);+ if (!dev || !dev.image) return [];+ const out = [];+ for (const r of list.slice(0, 50)) {+ if (!r || typeof r.tag_name !== 'string' || !TAG.test(r.tag_name) || r.draft) continue;+ const assets = Array.isArray(r.assets) ? r.assets : [];+ const find = (test) => {+ const a = assets.find((x) => x && typeof x.name === 'string' && NAME.test(x.name) && test(x.name) && Number.isSafeInteger(x.size) && x.size > 0);+ return a ? { name: a.name, size: a.size } : null;+ };+ const image = find((n) => dev.image.test(n));+ const sums = find((n) => n === 'SHA256SUMS');+ const sig = find((n) => n === 'SHA256SUMS.sig');+ if (!image || !sums || !sig || sums.size > 65536 || sig.size > 512) continue;+ const t = Date.parse(r.published_at || '');+ out.push({ tag: r.tag_name, version: r.tag_name.slice(1), date: Number.isFinite(t) ? t : 0, prerelease: !!r.prerelease, image, sums, sig });+ }+ return out.sort((a, b) => b.date - a.date);+}++// The size check before writing: the uncompressed image must fit (a card's real size is a bit+// below its label, so 5 % of slack is shown as a warning, not refused)+export function fits(rawSize, diskSize) {+ if (!rawSize || !diskSize) return 'unknown';+ if (rawSize > diskSize) return 'no';+ return diskSize - rawSize < diskSize * 0.05 ? 'tight' : 'yes';+}diff --git a/apps/imager/core/validate.js b/apps/imager/core/validate.jsnew file mode 100644index 0000000..17a0bc8--- /dev/null+++ b/apps/imager/core/validate.js@@ -0,0 +1,169 @@+// validate.js — the LordOS Imager's checks, the same rules as the first-run parser on the board+// (server/src/firstrun/firstrun.c, docs/IMAGER.md). Shared by the native app and the desktop app;+// plain JavaScript, no lord.* and no DOM. Each check returns null when the value is fine, or the+// i18n key (imager.err.*) of the problem.++// UTF-8 bytes of a string (QuickJS has no TextEncoder)+export function utf8(s) {+ const out = [];+ for (const ch of String(s)) {+ let c = ch.codePointAt(0);+ if (c < 0x80) out.push(c);+ else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));+ else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));+ else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));+ }+ return out;+}+export const hex = (bytes) => bytes.map((b) => b.toString(16).padStart(2, '0')).join('');++export function hostname(s) {+ if (!s) return 'imager.err.hostEmpty';+ if (s.length > 63) return 'imager.err.hostLong';+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(s)) return 'imager.err.hostChars';+ if (/^[0-9]+$/.test(s) || s === 'localhost') return 'imager.err.hostChars';+ return null;+}++// "Ana Pérez" → "ana-perez" (a suggestion; the user can change it)+export function suggestHostname(name, device = 'pi') {+ const base = String(name || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase()+ .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);+ return base ? `${base}-${device}`.slice(0, 63).replace(/-+$/, '') : `lordos-${device}`;+}++export const RESERVED_USERS = ['root', 'daemon', 'bin', 'sys', 'sync', 'games', 'man', 'lp', 'mail', 'news', 'uucp', 'proxy',+ 'www-data', 'backup', 'list', 'irc', 'nobody', 'lordos', 'lordos-greeter', 'messagebus', 'polkitd', 'sshd', 'pipewire',+ 'sudo', 'admin', 'wheel', 'users', 'staff', 'adm', 'disk', 'audio', 'video', 'input', 'render', 'plugdev', 'netdev',+ 'bluetooth', 'avahi', '_apt', 'lordos-remote', 'operator', 'shadow', 'utmp', 'tty', 'kmem', 'dialout', 'cdrom'];++export function username(s) {+ if (!s) return 'imager.err.userEmpty';+ if (s.length > 32) return 'imager.err.userLong';+ if (!/^[a-z_][a-z0-9_-]*$/.test(s)) return 'imager.err.userChars';+ if (s.startsWith('systemd-') || RESERVED_USERS.includes(s)) return 'imager.err.userReserved';+ return null;+}++// "Ana Pérez" → "ana"+export function suggestUser(full) {+ const first = String(full || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().trim().split(/\s+/)[0] || '';+ const u = first.replace(/[^a-z0-9_-]/g, '').replace(/^[^a-z_]+/, '').slice(0, 32);+ return username(u) ? '' : u;+}++const BAD_FULLNAME = /[\u0000-\u001f\u007f-\u009f\u2028-\u202e\u2066-\u2069:,=\\]/;+export function fullname(s) {+ if (!s) return null; // optional: the user name is used+ if (utf8(s).length > 128) return 'imager.err.nameLong';+ if (BAD_FULLNAME.test(s) || s !== s.trim() || s.startsWith('-')) return 'imager.err.nameChars';+ return null;+}++// Password: 1..1024 bytes for the hash; the strength is advice, never a rule.+export function password(p, confirm) {+ if (!p) return 'imager.err.passEmpty';+ if (utf8(p).length > 1024) return 'imager.err.passLong';+ if (confirm !== undefined && p !== confirm) return 'imager.err.passMismatch';+ return null;+}++const COMMON = ['password', '12345678', '123456789', 'qwertyui', 'iloveyou', 'raspberry', 'lordos', 'admin123', 'contrasena',+ 'contraseña', 'senha123', 'letmein1', 'welcome1', '11111111', '00000000', 'abc12345', 'password1'];+// 0 very weak … 4 strong, with the reasons to show+export function strength(p) {+ if (!p) return { score: 0, hints: [] };+ const hints = [];+ const len = [...p].length;+ let classes = 0;+ if (/[a-z]/.test(p)) classes++;+ if (/[A-Z]/.test(p)) classes++;+ if (/[0-9]/.test(p)) classes++;+ if (/[^A-Za-z0-9]/.test(p)) classes++;+ let score = len >= 16 ? 3 : len >= 12 ? 2 : len >= 8 ? 1 : 0;+ if (classes >= 3) score++;+ if (len < 12) hints.push('imager.hint.longer');+ if (classes < 3) hints.push('imager.hint.mix');+ if (/(.)\1\1/.test(p) || /(0123|1234|2345|3456|4567|5678|6789|abcd|qwer|asdf)/i.test(p)) { score--; hints.push('imager.hint.pattern'); }+ if (COMMON.includes(p.toLowerCase())) { score = 0; hints.unshift('imager.hint.common'); }+ return { score: Math.max(0, Math.min(4, score)), hints };+}++// Wi-Fi: the network name is 1..32 bytes; the WPA2 password 8..63 printable ASCII (or none: open)+export function ssid(s) {+ if (!s) return 'imager.err.ssidEmpty';+ const b = utf8(s);+ if (b.length > 32) return 'imager.err.ssidLong';+ if (b.includes(0)) return 'imager.err.ssidChars';+ return null;+}+export function wifiPassword(p) {+ if (!p) return null;+ if (p.length < 8 || p.length > 63) return 'imager.err.wifiPassLength';+ if (!/^[\x20-\x7e]+$/.test(p)) return 'imager.err.wifiPassChars';+ return null;+}++export function timezone(s) {+ if (!s) return null;+ if (s.length < 3 || s.length > 63 || !/^[A-Z][A-Za-z0-9_+\-/]*$/.test(s) || /\.\.|\/\/|\/$/.test(s)) return 'imager.err.zone';+ return null;+}++// ---- SSH public keys ----++const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';+export function base64Decode(s) {+ if (!s || s.length % 4) return null;+ const out = [];+ for (let i = 0; i < s.length; i += 4) {+ const v = [];+ let pad = 0;+ for (let k = 0; k < 4; k++) {+ const c = s[i + k];+ if (c === '=') { if (i + 4 !== s.length || k < 2) return null; pad++; v.push(0); continue; }+ if (pad) return null;+ const x = B64.indexOf(c);+ if (x < 0) return null;+ v.push(x);+ }+ const t = (v[0] << 18) | (v[1] << 12) | (v[2] << 6) | v[3];+ const b = [(t >> 16) & 255, (t >> 8) & 255, t & 255];+ out.push(...b.slice(0, 3 - pad));+ }+ return out;+}++export const KEY_TYPES = ['ssh-ed25519', '[email protected]', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384',+ 'ecdsa-sha2-nistp521', '[email protected]', 'ssh-rsa'];++// One line of a .pub file → { line, type, comment } (normalized: single spaces, no trailing space) or { error }+export function sshKey(raw) {+ const line = String(raw || '').trim().replace(/\s+/g, ' ');+ if (!line) return { error: 'imager.err.keyEmpty' };+ const parts = line.split(' ');+ const [type, blob] = parts;+ const comment = parts.slice(2).join(' ');+ if (!KEY_TYPES.includes(type)) return { error: type === 'ssh-dss' ? 'imager.err.keyDss' : 'imager.err.keyType' };+ const bytes = base64Decode(blob || '');+ if (!bytes || bytes.length < 4 + type.length) return { error: 'imager.err.keyData' };+ const sl = ((bytes[0] << 24) >>> 0) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3];+ if (sl !== type.length || String.fromCharCode(...bytes.slice(4, 4 + sl)) !== type) return { error: 'imager.err.keyData' };+ if (type === 'ssh-ed25519' && bytes.length !== 4 + 11 + 4 + 32) return { error: 'imager.err.keyData' };+ if (type === 'ssh-rsa' && bytes.length < 260) return { error: 'imager.err.keyRsaShort' };+ if (utf8(comment).length > 256 || BAD_FULLNAME.test(comment.replace(/[:,=\\]/g, ''))) return { error: 'imager.err.keyComment' };+ const out = comment ? `${type} ${blob} ${comment}` : `${type} ${blob}`;+ if (utf8(out).length >= 4096) return { error: 'imager.err.keyData' };+ return { line: out, type, comment };+}++// Every key line of a pasted text or a .pub file (comments and blank lines skipped)+export function sshKeys(text) {+ const keys = [], errors = [];+ for (const l of String(text || '').split(/\r?\n/)) {+ if (!l.trim() || l.trim().startsWith('#')) continue;+ const k = sshKey(l);+ if (k.error) errors.push(k.error); else if (!keys.some((x) => x.line === k.line)) keys.push(k);+ }+ return { keys: keys.slice(0, 16), errors, tooMany: keys.length > 16 };+}diff --git a/server/Makefile b/server/Makefileindex 9e4511e..45d8434 100644--- a/server/Makefile+++ b/server/Makefile@@ -103,7 +103,7 @@ SRC += $(DISK_SRC)HDR += $(wildcard src/disk/*.h)# LordOS Imager (docs/IMAGER.md): the imager-* actions (verified image → removable disk, downloads# as the user) and lordos-firstrun, the Raspberry Pi first-run file applier (src/firstrun)-IMAGER_SRC := src/imager/imgverify.c src/imager/imager_admin.c+IMAGER_SRC := src/imager/imgverify.c src/imager/imager_admin.c src/ui/js_imager.cSRC += $(IMAGER_SRC)HDR += $(wildcard src/imager/*.h)FIRSTRUN_SRC := src/firstrun/firstrun.c src/firstrun/firstrun_apply.c src/users/homedirs.cdiff --git a/server/src/firstrun/firstrun_apply.c b/server/src/firstrun/firstrun_apply.cindex 16d4d97..0d1f5bb 100644--- a/server/src/firstrun/firstrun_apply.c+++ b/server/src/firstrun/firstrun_apply.c@@ -141,6 +141,8 @@ static void jstr(char *out, size_t cap, const char *s) {/* ---- programs ---- */static char *const ENV[] = { "PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C.UTF-8", NULL };+/* --root: the image's SysV helpers (update-rc.d) may be of another architecture; the unit symlinks are enough */+static char *const ENV_TEST[] = { "PATH=/usr/sbin:/usr/bin:/sbin:/bin", "LANG=C.UTF-8", "SYSTEMCTL_SKIP_SYSV=1", NULL };static int run(const char *const argv[]) {pid_t pid = fork();@@ -149,7 +151,7 @@ static int run(const char *const argv[]) {int null = open("/dev/null", O_RDWR);if (null >= 0) { dup2(null, 0); }syscall(SYS_close_range, 3, ~0u, 0);- execve(argv[0], (char *const *)argv, ENV);+ execve(argv[0], (char *const *)argv, TEST ? ENV_TEST : ENV);_exit(127);}int st = 0;@@ -264,8 +266,14 @@ static void apply_locale(const FirstRun *fr) {} else say("time zone %s is not in this image: kept UTC", fr->timezone);}if (fr->has_lang) {- char p[PATH_MAX], line[64];+ char p[PATH_MAX], line[64], ln[64];rp(p, sizeof p, "/etc/default/locale");+ /* Debian 13 makes /etc/default/locale a link to /etc/locale.conf: write that file instead */+ ssize_t l = readlink(p, ln, sizeof ln - 1);+ if (l > 0) {+ ln[l] = 0;+ if (!strcmp(ln, "../locale.conf") || !strcmp(ln, "/etc/locale.conf")) rp(p, sizeof p, "/etc/locale.conf");+ }pathf(line, sizeof line, "LANG=%s\n", locale_of(fr->lang));if (write_str(p, line, 0644)) say("could not write /etc/default/locale");else say("language: %s", fr->lang);diff --git a/server/src/ui/js.c b/server/src/ui/js.cindex def7e1a..a7c080c 100644--- a/server/src/ui/js.c+++ b/server/src/ui/js.c@@ -25,6 +25,7 @@#include "js_media.h"#include "js_wm.h"#include "js_disk.h"+#include "js_imager.h"#include "js_logs.h"#include "js_help.h"#include "js_hw.h"@@ -424,6 +425,7 @@ static void session_context(void) {js_input_register(ctx, lord); /* lord.input: touchpads and touchscreens (tp/) */js_fw_register(ctx, lord); /* lord.fw: per-app network permissions (lord-netperm, docs/FIREWALL.md) */js_disk_register(ctx, lord); /* lord.disks: disks and partitions (Disks app) */+ js_imager_register(ctx, lord); /* lord.imager: LordOS Imager (docs/IMAGER.md) */js_backup_register(ctx, lord); /* lord.backup: Backups (backup/) */js_logs_register(ctx, lord); /* lord.logs: journal and LordOS logs (Logs app) */js_help_register(ctx, lord); /* lord.help (Help) and lord.time.zoneOffset (Clock, tzif.c) */diff --git a/server/src/ui/js_imager.c b/server/src/ui/js_imager.cnew file mode 100644index 0000000..e642022--- /dev/null+++ b/server/src/ui/js_imager.c@@ -0,0 +1,167 @@+/* js_imager.c — lord.imager: what the LordOS Imager (apps/imager, docs/IMAGER.md) needs from C in the+ * session. No root, nothing written, no programs run; everything that writes a disk or downloads is+ * an admin action (imager/imager_admin.c).+ *+ * lord.imager.hashPassword(pass) yescrypt crypt(3) hash ("$y$…", Debian's default), or null.+ * pass: 1..1024 bytes, no NUL. The password never leaves+ * this call; only the hash goes into the first-run file.+ * lord.imager.wifiPsk(ssid, pass) the WPA2 key, PBKDF2-HMAC-SHA1(pass, ssid, 4096, 32), as+ * 64 hex digits, or null. ssid 1..32 bytes, pass 8..63+ * printable ASCII (IEEE 802.11i)+ * lord.imager.checkSums(sums, sig) verifies SHA256SUMS (text) with SHA256SUMS.sig against the+ * release key compiled into LordOS: { ok, files: {name: hex} }+ * lord.imager.imageInfo(path) { kind: 'raw'|'xz', size, raw } of an image in the user's+ * folders (raw: uncompressed size from the .xz index), or null */+#include "js_imager.h"+#include "../fsops.h"+#include "../imager/imgverify.h"+#include "../net/netpriv.h"+#include "../pkg/crypto.h"+#include "../sec/codesig.h"++#include <crypt.h>+#include <errno.h>+#include <fcntl.h>+#include <limits.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <unistd.h>++static JSValue f_hash(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t;+ if (argc < 1 || !JS_IsString(argv[0])) return JS_NULL;+ size_t n;+ const char *p = JS_ToCStringLen(c, &n, argv[0]);+ if (!p) return JS_NULL;+ JSValue r = JS_NULL;+ if (n >= 1 && n <= 1024 && strlen(p) == n) {+ char *salt = crypt_gensalt_ra("$y$", 0, NULL, 0);+ struct crypt_data *cd = calloc(1, sizeof *cd);+ const char *h = salt && cd ? crypt_r(p, salt, cd) : NULL;+ if (h && h[0] == '$' && h[1] == 'y') r = JS_NewString(c, h);+ if (cd) { memset(cd, 0, sizeof *cd); free(cd); }+ free(salt);+ }+ memset((char *)p, 0, n); /* QuickJS's own copy of the UTF-8 string */+ JS_FreeCString(c, p);+ return r;+}++static JSValue f_psk(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t;+ if (argc < 2 || !JS_IsString(argv[0]) || !JS_IsString(argv[1])) return JS_NULL;+ size_t sn, pn;+ const char *ssid = JS_ToCStringLen(c, &sn, argv[0]);+ const char *pass = JS_ToCStringLen(c, &pn, argv[1]);+ JSValue r = JS_NULL;+ int ok = ssid && pass && sn >= 1 && sn <= 32 && strlen(ssid) == sn && pn >= 8 && pn <= 63;+ for (size_t i = 0; ok && i < pn; i++) if ((unsigned char)pass[i] < 0x20 || (unsigned char)pass[i] > 0x7e) ok = 0;+ if (ok) {+ uint8_t psk[32];+ char hex[65];+ pbkdf2_sha1((const uint8_t *)pass, pn, (const uint8_t *)ssid, sn, 4096, psk, 32);+ for (int i = 0; i < 32; i++) snprintf(hex + 2 * i, 3, "%02x", psk[i]);+ r = JS_NewString(c, hex);+ memset(psk, 0, sizeof psk);+ memset(hex, 0, sizeof hex);+ }+ if (pass) { memset((char *)pass, 0, pn); JS_FreeCString(c, pass); }+ if (ssid) JS_FreeCString(c, ssid);+ return r;+}++/* { ok, files } — files only when the signature is good */+static JSValue f_check_sums(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t;+ JSValue o = JS_NewObject(c);+ JS_SetPropertyStr(c, o, "ok", JS_FALSE);+ if (argc < 2 || !JS_IsString(argv[0]) || !JS_IsString(argv[1])) return o;+ size_t n, sn;+ const char *sums = JS_ToCStringLen(c, &n, argv[0]);+ const char *sig = JS_ToCStringLen(c, &sn, argv[1]);+ if (sums && sig && img_sig_verify((const uint8_t *)sums, n, sig, sn, codesig_release_key) == 0) {+ JSValue files = JS_NewObject(c);+ int bad = 0, count = 0;+ for (size_t i = 0; i < n && !bad;) {+ size_t e = i;+ while (e < n && sums[e] != '\n') e++;+ size_t len = e - i;+ if (len && sums[i + len - 1] == '\r') len--;+ if (len >= 67 && len < 67 + 200) {+ char name[260], hex[65];+ memcpy(hex, sums + i, 64);+ hex[64] = 0;+ memcpy(name, sums + i + 66, len - 66);+ name[len - 66] = 0;+ uint8_t h[32];+ if (img_valid_name(name) && img_sums_find(sums, n, name, h) == 0) {+ hex_encode(h, 32, hex);+ JS_SetPropertyStr(c, files, name, JS_NewString(c, hex));+ count++;+ } else bad = 1;+ } else if (len) bad = 1;+ i = e + 1;+ }+ if (!bad && count) { JS_SetPropertyStr(c, o, "ok", JS_TRUE); JS_SetPropertyStr(c, o, "files", files); }+ else JS_FreeValue(c, files);+ }+ if (sums) JS_FreeCString(c, sums);+ if (sig) JS_FreeCString(c, sig);+ return o;+}++typedef struct { int fd; } Fd;+static int fd_read(void *ud, uint64_t off, void *buf, size_t n) {+ Fd *f = ud;+ for (size_t o = 0; o < n;) {+ ssize_t k = pread(f->fd, (char *)buf + o, n - o, (off_t)(off + o));+ if (k < 0 && errno == EINTR) continue;+ if (k <= 0) return -1;+ o += (size_t)k;+ }+ return 0;+}++static JSValue f_image_info(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t;+ if (argc < 1 || !JS_IsString(argv[0])) return JS_NULL;+ const char *p = JS_ToCString(c, argv[0]);+ if (!p) return JS_NULL;+ char real[PATH_MAX];+ JSValue r = JS_NULL;+ int ok = p[0] == '/' && strlen(p) < PATH_MAX && realpath(p, real) && fsops_allowed(real);+ JS_FreeCString(c, p);+ if (!ok) return r;+ const char *base = strrchr(real, '/') + 1;+ int kind = img_kind(base);+ int fd = kind ? open(real, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) : -1;+ struct stat st;+ if (fd >= 0 && !fstat(fd, &st) && S_ISREG(st.st_mode) && st.st_size > 0) {+ uint64_t raw = (uint64_t)st.st_size;+ Fd f = { fd };+ int good = kind == 1 || img_xz_size(fd_read, &f, (uint64_t)st.st_size, &raw) == 0;+ r = JS_NewObject(c);+ JS_SetPropertyStr(c, r, "kind", JS_NewString(c, kind == 2 ? "xz" : "raw"));+ JS_SetPropertyStr(c, r, "size", JS_NewFloat64(c, (double)st.st_size));+ JS_SetPropertyStr(c, r, "raw", good ? JS_NewFloat64(c, (double)raw) : JS_NULL);+ JS_SetPropertyStr(c, r, "name", JS_NewString(c, base));+ JS_SetPropertyStr(c, r, "path", JS_NewString(c, real));+ }+ if (fd >= 0) close(fd);+ return r;+}++static const JSCFunctionListEntry funcs[] = {+ JS_CFUNC_DEF("hashPassword", 1, f_hash),+ JS_CFUNC_DEF("wifiPsk", 2, f_psk),+ JS_CFUNC_DEF("checkSums", 2, f_check_sums),+ JS_CFUNC_DEF("imageInfo", 1, f_image_info),+};++void js_imager_register(JSContext *c, JSValue lord) {+ JSValue o = JS_NewObject(c);+ JS_SetPropertyFunctionList(c, o, funcs, sizeof funcs / sizeof funcs[0]);+ JS_SetPropertyStr(c, lord, "imager", o);+}diff --git a/server/src/ui/js_imager.h b/server/src/ui/js_imager.hnew file mode 100644index 0000000..9af9e7a--- /dev/null+++ b/server/src/ui/js_imager.h@@ -0,0 +1,9 @@+/* js_imager.h — lord.imager (the LordOS Imager; see js_imager.c, docs/IMAGER.md). */+#ifndef LORD_JS_IMAGER_H+#define LORD_JS_IMAGER_H++#include "quickjs.h"++void js_imager_register(JSContext *c, JSValue lord);++#endifdiff --git a/server/tests/firstrun_image_test.sh b/server/tests/firstrun_image_test.shnew file mode 100644index 0000000..cabff58--- /dev/null+++ b/server/tests/firstrun_image_test.sh@@ -0,0 +1,62 @@+#!/bin/sh+# firstrun_image_test.sh — lordos-firstrun end to end on a real LordOS Raspberry Pi image written to a+# VIRTUAL USB stick (docs/IMAGER.md, "Tests"). Root; the stick is checked to be the USB gadget first.+#+# sudo tests/firstrun_image_test.sh <sdX> <backing file> <lordos-firstrun.txt>+#+# The stick must already hold the image (imager-write). The script puts the first-run file on its boot+# partition the way the imager does, mounts both partitions under /mnt/firstrun-test and runs+# build/lordos-firstrun apply with --root/--boot (useradd/usermod/systemctl --root: nothing runs on+# this machine), then checks every file it should have written, and that the file is gone.+set -u+D=${1:?sdX}; BACK=${2:?backing file}; FILE=${3:?lordos-firstrun.txt}+BIN=$(cd "$(dirname "$0")/.." && pwd)/build/lordos-firstrun+m=$(sed 's/ *$//' /sys/block/$D/device/model 2>/dev/null); sz=$(( $(cat /sys/block/$D/size) * 512 ))+echo "target /dev/$D: model=$m size=$sz (backing file $BACK, $(stat -c %s "$BACK") bytes)"+[ "$m" = "File-Stor Gadget" ] && [ "$sz" = "$(stat -c %s "$BACK")" ] || { echo "not the virtual stick: stopping"; exit 2; }+M=/mnt/firstrun-test+mkdir -p $M/boot $M/root+mount /dev/${D}1 $M/boot && mount /dev/${D}2 $M/root || { echo "cannot mount the image's partitions"; exit 2; }+trap 'umount $M/boot $M/root 2>/dev/null' EXIT+cp "$FILE" $M/boot/lordos-firstrun.txt+cp $M/boot/config.txt /tmp/config.before; cp $M/boot/cmdline.txt /tmp/cmdline.before+pass=0; fail=0+ok() { pass=$((pass + 1)); echo " ok $1"; }+bad() { fail=$((fail + 1)); echo " FAIL $1"; }+chk() { if eval "$2"; then ok "$1"; else bad "$1"; fi; }++"$BIN" apply $M/boot/lordos-firstrun.txt --root $M/root --boot $M/boot; rc=$?+echo "exit status $rc"+R=$M/root+chk "exit 0 (applied, with a user)" '[ $rc = 0 ]'+chk "the first-run file is gone" '[ ! -e $M/boot/lordos-firstrun.txt ]'+chk "hostname" 'grep -qx pi-living $R/etc/hostname && grep -q "^127.0.1.1 pi-living$" $R/etc/hosts'+chk "time zone" '[ "$(readlink $R/etc/localtime)" = /usr/share/zoneinfo/America/Argentina/Buenos_Aires ] && grep -qx America/Argentina/Buenos_Aires $R/etc/timezone'+chk "language (/etc/default/locale links to /etc/locale.conf)" 'grep -qx LANG=es_ES.UTF-8 $R/etc/default/locale'+chk "keyboard" 'grep -q "XKBLAYOUT=\"latam\"" $R/etc/default/keyboard'+chk "Wi-Fi country in cmdline.txt (one line)" 'grep -q "cfg80211.ieee80211_regdom=AR$" $M/boot/cmdline.txt && [ "$(wc -l < $M/boot/cmdline.txt)" = 1 ]'+chk "cmdline.txt keeps everything else" '[ "$(sed "s/ cfg80211.ieee80211_regdom=AR//" $M/boot/cmdline.txt)" = "$(cat /tmp/cmdline.before)" ]'+W=$R/etc/lordos/net/wifi/43617361204c6f726420e29da4+chk "Wi-Fi network saved (hidden, WPA2)" 'grep -q "\"security\":\"psk\",\"hidden\":true" $W.json'+chk "Wi-Fi key is the derived PSK, 0600" 'grep -qx "psk=2909c9807b542655513df419543d91e3c831ad3bff2e95ff6d2eb80cc3209424" $W.key && [ "$(stat -c %a $W.key)" = 600 ]'+chk "no Wi-Fi password anywhere" '! grep -rq "hunter2-wifi" $R/etc $M/boot 2>/dev/null'+chk "user ana created with the hash" 'grep -qF "ana:\$6\$imagertestsalt1\$" $R/etc/shadow && grep -q "^ana:x:[0-9]*:[0-9]*:Ana Pérez:/home/ana:/bin/bash$" $R/etc/passwd'+chk "ana is an administrator (sudo) and in audio/video/render" 'for g in sudo audio video render input; do grep -q "^$g:.*[:,]ana\(,\|$\)" $R/etc/group || exit 1; done'+chk "home folders in Spanish" '[ -d $R/home/ana/Escritorio ] && [ -d $R/home/ana/Descargas ]'+chk "settings.json: language, keyboard, Classic, light, violeta, wallpaper, updates off" 'grep -q "\"theme\": \"classic\"" $R/home/ana/.config/lordos/settings.json && grep -q "\"accent\": \"violeta\"" $R/home/ana/.config/lordos/settings.json && grep -q "\"autoCheck\": false" $R/home/ana/.config/lordos/settings.json && grep -q "\"layout\": \"latam\"" $R/home/ana/.config/lordos/settings.json'+U=$(grep "^ana:" $R/etc/passwd | cut -d: -f3)+chk "her files belong to her" '[ "$(stat -c %u $R/home/ana/.config/lordos/settings.json)" = "$U" ] && [ "$(stat -c %u $R/home/ana/.ssh/authorized_keys)" = "$U" ]'+chk "authorized_keys 0600 in a 0700 .ssh" '[ "$(stat -c %a $R/home/ana/.ssh)" = 700 ] && [ "$(stat -c %a $R/home/ana/.ssh/authorized_keys)" = 600 ] && grep -q "^ssh-ed25519 " $R/home/ana/.ssh/authorized_keys'+chk "linger (PipeWire before login)" '[ -e $R/var/lib/systemd/linger/ana ]'+chk "automatic login" 'grep -qx AUTOLOGIN=ana $R/etc/lordos/session.conf'+chk "SSH enabled, keys only" '[ -L $R/etc/systemd/system/multi-user.target.wants/ssh.service ] && grep -qx "PasswordAuthentication no" $R/etc/ssh/sshd_config.d/05-lordos-keys-only.conf'+chk "remote desktop on, port 5673, local network only" 'grep -qx enabled=1 $R/etc/lordos/remote/config && grep -qx port=5673 $R/etc/lordos/remote/config && grep -qx net=lan $R/etc/lordos/remote/config'+chk "fan profile performance (fan.json root-owned 0644)" 'grep -q "\"profile\":\"performance\"" $R/etc/lordos/fan.json && [ "$(stat -c %u%a $R/etc/lordos/fan.json)" = 0644 ]'+chk "performance governor at boot" 'grep -q "scaling_governor - - - - performance" $R/etc/tmpfiles.d/lordos-cpu-governor.conf'+chk "mild overclock block in config.txt, the rest untouched" 'grep -qx arm_freq=2600 $M/boot/config.txt && [ "$(sed "/^# >>> lordos-firstrun/,/^# <<< lordos-firstrun/d" $M/boot/config.txt)" = "$(cat /tmp/config.before)" ]'+# a second run with a broken file changes nothing and still deletes it+printf 'version=1\nhostname=OTHER\n' > $M/boot/lordos-firstrun.txt+"$BIN" apply $M/boot/lordos-firstrun.txt --root $M/root --boot $M/boot > /tmp/fr2.log; rc=$?+chk "a broken file: exit 1, nothing applied, file deleted" '[ $rc = 1 ] && grep -qx pi-living $R/etc/hostname && [ ! -e $M/boot/lordos-firstrun.txt ]'+echo "firstrun_image_test: $pass passed, $fail failed"+[ "$fail" = 0 ]diff --git a/server/tests/imager/releases.json b/server/tests/imager/releases.jsonnew file mode 100644index 0000000..7fca55e--- /dev/null+++ b/server/tests/imager/releases.json@@ -0,0 +1,194 @@+[+ {+ "tag_name": "v0.8.3-beta",+ "published_at": "2026-10-19T13:01:19Z",+ "prerelease": true,+ "draft": false,+ "assets": [+ {+ "name": "install.sh",+ "size": 50122+ },+ {+ "name": "lordos-0.8.3-rpi5-arm64.img.xz",+ "size": 558119764+ },+ {+ "name": "lordos-live-0.8.3-amd64.iso",+ "size": 1051269120+ },+ {+ "name": "lordos-release.pub.pem",+ "size": 113+ },+ {+ "name": "lordos_0.8.3_amd64.deb",+ "size": 10878096+ },+ {+ "name": "lordos_0.8.3_amd64.spdx.json",+ "size": 59222+ },+ {+ "name": "lordos_0.8.3_arm64.deb",+ "size": 10615196+ },+ {+ "name": "lordos_0.8.3_arm64.spdx.json",+ "size": 57102+ },+ {+ "name": "SHA256SUMS",+ "size": 636+ },+ {+ "name": "SHA256SUMS.sig",+ "size": 89+ }+ ]+ },+ {+ "tag_name": "v0.8.2-beta",+ "published_at": "2026-10-19T09:38:15Z",+ "prerelease": true,+ "draft": false,+ "assets": [+ {+ "name": "install.sh",+ "size": 50122+ },+ {+ "name": "lordos-0.8.2-rpi5-arm64.img.xz",+ "size": 554020004+ },+ {+ "name": "lordos-live-0.8.2-amd64.iso",+ "size": 1047648256+ },+ {+ "name": "lordos-release.pub.pem",+ "size": 113+ },+ {+ "name": "lordos_0.8.2_amd64.deb",+ "size": 10803348+ },+ {+ "name": "lordos_0.8.2_amd64.spdx.json",+ "size": 58609+ },+ {+ "name": "lordos_0.8.2_arm64.deb",+ "size": 10536780+ },+ {+ "name": "lordos_0.8.2_arm64.spdx.json",+ "size": 56126+ },+ {+ "name": "SHA256SUMS",+ "size": 636+ },+ {+ "name": "SHA256SUMS.sig",+ "size": 89+ }+ ]+ },+ {+ "tag_name": "v0.8.1-beta",+ "published_at": "2026-10-19T07:17:16Z",+ "prerelease": true,+ "draft": false,+ "assets": [+ {+ "name": "install.sh",+ "size": 50122+ },+ {+ "name": "lordos-0.8.1-rpi5-arm64.img.xz",+ "size": 550845932+ },+ {+ "name": "lordos-live-0.8.1-amd64.iso",+ "size": 1043156992+ },+ {+ "name": "lordos-release.pub.pem",+ "size": 113+ },+ {+ "name": "lordos_0.8.1_amd64.deb",+ "size": 6331840+ },+ {+ "name": "lordos_0.8.1_amd64.spdx.json",+ "size": 58609+ },+ {+ "name": "lordos_0.8.1_arm64.deb",+ "size": 6073936+ },+ {+ "name": "lordos_0.8.1_arm64.spdx.json",+ "size": 56126+ },+ {+ "name": "SHA256SUMS",+ "size": 636+ },+ {+ "name": "SHA256SUMS.sig",+ "size": 89+ }+ ]+ },+ {+ "tag_name": "v0.8.0-beta",+ "published_at": "2026-10-18T21:51:52Z",+ "prerelease": true,+ "draft": false,+ "assets": [+ {+ "name": "install.sh",+ "size": 48422+ },+ {+ "name": "lordos-0.8.0-rpi5-arm64.img.xz",+ "size": 532884784+ },+ {+ "name": "lordos-live-0.8.0-amd64.iso",+ "size": 1041377280+ },+ {+ "name": "lordos-release.pub.pem",+ "size": 113+ },+ {+ "name": "lordos_0.8.0_amd64.deb",+ "size": 6267748+ },+ {+ "name": "lordos_0.8.0_amd64.spdx.json",+ "size": 58604+ },+ {+ "name": "lordos_0.8.0_arm64.deb",+ "size": 6011900+ },+ {+ "name": "lordos_0.8.0_arm64.spdx.json",+ "size": 56121+ },+ {+ "name": "SHA256SUMS",+ "size": 636+ },+ {+ "name": "SHA256SUMS.sig",+ "size": 89+ }+ ]+ }+]diff --git a/server/tests/imager_core_test.mjs b/server/tests/imager_core_test.mjsnew file mode 100644index 0000000..79c4813--- /dev/null+++ b/server/tests/imager_core_test.mjs@@ -0,0 +1,119 @@+// imager_core_test.mjs — the LordOS Imager's shared logic (apps/imager/core): validators, the+// first-run file it writes, profiles without secrets, and the GitHub release list. Every file the+// serializer writes is also checked by the C parser the board uses (build/firstrun-test check), so+// the two can't drift apart.+//+// node tests/imager_core_test.mjs (from server/; run_suites.sh runs it when node exists)+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';++const here = path.dirname(fileURLToPath(import.meta.url));+const core = (f) => import(path.join(here, '../../apps/imager/core', f));+const v = await core('validate.js');+const fr = await core('firstrun.js');+const rel = await core('releases.js');+const cat = await core('catalog.js');++let n = 0, bad = 0;+const ok = (name, cond, info = '') => { n++; if (!cond) { bad++; console.log(`✗ ${name} ${info}`); } };++// ---- validators (the same cases as tests/firstrun_test.c) ----+for (const h of ['pi', 'living-room-pi5', 'a', 'pi5']) ok(`hostname ${h}`, v.hostname(h) === null);+for (const h of ['', '-pi', 'pi-', 'Pi', 'pi.local', 'pi_5', '12345', 'localhost', 'x'.repeat(64), 'piñ']) ok(`bad hostname ${h}`, v.hostname(h) !== null);+for (const u of ['ana', '_svc', 'ana-maria_2', 'a'.repeat(32)]) ok(`user ${u}`, v.username(u) === null);+for (const u of ['Ana', '1ana', '-ana', 'root', 'lordos', 'systemd-x', 'sudo', 'ana maria', '', 'a'.repeat(33)]) ok(`bad user ${u}`, v.username(u) !== null);+ok('suggest user', v.suggestUser('Ana Pérez') === 'ana');+ok('suggest user root → none', v.suggestUser('Root Admin') === '');+ok('suggest host', v.suggestHostname('Ana Pérez') === 'ana-perez-pi');+ok('fullname', v.fullname('Ana Pérez') === null && v.fullname('李小龍') === null);+for (const f of ['Ana:0', 'Ana, Room', ' Ana', 'Ana\u0001', 'AB', '-o']) ok(`bad fullname ${JSON.stringify(f)}`, v.fullname(f) !== null);+ok('ssid', v.ssid('My Red ❤') === null && v.utf8('My Red ❤').length === 10);+ok('ssid 33 bytes', v.ssid('é'.repeat(17)) !== null);+ok('wifi pass', v.wifiPassword('hunter22') === null && v.wifiPassword('short') !== null && v.wifiPassword('ñandú-ñandú') !== null && v.wifiPassword('x'.repeat(64)) !== null);+ok('password mismatch', v.password('a', 'b') === 'imager.err.passMismatch');+ok('strength common', v.strength('raspberry').score === 0);+ok('strength strong', v.strength('correct-Horse-battery-9').score >= 3);+ok('zone', v.timezone('America/Argentina/Buenos_Aires') === null && v.timezone('../etc') !== null && v.timezone('Europe//X') !== null);++const ED = 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIF8zdvpQ/Ic++n9TOGaDGEe9/+IRgtRBf1H86da41yJ8 ana@laptop';+const EC = 'ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBBwbMKUZp+OoFOXG9AqteOZlGM/WkyBjc1CpgUqvgeHFv2kzd7XYR87xzMpqjVv57J4/d1776zu3hG/O3KNB+EY= ';+ok('ed25519 key', v.sshKey(ED).line === ED);+ok('ecdsa key, trailing space trimmed', v.sshKey(EC).line === EC.trim());+ok('key with options refused', !!v.sshKey(`command="/bin/sh" ${ED}`).error);+ok('dss refused', v.sshKey('ssh-dss AAAAB3NzaC1kc3MAAACB').error === 'imager.err.keyDss');+ok('type mismatch', !!v.sshKey(ED.replace('ssh-ed25519', 'ssh-rsa')).error);+ok('truncated key', !!v.sshKey(ED.slice(0, 70)).error);+const many = v.sshKeys(`# my keys\n${ED}\n\n${EC}\n${ED}\nnot a key\n`);+ok('key list', many.keys.length === 2 && many.errors.length === 1);++// ---- the first-run file ----+const H = '$6$rounds=10000$saltstringsaltst$OW1/O6BYHV6BcXZu8QVeXbDWra3Oeqh0sbHbbMCVNSnCM/UrjmM0Dp8vOuZeHBy/YTBmSK6H9qs/y3RnOaw5v.';+const PSK = 'f42c6fc52df0ebef9ebb4b90b38a5f902e83fe1b135a70e23aed762e9710a12e';+const full = {+ ...cat.defaultConfig(), hostname: 'pi-living', lang: 'es', timezone: 'America/Argentina/Buenos_Aires', keyboard: 'latam', variant: '',+ wifiCountry: 'AR', user: { name: 'ana', fullname: 'Ana Pérez', autologin: false },+ wifi: { enabled: true, ssid: 'My Red ❤', hidden: true, open: false }, ssh: 'keys', sshKeys: [v.sshKey(ED), v.sshKey(EC)],+ remote: true, bluetooth: false, theme: 'classic', mode: 'light', accent: 'violeta', wallpaper: 'lumo-celestial',+ cooler: 'active-cooler', performance: 'performance', overclock: true, autoUpdates: true,+};+ok('check full', fr.check(full, { passwordHash: H, psk: PSK }).length === 0, JSON.stringify(fr.check(full, { passwordHash: H, psk: PSK })));+const text = fr.build(full, { passwordHash: H, psk: PSK });+ok('no plain secrets', !/password=|wifi_password|hunter/.test(text));+ok('ssid as hex', text.includes('wifi_ssid_hex=4d792052656420e29da4\n'));+ok('two keys', text.split('\nssh_key=').length === 3);+const minimal = fr.build({ ...cat.defaultConfig(), hostname: 'pi' }, {});+ok('minimal has no user lines', !/user=|ssh=|remote_desktop/.test(minimal));+let threw = '';+try { fr.build({ ...full }, { psk: PSK }); } catch (e) { threw = e.message; }+ok('a user without a hash is refused', threw === 'imager.err.passEmpty');+ok('overclock without a fan is caught', fr.check({ ...full, cooler: 'passive' }, { passwordHash: H, psk: PSK }).some((p) => p.field === 'overclock'));+ok('ssh keys without keys is caught', fr.check({ ...full, sshKeys: [] }, { passwordHash: H, psk: PSK }).some((p) => p.key === 'imager.err.sshNeedsKey'));+const openNet = fr.build({ ...cat.defaultConfig(), wifi: { enabled: true, ssid: 'Cafe', hidden: false, open: true } }, {});+ok('open network: no psk line', openNet.includes('wifi_ssid_hex=43616665') && !openNet.includes('wifi_psk'));++// the C parser accepts every file the serializer writes+const cbin = path.join(here, '../build/firstrun-test');+if (fs.existsSync(cbin)) {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'imager-core-'));+ const cases = [+ ['full', text], ['minimal', minimal], ['open', openNet],+ ['no cooling', fr.build({ ...cat.defaultConfig(), cooler: 'none', performance: 'conservative' }, {})],+ ['user only', fr.build({ ...cat.defaultConfig(), user: { name: 'bob', fullname: '', autologin: true }, ssh: 'password' }, { passwordHash: H })],+ ['defaults', fr.build(cat.defaultConfig(), {})],+ ];+ for (const [name, body] of cases) {+ const f = path.join(tmp, `${name.replace(/ /g, '-')}.txt`);+ fs.writeFileSync(f, body);+ let out = '';+ try { out = execFileSync(cbin, ['check', f], { encoding: 'utf8' }).trim(); } catch (e) { out = String(e.stdout || e).trim(); }+ ok(`C parser accepts "${name}"`, out === 'ok', out);+ }+ fs.rmSync(tmp, { recursive: true, force: true });+} else console.log(' (build/firstrun-test not built: the C cross-check is skipped)');++// ---- profiles never keep secrets ----+const prof = fr.toProfile('Living room', { ...full, passwordHash: H });+const ps = JSON.stringify(prof);+ok('profile has no hash or psk', !ps.includes(H) && !ps.includes(PSK) && !/password|psk/i.test(ps));+const back = fr.fromProfile(JSON.parse(ps), cat.defaultConfig());+ok('profile round trip', back.hostname === 'pi-living' && back.user.name === 'ana' && back.sshKeys.length === 2 && back.wifi.ssid === 'My Red ❤');+ok('foreign profile refused', fr.fromProfile({ format: 'x' }, cat.defaultConfig()) === null);++// ---- the release list ----+const list = rel.parseReleases(fs.readFileSync(path.join(here, 'imager/releases.json'), 'utf8'), 'rpi5');+ok('releases found', list.length >= 3, String(list.length));+ok('newest first', list[0].tag === 'v0.8.3-beta' && list[0].image.name === 'lordos-0.8.3-rpi5-arm64.img.xz' && list[0].image.size === 558119764);+ok('signature files', list.every((r) => r.sums.name === 'SHA256SUMS' && r.sig.name === 'SHA256SUMS.sig'));+const pc = rel.parseReleases(fs.readFileSync(path.join(here, 'imager/releases.json'), 'utf8'), 'pc');+ok('pc iso', pc[0].image.name === 'lordos-live-0.8.3-amd64.iso');+ok('garbage list', rel.parseReleases('nope', 'rpi5').length === 0 && rel.parseReleases('{}', 'rpi5').length === 0);+ok('hostile names dropped', rel.parseReleases([{ tag_name: 'v1.0.0', assets: [{ name: '../lordos-1.0.0-rpi5-arm64.img.xz', size: 5 }, { name: 'SHA256SUMS', size: 5 }, { name: 'SHA256SUMS.sig', size: 5 }] }], 'rpi5').length === 0);+ok('bad tag dropped', rel.parseReleases([{ tag_name: 'v1.0.0/../x', assets: [] }], 'rpi5').length === 0);+ok('fits', rel.fits(2.8e9, 4e9) === 'yes' && rel.fits(2.8e9, 2.9e9) === 'tight' && rel.fits(3e9, 2e9) === 'no');+ok('download url', rel.downloadUrl('v0.8.3-beta', 'SHA256SUMS') === 'https://github.com/lordbasex/LordOS/releases/download/v0.8.3-beta/SHA256SUMS');++console.log(`imager-core-test: ${n} checks, ${bad} failed`);+process.exit(bad ? 1 : 0);diff --git a/server/tests/run_suites.sh b/server/tests/run_suites.shindex 978a88b..8a5aaf4 100644--- a/server/tests/run_suites.sh+++ b/server/tests/run_suites.sh@@ -162,6 +162,9 @@ EOF# the Store's "Suggested for your computer" rules (assets/store/suggestions.json)if have node; then run "suggest-engine-test (sdk/suggestengine.js)" node tests/suggest_engine_test.mjselse skip "suggest-engine-test" "node"; fi+ # the LordOS Imager's shared logic (apps/imager/core) and its first-run files checked by the C parser+ if have node; then run "imager-core-test (apps/imager/core)" node tests/imager_core_test.mjs+ else skip "imager-core-test" "node"; fi# the overlay scroll bar's model (sdk/scrollbar.js): geometry, thumb hit-test and drag, fade timingif have node; then run "scrollbar-model-test (sdk/scrollbar.js)" node tests/scrollbar_model_test.mjselse skip "scrollbar-model-test" "node"; fidiff --git a/tools/iso/mkdeb.sh b/tools/iso/mkdeb.shindex 86aea56..1e71331 100755--- a/tools/iso/mkdeb.sh+++ b/tools/iso/mkdeb.sh@@ -55,6 +55,8 @@ install -m 755 server/build/lord-sessiond "$L/bin/lord-sessiond"install -m 755 server/build/lord-netd "$L/bin/lord-netd"install -m 755 server/build/lord-netperm "$L/bin/lord-netperm"install -m 755 server/build/lord-fand "$L/bin/lord-fand"+# the LordOS Imager's first-run file applier (Raspberry Pi image, rpi/firstboot; docs/IMAGER.md)+install -m 755 server/build/lordos-firstrun "$L/bin/lordos-firstrun"# isolated PDF and archive helper (optional: make skips it without libpoppler-glib-dev/libarchive-dev);# lord-server only launches the lord-doc in its own folder[ -x server/build/lord-doc ] && install -m 755 server/build/lord-doc "$L/bin/lord-doc"diff --git a/tools/rpi/rootfs/usr/lib/lordos/rpi/firstboot b/tools/rpi/rootfs/usr/lib/lordos/rpi/firstbootindex e9fe9a2..02e82f0 100755--- a/tools/rpi/rootfs/usr/lib/lordos/rpi/firstboot+++ b/tools/rpi/rootfs/usr/lib/lordos/rpi/firstboot@@ -4,6 +4,11 @@## 1. First boot: grows the system partition (number 2) to the end of the SD card or NVMe.# 2. First boot: the user.+# 0) If the boot partition has a lordos-firstrun.txt (written by the LordOS Imager,+# docs/IMAGER.md), /usr/lib/lordos/bin/lordos-firstrun validates it strictly and applies it+# once (computer name, language, time zone, keyboard, Wi-Fi, user, SSH, remote desktop,+# Bluetooth, appearance, cooling), then shreds it. If it is invalid, nothing of it is applied+# and the steps below run as if it weren't there.# a) If the boot partition (/boot/firmware) has a lordos-user.txt (or the userconf.txt# from Raspberry Pi Imager / Raspberry Pi OS: «user:hash»), that user is created with the same# rules as the installer's «User» step (docs/ISO.md, install.c) and the file is deleted.@@ -132,7 +137,27 @@ wifi_from() {fi}-# ---- 2. first boot: the user ----+# ---- 2. first boot: the LordOS Imager's first-run file, then the user ----+FIRSTRUN=/usr/lib/lordos/bin/lordos-firstrun+if [ -e "$STATE/firstboot-pending" ] && [ -f "$BOOT/lordos-firstrun.txt" ]; then+ if [ -x "$FIRSTRUN" ]; then+ log "applying lordos-firstrun.txt (LordOS Imager)"+ "$FIRSTRUN" apply "$BOOT/lordos-firstrun.txt"+ RC=$?+ else+ log "lordos-firstrun.txt found but this image has no lordos-firstrun: ignored"+ RC=1+ fi+ # it is shredded by lordos-firstrun; never leave it behind+ [ -e "$BOOT/lordos-firstrun.txt" ] && { dd if=/dev/zero of="$BOOT/lordos-firstrun.txt" bs=1 count="$(stat -c %s "$BOOT/lordos-firstrun.txt")" conv=notrunc 2>/dev/null; rm -f "$BOOT/lordos-firstrun.txt"; }+ if [ "$RC" = 0 ]; then+ # the account exists (and session.conf says whether it logs in automatically)+ drop_setup_user+ rm -f "$STATE/setup-mode" "$STATE/firstboot-pending"+ rm -f "$BOOT/lordos-user.txt" "$BOOT/userconf.txt"+ sync+ fi+fiif [ -e "$STATE/firstboot-pending" ]; thenF=""[ -f "$BOOT/lordos-user.txt" ] && F="$BOOT/lordos-user.txt"