diff --git a/Core/Api/ExtensionEndpoints.cs b/Core/Api/ExtensionEndpoints.cs index a967057..8ff3b3f 100644 --- a/Core/Api/ExtensionEndpoints.cs +++ b/Core/Api/ExtensionEndpoints.cs @@ -52,6 +52,24 @@ Acepta un enlace de GitHub (owner/repo, …/tree/ref/carpeta, …/releases/tag/x g.MapGet("/{id}/log", (string id, ExtensionManager m) => TypedResults.Ok(new ExtensionLogResponse(m.GetLog(id)))) .WithSummary("Registro de scripts de la extensión"); + // Iconos: imágenes de terceros. Con "sandbox" y nosniff, un SVG abierto fuera de un + // no puede ejecutar nada con el origen del panel. + g.MapGet("/{id}/icon", (string id, HttpContext ctx, ExtensionManager m) => + { + var file = m.ResolveIconFile(id); + if (file is null) return Results.NotFound(); + IconHeaders(ctx); + return Results.File(file, ExtensionFormat.IconContentType(file)); + }).WithSummary("Icono de una extensión instalada"); + + g.MapGet("/catalogs/icon", async (string url, int index, HttpContext ctx, ExtensionManager m, CancellationToken ct) => + { + var icon = await m.GetCatalogIconAsync(url, index, ct); + if (icon is not { } i) return Results.NotFound(); + IconHeaders(ctx); + return Results.Bytes(i.Bytes, i.ContentType); + }).WithSummary("Icono de una entrada de catálogo (se descarga de GitHub y se guarda una hora)"); + g.MapGet("/catalogs", (bool? refresh, ExtensionManager m, CancellationToken ct) => Guard(async () => Results.Ok(await m.GetCatalogsAsync(refresh == true, ct)))) .WithSummary("Catálogos y sus extensiones"); @@ -84,6 +102,16 @@ Acepta un enlace de GitHub (owner/repo, …/tree/ref/carpeta, …/releases/tag/x return app; } + static void IconHeaders(HttpContext ctx) + { + var h = ctx.Response.Headers; + h["Content-Security-Policy"] = "default-src 'none'; style-src 'unsafe-inline'; sandbox"; + h["X-Content-Type-Options"] = "nosniff"; + h["Cross-Origin-Resource-Policy"] = "same-origin"; + // La URL lleva la versión (?v=), así que puede guardarse. + h["Cache-Control"] = "private, max-age=86400"; + } + /// Errores esperables → 400/409/502 con el mensaje (ya traducido), no un 500. static async Task Guard(Func> action) { diff --git a/Core/wwwroot/extensions.js b/Core/wwwroot/extensions.js index 1b33f0d..6da0643 100644 --- a/Core/wwwroot/extensions.js +++ b/Core/wwwroot/extensions.js @@ -9,7 +9,73 @@ let extTimer = null; let extPreview = null; // vista previa en el modal de instalación let extOpWatch = null; // sondeo mientras corre una operación +// Categorías que entiende el panel, en el orden del backend (ExtensionFormat.KnownCategories). +const EXT_CATEGORIES = ['remote-desktop', 'streaming', 'display', 'input', 'audio', 'network', 'games', 'monitoring', 'tools']; +let extCategory = ''; // filtro elegido ('' = todas); se recuerda en este navegador +try { extCategory = localStorage.getItem('osms.ext.category') || ''; } catch { /* sin almacenamiento */ } + function extCapLabel(cap) { return t(`ext.cap.${cap}`); } +function extCategoryLabel(cat) { return t(`ext.category.${cat}`); } + +// Entrada de catálogo de una instalada (para lo que no trae su manifiesto). +function extCatalogEntryOf(x) { + for (const c of extCatalogs) + for (const e of c.extensions || []) + if (e.installedId === x.id) return e; + return null; +} + +// Categorías e icono de una instalada: los suyos o, si no trae, los que le da su catálogo. +function extInstalledCategories(x) { + if (x.categories && x.categories.length) return x.categories; + const e = extCatalogEntryOf(x); + return e && e.categories ? e.categories : []; +} + +function extInstalledIcon(x) { + return x.iconUrl || (extCatalogEntryOf(x) || {}).iconUrl || null; +} + +function extIcon(url, name) { + const letter = esc((name || '?').trim().charAt(0).toUpperCase() || '?'); + // Si la imagen no carga, se queda la inicial (está debajo). + return ``; +} + +function extCategoryChips(cats) { + return (cats || []).map(c => `${esc(extCategoryLabel(c))}`).join(''); +} + +function setExtCategory(cat) { + extCategory = cat; + try { cat ? localStorage.setItem('osms.ext.category', cat) : localStorage.removeItem('osms.ext.category'); } catch { /* idem */ } + renderExtensions(); +} + +// Barra de filtros: "Todas" y cada categoría que tenga alguna extensión (instalada o en catálogos). +function renderExtCategoryBar(installed, available) { + const counts = new Map(); + const seen = new Set(); + const add = (key, cats) => { + if (seen.has(key)) return; + seen.add(key); + for (const c of cats) counts.set(c, (counts.get(c) || 0) + 1); + }; + for (const x of installed) add(`i:${x.id}`, extInstalledCategories(x)); + for (const { e } of available) add(e.installedId ? `i:${e.installedId}` : `c:${e.repo}/${e.path || ''}`, e.categories || []); + + const present = EXT_CATEGORIES.filter(c => counts.has(c)); + if (extCategory && !present.includes(extCategory)) extCategory = ''; + const bar = byId('ext-categories'); + if (!present.length) { bar.classList.add('hidden'); renderInto(bar, ''); return; } + bar.classList.remove('hidden'); + const btn = (cat, label, n) => + ``; + renderInto(bar, btn('', t('ext.categoryAll'), seen.size) + + present.map(c => btn(c, extCategoryLabel(c), counts.get(c))).join('')); +} async function loadExtensions() { const res = await api('GET', '/api/extensions'); @@ -29,24 +95,35 @@ async function loadExtensionCatalogs(refresh = false) { // ── Vista principal ───────────────────────────────────────────────────────── function renderExtensions() { - const list = extState.installed || []; - byId('ext-count').textContent = list.length; - renderInto(byId('ext-installed-grid'), list.length - ? list.map(extCard).join('') - : `

${esc(t('ext.noneInstalled'))}

`); + const all = extState.installed || []; + byId('ext-count').textContent = all.length; const q = (byId('ext-search').value || '').trim().toLowerCase(); - const rows = []; + const allRows = []; for (const c of extCatalogs) { for (const e of c.extensions || []) { - const text = `${e.name} ${e.description || ''} ${e.repo} ${(e.tags || []).join(' ')}`.toLowerCase(); - if (!q || text.includes(q)) rows.push({ c, e }); + const cats = (e.categories || []).map(extCategoryLabel).join(' '); + const text = `${e.name} ${e.description || ''} ${e.repo} ${(e.tags || []).join(' ')} ${cats}`.toLowerCase(); + if (!q || text.includes(q)) allRows.push({ c, e }); } } + renderExtCategoryBar(all, allRows); + + const inCategory = cats => !extCategory || cats.includes(extCategory); + const list = all.filter(x => inCategory(extInstalledCategories(x))); + const rows = allRows.filter(({ e }) => inCategory(e.categories || [])); + const emptyFiltered = `

${esc(t('ext.noneInCategory', { category: extCategoryLabel(extCategory) }))}

`; + + renderInto(byId('ext-installed-grid'), list.length + ? list.map(extCard).join('') + : all.length && extCategory ? emptyFiltered + : `

${esc(t('ext.noneInstalled'))}

`); + const errors = extCatalogs.filter(c => c.error) .map(c => `
${esc(c.name)}: ${esc(t('ext.catalogError', { msg: c.error }))}
`).join(''); renderInto(byId('ext-available-grid'), errors + (rows.length ? rows.map(({ c, e }) => extCatalogCard(c, e)).join('') + : allRows.length && extCategory ? emptyFiltered : `

${esc(t('ext.noneAvailable'))}

`)); } @@ -63,6 +140,7 @@ function extCard(x) { const cat = extCatalogs.find(c => c.url === x.catalogUrl); return `
+ ${extIcon(extInstalledIcon(x), x.name)}
${esc(x.name)}
${esc(x.version)} · ${esc(x.repo)}${ @@ -71,7 +149,7 @@ function extCard(x) {
${x.description ? `

${esc(x.description)}

` : ''} -
${extChips(x.capabilities)}${status.join('')}${ +
${extCategoryChips(extInstalledCategories(x))}${extChips(x.capabilities)}${status.join('')}${ cat ? `${esc(t('ext.fromCatalog', { catalog: cat.name }))}` : ''}
`; } @@ -83,6 +161,7 @@ function extCatalogCard(c, e) { const args = JSON.stringify({ source: e.repo, path: e.path, catalogUrl: c.url }).replace(/"/g, '"'); return `
+

Instaladas

Cargando…

diff --git a/Core/wwwroot/locales/bg.json b/Core/wwwroot/locales/bg.json index 9104823..c4747ef 100644 --- a/Core/wwwroot/locales/bg.json +++ b/Core/wwwroot/locales/bg.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Вашите каталози не съдържат разширения.", "ext.search": "Търсене…", "ext.refresh": "Опресняване", + "ext.categories": "Категории", + "ext.categoryAll": "Всички", + "ext.noneInCategory": "Няма разширения в „{category}“.", + "ext.category.remote-desktop": "Отдалечен работен плот", + "ext.category.streaming": "Стрийминг", + "ext.category.display": "Дисплеи", + "ext.category.input": "Контролери и въвеждане", + "ext.category.audio": "Звук", + "ext.category.network": "Мрежа", + "ext.category.games": "Игри", + "ext.category.monitoring": "Наблюдение", + "ext.category.tools": "Инструменти", "ext.cap.component": "Инсталира софтуер", "ext.cap.component_desc": "Изпълнява инсталационния си скрипт като SYSTEM, с пълен контрол над този компютър.", "ext.cap.hooks": "Скриптове за сесии", diff --git a/Core/wwwroot/locales/cs.json b/Core/wwwroot/locales/cs.json index 83899f2..9d4daed 100644 --- a/Core/wwwroot/locales/cs.json +++ b/Core/wwwroot/locales/cs.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Vaše katalogy neobsahují žádná rozšíření.", "ext.search": "Hledat…", "ext.refresh": "Obnovit", + "ext.categories": "Kategorie", + "ext.categoryAll": "Vše", + "ext.noneInCategory": "V kategorii „{category}“ nejsou žádná rozšíření.", + "ext.category.remote-desktop": "Vzdálená plocha", + "ext.category.streaming": "Streamování", + "ext.category.display": "Displeje", + "ext.category.input": "Ovladače a vstup", + "ext.category.audio": "Zvuk", + "ext.category.network": "Síť", + "ext.category.games": "Hry", + "ext.category.monitoring": "Monitorování", + "ext.category.tools": "Nástroje", "ext.cap.component": "Instaluje software", "ext.cap.component_desc": "Spouští svůj instalační skript jako SYSTEM, s plnou kontrolou nad tímto PC.", "ext.cap.hooks": "Skripty relací", diff --git a/Core/wwwroot/locales/de.json b/Core/wwwroot/locales/de.json index b71fd9d..a3cf584 100644 --- a/Core/wwwroot/locales/de.json +++ b/Core/wwwroot/locales/de.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Deine Kataloge enthalten keine Erweiterungen.", "ext.search": "Suchen…", "ext.refresh": "Aktualisieren", + "ext.categories": "Kategorien", + "ext.categoryAll": "Alle", + "ext.noneInCategory": "Keine Erweiterungen in „{category}“.", + "ext.category.remote-desktop": "Remotedesktop", + "ext.category.streaming": "Streaming", + "ext.category.display": "Anzeigen", + "ext.category.input": "Controller und Eingabe", + "ext.category.audio": "Audio", + "ext.category.network": "Netzwerk", + "ext.category.games": "Spiele", + "ext.category.monitoring": "Überwachung", + "ext.category.tools": "Werkzeuge", "ext.cap.component": "Installiert Software", "ext.cap.component_desc": "Führt sein Installationsskript als SYSTEM aus, mit voller Kontrolle über diesen PC.", "ext.cap.hooks": "Sitzungsskripte", diff --git a/Core/wwwroot/locales/en.json b/Core/wwwroot/locales/en.json index be7224f..3263e1a 100644 --- a/Core/wwwroot/locales/en.json +++ b/Core/wwwroot/locales/en.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Your catalogs don't list any extensions.", "ext.search": "Search…", "ext.refresh": "Refresh", + "ext.categories": "Categories", + "ext.categoryAll": "All", + "ext.noneInCategory": "No extensions in “{category}”.", + "ext.category.remote-desktop": "Remote desktop", + "ext.category.streaming": "Streaming", + "ext.category.display": "Displays", + "ext.category.input": "Controllers and input", + "ext.category.audio": "Audio", + "ext.category.network": "Network", + "ext.category.games": "Games", + "ext.category.monitoring": "Monitoring", + "ext.category.tools": "Tools", "ext.cap.component": "Installs software", "ext.cap.component_desc": "Runs its install script as SYSTEM, with full control of this PC.", "ext.cap.hooks": "Session scripts", diff --git a/Core/wwwroot/locales/en_GB.json b/Core/wwwroot/locales/en_GB.json index 5d0f6a5..94271b0 100644 --- a/Core/wwwroot/locales/en_GB.json +++ b/Core/wwwroot/locales/en_GB.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Your catalogues don't list any extensions.", "ext.search": "Search…", "ext.refresh": "Refresh", + "ext.categories": "Categories", + "ext.categoryAll": "All", + "ext.noneInCategory": "No extensions in “{category}”.", + "ext.category.remote-desktop": "Remote desktop", + "ext.category.streaming": "Streaming", + "ext.category.display": "Displays", + "ext.category.input": "Controllers and input", + "ext.category.audio": "Audio", + "ext.category.network": "Network", + "ext.category.games": "Games", + "ext.category.monitoring": "Monitoring", + "ext.category.tools": "Tools", "ext.cap.component": "Installs software", "ext.cap.component_desc": "Runs its install script as SYSTEM, with full control of this PC.", "ext.cap.hooks": "Session scripts", diff --git a/Core/wwwroot/locales/en_US.json b/Core/wwwroot/locales/en_US.json index edb5462..4a07ac4 100644 --- a/Core/wwwroot/locales/en_US.json +++ b/Core/wwwroot/locales/en_US.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Your catalogs don't list any extensions.", "ext.search": "Search…", "ext.refresh": "Refresh", + "ext.categories": "Categories", + "ext.categoryAll": "All", + "ext.noneInCategory": "No extensions in “{category}”.", + "ext.category.remote-desktop": "Remote desktop", + "ext.category.streaming": "Streaming", + "ext.category.display": "Displays", + "ext.category.input": "Controllers and input", + "ext.category.audio": "Audio", + "ext.category.network": "Network", + "ext.category.games": "Games", + "ext.category.monitoring": "Monitoring", + "ext.category.tools": "Tools", "ext.cap.component": "Installs software", "ext.cap.component_desc": "Runs its install script as SYSTEM, with full control of this PC.", "ext.cap.hooks": "Session scripts", diff --git a/Core/wwwroot/locales/es.json b/Core/wwwroot/locales/es.json index d3bf08b..0fbdf49 100644 --- a/Core/wwwroot/locales/es.json +++ b/Core/wwwroot/locales/es.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Tus catálogos no tienen extensiones.", "ext.search": "Buscar…", "ext.refresh": "Actualizar", + "ext.categories": "Categorías", + "ext.categoryAll": "Todas", + "ext.noneInCategory": "No hay extensiones en «{category}».", + "ext.category.remote-desktop": "Escritorio remoto", + "ext.category.streaming": "Streaming", + "ext.category.display": "Pantallas", + "ext.category.input": "Mandos y entrada", + "ext.category.audio": "Audio", + "ext.category.network": "Red", + "ext.category.games": "Juegos", + "ext.category.monitoring": "Monitorización", + "ext.category.tools": "Herramientas", "ext.cap.component": "Instala software", "ext.cap.component_desc": "Ejecuta su script de instalación como SYSTEM, con control total del PC.", "ext.cap.hooks": "Scripts de sesión", diff --git a/Core/wwwroot/locales/fr.json b/Core/wwwroot/locales/fr.json index 839b298..64e0eff 100644 --- a/Core/wwwroot/locales/fr.json +++ b/Core/wwwroot/locales/fr.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Vos catalogues ne proposent aucune extension.", "ext.search": "Rechercher…", "ext.refresh": "Actualiser", + "ext.categories": "Catégories", + "ext.categoryAll": "Toutes", + "ext.noneInCategory": "Aucune extension dans « {category} ».", + "ext.category.remote-desktop": "Bureau à distance", + "ext.category.streaming": "Streaming", + "ext.category.display": "Écrans", + "ext.category.input": "Manettes et saisie", + "ext.category.audio": "Audio", + "ext.category.network": "Réseau", + "ext.category.games": "Jeux", + "ext.category.monitoring": "Supervision", + "ext.category.tools": "Outils", "ext.cap.component": "Installe des logiciels", "ext.cap.component_desc": "Exécute son script d'installation en tant que SYSTEM, avec un contrôle total de ce PC.", "ext.cap.hooks": "Scripts de session", diff --git a/Core/wwwroot/locales/hu.json b/Core/wwwroot/locales/hu.json index bb4382b..8b3fdb8 100644 --- a/Core/wwwroot/locales/hu.json +++ b/Core/wwwroot/locales/hu.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "A katalógusaid nem tartalmaznak bővítményt.", "ext.search": "Keresés…", "ext.refresh": "Frissítés", + "ext.categories": "Kategóriák", + "ext.categoryAll": "Összes", + "ext.noneInCategory": "Nincs bővítmény a(z) „{category}” kategóriában.", + "ext.category.remote-desktop": "Távoli asztal", + "ext.category.streaming": "Streamelés", + "ext.category.display": "Kijelzők", + "ext.category.input": "Kontrollerek és bevitel", + "ext.category.audio": "Hang", + "ext.category.network": "Hálózat", + "ext.category.games": "Játékok", + "ext.category.monitoring": "Megfigyelés", + "ext.category.tools": "Eszközök", "ext.cap.component": "Szoftvert telepít", "ext.cap.component_desc": "A telepítőszkriptjét SYSTEM-ként futtatja, teljes hozzáféréssel ehhez a PC-hez.", "ext.cap.hooks": "Munkamenet-szkriptek", diff --git a/Core/wwwroot/locales/it.json b/Core/wwwroot/locales/it.json index 0cba019..a35a30c 100644 --- a/Core/wwwroot/locales/it.json +++ b/Core/wwwroot/locales/it.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "I tuoi cataloghi non elencano estensioni.", "ext.search": "Cerca…", "ext.refresh": "Aggiorna", + "ext.categories": "Categorie", + "ext.categoryAll": "Tutte", + "ext.noneInCategory": "Nessuna estensione in «{category}».", + "ext.category.remote-desktop": "Desktop remoto", + "ext.category.streaming": "Streaming", + "ext.category.display": "Schermi", + "ext.category.input": "Controller e input", + "ext.category.audio": "Audio", + "ext.category.network": "Rete", + "ext.category.games": "Giochi", + "ext.category.monitoring": "Monitoraggio", + "ext.category.tools": "Strumenti", "ext.cap.component": "Installa software", "ext.cap.component_desc": "Esegue il suo script di installazione come SYSTEM, con pieno controllo di questo PC.", "ext.cap.hooks": "Script di sessione", diff --git a/Core/wwwroot/locales/ja.json b/Core/wwwroot/locales/ja.json index 9faf60e..881f3ce 100644 --- a/Core/wwwroot/locales/ja.json +++ b/Core/wwwroot/locales/ja.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "カタログに拡張機能がありません。", "ext.search": "検索…", "ext.refresh": "更新", + "ext.categories": "カテゴリ", + "ext.categoryAll": "すべて", + "ext.noneInCategory": "「{category}」の拡張機能はありません。", + "ext.category.remote-desktop": "リモート デスクトップ", + "ext.category.streaming": "ストリーミング", + "ext.category.display": "ディスプレイ", + "ext.category.input": "コントローラーと入力", + "ext.category.audio": "オーディオ", + "ext.category.network": "ネットワーク", + "ext.category.games": "ゲーム", + "ext.category.monitoring": "モニタリング", + "ext.category.tools": "ツール", "ext.cap.component": "ソフトウェアをインストール", "ext.cap.component_desc": "インストールスクリプトを SYSTEM として実行し、この PC を完全に制御します。", "ext.cap.hooks": "セッションスクリプト", diff --git a/Core/wwwroot/locales/ko.json b/Core/wwwroot/locales/ko.json index 1e4d94c..f804ead 100644 --- a/Core/wwwroot/locales/ko.json +++ b/Core/wwwroot/locales/ko.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "카탈로그에 확장이 없습니다.", "ext.search": "검색…", "ext.refresh": "새로 고침", + "ext.categories": "카테고리", + "ext.categoryAll": "전체", + "ext.noneInCategory": "'{category}'에 확장 프로그램이 없습니다.", + "ext.category.remote-desktop": "원격 데스크톱", + "ext.category.streaming": "스트리밍", + "ext.category.display": "디스플레이", + "ext.category.input": "컨트롤러 및 입력", + "ext.category.audio": "오디오", + "ext.category.network": "네트워크", + "ext.category.games": "게임", + "ext.category.monitoring": "모니터링", + "ext.category.tools": "도구", "ext.cap.component": "소프트웨어 설치", "ext.cap.component_desc": "설치 스크립트를 SYSTEM으로 실행하며, 이 PC를 완전히 제어합니다.", "ext.cap.hooks": "세션 스크립트", diff --git a/Core/wwwroot/locales/pl.json b/Core/wwwroot/locales/pl.json index bfa2290..5221866 100644 --- a/Core/wwwroot/locales/pl.json +++ b/Core/wwwroot/locales/pl.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Twoje katalogi nie zawierają żadnych rozszerzeń.", "ext.search": "Szukaj…", "ext.refresh": "Odśwież", + "ext.categories": "Kategorie", + "ext.categoryAll": "Wszystkie", + "ext.noneInCategory": "Brak rozszerzeń w kategorii „{category}”.", + "ext.category.remote-desktop": "Pulpit zdalny", + "ext.category.streaming": "Streaming", + "ext.category.display": "Ekrany", + "ext.category.input": "Kontrolery i wejście", + "ext.category.audio": "Dźwięk", + "ext.category.network": "Sieć", + "ext.category.games": "Gry", + "ext.category.monitoring": "Monitorowanie", + "ext.category.tools": "Narzędzia", "ext.cap.component": "Instaluje oprogramowanie", "ext.cap.component_desc": "Uruchamia swój skrypt instalacyjny jako SYSTEM, z pełną kontrolą nad tym komputerem.", "ext.cap.hooks": "Skrypty sesji", diff --git a/Core/wwwroot/locales/pt.json b/Core/wwwroot/locales/pt.json index 9a291e6..1b69c9e 100644 --- a/Core/wwwroot/locales/pt.json +++ b/Core/wwwroot/locales/pt.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Os seus catálogos não têm extensões.", "ext.search": "Pesquisar…", "ext.refresh": "Atualizar", + "ext.categories": "Categorias", + "ext.categoryAll": "Todas", + "ext.noneInCategory": "Não há extensões em «{category}».", + "ext.category.remote-desktop": "Ambiente de trabalho remoto", + "ext.category.streaming": "Streaming", + "ext.category.display": "Ecrãs", + "ext.category.input": "Comandos e entrada", + "ext.category.audio": "Áudio", + "ext.category.network": "Rede", + "ext.category.games": "Jogos", + "ext.category.monitoring": "Monitorização", + "ext.category.tools": "Ferramentas", "ext.cap.component": "Instala software", "ext.cap.component_desc": "Executa o seu script de instalação como SYSTEM, com controlo total deste PC.", "ext.cap.hooks": "Scripts de sessão", diff --git a/Core/wwwroot/locales/pt_BR.json b/Core/wwwroot/locales/pt_BR.json index e3e8892..af608cf 100644 --- a/Core/wwwroot/locales/pt_BR.json +++ b/Core/wwwroot/locales/pt_BR.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Seus catálogos não têm extensões.", "ext.search": "Pesquisar…", "ext.refresh": "Atualizar", + "ext.categories": "Categorias", + "ext.categoryAll": "Todas", + "ext.noneInCategory": "Nenhuma extensão em “{category}”.", + "ext.category.remote-desktop": "Área de trabalho remota", + "ext.category.streaming": "Streaming", + "ext.category.display": "Telas", + "ext.category.input": "Controles e entrada", + "ext.category.audio": "Áudio", + "ext.category.network": "Rede", + "ext.category.games": "Jogos", + "ext.category.monitoring": "Monitoramento", + "ext.category.tools": "Ferramentas", "ext.cap.component": "Instala software", "ext.cap.component_desc": "Executa seu script de instalação como SYSTEM, com controle total deste PC.", "ext.cap.hooks": "Scripts de sessão", diff --git a/Core/wwwroot/locales/ru.json b/Core/wwwroot/locales/ru.json index 3718c5a..a502a09 100644 --- a/Core/wwwroot/locales/ru.json +++ b/Core/wwwroot/locales/ru.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "В ваших каталогах нет расширений.", "ext.search": "Поиск…", "ext.refresh": "Обновить", + "ext.categories": "Категории", + "ext.categoryAll": "Все", + "ext.noneInCategory": "В категории «{category}» нет расширений.", + "ext.category.remote-desktop": "Удалённый рабочий стол", + "ext.category.streaming": "Стриминг", + "ext.category.display": "Дисплеи", + "ext.category.input": "Контроллеры и ввод", + "ext.category.audio": "Звук", + "ext.category.network": "Сеть", + "ext.category.games": "Игры", + "ext.category.monitoring": "Мониторинг", + "ext.category.tools": "Инструменты", "ext.cap.component": "Устанавливает ПО", "ext.cap.component_desc": "Запускает свой скрипт установки от имени SYSTEM с полным контролем над этим ПК.", "ext.cap.hooks": "Скрипты сеансов", diff --git a/Core/wwwroot/locales/sv.json b/Core/wwwroot/locales/sv.json index f1295e1..756c026 100644 --- a/Core/wwwroot/locales/sv.json +++ b/Core/wwwroot/locales/sv.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Dina kataloger innehåller inga tillägg.", "ext.search": "Sök…", "ext.refresh": "Uppdatera", + "ext.categories": "Kategorier", + "ext.categoryAll": "Alla", + "ext.noneInCategory": "Inga tillägg i ”{category}”.", + "ext.category.remote-desktop": "Fjärrskrivbord", + "ext.category.streaming": "Streaming", + "ext.category.display": "Skärmar", + "ext.category.input": "Handkontroller och inmatning", + "ext.category.audio": "Ljud", + "ext.category.network": "Nätverk", + "ext.category.games": "Spel", + "ext.category.monitoring": "Övervakning", + "ext.category.tools": "Verktyg", "ext.cap.component": "Installerar programvara", "ext.cap.component_desc": "Kör sitt installationsskript som SYSTEM, med full kontroll över den här datorn.", "ext.cap.hooks": "Sessionsskript", diff --git a/Core/wwwroot/locales/tr.json b/Core/wwwroot/locales/tr.json index 7ac04f0..3a24abf 100644 --- a/Core/wwwroot/locales/tr.json +++ b/Core/wwwroot/locales/tr.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Kataloglarınızda uzantı yok.", "ext.search": "Ara…", "ext.refresh": "Yenile", + "ext.categories": "Kategoriler", + "ext.categoryAll": "Tümü", + "ext.noneInCategory": "“{category}” kategorisinde uzantı yok.", + "ext.category.remote-desktop": "Uzak masaüstü", + "ext.category.streaming": "Yayın", + "ext.category.display": "Ekranlar", + "ext.category.input": "Oyun kumandaları ve giriş", + "ext.category.audio": "Ses", + "ext.category.network": "Ağ", + "ext.category.games": "Oyunlar", + "ext.category.monitoring": "İzleme", + "ext.category.tools": "Araçlar", "ext.cap.component": "Yazılım yükler", "ext.cap.component_desc": "Kurulum betiğini SYSTEM olarak, bu bilgisayar üzerinde tam denetimle çalıştırır.", "ext.cap.hooks": "Oturum betikleri", diff --git a/Core/wwwroot/locales/uk.json b/Core/wwwroot/locales/uk.json index 637806e..b9db9c1 100644 --- a/Core/wwwroot/locales/uk.json +++ b/Core/wwwroot/locales/uk.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "У ваших каталогах немає розширень.", "ext.search": "Пошук…", "ext.refresh": "Оновити", + "ext.categories": "Категорії", + "ext.categoryAll": "Усі", + "ext.noneInCategory": "У категорії «{category}» немає розширень.", + "ext.category.remote-desktop": "Віддалений робочий стіл", + "ext.category.streaming": "Стрімінг", + "ext.category.display": "Дисплеї", + "ext.category.input": "Контролери та введення", + "ext.category.audio": "Звук", + "ext.category.network": "Мережа", + "ext.category.games": "Ігри", + "ext.category.monitoring": "Моніторинг", + "ext.category.tools": "Інструменти", "ext.cap.component": "Встановлює ПЗ", "ext.cap.component_desc": "Запускає свій скрипт встановлення від імені SYSTEM з повним контролем над цим ПК.", "ext.cap.hooks": "Скрипти сеансів", diff --git a/Core/wwwroot/locales/vi.json b/Core/wwwroot/locales/vi.json index fb27639..14ab117 100644 --- a/Core/wwwroot/locales/vi.json +++ b/Core/wwwroot/locales/vi.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "Danh mục của bạn không có tiện ích mở rộng nào.", "ext.search": "Tìm kiếm…", "ext.refresh": "Làm mới", + "ext.categories": "Danh mục", + "ext.categoryAll": "Tất cả", + "ext.noneInCategory": "Không có tiện ích mở rộng nào trong “{category}”.", + "ext.category.remote-desktop": "Máy tính từ xa", + "ext.category.streaming": "Phát trực tuyến", + "ext.category.display": "Màn hình", + "ext.category.input": "Tay cầm và nhập liệu", + "ext.category.audio": "Âm thanh", + "ext.category.network": "Mạng", + "ext.category.games": "Trò chơi", + "ext.category.monitoring": "Giám sát", + "ext.category.tools": "Công cụ", "ext.cap.component": "Cài đặt phần mềm", "ext.cap.component_desc": "Chạy script cài đặt của nó với quyền SYSTEM, toàn quyền kiểm soát PC này.", "ext.cap.hooks": "Script phiên", diff --git a/Core/wwwroot/locales/zh.json b/Core/wwwroot/locales/zh.json index 5284205..d16ec42 100644 --- a/Core/wwwroot/locales/zh.json +++ b/Core/wwwroot/locales/zh.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "你的目录中没有扩展。", "ext.search": "搜索…", "ext.refresh": "刷新", + "ext.categories": "分类", + "ext.categoryAll": "全部", + "ext.noneInCategory": "“{category}”中没有扩展。", + "ext.category.remote-desktop": "远程桌面", + "ext.category.streaming": "串流", + "ext.category.display": "显示器", + "ext.category.input": "手柄和输入", + "ext.category.audio": "音频", + "ext.category.network": "网络", + "ext.category.games": "游戏", + "ext.category.monitoring": "监控", + "ext.category.tools": "工具", "ext.cap.component": "安装软件", "ext.cap.component_desc": "以 SYSTEM 身份运行其安装脚本,完全控制这台电脑。", "ext.cap.hooks": "会话脚本", diff --git a/Core/wwwroot/locales/zh_TW.json b/Core/wwwroot/locales/zh_TW.json index 0c15eed..e4906c7 100644 --- a/Core/wwwroot/locales/zh_TW.json +++ b/Core/wwwroot/locales/zh_TW.json @@ -788,6 +788,18 @@ "ext.noneAvailable": "你的目錄中沒有擴充功能。", "ext.search": "搜尋…", "ext.refresh": "重新整理", + "ext.categories": "分類", + "ext.categoryAll": "全部", + "ext.noneInCategory": "「{category}」中沒有擴充功能。", + "ext.category.remote-desktop": "遠端桌面", + "ext.category.streaming": "串流", + "ext.category.display": "顯示器", + "ext.category.input": "控制器與輸入", + "ext.category.audio": "音訊", + "ext.category.network": "網路", + "ext.category.games": "遊戲", + "ext.category.monitoring": "監控", + "ext.category.tools": "工具", "ext.cap.component": "安裝軟體", "ext.cap.component_desc": "以 SYSTEM 身分執行其安裝指令碼,完全控制這部電腦。", "ext.cap.hooks": "工作階段指令碼", diff --git a/Core/wwwroot/style.css b/Core/wwwroot/style.css index f404a58..ad26a2e 100644 --- a/Core/wwwroot/style.css +++ b/Core/wwwroot/style.css @@ -2221,6 +2221,22 @@ input[type="password"]:focus-visible, input[type="search"]:focus-visible { .ext-available-bar { margin-top: 1.4rem; } .ext-available-bar .ext-section-title { margin: 0; } .ext-card .ext-desc { color: var(--muted-h); font-size: .88rem; margin: .2rem 0 .6rem; } +.ext-card .card-header { justify-content: flex-start; } +.ext-card .card-title-wrap { flex: 1; min-width: 0; } +/* Icono: la inicial queda debajo y la imagen la tapa si carga. */ +.ext-icon { + position: relative; flex: none; width: 40px; height: 40px; border-radius: 10px; overflow: hidden; + display: flex; align-items: center; justify-content: center; + background: rgba(var(--c-accent),.12); border: 1px solid rgba(var(--c-ink),.08); + color: var(--accent-soft); font-weight: 700; font-size: 1.05rem; +} +.ext-icon img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; background: var(--surface, transparent); } +.ext-categories { display: flex; flex-wrap: wrap; gap: .4rem; margin: .9rem 0 .2rem; } +.chip.chip-btn { cursor: pointer; font: inherit; font-size: .78rem; } +.chip.chip-btn:hover { color: var(--text); border-color: rgba(var(--c-ink),.2); } +.chip.chip-btn.active { color: var(--text); border-color: rgba(var(--c-accent),.5); background: rgba(var(--c-accent),.14); } +.chip.chip-btn b { font-weight: 600; color: inherit; opacity: .7; } +.chip.chip-cat { color: var(--accent-soft); border-color: rgba(var(--c-accent),.3); } .ext-card .card-subtitle a { color: inherit; } .chip.chip-ok { color: var(--text); border-color: rgba(var(--c-ok),.45); background: rgba(var(--c-ok),.1); } .chip.chip-warn { color: var(--text); border-color: rgba(var(--c-orange),.45); background: rgba(var(--c-orange),.1); } diff --git a/Services/Extensions/ExtensionManager.cs b/Services/Extensions/ExtensionManager.cs index a38a9ec..4805011 100644 --- a/Services/Extensions/ExtensionManager.cs +++ b/Services/Extensions/ExtensionManager.cs @@ -66,7 +66,7 @@ public sealed record ExtensionPreview( string Sha256, bool Sha256Pinned, string? CatalogUrl, string? InstalledVersion, bool ReplacesOtherSource, string? HookRunAs, IReadOnlyList Hooks, IReadOnlyList Apps, string? PanelTitle, - bool HasComponent, bool Compatible, string? MinOsmsVersion); + bool HasComponent, bool Compatible, string? MinOsmsVersion, IReadOnlyList Categories); public sealed record ExtensionInfo( string Id, string Name, string? Description, string? Author, string? Homepage, string? Notice, @@ -74,7 +74,7 @@ public sealed record ExtensionInfo( string? CatalogUrl, DateTime InstalledAt, DateTime? UpdatedAt, bool Enabled, bool RebootPending, IReadOnlyList Capabilities, bool? ComponentInstalled, string? HookRunAs, IReadOnlyList Hooks, IReadOnlyList Apps, - string? PanelTitle, string? PanelUrl, bool Broken); + string? PanelTitle, string? PanelUrl, bool Broken, string? IconUrl, IReadOnlyList Categories); public sealed record ExtensionOperation( string Kind, string Id, string Name, string State, string? Message, bool RebootRequired, @@ -89,7 +89,8 @@ public sealed record CatalogView( public sealed record CatalogEntryView( string Repo, string RepoUrl, string? Path, string? Ref, bool Sha256Pinned, string? Id, string Name, - string? Description, string? Notice, IReadOnlyList Tags, string? InstalledId); + string? Description, string? Notice, IReadOnlyList Tags, string? InstalledId, + string? IconUrl, IReadOnlyList Categories); public sealed record UpdateCheck(string Id, string CurrentVersion, string? LatestVersion, bool UpToDate, ExtensionPreview? Preview); @@ -125,6 +126,8 @@ public sealed class ExtensionManager readonly ConcurrentDictionary _panelTokens = new(StringComparer.OrdinalIgnoreCase); readonly ConcurrentDictionary _catalogCache = new(StringComparer.OrdinalIgnoreCase); + // Iconos de catálogo descargados: clave "url del catálogo|ruta del icono". Null = no existe o no vale. + readonly ConcurrentDictionary _catalogIcons = new(StringComparer.OrdinalIgnoreCase); readonly List _opLog = []; ExtensionState _state; ExtensionOperation? _op; @@ -208,7 +211,56 @@ ExtensionInfo ToInfo(InstalledExtension e) e.CatalogUrl, e.InstalledAt, e.UpdatedAt, e.Enabled, e.RebootPending, m?.Capabilities ?? [], m?.Component is null ? null : _componentInstalled.GetValueOrDefault(e.Id), m?.Hooks?.Any == true ? m.Hooks.RunAs : null, HookNames(m), m?.Apps?.Select(a => a.Name).ToList() ?? [], - m?.Panel?.Title, panelUrl, m is null); + m?.Panel?.Title, panelUrl, m is null, + m?.Icon is null ? null : $"/api/extensions/{e.Id}/icon?v={s.Sha256[..Math.Min(12, s.Sha256.Length)]}", + ExtensionFormat.NormalizeCategories(m?.Categories) is { Count: > 0 } own ? own : CatalogCategories(e)); + } + + /// Categorías que da el catálogo del que se instaló, si el manifiesto no trae (catálogo en caché). + IReadOnlyList CatalogCategories(InstalledExtension e) + { + if (e.CatalogUrl is null || !_catalogCache.TryGetValue(e.CatalogUrl, out var c) || c.Catalog is null) return []; + var entry = c.Catalog.Extensions.FirstOrDefault(x => + GitHubRef.TryParse(x.Repo, out var r) && + r.Slug.Equals(e.Source.Slug, StringComparison.OrdinalIgnoreCase) && + string.Equals(x.Path?.Trim('/'), e.Source.Path, StringComparison.OrdinalIgnoreCase)); + return ExtensionFormat.NormalizeCategories(entry?.Categories); + } + + /// Fichero del icono de una extensión instalada, o null si no tiene o no vale. + public string? ResolveIconFile(string id) + { + if (!ExtensionFormat.IsValidId(id) || !_manifests.TryGetValue(id, out var m) || m.Icon is null) return null; + var root = Path.GetFullPath(PackageDir(id)) + Path.DirectorySeparatorChar; + var full = Path.GetFullPath(Path.Combine(root, m.Icon)); + if (!full.StartsWith(root, StringComparison.OrdinalIgnoreCase) || !File.Exists(full)) return null; + return new FileInfo(full).Length <= ExtensionFormat.MaxIconBytes ? full : null; + } + + /// + /// Icono de una entrada de catálogo (por su posición en el catálogo): se descarga de + /// raw.githubusercontent.com y se guarda una hora. Solo de catálogos añadidos. + /// + public async Task<(byte[] Bytes, string ContentType)?> GetCatalogIconAsync(string catalogUrl, int index, CancellationToken ct = default) + { + if (!CatalogUrls().Any(u => SameUrl(u, catalogUrl))) return null; + var (_, catalog) = await LoadCatalogAsync(catalogUrl, refresh: false, ct); + if (catalog is null || index < 0 || index >= catalog.Extensions.Count) return null; + var icon = catalog.Extensions[index].Icon; + if (icon is null || !GitHubRef.TryParse(catalogUrl, out var repo)) return null; + + var path = repo.Path is null ? icon : $"{repo.Path.Trim('/')}/{icon}"; + var key = $"{catalogUrl}|{path}"; + if (!_catalogIcons.TryGetValue(key, out var cached) || cached.At < DateTime.UtcNow.AddHours(-1)) + { + byte[]? bytes; + try { bytes = await _github.GetRawFileAsync(repo with { Path = null }, path, ExtensionFormat.MaxIconBytes, ct); } + catch (GitHubException) { bytes = null; } + if (bytes is not null && !ExtensionFormat.LooksLikeIcon(icon, bytes)) bytes = null; + cached = (DateTime.UtcNow, bytes); + _catalogIcons[key] = cached; + } + return cached.Bytes is null ? null : (cached.Bytes, ExtensionFormat.IconContentType(icon)); } static List HookNames(ExtensionManifest? m) => @@ -292,7 +344,8 @@ public async Task PreviewAsync(PreviewRequest req, Cancellatio resolved.IsRelease, resolved.PublishedAt, sha, expectedSha is not null, req.CatalogUrl, current?.Source.VersionLabel, otherSource, m.Hooks?.Any == true ? m.Hooks.RunAs : null, HookNames(m), m.Apps?.Select(a => a.Name).ToList() ?? [], - m.Panel?.Title, m.Component is not null, ExtensionFormat.SupportsVersion(m, _osmsVersion), m.MinOsmsVersion); + m.Panel?.Title, m.Component is not null, ExtensionFormat.SupportsVersion(m, _osmsVersion), m.MinOsmsVersion, + ExtensionFormat.NormalizeCategories(m.Categories)); } catch { @@ -312,6 +365,16 @@ static void CheckFilesExist(ExtensionManifest m, string pkg) foreach (var f in files.OfType()) if (!File.Exists(Path.Combine(pkg, f))) throw Err("ext.invalidPackage", $"missing file: {f}"); + + if (m.Icon is { } icon) + { + var file = Path.Combine(pkg, icon); + if (!File.Exists(file)) throw Err("ext.invalidPackage", $"missing file: {icon}"); + if (new FileInfo(file).Length > ExtensionFormat.MaxIconBytes) + throw Err("ext.invalidPackage", $"icon larger than {ExtensionFormat.MaxIconBytes / 1024} KB: {icon}"); + if (!ExtensionFormat.LooksLikeIcon(icon, File.ReadAllBytes(file))) + throw Err("ext.invalidPackage", $"icon isn't a valid {Path.GetExtension(icon)} image: {icon}"); + } } void PurgeExpiredPending() @@ -565,15 +628,25 @@ public void RemoveCatalog(string url) var catalog = ExtensionFormat.ParseCatalog(json); List installed = Snapshot(); - var entries = catalog.Extensions.Select(x => + var fetched = DateTime.UtcNow; + var entries = catalog.Extensions.Select((x, idx) => { GitHubRef.TryParse(x.Repo, out var r); var inst = installed.FirstOrDefault(i => i.Source.Slug.Equals(r.Slug, StringComparison.OrdinalIgnoreCase) && string.Equals(i.Source.Path, x.Path?.Trim('/'), StringComparison.OrdinalIgnoreCase)); + // Con el icono del catálogo, ese; si no, el de la extensión instalada. + string? iconUrl = x.Icon is not null + ? $"/api/extensions/catalogs/icon?url={Uri.EscapeDataString(url)}&index={idx}&v={fetched.Ticks:x}" + : inst is not null && _manifests.TryGetValue(inst.Id, out var im) && im.Icon is not null + ? $"/api/extensions/{inst.Id}/icon?v={inst.Source.Sha256[..Math.Min(12, inst.Source.Sha256.Length)]}" + : null; + var categories = ExtensionFormat.NormalizeCategories(x.Categories); + if (categories.Count == 0 && inst is not null && _manifests.TryGetValue(inst.Id, out var cm)) + categories = ExtensionFormat.NormalizeCategories(cm.Categories); return new CatalogEntryView(r.Slug, r.Url + (x.Path is null ? "" : $"/tree/{x.Ref ?? "HEAD"}/{x.Path.Trim('/')}"), x.Path?.Trim('/'), x.Ref, x.Sha256 is not null, x.Id, x.Name ?? x.Id ?? r.Repo, x.Description, x.Notice, - x.Tags ?? [], inst?.Id); + x.Tags ?? [], inst?.Id, iconUrl, categories); }).ToList(); var view = new CatalogView(url, string.IsNullOrWhiteSpace(catalog.Name) ? repo.Slug : catalog.Name, catalog.Description, official, null, entries, DateTime.UtcNow); diff --git a/Services/Extensions/ExtensionManifest.cs b/Services/Extensions/ExtensionManifest.cs index 2a3b74c..3b80306 100644 --- a/Services/Extensions/ExtensionManifest.cs +++ b/Services/Extensions/ExtensionManifest.cs @@ -25,6 +25,10 @@ public sealed record ExtensionManifest public string? Notice { get; init; } /// Versión mínima de OpenStreamMS (x.y.z), si la necesita. public string? MinOsmsVersion { get; init; } + /// Icono (PNG, JPEG, WebP, GIF o SVG) relativo al paquete, de hasta 256 KB. + public string? Icon { get; init; } + /// Categorías para filtrar en el panel (ver ). + public List? Categories { get; init; } public ExtensionComponent? Component { get; init; } public ExtensionHooks? Hooks { get; init; } @@ -142,6 +146,10 @@ public sealed record CatalogEntry public string? Description { get; init; } public string? Notice { get; init; } public List? Tags { get; init; } + /// Icono relativo a la carpeta del catálogo en su repositorio (se ve antes de instalar). + public string? Icon { get; init; } + /// Categorías; si faltan, las del manifiesto cuando la extensión está instalada. + public List? Categories { get; init; } } // ── Lectura y validación ────────────────────────────────────────────────────── @@ -168,6 +176,69 @@ public static partial class ExtensionFormat public static bool IsValidId(string? id) => id is not null && IdRegex().IsMatch(id); + /// + /// Categorías que entiende el panel, en el orden en que se enseñan. Una que no esté aquí + /// se acepta (con el formato de un id) y se ignora: así una extensión hecha para una + /// versión más nueva se sigue pudiendo instalar. + /// + public static readonly IReadOnlyList KnownCategories = + ["remote-desktop", "streaming", "display", "input", "audio", "network", "games", "monitoring", "tools"]; + + public const int MaxCategories = 3; + public const long MaxIconBytes = 256 * 1024; + + static readonly string[] IconExtensions = [".png", ".jpg", ".jpeg", ".webp", ".gif", ".svg"]; + + /// Ruta relativa segura a una imagen de un formato admitido. + public static bool IsIconPath(string? path) => + IsSafeRelativePath(path) && IconExtensions.Contains(Path.GetExtension(path!).ToLowerInvariant()); + + /// Las categorías conocidas de la lista, sin repetir, en el orden de . + public static IReadOnlyList NormalizeCategories(IEnumerable? categories) + { + if (categories is null) return []; + var wanted = categories.OfType().Select(c => c.Trim().ToLowerInvariant()).ToHashSet(); + return KnownCategories.Where(wanted.Contains).ToList(); + } + + /// Tipo MIME de un icono por su extensión. + public static string IconContentType(string path) => Path.GetExtension(path).ToLowerInvariant() switch + { + ".png" => "image/png", + ".jpg" or ".jpeg" => "image/jpeg", + ".webp" => "image/webp", + ".gif" => "image/gif", + ".svg" => "image/svg+xml", + _ => "application/octet-stream", + }; + + /// ¿Empiezan los bytes como el formato que dice la extensión? Evita servir otra cosa como imagen. + public static bool LooksLikeIcon(string path, ReadOnlySpan bytes) + { + if (bytes.Length == 0 || bytes.Length > MaxIconBytes) return false; + static bool Starts(ReadOnlySpan b, ReadOnlySpan sig) => b.Length >= sig.Length && b[..sig.Length].SequenceEqual(sig); + switch (Path.GetExtension(path).ToLowerInvariant()) + { + case ".png": return Starts(bytes, [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); + case ".jpg": + case ".jpeg": return Starts(bytes, [0xFF, 0xD8, 0xFF]); + case ".gif": return Starts(bytes, "GIF8"u8); + case ".webp": return bytes.Length >= 12 && Starts(bytes, "RIFF"u8) && bytes[8..12].SequenceEqual("WEBP"u8); + case ".svg": + var head = System.Text.Encoding.UTF8.GetString(bytes[..Math.Min(bytes.Length, 4096)]).TrimStart('', ' ', '\t', '\r', '\n'); + return head.StartsWith('<') && head.Contains("? categories, Action fail, string field) + { + if (categories is null) return; + if (categories.Count > MaxCategories) fail($"{field}: {MaxCategories} at most"); + foreach (var c in categories) + if (!IsValidId(c)) fail($"{field}: invalid category '{c}' (lowercase letters, digits and hyphens)"); + } + public static ExtensionManifest ParseManifest(string json) { ExtensionManifest? m; @@ -193,6 +264,9 @@ public static ExtensionCatalog ParseCatalog(string json) throw new ExtensionFormatException($"{CatalogFile}: invalid path '{e.Path}'"); if (e.Sha256 is not null && !IsSha256(e.Sha256)) throw new ExtensionFormatException($"{CatalogFile}: invalid sha256 for '{e.Repo}'"); + if (e.Icon is not null && !IsIconPath(e.Icon)) + throw new ExtensionFormatException($"{CatalogFile}: icon of '{e.Repo}' must be a relative path to a .png, .jpg, .webp, .gif or .svg"); + ValidateCategories(e.Categories, msg => throw new ExtensionFormatException($"{CatalogFile}: '{e.Repo}' {msg}"), "categories"); } return c; } @@ -207,6 +281,8 @@ public static void Validate(ExtensionManifest m) if (m.MinOsmsVersion is not null && !Version.TryParse(m.MinOsmsVersion, out _)) Fail("invalid minOsmsVersion"); if (m.Homepage is not null && !IsHttpsUrl(m.Homepage)) Fail("homepage must be https"); if (m.Capabilities.Count == 0) Fail("declares nothing to do (component, hooks, apps or panel)"); + if (m.Icon is not null && !IsIconPath(m.Icon)) Fail("icon must be a relative path to a .png, .jpg, .webp, .gif or .svg in the package"); + ValidateCategories(m.Categories, Fail, "categories"); void Script(string? path, string field) { diff --git a/Services/Extensions/GitHubSource.cs b/Services/Extensions/GitHubSource.cs index 4a1261d..13aed81 100644 --- a/Services/Extensions/GitHubSource.cs +++ b/Services/Extensions/GitHubSource.cs @@ -206,6 +206,30 @@ public async Task GetFileAsync(GitHubRef repo, string path, Cancellation return System.Text.Encoding.UTF8.GetString(bytes); } + /// + /// Un fichero pequeño del repositorio, en bytes, desde raw.githubusercontent.com (no gasta + /// del límite por hora de la API). Sin ref, la rama principal. Null si no existe. + /// + public async Task GetRawFileAsync(GitHubRef repo, string path, long maxBytes, CancellationToken ct = default) + { + static string Escape(string p) => string.Join('/', p.Split('/').Select(Uri.EscapeDataString)); + var url = $"https://raw.githubusercontent.com/{repo.Slug}/{Escape(repo.Ref ?? "HEAD")}/{Escape(path)}"; + using var resp = await SendFollowingRedirectsAsync(url, ct, allowNotFound: true); + if (resp.StatusCode == HttpStatusCode.NotFound) return null; + if (resp.Content.Headers.ContentLength > maxBytes) throw new GitHubException($"{path}: too large"); + + await using var src = await resp.Content.ReadAsStreamAsync(ct); + using var buf = new MemoryStream(); + var chunk = new byte[16384]; + int n; + while ((n = await src.ReadAsync(chunk, ct)) > 0) + { + if (buf.Length + n > maxBytes) throw new GitHubException($"{path}: too large"); + buf.Write(chunk, 0, n); + } + return buf.ToArray(); + } + // ── Descargar y descomprimir ──────────────────────────────────────────── /// Descarga el paquete a y devuelve su SHA-256 (hex, minúsculas). diff --git a/docs/extensions.md b/docs/extensions.md index be56a3f..622d0b3 100644 --- a/docs/extensions.md +++ b/docs/extensions.md @@ -46,6 +46,8 @@ Limits: 300 MB download, 1 GB extracted, 20 000 files. Paths can't leave the pac "license": "MIT", "notice": "Shown in the install dialog: licenses, risks, requirements.", "minOsmsVersion": "1.7.0", // optional + "icon": "icon.png", // optional: .png, .jpg, .webp, .gif or .svg in the package, up to 256 KB + "categories": ["tools"], // optional: up to 3, see Categories below "component": { "install": "install.ps1", // required; exit 0 = OK, 3010 = OK, restart Windows @@ -86,6 +88,29 @@ Limits: 300 MB download, 1 GB extracted, 20 000 files. Paths can't leave the pac At least one of `component`, `hooks`, `apps` or `panel` is required. All script paths are relative to the package and must be `.ps1` files that exist in it. +### Icon and categories + +`icon` is shown on the extension's card. It must be a PNG, JPEG, WebP, GIF or SVG file in the +package, up to 256 KB, and its content has to match its extension. A square image of 128×128 or +more looks best. Without one, the card shows the name's first letter. + +`categories` let users filter the Extensions tab. Use up to three of: + +| Category | For | +|---|---| +| `remote-desktop` | Several sessions at once, Remote Desktop patches and settings. | +| `streaming` | Streaming hosts, encoders and clients. | +| `display` | Virtual displays and display drivers. | +| `input` | Controllers, keyboards, mice and other input devices. | +| `audio` | Audio devices and routing. | +| `network` | Networking for sessions and seats. | +| `games` | Game launchers, stores and apps for Moonlight. | +| `monitoring` | Dashboards, metrics and status pages. | +| `tools` | Anything else. | + +Unknown categories are accepted and ignored, so an extension written for a newer OpenStreamMS +still installs. + ### Scripts Scripts run with `powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File`, @@ -163,12 +188,17 @@ A catalog is a GitHub repository with `osms-catalog.json` at its root (or in the "name": "My extension", "description": "…", "notice": "Shown in the install dialog next to the author's notice.", - "tags": ["tools"] + "tags": ["tools"], + "icon": "icons/my-extension.png", // optional: relative to the catalog's folder + "categories": ["tools"] // optional: overrides the extension's own } ] } ``` +The catalog's `icon` and `categories` are shown before anything is installed. Without them, the +dashboard uses the extension's own once it's installed. + With `ref` and `sha256`, the catalog decides exactly what gets installed, and updates follow the catalog. Without them, extensions follow their latest release. diff --git a/tests/OpenStreamMS.Tests/ExtensionTests.cs b/tests/OpenStreamMS.Tests/ExtensionTests.cs index a6d2c9c..f2b2a50 100644 --- a/tests/OpenStreamMS.Tests/ExtensionTests.cs +++ b/tests/OpenStreamMS.Tests/ExtensionTests.cs @@ -83,6 +83,56 @@ public void Manifest_ParsesAndListsCapabilities() public void Manifest_RejectsInvalid(string json) => Assert.Throws(() => ExtensionFormat.ParseManifest(json)); + [Fact] + public void Manifest_IconAndCategories() + { + var m = ExtensionFormat.ParseManifest(""" + { "id": "ok", "name": "x", "apps": [ { "name": "a" } ], + "icon": "img/icon.svg", "categories": ["tools", "remote-desktop", "from-the-future"] } + """); + Assert.Equal("img/icon.svg", m.Icon); + // Conocidas, en el orden del panel; las desconocidas se ignoran sin impedir la instalación. + Assert.Equal(["remote-desktop", "tools"], ExtensionFormat.NormalizeCategories(m.Categories)); + Assert.Empty(ExtensionFormat.NormalizeCategories(null)); + } + + [Theory] + [InlineData("""{ "id": "ok", "name": "x", "apps": [ { "name": "a" } ], "icon": "../icon.png" }""")] + [InlineData("""{ "id": "ok", "name": "x", "apps": [ { "name": "a" } ], "icon": "icon.exe" }""")] + [InlineData("""{ "id": "ok", "name": "x", "apps": [ { "name": "a" } ], "categories": ["games", "tools", "audio", "network"] }""")] + [InlineData("""{ "id": "ok", "name": "x", "apps": [ { "name": "a" } ], "categories": ["Bad Category"] }""")] + public void Manifest_RejectsBadIconOrCategories(string json) => + Assert.Throws(() => ExtensionFormat.ParseManifest(json)); + + [Fact] + public void Catalog_IconAndCategories() + { + var c = ExtensionFormat.ParseCatalog(""" + { "extensions": [ { "repo": "o/r", "icon": "icons/r.webp", "categories": ["games"] } ] } + """); + Assert.Equal(("icons/r.webp", "games"), (c.Extensions[0].Icon, c.Extensions[0].Categories![0])); + Assert.Throws(() => ExtensionFormat.ParseCatalog("""{ "extensions": [ { "repo": "o/r", "icon": "/etc/x.png" } ] }""")); + Assert.Throws(() => ExtensionFormat.ParseCatalog("""{ "extensions": [ { "repo": "o/r", "categories": ["a","b","c","d"] } ] }""")); + } + + [Theory] + [InlineData("i.png", new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0 }, true)] + [InlineData("i.jpg", new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 }, true)] + [InlineData("i.gif", new byte[] { (byte)'G', (byte)'I', (byte)'F', (byte)'8', (byte)'9', (byte)'a' }, true)] + [InlineData("i.png", new byte[] { (byte)'<', (byte)'s', (byte)'v', (byte)'g' }, false)] + [InlineData("i.webp", new byte[] { (byte)'R', (byte)'I', (byte)'F', (byte)'F', 0, 0, 0, 0, (byte)'A', (byte)'V', (byte)'I', (byte)' ' }, false)] + [InlineData("i.png", new byte[0], false)] + public void Icon_ContentMustMatchItsExtension(string name, byte[] bytes, bool ok) => + Assert.Equal(ok, ExtensionFormat.LooksLikeIcon(name, bytes)); + + [Fact] + public void Icon_SvgNeedsAnSvgElement() + { + Assert.True(ExtensionFormat.LooksLikeIcon("a.svg", "\n"u8.ToArray())); + Assert.False(ExtensionFormat.LooksLikeIcon("a.svg", ""u8.ToArray())); + Assert.Equal("image/svg+xml", ExtensionFormat.IconContentType("x/A.SVG")); + } + [Fact] public void Catalog_ValidatesEntries() { @@ -316,4 +366,85 @@ public async Task PanelFiles_NeedTheToken() Assert.Null(m.ResolvePanelFile("demo", "x", "panel/index.html")); await Task.CompletedTask; } + + static readonly byte[] Png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 13]; + + [Fact] + public async Task IconsAndCategories_FromCatalogAndManifest() + { + // Paquete con icono propio y categoría; el catálogo trae otro icono y otra categoría. + byte[] pkg; + using (var ms = new MemoryStream()) + { + using (var zip = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true)) + { + void Add(string name, byte[] data) { using var s = zip.CreateEntry($"owner-demo-{Commit[..7]}/{name}").Open(); s.Write(data); } + Add("osms-extension.json", Json("""{ "id": "demo", "name": "Demo", "icon": "icon.png", "categories": ["tools"], "apps": [ { "name": "Demo app" } ] }""")); + Add("icon.png", Png); + } + pkg = ms.ToArray(); + } + var catalog = """{ "extensions": [ { "repo": "owner/demo", "icon": "icons/demo.png", "categories": ["games"] }, { "repo": "owner/other" } ] }"""; + var gh = new FakeGitHub(new() + { + ["https://api.github.com/repos/owner/demo"] = (HttpStatusCode.OK, Json("""{ "default_branch": "main" }""")), + ["https://api.github.com/repos/owner/demo/commits/main"] = (HttpStatusCode.OK, Json($$"""{ "sha": "{{Commit}}" }""")), + [$"https://api.github.com/repos/owner/demo/zipball/{Commit}"] = (HttpStatusCode.OK, pkg), + ["https://api.github.com/repos/owner/catalog/contents/osms-catalog.json"] = + (HttpStatusCode.OK, Json($$"""{ "type": "file", "content": "{{Convert.ToBase64String(Encoding.UTF8.GetBytes(catalog))}}" }""")), + ["https://raw.githubusercontent.com/owner/catalog/HEAD/icons/demo.png"] = (HttpStatusCode.OK, Png), + }); + var m = new ExtensionManager(_root, new GitHubSource(gh), new Version(1, 6, 0)); + const string Url = "https://github.com/owner/catalog"; + + // Antes de añadir el catálogo no se descarga nada de él. + Assert.Null(await m.GetCatalogIconAsync(Url, 0)); + + var view = await m.AddCatalogAsync(Url); + var entry = view.Extensions[0]; + Assert.Equal(["games"], entry.Categories); + Assert.StartsWith("/api/extensions/catalogs/icon?url=", entry.IconUrl); + Assert.Null(view.Extensions[1].IconUrl); + Assert.Empty(view.Extensions[1].Categories); + + var icon = await m.GetCatalogIconAsync(Url, 0); + Assert.Equal(("image/png", Png.Length), (icon!.Value.ContentType, icon.Value.Bytes.Length)); + Assert.Null(await m.GetCatalogIconAsync(Url, 1)); // sin icono + Assert.Null(await m.GetCatalogIconAsync(Url, 9)); // no existe + + var p = await m.PreviewAsync(new PreviewRequest("owner/demo", CatalogUrl: Url)); + Assert.Equal(["tools"], p.Categories); + m.StartInstall(p.Token, p.Sha256, false); + await WaitIdle(m); + + var x = Assert.Single(m.GetAll().Installed); + Assert.Equal(["tools"], x.Categories); // las suyas mandan en la instalada + Assert.StartsWith("/api/extensions/demo/icon?v=", x.IconUrl); + Assert.Equal(Path.Combine(m.PackageDir("demo"), "icon.png"), m.ResolveIconFile("demo")); + Assert.Null(m.ResolveIconFile("../demo")); + } + + [Fact] + public async Task Preview_RejectsAnIconThatIsntAnImage() + { + byte[] pkg; + using (var ms = new MemoryStream()) + { + using (var zip = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true)) + { + void Add(string name, string data) { using var w = new StreamWriter(zip.CreateEntry($"owner-demo-{Commit[..7]}/{name}").Open()); w.Write(data); } + Add("osms-extension.json", """{ "id": "demo", "name": "Demo", "icon": "icon.png", "apps": [ { "name": "Demo app" } ] }"""); + Add("icon.png", ""); + } + pkg = ms.ToArray(); + } + var gh = new FakeGitHub(new() + { + ["https://api.github.com/repos/owner/demo"] = (HttpStatusCode.OK, Json("""{ "default_branch": "main" }""")), + ["https://api.github.com/repos/owner/demo/commits/main"] = (HttpStatusCode.OK, Json($$"""{ "sha": "{{Commit}}" }""")), + [$"https://api.github.com/repos/owner/demo/zipball/{Commit}"] = (HttpStatusCode.OK, pkg), + }); + var m = new ExtensionManager(_root, new GitHubSource(gh), new Version(1, 6, 0)); + await Assert.ThrowsAsync(() => m.PreviewAsync(new PreviewRequest("owner/demo"))); + } }