Compare commits

..
Author SHA1 Message Date
陈奇 05a773b426 docs(plugins): clarify default directory enumeration boundary 2026-10-27 11:25:54 +00:00
33 changed files with 49 additions and 840 deletions

No files matched your search

+1 -3
View File
@@ -1262,8 +1262,6 @@ Highlight the focused split pane:
'deepLink.jms.unsupported': 'Unsupported JumpServer protocol: {{protocol}}',
'settings.tab.plugins': 'Plugins',
"settings.plugins.manager.installed": "Installed plugins",
"settings.plugins.author.official": "Official maintainer",
"settings.plugins.author.officialMeaning": "Maintained by the Netcatty project. This is not a safety certification.",
"settings.plugins.manager.import": "Import .ncpkg",
"settings.plugins.manager.preview": "Imported packages stay disabled until you review and enable them.",
"settings.plugins.manager.empty": "Import a local plugin package to get started.",
@@ -1421,7 +1419,7 @@ Highlight the focused split pane:
'plugins.authentication.responseFailedWithMessage': 'Could not send the authentication response: {message}. Try again or cancel the request.',
'plugins.authentication.continue': 'Continue',
'plugins.hostActions.select': 'Share selected host metadata',
'plugins.hostActions.selectionNote': 'Only the selected hosts\' saved labels, addresses, usernames, protocols, groups and tags are shared. Group selection includes only the hosts selected now. Later edit or connection requests follow this plugin\'s permission settings.',
'plugins.hostActions.selectionNote': 'Share saved labels, addresses, usernames, protocols, groups and tags with this plugin. Group selection includes only the hosts selected now. Connecting requires a separate confirmation.',
'plugins.hostActions.create': 'Review host draft',
'plugins.hostActions.edit': 'Review host changes',
'plugins.hostActions.connect': 'Confirm connection',
+1 -3
View File
@@ -1261,8 +1261,6 @@ Resalta el panel dividido enfocado:
'deepLink.jms.invalid': 'Enlace JumpServer inválido',
'deepLink.jms.unsupported': 'Protocolo JumpServer no compatible: {{protocol}}',
'settings.tab.plugins': 'Plugins',
"settings.plugins.author.official": "Mantenimiento oficial",
"settings.plugins.author.officialMeaning": "Mantenido por el proyecto Netcatty. No es una certificación de seguridad.",
"settings.plugins.manager.installed": "Plugins instalados",
"settings.plugins.manager.import": "Importar .ncpkg",
"settings.plugins.manager.preview": "Los paquetes importados permanecen desactivados hasta que los revises y actives.",
@@ -1421,7 +1419,7 @@ Resalta el panel dividido enfocado:
'plugins.authentication.responseFailedWithMessage': 'No se pudo enviar la respuesta de autenticación: {message}. Inténtalo de nuevo o cancela la solicitud.',
'plugins.authentication.continue': 'Continuar',
'plugins.hostActions.select': 'Compartir metadatos de los equipos seleccionados',
'plugins.hostActions.selectionNote': 'Solo se comparten los nombres, direcciones, usuarios, protocolos, grupos y etiquetas guardados de los equipos seleccionados. Los grupos solo incluyen los equipos seleccionados ahora. Las solicitudes posteriores de edición o conexión siguen los permisos de este complemento.',
'plugins.hostActions.selectionNote': 'Comparte nombres, direcciones, usuarios, protocolos, grupos y etiquetas guardados con este complemento. Los grupos solo incluyen los equipos seleccionados ahora. Conectar requiere otra confirmación.',
'plugins.hostActions.create': 'Revisar borrador de equipo',
'plugins.hostActions.edit': 'Revisar cambios del equipo',
'plugins.hostActions.connect': 'Confirmar conexión',
+1 -3
View File
@@ -1130,8 +1130,6 @@ export const ruCoreMessages: Messages = {
'deepLink.jms.unsupported': 'Неподдерживаемый протокол JumpServer: {{protocol}}',
'settings.tab.plugins': 'Плагины',
"settings.plugins.author.official": "Официальная поддержка",
"settings.plugins.author.officialMeaning": "Поддерживается проектом Netcatty. Это не сертификат безопасности.",
"settings.plugins.manager.installed": "Установленные плагины",
"settings.plugins.manager.import": "Импорт .ncpkg",
"settings.plugins.manager.preview": "Импортированные пакеты отключены до проверки и включения.",
@@ -1286,7 +1284,7 @@ export const ruCoreMessages: Messages = {
'plugins.authentication.responseFailedWithMessage': 'Не удалось отправить ответ аутентификации: {message}. Повторите попытку или отмените запрос.',
'plugins.authentication.continue': 'Продолжить',
'plugins.hostActions.select': 'Передать метаданные выбранных хостов',
'plugins.hostActions.selectionNote': 'Передаются только метаданные выбранных хостов: сохранённые имена, адреса, пользователи, протоколы, группы и теги. Группа включает только выбранные сейчас хосты. Дальнейшие запросы изменения или подключения зависят от настроек разрешений плагина.',
'plugins.hostActions.selectionNote': 'Плагину будут переданы сохранённые имена, адреса, пользователи, протоколы, группы и теги. Группа включает только выбранные сейчас хосты. Подключение требует отдельного подтверждения.',
'plugins.hostActions.create': 'Проверить черновик хоста',
'plugins.hostActions.edit': 'Проверить изменения хоста',
'plugins.hostActions.connect': 'Подтвердить подключение',
@@ -29,16 +29,6 @@ const ALL_SETTINGS_LOCALES = [
...LOCALIZED_SETTINGS_LOCALES,
];
test("Host selection disclosure describes later permission-controlled actions without promising another confirmation", () => {
const permissionWords: Record<string, RegExp> = { en: /permission settings/i, es: /permisos/i, ru: /разрешени/u, 'zh-CN': /权限设置/u, 'zh-TW': /權限設定/u };
const oldPromise = /requires a separate confirmation|requiere otra confirmación|требует отдельного подтверждения|需要单独确认|需要另外確認/iu;
for (const locale of ALL_SETTINGS_LOCALES) {
const note = locale.messages['plugins.hostActions.selectionNote'];
assert.match(note, permissionWords[locale.name], locale.name);
assert.doesNotMatch(note, oldPromise, locale.name);
}
});
test("localized settings include names for every default shortcut", () => {
for (const locale of ALL_SETTINGS_LOCALES) {
const missing = DEFAULT_KEY_BINDINGS
+1 -3
View File
@@ -1177,8 +1177,6 @@ Vaults 标签保持扁平,不使用这块背景。
'qs.default': '默认',
'settings.tab.plugins': '插件',
"settings.plugins.manager.installed": "已安装插件",
"settings.plugins.author.official": "官方维护",
"settings.plugins.author.officialMeaning": "由 Netcatty 项目维护。这不是安全认证。",
"settings.plugins.manager.import": "导入 .ncpkg",
"settings.plugins.manager.preview": "导入的插件保持停用,请检查后再启用。",
"settings.plugins.manager.empty": "导入本地插件包以开始使用。",
@@ -1336,7 +1334,7 @@ Vaults 标签保持扁平,不使用这块背景。
'plugins.authentication.responseFailedWithMessage': '无法发送认证响应:{message}。请重试或取消此请求。',
'plugins.authentication.continue': '继续',
'plugins.hostActions.select': '分享所选主机的元数据',
'plugins.hostActions.selectionNote': '仅向此插件共享所选主机的元数据:名称、地址、用户名、协议、分组和标签。选择分组仅包含本次选中的成员。后续编辑或连接请求遵循此插件的权限设置。',
'plugins.hostActions.selectionNote': '向此插件分享已保存的名称、地址、用户名、协议、分组和标签。选择分组仅包含本次选中的成员。连接主机需要单独确认。',
'plugins.hostActions.create': '预览主机草稿',
'plugins.hostActions.edit': '预览主机修改',
'plugins.hostActions.connect': '确认连接',
+1 -3
View File
@@ -1179,8 +1179,6 @@ Vaults 分頁維持扁平,不使用這塊背景。
'qs.default': '預設',
'settings.tab.plugins': '外掛程式',
"settings.plugins.author.official": "官方維護",
"settings.plugins.author.officialMeaning": "由 Netcatty 專案維護。這不是安全認證。",
"settings.plugins.manager.installed": "已安裝插件",
"settings.plugins.manager.import": "導入 .ncpkg",
"settings.plugins.manager.preview": "導入的插件保持停用,請檢查後再啟用。",
@@ -1339,7 +1337,7 @@ Vaults 分頁維持扁平,不使用這塊背景。
'plugins.authentication.responseFailedWithMessage': '無法送出驗證回應:{message}。請重試或取消此要求。',
'plugins.authentication.continue': '繼續',
'plugins.hostActions.select': '分享所選主機的中繼資料',
'plugins.hostActions.selectionNote': '僅向此外掛分享所選主機的中繼資料:名稱、位址、使用者名稱、協定、群組和標籤。選擇群組僅包含本次選取的成員。後續編輯或連線請求遵循此外掛的權限設定。',
'plugins.hostActions.selectionNote': '向此外掛分享已儲存的名稱、位址、使用者名稱、協定、群組和標籤。選擇群組僅包含本次選取的成員。連線需要另外確認。',
'plugins.hostActions.create': '預覽主機草稿',
'plugins.hostActions.edit': '預覽主機修改',
'plugins.hostActions.connect': '確認連線',
@@ -1,41 +0,0 @@
import { useEffect, useMemo, useState } from 'react';
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
export function usePluginAuthorIdentity({ entry, plugin, sourceId = 'official' }: {
entry?: NetcattyPluginCatalogEntry; plugin?: NetcattyInstalledPlugin; sourceId?: string;
}) {
const [element, setElement] = useState<HTMLElement | null>(null);
const [loaded, setLoaded] = useState<{ key: string; value: NetcattyPluginAuthorPresentation } | null>(null);
const pluginId = plugin?.id;
const entryId = entry?.id;
const selectionToken = entry?.selectionToken;
const request = useMemo<NetcattyPluginAuthorRequest | null>(() => pluginId
? { kind: 'installed', pluginId }
: entryId && selectionToken ? { kind: 'catalog', pluginId: entryId, selectionToken, sourceId } : null,
[pluginId, entryId, selectionToken, sourceId]);
const key = JSON.stringify([request, plugin?.activeVersion, plugin?.archiveSha256, plugin?.source?.id, plugin?.runtime?.quarantinedAt]);
const installed = Boolean(plugin);
const version = plugin?.activeVersion;
const archiveSha256 = plugin?.archiveSha256 ?? null;
const installedSourceId = plugin?.source?.id ?? 'local';
useEffect(() => {
if (!element || !request) return;
let active = true;
let started = false;
const load = () => {
if (started) return;
started = true;
void netcattyBridge.get()?.getPluginAuthorPresentation?.(request).then((value) => {
if (!active || !value) return;
if (installed && (value.version !== version || value.archiveSha256 !== archiveSha256 || value.sourceId !== installedSourceId)) return;
setLoaded({ key, value });
}).catch(() => { /* The visible author placeholder remains usable offline. */ });
};
const observer = typeof IntersectionObserver === 'undefined' ? null : new IntersectionObserver((entries) => {
if (entries.some((entry) => entry.isIntersecting)) { load(); observer?.disconnect(); }
}, { rootMargin: '64px' });
if (observer) observer.observe(element); else load();
return () => { active = false; observer?.disconnect(); };
}, [element, request, key, installed, version, archiveSha256, installedSourceId]);
return { ref: setElement, identity: loaded?.key === key ? loaded.value : null };
}
-26
View File
@@ -1,26 +0,0 @@
import React, { useState } from 'react';
import { UserRound } from 'lucide-react';
import { usePluginAuthorIdentity } from '../../application/state/usePluginAuthorIdentity';
import { useI18n } from '../../application/i18n/I18nProvider';
import { Badge } from '../ui/badge';
export function PluginAuthorRow({ entry, plugin, sourceId }: {
entry?: NetcattyPluginCatalogEntry; plugin?: NetcattyInstalledPlugin; sourceId?: string;
}) {
const { t } = useI18n();
const { ref, identity } = usePluginAuthorIdentity({ entry, plugin, sourceId });
const [failed, setFailed] = useState<string | null>(null);
const author = identity?.author ?? entry?.author ?? plugin?.manifest?.publisher ?? '';
const imageKey = JSON.stringify([entry?.id, entry?.selectionToken, plugin?.id, plugin?.activeVersion, plugin?.archiveSha256, sourceId, identity?.avatar]);
const avatar = identity?.avatar;
const showImage = avatar && avatar.length <= 700_000 && /^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(avatar) && failed !== imageKey;
return <div ref={ref} className="flex min-w-0 items-center gap-2 text-xs text-muted-foreground" data-plugin-author-row>
<span className="inline-flex h-5 w-5 shrink-0 items-center justify-center overflow-hidden rounded-full bg-muted/60" aria-hidden="true">
{showImage ? <img src={avatar} alt="" width={20} height={20} className="h-full w-full object-cover" onError={() => setFailed(imageKey)} />
: <UserRound size={13} data-plugin-author-placeholder />}
</span>
<span className="min-w-0 truncate" title={author}>{author}</span>
{identity?.officialMaintained === true && <Badge className="shrink-0 whitespace-nowrap border-0 bg-amber-500/15 px-2 py-0.5 text-[10px] font-medium text-amber-800 hover:bg-amber-500/15 dark:bg-amber-400/15 dark:text-amber-300 dark:hover:bg-amber-400/15"
title={t('settings.plugins.author.officialMeaning')} data-plugin-official-maintainer>{t('settings.plugins.author.official')}</Badge>}
</div>;
}
@@ -1,116 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { JSDOM } from 'jsdom';
import { PluginAuthorRow } from '../../plugins/PluginAuthorRow';
import { I18nProvider } from '../../../application/i18n/I18nProvider';
const entry = { id: 'com.netcatty.starter', name: 'Starter', author: 'Netcatty', version: '0.1.2',
repository: 'binaricat/Netcatty', commit: 'a'.repeat(40), selectionToken: 'b'.repeat(64),
manifest: { publisher: 'netcatty' } } as NetcattyPluginCatalogEntry;
const identity = { author: 'Netcatty', avatar: 'data:image/png;base64,eA==', officialMaintained: true,
sourceId: 'official', version: entry.version, archiveSha256: null };
test('untrusted entry strings and absent imagery produce a compact placeholder without an official badge', () => {
const claimed = { ...entry, author: '<img src="https://avatars.githubusercontent.com/u/1">',
officialMaintained: true, avatar: 'https://avatars.githubusercontent.com/u/1' };
const html = renderToStaticMarkup(<I18nProvider locale="en"><PluginAuthorRow entry={claimed} /></I18nProvider>);
assert.match(html, /data-plugin-author-placeholder/);
assert.doesNotMatch(html, /<img|data-plugin-official-maintainer/);
assert.match(html, /&lt;img/);
assert.match(html, /items-center/);
});
test('mounted author rows load only when visible, retain fallbacks, cancel stale results and show a borderless themed maintainer pill', async () => {
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>', { pretendToBeVisual: true });
const previous = new Map<string, PropertyDescriptor | undefined>();
const install = (key: string, value: unknown) => {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
};
const observers: Array<{ target: Element | null; callback: IntersectionObserverCallback }> = [];
class VisibilityObserver {
record: typeof observers[number];
constructor(callback: IntersectionObserverCallback) { this.record = { callback, target: null }; observers.push(this.record); }
observe(target: Element) { this.record.target = target; }
disconnect() { this.record.target = null; }
}
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event']) {
install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]);
}
install('IntersectionObserver', VisibilityObserver);
install('IS_REACT_ACT_ENVIRONMENT', true);
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const root = createRoot(document.getElementById('root')!);
const calls: NetcattyPluginAuthorRequest[] = [];
const pending: Array<(value: NetcattyPluginAuthorPresentation | null) => void> = [];
Object.assign(window, { netcatty: { getPluginAuthorPresentation: (request: NetcattyPluginAuthorRequest) => {
calls.push(request); return new Promise((resolve) => pending.push(resolve));
} } });
const render = async (value = entry, sourceId = 'official') => {
await act(async () => root.render(<I18nProvider locale="en"><PluginAuthorRow entry={value} sourceId={sourceId} /></I18nProvider>));
};
const visible = async () => {
await act(async () => {
for (const observer of [...observers]) if (observer.target) observer.callback([{ target: observer.target, isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver);
});
};
try {
await render(); assert.equal(calls.length, 0); assert.ok(document.querySelector('[data-plugin-author-placeholder]'));
await visible(); assert.deepEqual(calls[0], { kind: 'catalog', pluginId: entry.id, selectionToken: entry.selectionToken, sourceId: 'official' });
assert.ok(document.querySelector('[data-plugin-author-placeholder]'), 'loading uses the default placeholder');
await act(async () => pending.shift()!(identity));
const image = document.querySelector('img')!;
assert.equal(image.getAttribute('src'), identity.avatar); assert.equal(image.width, 20); assert.equal(image.height, 20);
const badge = document.querySelector<HTMLElement>('[data-plugin-official-maintainer]')!;
assert.equal(badge.textContent, 'Official maintainer'); assert.match(badge.title, /not a safety certification/);
assert.ok(badge.classList.contains('border-0'));
assert.ok(badge.classList.contains('bg-amber-500/15')); assert.ok(badge.classList.contains('dark:bg-amber-400/15'));
assert.ok(badge.classList.contains('text-amber-800')); assert.ok(badge.classList.contains('dark:text-amber-300'));
document.documentElement.classList.add('dark');
assert.ok(document.querySelector('[data-plugin-author-row]')?.classList.contains('items-center'));
await act(async () => image.dispatchEvent(new Event('error')));
assert.equal(document.querySelector('img'), null); assert.ok(document.querySelector('[data-plugin-author-placeholder]'));
assert.ok(document.querySelector('[data-plugin-official-maintainer]'), 'image failure does not alter maintenance identity');
const next = { ...entry, selectionToken: 'c'.repeat(64) };
await render(next); assert.equal(document.querySelector('[data-plugin-official-maintainer]'), null);
await visible(); const stale = pending.shift()!;
const copied = { ...entry, author: 'Community author', selectionToken: 'd'.repeat(64) };
await render(copied, 'third-party:copy'); await visible();
await act(async () => stale(identity));
assert.equal(document.querySelector('[data-plugin-official-maintainer]'), null);
assert.match(document.querySelector('[data-plugin-author-row]')!.textContent!, /Community author/);
await act(async () => pending.shift()!({ ...identity, author: copied.author, sourceId: 'third-party:copy', officialMaintained: false, avatar: 'https://avatars.githubusercontent.com/u/1' }));
assert.equal(document.querySelector('img'), null, 'renderer never uses a remote avatar URL');
assert.equal(document.querySelector('[data-plugin-official-maintainer]'), null);
await render({ ...entry, selectionToken: 'f'.repeat(64) }); await visible();
await act(async () => pending.shift()!({ ...identity, avatar: null, officialMaintained: false }));
assert.ok(document.querySelector('[data-plugin-author-placeholder]'));
const installed = { id: entry.id, activeVersion: entry.version, archiveSha256: 'a'.repeat(64),
source: { id: 'official', kind: 'official', origin: 'https://plugins.netcatty.app', name: 'Official' },
manifest: entry.manifest, runtime: {} } as NetcattyInstalledPlugin;
await act(async () => root.render(<I18nProvider locale="en"><PluginAuthorRow plugin={installed} /></I18nProvider>));
await visible(); assert.deepEqual(calls.at(-1), { kind: 'installed', pluginId: installed.id });
await act(async () => pending.shift()!({ ...identity, version: '9.0.0', archiveSha256: installed.archiveSha256! }));
assert.equal(document.querySelector('[data-plugin-official-maintainer]'), null, 'a stale installed version cannot gain a badge');
const count = calls.length;
await act(async () => root.render(<I18nProvider locale="en"><PluginAuthorRow plugin={{ ...installed }} /></I18nProvider>));
await visible(); assert.equal(calls.length, count, 'unchanged installed identity does not reload on a new object reference');
await render({ ...entry, selectionToken: 'e'.repeat(64) }); await visible();
const late = pending.shift()!;
await act(async () => root.unmount());
await act(async () => late(identity));
assert.equal(document.querySelector('[data-plugin-author-row]'), null);
assert.ok(observers.every((observer) => observer.target === null));
} finally {
dom.window.close();
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key);
}
}
});
@@ -32,9 +32,7 @@ test('installed grid filters, opens one detail and restores search, scroll and c
assert.equal(cards().length, 2);
const alphaCard = renderer.root.findAllByType('article')[0];
assert.match(JSON.stringify(renderer.toJSON()), /Alpha safely formats synthetic greetings/);
const authorRow = alphaCard.findByProps({ 'data-plugin-author-row': true });
assert.ok(authorRow.findAllByType('span').some((node) => node.children.includes('Example')), 'author has its own compact row');
assert.ok(authorRow.findByProps({ 'data-plugin-author-placeholder': true }), 'an unverified installed publisher has a default avatar');
assert.ok(alphaCard.findAllByType('p').some((node) => node.children.includes('Example')), 'author has its own line');
assert.ok(alphaCard.findAllByType('p').some((node) => node.props.className?.includes('line-clamp-3')), 'card description is bounded');
assert.match(JSON.stringify(renderer.toJSON()), /MIT/);
assert.match(JSON.stringify(renderer.toJSON()), /Incompatible version/);
@@ -4,7 +4,6 @@ import { Dialog, DialogContent, DialogDescription, DialogTitle } from '../../ui/
import { PluginInfo } from './PluginInfo';
import React, { useRef, useState } from 'react';
import { PluginBrandIcon } from '../../plugins/PluginBrandIcon';
import { PluginAuthorRow } from '../../plugins/PluginAuthorRow';
import { ArrowLeft } from 'lucide-react';
import { useI18n } from '../../../application/i18n/I18nProvider';
import { usePluginCatalog } from '../../../application/state/usePluginCatalog';
@@ -83,7 +82,7 @@ export function PluginMarketplaceContent({ catalog, installed, selected, onSelec
return <button key={item.id} type="button" data-plugin-id={item.id} aria-current={selected === item.id ? 'true' : undefined} onClick={() => choose(item.id)}
className="plugin-card min-w-0 flex min-h-[200px] flex-col gap-3 rounded-lg bg-card p-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<div className="flex items-center gap-3"><span className="flex h-8 w-8 shrink-0 items-center justify-center"><PluginBrandIcon entry={item} size={32} className="text-muted-foreground" /></span><span className="min-w-0 break-words text-sm font-semibold leading-5">{item.name}</span></div>
<PluginAuthorRow entry={item} sourceId={sourceId} />
<p className="break-words text-xs text-muted-foreground">{item.author}</p>
<p className="line-clamp-3 break-words text-sm leading-5 text-muted-foreground">{item.description}</p>
<div className="mt-auto flex flex-wrap items-center justify-between gap-2 pt-1 text-xs text-muted-foreground"><span>{item.version} · {item.license}</span><span className="text-foreground">{t('settings.plugins.manager.details')}</span></div>
<div className="flex flex-wrap gap-2 text-xs text-muted-foreground">{isInstalled && <span className="rounded bg-muted px-2 py-0.5 text-foreground">{t('settings.plugins.market.installed')}</span>}{!item.artifact && <span className="rounded bg-muted/40 px-2 py-0.5">{t('settings.plugins.market.sourceBadge')}</span>}</div>
@@ -92,7 +91,7 @@ export function PluginMarketplaceContent({ catalog, installed, selected, onSelec
</div>}
{entry && <article key={entry.id} aria-label={entry.name} className="plugin-marketplace-detail mx-auto w-full max-w-[920px] min-w-0 space-y-6 focus:outline-none">
<Button variant="ghost" size="sm" onClick={back}><ArrowLeft size={14} className="mr-2" />{t('settings.plugins.market.back')}</Button>
<div className="space-y-2"><div className="flex items-center gap-3"><PluginBrandIcon entry={entry} size={48} /><h4 ref={detailRef} tabIndex={-1} className="break-words text-xl font-semibold focus:outline-none">{entry.name}</h4></div><PluginAuthorRow entry={entry} sourceId={sourceId} /><p className="text-xs text-muted-foreground">{entry.version} · {entry.license}</p>
<div className="space-y-2"><div className="flex items-center gap-3"><PluginBrandIcon entry={entry} size={48} /><h4 ref={detailRef} tabIndex={-1} className="break-words text-xl font-semibold focus:outline-none">{entry.name}</h4></div><p className="text-xs text-muted-foreground">{entry.author} · {entry.version} · {entry.license}</p>
{installedEntry && <p className="text-xs text-muted-foreground">{t('settings.plugins.market.installed')} · {installedEntry.activeVersion} · {t(installedEntry.enabled ? 'settings.plugins.manager.enabled' : 'settings.plugins.manager.disabled')}</p>}
</div>
{installedEntry?.runtime?.lastError && <p role="status" className="break-words text-xs text-destructive">{t('settings.plugins.manager.lastError')}: {installedEntry.runtime.lastError}</p>}
@@ -3,7 +3,6 @@ import { describePluginRuntime } from '@/domain/pluginRuntimePolicy.cjs';
import React, { useRef, useState } from 'react';
import { PluginPermissionPanel } from './PluginPermissionPanel';
import { PluginBrandIcon } from '../../plugins/PluginBrandIcon';
import { PluginAuthorRow } from '../../plugins/PluginAuthorRow';
import { ArrowLeft } from 'lucide-react';
import { usePluginManager } from '../../../application/state/usePluginManager';
import { useI18n } from '../../../application/i18n/I18nProvider';
@@ -104,7 +103,7 @@ export function PluginPackageManager({ manager, onSelectionChange, initialSelect
</Button>
</div>
<p className="break-all text-xs text-muted-foreground">{t('settings.plugins.sources.source')}: {t(plugin.source?.kind === 'official' ? 'settings.plugins.sources.official' : plugin.source?.kind === 'third-party' ? 'settings.plugins.sources.thirdparty' : 'settings.plugins.sources.local')}{plugin.source?.origin ? ` · ${plugin.source.origin}` : ''}</p>
{plugin.manifest?.publisher && <PluginAuthorRow plugin={plugin} />}
{plugin.manifest?.publisher && <p className="break-words text-xs text-muted-foreground">{plugin.manifest.publisher}</p>}
<p className={`break-words text-sm leading-5 text-muted-foreground ${selectedPlugin ? 'whitespace-pre-wrap' : 'line-clamp-3'}`}>{descriptionOf(plugin) || t('settings.plugins.manager.noDescription')}</p>
{!selectedPlugin ? <div className="mt-auto flex flex-wrap items-center justify-between gap-2 pt-1">
<p className="break-words text-xs text-muted-foreground">{plugin.activeVersion}{plugin.manifest?.license ? ` · ${plugin.manifest.license}` : ''}</p>
@@ -6,7 +6,6 @@ import type { usePluginManager } from '../../../application/state/usePluginManag
import { Button } from '../../ui/button';
import { Input } from '../../ui/input';
import { PluginBrandIcon } from '../../plugins/PluginBrandIcon';
import { PluginAuthorRow } from '../../plugins/PluginAuthorRow';
import { SettingCard, SettingRow, SettingsSection, Toggle } from '../settings-ui';
import { PluginLogSettings } from './PluginLogSettings';
@@ -73,8 +72,7 @@ export function PluginSettingsLanding({ manager, settingsAvailable, settingsErro
<span className="truncate" title={name}>{name}</span>
{plugin.activeVersion && <span className="shrink-0 text-xs font-normal text-muted-foreground">{plugin.activeVersion}</span>}
</span>} description={<>
{plugin.manifest?.publisher && <PluginAuthorRow plugin={plugin} />}
<span className="block break-words">{[sourceOf(plugin), statusOf(plugin)].filter(Boolean).join(' · ')}</span>
<span className="block break-words">{[plugin.manifest?.publisher, sourceOf(plugin), statusOf(plugin)].filter(Boolean).join(' · ')}</span>
{availableUpdate && <span className="block text-primary">{t('settings.plugins.landing.updateAvailable').replace('{version}', availableUpdate.availableVersion)}</span>}
{description && <span className="line-clamp-2 break-words">{description}</span>}
</>}>
-58
View File
@@ -1,58 +0,0 @@
# Plugin author presentation
The marketplace displays the catalog's author next to a small avatar. Installed
views reuse the author row. Missing, loading, unavailable, or invalid imagery
uses a bundled placeholder. An avatar is presentation metadata, not proof of an
authenticated GitHub publisher.
The registry binds an image to its reviewed displayed-author subject. Repository
ownership alone does not establish that subject. The current first-party author
is the Netcatty project, not an assumed personal GitHub identity. Until an image
pin is reviewed, its avatar remains null.
## Avatar delivery
Delivery v2 extends the reserved `avatar` field to null or
`{path, sha256, size}`. The path is exactly `/assets/<sha256>.png` or `.webp`.
Size is a positive integer no greater than 256KiB. The delivery digest and existing
id/version/repository/commit tuple bind the reference. Catalog and index identity
fields do not change. Source-only delivery v1 remains supported.
Only the main process fetches the selected source's same-origin asset. Existing
URL, credential, redirect, timeout, byte-count, and SHA-256 checks apply. The host
rechecks the source and selection after asynchronous work. The existing isolated
icon rasterizer validates and converts PNG or WebP to a bounded PNG data URI,
using its current queue, pending-work map, and cache. No renderer URL, arbitrary
file path, GitHub API, or GitHub avatar URL is accepted. Visible rows load lazily.
Installed presentation uses already validated catalog metadata only when source,
version, package digest, and manifest match the active installation. It does not
fetch a catalog just because the installed list opens. Without an exact match,
the declared publisher and placeholder remain visible, without a maintenance
badge. No installed-data migration or persistent identity cache is added.
## Official maintenance
The borderless gold pill means that the Netcatty project maintains the plugin.
It does not certify the plugin's safety or grant permissions. It is separate
from the official marketplace source label.
The main process requires the built-in official source and one of these explicit
first-party ID and repository pairs:
- `com.netcatty.starter`, `binaricat/Netcatty`
- `com.netcatty.hello`, `binaricat/Netcatty`
A local import, a third-party copy, an ID prefix, author text, manifest publisher,
README, or membership in the official marketplace cannot create this badge.
The renderer consumes the host result through the existing trusted-app IPC
boundary. No new plugin permission or plugin RPC is introduced.
## Validation scope
Focused registered tests cover source spoofing, exact installed identity,
hash-bound images, invalid metadata and decoding, redirects, source removal,
selection changes, cache reuse, lazy loading, stale UI cleanup, placeholders,
and borderless light/dark theme classes. These tests do not establish native
layout, actual account identity, live CDN deployment, or successful network access.
Actual app screenshots and native acceptance remain separately scheduled.
+5
View File
@@ -450,6 +450,11 @@ new child to an opened parent directory without a path race.
`readDirectory()` likewise keeps its stable SDK/RPC method but fails closed
unless the main process supplies a native adapter whose inode checks and entry
enumeration are bound to the same directory handle.
The default host supplies no `openPluginDirectoryHandle` adapter. The SDK exposes
the method and the router registers it, but there is no separate advertised
feature flag that enables enumeration. Even with an allowed `filesystem.read`
directory resource, the default runtime returns `unsupported`. Do not interpret
the method's presence or a filesystem permission as directory-listing support.
Permission names already use the phase-3 enforcement boundaries: clipboard
read/write, terminal metadata/output/input and input/output interception, Vault
@@ -1,8 +1,8 @@
# Host and Vault actions
Feature: `vault.host-actions`. The SDK registers three methods under
`context.vault`. Netcatty owns the picker, field-diff review, permission routing,
and normal connection dispatch. Plugin business logic stays in the offline browser sandbox.
`context.vault`. Netcatty owns the picker, field-diff review, and connection
confirmation. Plugin business logic stays in the offline browser sandbox.
Base: source integration #3981 at
`4213d8e6726c44e7a479418ece3adf16ea494782`.
@@ -36,12 +36,10 @@ remain behind the typed target reference; its revision is the expected revision.
Group metadata describes the explicitly selected current member handles. The
grant never expands when another host joins a group.
Selection shares the chosen metadata only. Later edit and connection requests
follow the plugin's Allow, Ask, or Deny settings. Draft saves retain the mandatory
host editor. Connection Ask displays the saved target and whether saved scripts
can run; Allow can dispatch without that permission-only dialog. Normal SSH
authentication remains unchanged. These actions grant no terminal input, output,
or session access.
Selection grants metadata access only. Each draft save and each connection
requires its own host-owned confirmation. A connection confirmation displays the
saved target and whether saved scripts can run. It does not grant terminal input,
terminal output, or session access.
All requests are bounded and cancel on runtime stop, source replacement, revoke,
Vault lock, owner window replacement, expiry, or user cancellation. The host
@@ -49,7 +47,7 @@ revalidates authority and expected revision after asynchronous work and before
the Vault write or connection dispatch.
Bounds reuse `HostInteractionLimits`: one pending request per runtime,
eight total, ten per minute, a 60-second host-interaction deadline, and a 64-KiB
eight total, ten per minute, a 60-second confirmation deadline, and a 64-KiB
request ceiling. Selection adds a maximum of 50 current hosts. Titles use the
existing 128-character single-line limit. Draft field lengths use
`ImporterHostDraft`. Unknown properties are rejected by the shared schema.
@@ -88,16 +86,15 @@ It revalidates after asynchronous authentication. AI selected-context handles ar
text-disclosure handles and cannot target these actions.
The permission engine gates selection with `vault.metadata`, drafts with
`vault.write`, and connection requests with `ui.interact`. Each committed save or
connection uses a signed one-use action claim. Permission settings control the
permission-only prompt; an Allow setting does not bypass the draft editor or
normal SSH authentication.
`vault.write`, and connection requests with `ui.interact`. Every save or connection
also requires a separate host-owned confirmation and a signed one-use action
claim. A stored permission grant cannot bypass this review.
After review, the renderer prepares the existing transaction or connection
request. It claims action authority after the final asynchronous preparation,
immediately before persistence or dispatch. This claim is the action's commit
point. Completion only acknowledges the committed action. Automation changes
during an Ask connection review require fresh confirmation.
during connection review require fresh confirmation.
The connection label uses the same `resolveEffectiveTerminalProtocol` helper as
the launcher, including Mosh/ET flags and implicit localhost shells. Local
execution displays an explicit on-device shell notice and omits the remote SSH
+7 -13
View File
@@ -3,10 +3,8 @@
The plugin manager has Installed, Official marketplace and Third-party marketplace
pages. Listing a plugin in the official market does not certify it or establish
that Netcatty maintains it. Remote manifests, publisher names, source names and
README content cannot create a host-issued official badge. The separate gold
maintainer badge requires the built-in official source and an exact host-curated
first-party ID/repository pair. It describes maintenance, not safety certification.
README text and images remain author content.
README content cannot create a host-issued official badge. This revision does not
issue maintainer badges. README text and images remain author content.
## Add a source
@@ -35,24 +33,20 @@ manifest, compatibility, browser-runtime admission and archive validation still
apply. Third-party source consent is not permission consent.
Delivery v1 is unchanged and source-only. Delivery **v2** has the same fields and
strict schema as v1, with `schemaVersion: 2`. Each plugin's `artifact` can be null
or a package reference:
strict schema as v1, with `schemaVersion: 2` and one extension: each plugin's
`artifact` can be null or a package reference:
```json
{"path":"/assets/<64-lowercase-hex-sha256>.ncpkg","sha256":"<same-sha256>","size":12345}
```
V2 delivery packages are at most 16 MiB. The catalog entry must contain
Packages are at most 32 MiB. The catalog entry must contain
`artifact: {url: "https://plugins.example.com/assets/<same-sha256>.ncpkg", sha256}`.
The index's current, non-withdrawn version must exactly equal the catalog entry
and use `distribution: "release"`. Source-only entries retain null delivery
artifacts and `distribution: "source-only"`. The reserved `avatar` can also be
null or a same-origin `/assets/<sha256>.png` or `.webp` reference, with a positive
size no greater than 256KiB. The host verifies and rasterizes its bytes through
the existing image infrastructure. Missing or invalid imagery uses a placeholder.
Remote README embeds are not loaded. README and PNG/WebP references retain the v1 bounds.
artifacts and `distribution: "source-only"`. Avatars remain null; remote README
embeds are not loaded. README and PNG/WebP references retain the v1 bounds.
Existing official bootstrap entries are not changed or made installable.
See [author presentation](author-identity.md) for subject and maintenance authority.
Before every install, refresh and validate the entire snapshot again. A changed
selection, withdrawal, unavailable source, altered hash or size prevents install;
+1 -8
View File
@@ -29,13 +29,6 @@ for brand icons. This v1 publishing schema requires **avatar and artifact to
be null**. The client rejects unsupported delivery metadata rather than
inventing installable packages or deriving a GitHub avatar URL.
Delivery v2 retains those fields and admits hash-bound packages plus the reserved
avatar as null or a positive-size PNG/WebP asset reference of at most 256KiB.
The host fetches only the selected source's same-origin asset, verifies bytes,
and reuses its bounded icon rasterizer and cache. The renderer receives a PNG
data URI. Author imagery does not verify a GitHub account, and no GitHub avatar
URL is derived. See [author presentation](author-identity.md).
Index is validated with its pinned schema. Plugin/version identities must be
unique; each catalog entry must exactly equal the index's current, non-withdrawn,
source-only entry. Withdrawal does not disable, uninstall or delete any existing
@@ -80,7 +73,7 @@ exact SHA-256 bytes; it does not relax those future gates or auto-enable code.
| README details | Exact delivery `/assets/<hash>.md` | Visible error/Retry, no upstream fallback |
| Uninstalled brand icons | Existing reviewed bundled previews | Default icon; delivery icon metadata validated but not fetched by UI |
| Installed brand icons | Host-owned local package decoder | Default icon; no activation/network request |
| Author avatars | Visible-row host fetch of a validated v2 same-origin resource; v1 remains null | Default placeholder; no GitHub lookup or renderer URL fetch |
| Author avatars | Not implemented; delivery v1 requires null | Existing local presentation; no avatar lookup |
| Package artifacts | Not published or admitted by delivery v1 | Source-only; no download action fabricated |
| Source/README links | Explicit user-opened external HTTPS link | May open GitHub; no background dependency |
@@ -1,162 +0,0 @@
"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const { RegistryCatalogService } = require("./registryCatalogService.cjs");
const { PluginContributionIconService } = require("./contributionIconService.cjs");
const { MarketSourcesService } = require("./marketSourcesService.cjs");
const { OFFICIAL_SOURCE, LOCAL_SOURCE, thirdPartySource } = require("./sourceIdentity.cjs");
const { catalog, delivery, digest, makeFiles, read } = require("./fixtures/staticDistributionFixture.cjs");
const sourcePng = read(delivery.plugins[0].iconLight.path.slice(1));
const avatar = { path: `/assets/${digest(sourcePng)}.png`, sha256: digest(sourcePng), size: sourcePng.length };
function filesFor(entries = catalog, change = () => {}) {
const files = makeFiles(entries, (index, sidecar) => {
sidecar.schemaVersion = 2;
for (const item of sidecar.plugins) {
item.avatar = structuredClone(avatar);
const entry = entries.find((entry) => entry.id === item.id);
if (entry.artifact) {
item.artifact = { path: `/assets/${entry.artifact.sha256}.ncpkg`, sha256: entry.artifact.sha256, size: 1 };
index.plugins.find((plugin) => plugin.id === item.id).versions[0].distribution = "release";
}
}
change(index, sidecar);
});
files.set(avatar.path, sourcePng);
return files;
}
function imageService(rasterizeIcon) {
return new PluginContributionIconService({ rasterizeIcon: rasterizeIcon ?? (async () => {
const png = Buffer.alloc(24); Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(png);
png.write("IHDR", 12); png.writeUInt32BE(32, 16); png.writeUInt32BE(32, 20); return png;
}) });
}
function registry(options = {}) {
const requests = [];
let files = options.files ?? filesFor();
const service = new RegistryCatalogService({ ...options,
fetch: options.fetch ?? (async (url, init) => {
requests.push(url);
assert.equal(new URL(url).origin, options.source?.origin ?? OFFICIAL_SOURCE.origin);
assert.equal(init.redirect, "manual"); assert.equal(init.credentials, "omit");
return files.has(new URL(url).pathname) ? new Response(files.get(new URL(url).pathname)) : new Response(null, { status: 404 });
}),
resolveAvatar: options.resolveAvatar ?? ((request) => imageServiceSingleton.resolveCatalogAvatar(request)),
});
const imageServiceSingleton = imageService();
return { service, requests, setFiles(value) { files = value; } };
}
test("v2 avatars use verified same-origin bytes and the shared image cache without GitHub", async () => {
const r = registry(); const snapshot = await r.service.list(); assert.equal(snapshot.error, null);
const entry = snapshot.entries[0];
const values = await Promise.all([r.service.author(entry.id, entry.selectionToken), r.service.author(entry.id, entry.selectionToken)]);
assert.deepEqual(values[0], values[1]); assert.match(values[0].avatar, /^data:image\/png;base64,/);
assert.equal(values[0].officialMaintained, true); assert.equal(values[0].author, "Netcatty");
assert.equal(r.requests.filter((url) => new URL(url).pathname === avatar.path).length, 1);
assert.ok(r.requests.every((url) => new URL(url).origin === OFFICIAL_SOURCE.origin));
await r.service.author(entry.id, entry.selectionToken);
assert.equal(r.requests.length, 5, "cached raster avoids another download");
});
test("third-party copies, community entries and local imports cannot acquire maintenance authority", async () => {
const copied = registry({ source: thirdPartySource("Netcatty official", "https://community.example.com") });
const entry = (await copied.service.list()).entries[0];
assert.equal((await copied.service.author(entry.id, entry.selectionToken)).officialMaintained, false);
const community = structuredClone(catalog[0]); community.id = "com.community.official";
community.manifest.id = community.id; community.author = "Netcatty official"; community.manifest.publisher = "netcatty";
const r = registry({ files: filesFor([community]) }); const listed = (await r.service.list()).entries[0];
assert.equal((await r.service.author(listed.id, listed.selectionToken)).officialMaintained, false);
const local = new MarketSourcesService({ database: { getActivePlugin: () => ({ id: catalog[0].id, activeVersion: catalog[0].version,
source: LOCAL_SOURCE, archiveSha256: "a".repeat(64), manifest: catalog[0].manifest, runtime: {} }) } });
assert.equal((await local.author({ kind: "installed", pluginId: catalog[0].id })).officialMaintained, false);
await assert.rejects(local.author({ kind: "installed", pluginId: catalog[0].id, officialMaintained: true }), /Invalid/);
});
test("avatar failure, redirects and mismatched bytes yield a placeholder without another origin", async () => {
for (const kind of ["missing", "hash", "format", "redirect"]) {
const files = filesFor(); const requests = [];
const r = registry({ files, fetch: async (url) => {
requests.push(url); const p = new URL(url).pathname;
if (p === avatar.path) {
if (kind === "redirect") return new Response(null, { status: 302, headers: { location: "https://avatars.githubusercontent.com/u/1" } });
if (kind === "missing") return new Response(null, { status: 404 });
if (kind === "hash") return new Response(Buffer.alloc(sourcePng.length));
}
return new Response(files.get(p));
}, ...(kind === "format" ? { resolveAvatar: async () => { throw new Error("Invalid PNG"); } } : {}) });
const entry = (await r.service.list()).entries[0]; const value = await r.service.author(entry.id, entry.selectionToken);
assert.equal(value.avatar, null, kind); assert.equal(value.officialMaintained, true);
assert.ok(requests.every((url) => new URL(url).origin === OFFICIAL_SOURCE.origin));
}
});
test("avatar schema rejects foreign paths, non-raster formats and invalid sizes before fetching", async () => {
for (const ref of [
{ ...avatar, path: "https://avatars.githubusercontent.com/u/1" },
{ ...avatar, path: `/assets/${avatar.sha256}.svg` },
{ ...avatar, path: `/assets/${"a".repeat(64)}.png` },
{ ...avatar, size: 0 }, { ...avatar, size: 256 * 1024 + 1 }, { ...avatar, size: 1.5 },
]) {
const r = registry({ files: filesFor(catalog, (_index, delivery) => { delivery.plugins[0].avatar = ref; }) });
const result = await r.service.list(); assert.ok(result.error, JSON.stringify(ref));
assert.equal(r.requests.length, 4, "invalid delivery cannot cause an avatar request");
}
});
test("v2 package references enforce the publisher's positive 16MiB bound without installing", async () => {
const entry = structuredClone(catalog[0]);
entry.artifact = { sha256: "a".repeat(64), url: `${OFFICIAL_SOURCE.origin}/assets/${"a".repeat(64)}.ncpkg` };
for (const size of [0, 16 * 1024 * 1024, 16 * 1024 * 1024 + 1]) {
const r = registry({ files: filesFor([entry], (_index, sidecar) => { sidecar.plugins[0].artifact.size = size; }) });
const snapshot = await r.service.list();
assert.equal(Boolean(snapshot.error), size !== 16 * 1024 * 1024);
assert.equal(r.requests.length, 4, "catalog validation never downloads or installs the package");
}
});
test("a changed selection or removed source cannot publish an in-flight avatar result", async () => {
for (const change of ["selection", "source"]) {
let release; let entered; let enabled = true;
const started = new Promise((resolve) => { entered = resolve; });
const gate = new Promise((resolve) => { release = resolve; });
const r = registry({ sourceGuard() { if (!enabled) throw new Error("Source removed"); }, resolveAvatar: async () => { entered(); await gate; return "data:image/png;base64,eA=="; } });
const entry = (await r.service.list()).entries[0]; const pending = r.service.author(entry.id, entry.selectionToken); await started;
if (change === "selection") { r.setFiles(filesFor(catalog, (_i, sidecar) => { sidecar.plugins[0].avatar = null; })); await r.service.refresh(); }
else enabled = false;
release(); await assert.rejects(pending, /changed|removed/);
}
});
test("installed presentation requires exact source/version/package/manifest and rejects replacement during load", async () => {
const entry = structuredClone(catalog[0]); entry.artifact = { sha256: "a".repeat(64), url: `${OFFICIAL_SOURCE.origin}/assets/${"a".repeat(64)}.ncpkg` };
let plugin = { id: entry.id, activeVersion: entry.version, archiveSha256: entry.artifact.sha256, source: OFFICIAL_SOURCE, manifest: entry.manifest, runtime: {} };
const requests = []; const files = filesFor([entry]);
const database = { getActivePlugin: () => plugin, db: { prepare: () => ({ get: () => undefined }) } };
const service = new MarketSourcesService({ database, fetch: async (url) => { requests.push(url); return new Response(files.get(new URL(url).pathname)); } });
const query = { kind: "installed", pluginId: entry.id };
assert.equal((await service.author(query)).officialMaintained, false); assert.equal(requests.length, 0);
await service.list(); assert.equal((await service.author(query)).officialMaintained, true);
for (const patch of [{ activeVersion: "9.0.0" }, { archiveSha256: "b".repeat(64) }, { manifest: { ...entry.manifest, publisher: "other" } }, { source: LOCAL_SOURCE }]) {
const saved = plugin; plugin = { ...plugin, ...patch };
assert.equal((await service.author(query)).officialMaintained, false); plugin = saved;
}
let release; let entered;
const started = new Promise((resolve) => { entered = resolve; });
service.catalogs.get("official").resolveAvatar = async () => { entered(); await new Promise((resolve) => { release = resolve; }); return null; };
const pending = service.author(query); await started; plugin = { ...plugin, archiveSha256: "b".repeat(64) }; release();
await assert.rejects(pending, /Installed plugin changed/);
});
test("avatar decoding validates bytes and uses the existing bounded rasterizer", async () => {
let calls = 0;
const service = imageService(async () => { calls++; throw new Error("Decode failed"); });
const request = { sourceId: "official", reference: avatar, read: async () => sourcePng };
await assert.rejects(service.resolveCatalogAvatar(request), /Decode failed/); assert.equal(calls, 1);
await assert.rejects(service.resolveCatalogAvatar({ ...request, read: async () => Buffer.alloc(sourcePng.length) }), /bytes/); assert.equal(calls, 1);
await assert.rejects(service.resolveCatalogAvatar({ ...request, reference: { ...avatar, path: `/assets/${avatar.sha256}.webp` } }), /format|signature/); assert.equal(calls, 1);
const cached = imageService();
await cached.resolveCatalogAvatar(request);
await assert.rejects(cached.resolveCatalogAvatar({ ...request, reference: { ...avatar, size: avatar.size + 1 } }), /bytes/);
await assert.rejects(cached.resolveCatalogAvatar({ ...request, reference: { ...avatar, path: `/assets/${avatar.sha256}.webp` } }), /format|signature/);
});
@@ -1,7 +1,6 @@
"use strict";
const path = require("node:path");
const { createHash } = require("node:crypto");
const { readContainedFile } = require("./pluginProtocol.cjs");
const { createIsolatedContributionIconRasterizer } = require("./contributionIconRasterizer.cjs");
@@ -215,35 +214,6 @@ class PluginContributionIconService {
return pending;
}
// Called only with a host-selected, hash-bound registry reference. It shares
// the existing decoder, queue, cache and pending work with package icons.
async resolveCatalogAvatar({ sourceId, reference, read }) {
const key = JSON.stringify(["catalog-avatar", sourceId, reference.path, reference.sha256, reference.size]);
if (this.cache.has(key)) return this.cache.get(key);
if (this.pending.has(key)) return this.pending.get(key);
if (this.pending.size >= MAX_QUEUED_ICON_RASTERIZATIONS + MAX_CONCURRENT_ICON_RASTERIZATIONS) {
throw new Error("Plugin image queue is full");
}
const pending = (async () => {
const body = await read();
if (!Buffer.isBuffer(body) || body.length !== reference.size || body.length > 256 * 1024
|| createHash("sha256").update(body).digest("hex") !== reference.sha256) throw new Error("Invalid plugin avatar bytes");
const extension = path.extname(reference.path);
if (![".png", ".webp"].includes(extension)) throw new Error("Invalid plugin avatar format");
const inspected = inspectContributionIconSource(body, extension);
if (inspected.mimeType !== (extension === ".png" ? "image/png" : "image/webp")) throw new Error("Plugin avatar format mismatch");
const png = await this.rasterizeIcon({ body, ...inspected, maxEdge: MAX_ICON_EDGE });
if (!png.length || png.length > MAX_ICON_PNG_BYTES) throw new Error("Plugin avatar output is too large");
inspectContributionIconSource(png, ".png", MAX_ICON_EDGE);
const value = `data:image/png;base64,${png.toString("base64")}`;
if (this.cache.size >= 256) this.cache.clear();
this.cache.set(key, value);
return value;
})().finally(() => this.pending.delete(key));
this.pending.set(key, pending);
return pending;
}
async #resolveUncached({ pluginId, plugin, icon, cacheKey }) {
const packageRoot = await this.packageStore.preparePackageRoot(plugin);
const result = Object.freeze({
-9
View File
@@ -14,12 +14,3 @@ The fixture includes no executable plugin package, avatar or credentials.
Schema revisions must be coordinated with the registry publisher. In particular,
artifact/avatar are deliberately null in v1; do not expand this consumer alone.
`delivery-v2.schema.json` is vendored without changes from
`binaricat/netcatty-plugins@2ffed31ad6a430e3711a63a902305063bd2504f8`,
`schema/delivery-v2.schema.json` (Git blob
`7a57504fbea272ca0e873725e050d1f15352cb5b`). The v2 consumer retains the pinned v1
schema and permits positive-size package references up to 16MiB and PNG/WebP avatar references.
Avatar references require positive size up to 256KiB and exact content-addressed
paths. No v3 path is added. The original bootstrap bytes remain unchanged, and
client support does not publish or activate live metadata.
@@ -1,222 +0,0 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Netcatty static delivery v2 (reviewed avatars and packages)",
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"registryCommit",
"plugins",
"catalogSha256",
"indexSha256",
"sourceLockSha256",
"builderSha256"
],
"properties": {
"schemaVersion": {
"const": 2
},
"registryCommit": {
"type": "string",
"pattern": "^[a-f0-9]{40}$"
},
"plugins": {
"type": "array",
"maxItems": 1000,
"items": {
"type": "object",
"additionalProperties": false,
"required": [
"id",
"version",
"repository",
"commit",
"readme",
"iconLight",
"iconDark",
"avatar",
"artifact"
],
"properties": {
"id": {
"type": "string"
},
"version": {
"type": "string"
},
"repository": {
"type": "string"
},
"commit": {
"type": "string",
"pattern": "^[a-f0-9]{40}$"
},
"readme": {
"type": "object",
"additionalProperties": false,
"required": [
"path",
"sha256",
"size"
],
"properties": {
"path": {
"type": "string",
"pattern": "^/assets/[a-f0-9]{64}\\.(md|png|webp|ncpkg)$"
},
"sha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"size": {
"type": "integer",
"minimum": 0,
"maximum": 262144
}
}
},
"iconLight": {
"oneOf": [
{
"type": "null"
},
{
"type": "object",
"additionalProperties": false,
"required": [
"path",
"sha256",
"size"
],
"properties": {
"path": {
"type": "string",
"pattern": "^/assets/[a-f0-9]{64}\\.(md|png|webp|ncpkg)$"
},
"sha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"size": {
"type": "integer",
"minimum": 0,
"maximum": 262144
}
}
}
]
},
"iconDark": {
"oneOf": [
{
"type": "null"
},
{
"type": "object",
"additionalProperties": false,
"required": [
"path",
"sha256",
"size"
],
"properties": {
"path": {
"type": "string",
"pattern": "^/assets/[a-f0-9]{64}\\.(md|png|webp|ncpkg)$"
},
"sha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"size": {
"type": "integer",
"minimum": 0,
"maximum": 262144
}
}
}
]
},
"avatar": {
"oneOf": [
{
"type": "null"
},
{
"type": "object",
"additionalProperties": false,
"required": [
"path",
"sha256",
"size"
],
"properties": {
"path": {
"type": "string",
"pattern": "^/assets/[a-f0-9]{64}\\.(png|webp)$"
},
"sha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"size": {
"type": "integer",
"minimum": 1,
"maximum": 262144
}
}
}
]
},
"artifact": {
"oneOf": [
{
"type": "null"
},
{
"type": "object",
"additionalProperties": false,
"required": [
"path",
"sha256",
"size"
],
"properties": {
"path": {
"type": "string",
"pattern": "^/assets/[a-f0-9]{64}\\.ncpkg$"
},
"sha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"size": {
"type": "integer",
"minimum": 1,
"maximum": 16777216
}
}
}
]
}
}
}
},
"catalogSha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"indexSha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"sourceLockSha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
},
"builderSha256": {
"type": "string",
"pattern": "^[a-f0-9]{64}$"
}
}
}
+9 -3
View File
@@ -16,7 +16,14 @@ ajv.addSchema(require("./generated/plugin-contract.schema.json"));
const validateIndex = ajv.compile(require("./distribution/index.schema.json"));
const deliverySchema = require("./distribution/delivery.schema.json");
const validateDelivery = ajv.compile(deliverySchema);
const validateDeliveryV2 = ajv.compile(require("./distribution/delivery-v2.schema.json"));
const deliveryV2 = structuredClone(deliverySchema);
deliveryV2.title = "Netcatty static delivery v2 (hash-bound packages)";
deliveryV2.properties.schemaVersion.const = 2;
const packageRef = structuredClone(deliveryV2.properties.plugins.items.properties.readme);
packageRef.properties.path.pattern = "^/assets/[a-f0-9]{64}\\.ncpkg$";
packageRef.properties.size.maximum = 32 * 1024 * 1024;
deliveryV2.properties.plugins.items.properties.artifact = { oneOf: [{ type: "null" }, packageRef] };
const validateDeliveryV2 = ajv.compile(deliveryV2);
const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
const tuple = (entry) => JSON.stringify([entry.id, entry.version, entry.repository, entry.commit]);
@@ -94,10 +101,9 @@ function validateSet(pointer, entries, index, delivery, origin = DISTRIBUTION_OR
if (!catalogTuples.has(key) || resources.has(key)) throw new Error("Delivery identity does not match catalog tuple");
assertAsset(plugin.readme, ["md"]);
for (const icon of [plugin.iconLight, plugin.iconDark]) if (icon !== null) assertAsset(icon, ["png", "webp"]);
if (plugin.avatar !== null) assertAsset(plugin.avatar, ["png", "webp"]);
const entry = entries.find((item) => tuple(item) === key);
if (plugin.artifact !== null) {
assertReference(plugin.artifact, `/assets/${plugin.artifact.sha256}.ncpkg`, 16 * 1024 * 1024);
assertReference(plugin.artifact, `/assets/${plugin.artifact.sha256}.ncpkg`, 32 * 1024 * 1024);
if (!entry.artifact || entry.artifact.sha256 !== plugin.artifact.sha256 || entry.artifact.url !== `${origin}${plugin.artifact.path}`) throw new Error("Package delivery does not match catalog hash and source");
} else if (entry.artifact) throw new Error("Catalog package has no delivery resource");
resources.set(key, plugin);
+1 -2
View File
@@ -478,8 +478,7 @@ function createPluginHostService(options) {
themeService,
interactionService,
hostVaultService,
catalogService: new MarketSourcesService({ database, manager, fetch: options.electron.net?.fetch?.bind(options.electron.net),
resolveAvatar: (request) => contributionIconService.resolveCatalogAvatar(request) }),
catalogService: new MarketSourcesService({ database, manager, fetch: options.electron.net?.fetch?.bind(options.electron.net) }),
companionSupervisor,
contributionIconService,
contributionService,
-30
View File
@@ -2,9 +2,6 @@
const { PluginSourceRegistry } = require("./sourceRegistry.cjs");
const { RegistryCatalogService } = require("./registryCatalogService.cjs");
const { createSourceFetch } = require("./sourceFetch.cjs");
const { isDeepStrictEqual } = require("node:util");
const installedIdentity = (plugin) => JSON.stringify([plugin?.id, plugin?.activeVersion, plugin?.archiveSha256, plugin?.source, plugin?.manifest, plugin?.runtime?.quarantinedAt]);
class MarketSourcesService {
constructor(options) {
@@ -27,33 +24,6 @@ class MarketSourcesService {
}
list(sourceId) { return this.#catalog(sourceId).list(); }
readme(id, token, sourceId) { return this.#catalog(sourceId).readme(id, token); }
async author(request) {
if (!request || typeof request !== "object" || Array.isArray(request)
|| typeof request.pluginId !== "string" || !/^[a-z0-9][a-z0-9.-]{1,127}$/u.test(request.pluginId)) throw new TypeError("Invalid plugin author request");
if (request.kind === "catalog") {
if (Object.keys(request).some((key) => !["kind", "pluginId", "selectionToken", "sourceId"].includes(key))) throw new TypeError("Invalid plugin author request");
return this.#catalog(request.sourceId).author(request.pluginId, request.selectionToken);
}
if (request.kind !== "installed" || Object.keys(request).some((key) => !["kind", "pluginId"].includes(key))) throw new TypeError("Invalid installed author request");
const plugin = this.options.database.getActivePlugin(request.pluginId);
if (!plugin?.activeVersion) return null;
const captured = installedIdentity(plugin);
let value = { author: plugin.manifest?.publisher ?? "", avatar: null, officialMaintained: false,
sourceId: plugin.source.id, version: plugin.activeVersion, archiveSha256: plugin.archiveSha256 ?? null };
if (plugin.runtime?.quarantinedAt == null) {
try {
// Presentation reuses an already validated catalog. It never refreshes
// a source merely because the installed list becomes visible.
this.registry.get(plugin.source.id);
const catalog = this.catalogs.get(plugin.source.id);
const entry = catalog?.publicEntries.find((item) => item.id === plugin.id && item.version === plugin.activeVersion
&& item.artifact?.sha256 === plugin.archiveSha256 && isDeepStrictEqual(item.manifest, plugin.manifest));
if (entry) value = await catalog.author(entry.id, entry.selectionToken);
} catch { /* No exact current source match confers no maintenance badge. */ }
}
if (captured !== installedIdentity(this.options.database.getActivePlugin(request.pluginId))) throw new Error("Installed plugin changed while loading its author");
return value;
}
install(id, token, sourceId = "official", acceptedSourceId) {
if (sourceId !== "official" && acceptedSourceId !== sourceId) throw new Error("Review and confirm this third-party source before installing");
return this.#catalog(sourceId).install(id, token);
-5
View File
@@ -42,7 +42,6 @@ const CHANNELS = Object.freeze({
removeSource: "netcatty:plugins:remove-source",
catalog: "netcatty:plugins:catalog",
catalogReadme: "netcatty:plugins:catalog-readme",
author: "netcatty:plugins:author",
catalogInstall: "netcatty:plugins:catalog-install",
install: "netcatty:plugins:install",
setEnabled: "netcatty:plugins:set-enabled",
@@ -680,10 +679,6 @@ function registerPluginBridge(ipcMain, options) {
handle(CHANNELS.updateSource, async (_manager, payload) => options.catalogService.updateSource(payload));
handle(CHANNELS.removeSource, async (_manager, payload) => options.catalogService.removeSource(payload));
handle(CHANNELS.catalog, async (_manager, payload) => options.catalogService?.list(payload?.sourceId) ?? { entries: [], source: "builtin", error: "Plugin catalog unavailable" });
handle(CHANNELS.author, async (_manager, payload) => {
if (!options.catalogService) throw new Error("Plugin catalog unavailable");
return options.catalogService.author(payload);
});
handle(CHANNELS.catalogReadme, async (_manager, payload) => {
if (!options.catalogService) throw new Error("Plugin catalog unavailable");
return options.catalogService.readme(payload?.id, payload?.selectionToken, payload?.sourceId);
-13
View File
@@ -101,19 +101,6 @@ test("plugin management bridge checks sender ownership before invoking manager",
);
});
test("author presentation is a trusted-app-only route and forwards no invented authority", async () => {
const ipcMain = createIpcMain(); const calls = [];
registerPluginBridge(ipcMain, { manager: { initialize: async () => {} }, isTrustedSender: createTrustedPluginBridgeSender({ devServerUrl: "http://localhost:5173" }),
catalogService: { author: async (request) => { calls.push(request); return { author: "Netcatty", avatar: null, officialMaintained: false }; } } });
const payload = { kind: "catalog", pluginId: "com.netcatty.starter", selectionToken: "a".repeat(64), sourceId: "official" };
for (const url of ["netcatty-plugin://plugin-runtime/index.html", "https://attacker.invalid/"]) {
await assert.rejects(ipcMain.handlers.get(CHANNELS.author)({ senderFrame: { url } }, payload), /Untrusted/);
}
assert.deepEqual(calls, []);
const result = await ipcMain.handlers.get(CHANNELS.author)({ senderFrame: { url: "app://netcatty/index.html" } }, payload);
assert.equal(result.officialMaintained, false); assert.deepEqual(calls, [payload]);
});
test("plugin Vault credential catalog updates only through the trusted host bridge", async () => {
const ipcMain = createIpcMain();
const updates = [];
@@ -3,7 +3,6 @@
const { createHash } = require("node:crypto");
const { PluginCatalogService, validateCatalog, MAX_CATALOG_BYTES } = require("./catalogService.cjs");
const { REGISTRY_URL, fetchDistribution, fetchVerified, tuple } = require("./distributionSnapshot.cjs");
const { isOfficialMaintained } = require("./sourceIdentity.cjs");
const tokenFor = (entry) => createHash("sha256").update(JSON.stringify(entry)).digest("hex");
function prepareSnapshot(value, resources = new Map(), source) {
@@ -20,7 +19,6 @@ class RegistryCatalogService extends PluginCatalogService {
this.source = "builtin";
this.error = null;
this.refreshing = null;
this.resolveAvatar = options.resolveAvatar;
}
async refresh() {
if (this.refreshing) return this.refreshing;
@@ -60,22 +58,6 @@ class RegistryCatalogService extends PluginCatalogService {
return entry;
}
artifactSize(entry) { return this.resources.get(tuple(entry))?.artifact?.size; }
async author(id, token) {
this.sourceGuard();
const entry = this.selected(id, token);
const reference = this.resources.get(tuple(entry))?.avatar;
let avatar = null;
if (reference && this.resolveAvatar) {
try {
avatar = await this.resolveAvatar({ sourceId: this.marketSource.id, reference,
read: () => fetchVerified(reference, this.fetch, this.origin) });
} catch { /* Missing or invalid imagery uses the same author placeholder. */ }
}
this.sourceGuard();
this.selected(id, token);
return { author: entry.author, avatar, officialMaintained: isOfficialMaintained(entry, this.marketSource),
sourceId: this.marketSource.id, version: entry.version, archiveSha256: entry.artifact?.sha256 ?? null };
}
async readme(id, token) {
const entry = this.selected(id, token);
const resource = this.resources.get(tuple(entry))?.readme;
+1 -13
View File
@@ -6,11 +6,6 @@ const { isIP } = require("node:net");
const OFFICIAL_ORIGIN = "https://plugins.netcatty.app";
const OFFICIAL_SOURCE = Object.freeze({ id: "official", kind: "official", name: "Netcatty marketplace", origin: OFFICIAL_ORIGIN });
const LOCAL_SOURCE = Object.freeze({ id: "local", kind: "local", name: "Local import", origin: null });
// Curated first-party maintenance authority, independent of manifest publisher text.
const FIRST_PARTY_PLUGINS = Object.freeze([
Object.freeze({ id: "com.netcatty.starter", repository: "binaricat/Netcatty" }),
Object.freeze({ id: "com.netcatty.hello", repository: "binaricat/Netcatty" }),
]);
const hash = (value) => createHash("sha256").update(value).digest("hex");
// Source identity is host-owned. Neither a manifest nor a catalog supplies kind/id.
@@ -46,11 +41,4 @@ function privateOwner(source, pluginId) {
return `source:${hash(assertSource(source).id)}:${pluginId}`;
}
function isOfficialMaintained(entry, source) {
const trusted = assertSource(source);
return trusted.id === OFFICIAL_SOURCE.id && trusted.kind === OFFICIAL_SOURCE.kind
&& trusted.origin === OFFICIAL_SOURCE.origin
&& FIRST_PARTY_PLUGINS.some((pair) => pair.id === entry.id && pair.repository === entry.repository);
}
module.exports = { OFFICIAL_SOURCE, LOCAL_SOURCE, canonicalSourceOrigin, thirdPartySource, assertSource, privateOwner, isOfficialMaintained };
module.exports = { OFFICIAL_SOURCE, LOCAL_SOURCE, canonicalSourceOrigin, thirdPartySource, assertSource, privateOwner };
-1
View File
@@ -106,7 +106,6 @@ function createPreloadApi(ctx) {
updatePluginSource: (source) => ipcRenderer.invoke("netcatty:plugins:update-source", source),
removePluginSource: (id, disablePlugins) => ipcRenderer.invoke("netcatty:plugins:remove-source", { id, disablePlugins }),
listPluginCatalog: (sourceId) => ipcRenderer.invoke("netcatty:plugins:catalog", { sourceId }),
getPluginAuthorPresentation: (request) => ipcRenderer.invoke("netcatty:plugins:author", request),
getPluginCatalogReadme: (id, selectionToken, sourceId) => ipcRenderer.invoke("netcatty:plugins:catalog-readme", { id, selectionToken, sourceId }),
installCatalogPlugin: (id, selectionToken, sourceId, acceptedSourceId) => ipcRenderer.invoke("netcatty:plugins:catalog-install", { id, selectionToken, sourceId, acceptedSourceId }),
setPluginAIHostReady: (ready) => ipcRenderer.invoke("netcatty:plugins:ai-host-ready", ready),
+3 -5
View File
@@ -11,11 +11,9 @@ Group results contain the chosen current members and never include future member
label change for the first chosen host. Netcatty displays editable fields and the
normalized field diff before either action saves.
`connect` requests a saved-host connection under the plugin's permission settings.
Ask displays the target and whether saved scripts can run; Allow can dispatch
without that permission-only dialog, and Deny blocks the request. Normal SSH
authentication still applies. The acknowledgement contains no session identifier
or terminal data. Selecting metadata does not change those permission settings.
`connect` asks Netcatty to confirm a saved-host connection. The confirmation shows
whether saved scripts can run. The acknowledgement contains no session identifier
or terminal data. Selecting metadata never authorizes a connection by itself.
All sample test resources use synthetic hostnames. Native acceptance must use
synthetic hosts and must not establish a real host connection.
Vendored
-13
View File
@@ -355,18 +355,6 @@ declare global {
artifact?: { url: string; sha256: string };
}
type NetcattyPluginAuthorRequest =
| { kind: 'catalog'; pluginId: string; selectionToken: string; sourceId: string }
| { kind: 'installed'; pluginId: string };
interface NetcattyPluginAuthorPresentation {
author: string;
avatar: string | null;
officialMaintained: boolean;
sourceId: string;
version: string;
archiveSha256: string | null;
}
type PluginPermissionMode = 'allow' | 'ask' | 'deny';
type NetcattyPluginPermissionPrompt = import('@netcatty/plugin-contract').PermissionRequest & {
actionToken: string; resources: string[];
@@ -489,7 +477,6 @@ declare global {
updatePluginSource?(source: { id: string; name: string; enabled: boolean }): Promise<NetcattyPluginSource>;
removePluginSource?(id: string, disablePlugins: boolean): Promise<void>;
listPluginCatalog?(sourceId?: string): Promise<NetcattyPluginCatalogSnapshot>;
getPluginAuthorPresentation?(request: NetcattyPluginAuthorRequest): Promise<NetcattyPluginAuthorPresentation | null>;
getPluginCatalogReadme?(id: string, selectionToken?: string, sourceId?: string): Promise<string>;
installCatalogPlugin?(id: string, selectionToken?: string, sourceId?: string, acceptedSourceId?: string): Promise<NetcattyInstalledPlugin>;
setPluginAIHostReady?(ready: boolean): Promise<boolean>;
+1 -2
View File
@@ -117,8 +117,7 @@ export interface PluginHostUI {
}
/** Saved-host selection does not grant editing, connecting or session access.
* Later actions follow the plugin's permission settings. Host drafts retain
* the host editor; connections retain normal authentication. */
* Each action uses the host's separate review and confirmation UI. */
export interface PluginVault {
selectHosts(params: import("@netcatty/plugin-contract").VaultSelectHostsParams): Promise<import("@netcatty/plugin-contract").VaultHostSelectionResult>;
/** Managed SSH-config drafts require the full Vault host editor. */