From bb3fbda8e77ab9e1a602272018e70354d9814fa3 Mon Sep 17 00:00:00 2001 From: John McLear Date: Sat, 21 Nov 2026 12:14:14 +0000 Subject: [PATCH 1/3] feat(admin): label official vs third-party plugins in the catalog Anyone can publish an ep_* package, and junk placeholders (0.0.0-stage, no repository) have started showing up in the plugin feed and the admin catalog. The project cannot review every plugin, so the catalog now marks plugins it publishes as Official and everything else as Third-party. Official is decided by npm provenance, not by self-declared fields: the SLSA attestation for the exact name@version (digest checked against dist.integrity) must come from a github.com/ether/* repository with the ether org's numeric owner ID. It is computed at catalog refresh and cached per version. The feed's own `official` flag is overwritten. - Third-party plugins stay listed with a badge; installing one asks for confirmation first. Official plugins install with one click. - Placeholder packages are left out of browsing but still found by an exact-name search. - New pluginCatalogThirdParty setting: label (default), hide, all. - CLI installs are unaffected. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TcYAoDMav4BPPE9JrMtSvw --- admin/src/index.css | 32 +++ admin/src/pages/HomePage.tsx | 61 ++++- admin/src/pages/Plugin.ts | 4 + doc/plugins.adoc | 35 +++ doc/plugins.md | 33 +++ settings.json.template | 15 ++ src/locales/en.json | 6 + src/node/types/PackageInfo.ts | 11 + src/node/utils/Settings.ts | 12 + src/static/js/pluginfw/installer.ts | 180 ++++++++++++--- src/static/js/pluginfw/pluginTrust.ts | 156 +++++++++++++ src/tests/backend/specs/pluginCatalog.ts | 142 +++++++++++- src/tests/backend/specs/pluginTrust.ts | 210 ++++++++++++++++++ .../admin-spec/admin_plugin_trust.spec.ts | 118 ++++++++++ .../admin-spec/adminupdateplugins.spec.ts | 7 + 15 files changed, 987 insertions(+), 35 deletions(-) create mode 100644 src/static/js/pluginfw/pluginTrust.ts create mode 100644 src/tests/backend/specs/pluginTrust.ts create mode 100644 src/tests/frontend-new/admin-spec/admin_plugin_trust.spec.ts diff --git a/admin/src/index.css b/admin/src/index.css index bfbb645e1c8..29413dee9f3 100644 --- a/admin/src/index.css +++ b/admin/src/index.css @@ -1314,6 +1314,38 @@ a.pm-btn-primary:link, a.pm-btn-primary:visited { color: #fff; } cursor: help; } +.pm-tag--official { + background: rgba(20,148,116,.12); + color: var(--ep-accent-d); + border: 1px solid rgba(20,148,116,.3); + cursor: help; +} +.pm-tag--third-party { + background: var(--line-2); + color: var(--ink-2); + border: 1px solid var(--line); + cursor: help; +} + +/* Third-party install confirmation */ +.pm-dialog-content { + position: fixed; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + z-index: 101; + width: min(460px, calc(100vw - 32px)); + background: var(--panel); + color: var(--ink); + border: 1px solid var(--line); + border-radius: var(--r-lg); + padding: 20px; + box-shadow: 0 10px 38px -10px rgba(0,0,0,.35); +} +.pm-dialog-title { margin: 0 0 8px; font-size: 16px; font-weight: 600; } +.pm-dialog-body { margin: 0; font-size: 13.5px; line-height: 1.5; color: var(--ink-2); } +.pm-dialog-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 18px; } + /* Toolbar (search + sort) */ .pm-toolbar { display: flex; diff --git a/admin/src/pages/HomePage.tsx b/admin/src/pages/HomePage.tsx index e879820ec84..3227c60bdaa 100644 --- a/admin/src/pages/HomePage.tsx +++ b/admin/src/pages/HomePage.tsx @@ -5,6 +5,7 @@ import {useDebounce} from "../utils/useDebounce.ts"; import {Trans, useTranslation} from "react-i18next"; import {ArrowUpFromDot, Download, ExternalLink, Plug, RefreshCw, Search, Trash, X} from "lucide-react"; import {IconButton} from "../components/IconButton.tsx"; +import * as Dialog from "@radix-ui/react-dialog"; export const HomePage = () => { const pluginsSocket = useStore(state => state.pluginsSocket) @@ -24,6 +25,8 @@ export const HomePage = () => { searchTerm: '', }) const [searchTerm, setSearchTerm] = useState('') + // Third-party plugin awaiting the admin's confirmation before install. + const [confirmInstall, setConfirmInstall] = useState(null) const {t} = useTranslation() const updatableCount = useMemo( @@ -145,6 +148,17 @@ export const HomePage = () => { setPlugins(plugins.filter(p => p.name !== pluginName)) } + // Official plugins install with one click. A third-party plugin runs code + // the Etherpad project has not reviewed, so the admin confirms first; the + // extra, deliberate click also blunts clickjacking of the Install button. + const requestInstall = (plugin: PluginDef) => { + if (plugin.official) { + installPlugin(plugin.name) + } else { + setConfirmInstall(plugin.name) + } + } + useDebounce(() => { setSearchParams({...searchParams, offset: 0, searchTerm}) }, 500, [searchTerm]) @@ -152,6 +166,40 @@ export const HomePage = () => { return (
+ { if (!open) setConfirmInstall(null) }} + > + + + + + + + + {t('admin_plugins.third_party_confirm_body', {plugin: confirmInstall ?? ''})} + +
+ + + + +
+
+
+
+ {catalogDisabled && (
@@ -362,6 +410,17 @@ export const HomePage = () => { target="_blank" rel="noopener noreferrer" >{plugin.name} + {plugin.official ? ( + + ) : ( + + )}
@@ -385,7 +444,7 @@ export const HomePage = () => { diff --git a/admin/src/pages/Plugin.ts b/admin/src/pages/Plugin.ts index db28fa732f3..a1374058e72 100644 --- a/admin/src/pages/Plugin.ts +++ b/admin/src/pages/Plugin.ts @@ -3,6 +3,10 @@ export type PluginDef = { description: string, version: string, time: string, + /** + * Published from an ether/* GitHub repository, as shown by npm provenance. + * Computed by the server; anything else is third-party. + */ official: boolean, /** * `@feature:*` Playwright tags for core specs the plugin intentionally diff --git a/doc/plugins.adoc b/doc/plugins.adoc index 5e19630acf0..91d17901295 100644 --- a/doc/plugins.adoc +++ b/doc/plugins.adoc @@ -26,6 +26,41 @@ a failed lookup — if the npm registry cannot be reached the full catalog is listed and installs proceed — and `pnpm run plugins i ep_` on the server installs it anyway, for an operator who knows what they are doing. +==== Official and third-party plugins + +Anyone can publish an `ep_*` package to npm, and the Etherpad project cannot +review all of them. The catalog marks a plugin *Official* when npm +provenance shows that the published version was built by GitHub Actions from +a repository in the https://github.com/ether[ether] GitHub org. Everything +else is labelled *Third-party*: it is not maintained by the Etherpad +project and it runs code on your server. The admin UI asks for confirmation +before installing a third-party plugin; official plugins install with one +click. + +The check is done when the catalog is refreshed and cached per published +version, so it adds no latency to browsing. It relies on npm provenance +rather than on the package's `repository` field, its maintainer list or the +feed's own flags, because a publisher can set any of those to whatever they +like (`src/static/js/pluginfw/pluginTrust.ts`). A plugin from the ether org +that has not been released with provenance yet shows as third-party until its +next release. + +Placeholder packages (a `0.0.0-*` version, or no `repository` in +package.json) are left out of the list, but a search for the exact package +name still finds them, so you can find a package you have just published. + +The `pluginCatalogThirdParty` setting in `settings.json` changes this: + +|=== +| Value | Effect + +| `label` (default) | List third-party plugins with a badge; placeholders only on an exact-name search. +| `hide` | List official plugins only. +| `all` | List everything, placeholders included. +|=== + +None of this affects `pnpm run plugins i ep_` on the server. + === Folder structure Ideally a plugin has the following folder structure: diff --git a/doc/plugins.md b/doc/plugins.md index 4ec6700b350..fe76f4a0a6f 100644 --- a/doc/plugins.md +++ b/doc/plugins.md @@ -27,6 +27,39 @@ a failed lookup — if the npm registry cannot be reached the full catalog is listed and installs proceed — and `pnpm run plugins i ep_` on the server installs it anyway, for an operator who knows what they are doing. +### Official and third-party plugins + +Anyone can publish an `ep_*` package to npm, and the Etherpad project cannot +review all of them. The catalog marks a plugin **Official** when npm +provenance shows that the published version was built by GitHub Actions from +a repository in the [ether](https://github.com/ether) GitHub org. Everything +else is labelled **Third-party**: it is not maintained by the Etherpad +project and it runs code on your server. The admin UI asks for confirmation +before installing a third-party plugin; official plugins install with one +click. + +The check is done when the catalog is refreshed and cached per published +version, so it adds no latency to browsing. It relies on npm provenance +rather than on the package's `repository` field, its maintainer list or the +feed's own flags, because a publisher can set any of those to whatever they +like (`src/static/js/pluginfw/pluginTrust.ts`). A plugin from the ether org +that has not been released with provenance yet shows as third-party until its +next release. + +Placeholder packages — a `0.0.0-*` version, or no `repository` in +package.json — are left out of the list, but a search for the exact package +name still finds them, so you can find a package you have just published. + +The `pluginCatalogThirdParty` setting in `settings.json` changes this: + +| Value | Effect | +| --- | --- | +| `label` (default) | List third-party plugins with a badge; placeholders only on an exact-name search. | +| `hide` | List official plugins only. | +| `all` | List everything, placeholders included. | + +None of this affects `pnpm run plugins i ep_` on the server. + ## Folder structure Ideally a plugin has the following folder structure: diff --git a/settings.json.template b/settings.json.template index f6ab6f114b9..26f8aac9205 100644 --- a/settings.json.template +++ b/settings.json.template @@ -488,6 +488,21 @@ "pluginCatalog": "${PRIVACY_PLUGIN_CATALOG:true}" }, + /* + * Plugins in the admin catalog that are not published by the Etherpad + * project are labelled "Third-party": they are not reviewed by the project + * and run code on your server. "Official" means npm provenance shows the + * package was built from a repository in the ether GitHub org. + * - "label" (default): list third-party plugins with a badge and ask for + * confirmation before installing them. Placeholder + * packages (0.0.0-* versions, no repository) are only + * listed when searched for by their exact name. + * - "hide" : list official plugins only. + * - "all" : list everything, placeholders included. + * `pnpm run plugins i ep_` on the server is never affected. + */ + "pluginCatalogThirdParty": "${PLUGIN_CATALOG_THIRD_PARTY:label}", + /* * Should we suppress errors from being visible in the default Pad Text? */ diff --git a/src/locales/en.json b/src/locales/en.json index 7160819df6a..fbc722f1a1d 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -94,6 +94,12 @@ "admin_plugins.deprecated_title": "This plugin is no longer maintained and may break Etherpad. Consider uninstalling it.", "admin_plugins.tag_core": "Core", "admin_plugins.tag_deprecated": "Deprecated", + "admin_plugins.tag_official": "Official", + "admin_plugins.tag_official_title": "Published by the Etherpad project from the ether GitHub organization.", + "admin_plugins.tag_third_party": "Third-party", + "admin_plugins.tag_third_party_title": "Not maintained by the Etherpad project. Plugins run code on your server.", + "admin_plugins.third_party_confirm_title": "Install a third-party plugin?", + "admin_plugins.third_party_confirm_body": "{{plugin}} is not maintained by the Etherpad project and has not been reviewed by it. Plugins run code on your server, with access to your pads and settings. Only install it if you trust its author.", "admin_plugins.update_tooltip": "Update", "admin_plugins.updates_available": "Updates available", "admin_plugins.update_now": "Update", diff --git a/src/node/types/PackageInfo.ts b/src/node/types/PackageInfo.ts index ea10c6a360a..b18d00447c8 100644 --- a/src/node/types/PackageInfo.ts +++ b/src/node/types/PackageInfo.ts @@ -24,6 +24,17 @@ export type PackageInfo = { * `warning` or `failed`. Feed-provided; see pluginCatalogFilter.ts. */ compatibility?: string, + /** + * Catalog entries only: published from an ether/* GitHub repository, as + * shown by npm provenance. Set by core (pluginTrust.ts); the feed's own + * `official` flag is overwritten because it cannot be verified. + */ + official?: boolean, + /** + * Catalog entries only: a `0.0.0-*` or repository-less package, left out + * of browsing and listed only on an exact-name search. + */ + placeholder?: boolean, /** Set on *installed* plugins when a newer version is available. */ updatable?: boolean, /** diff --git a/src/node/utils/Settings.ts b/src/node/utils/Settings.ts index 660bb2e273a..c542145f8ec 100644 --- a/src/node/utils/Settings.ts +++ b/src/node/utils/Settings.ts @@ -207,6 +207,7 @@ export type SettingsType = { updateCheck: boolean, pluginCatalog: boolean, }, + pluginCatalogThirdParty: string, skinName: string | null, skinVariants: string, ip: string, @@ -495,6 +496,17 @@ const settings: SettingsType = { // (installer.ts). Manual install via CLI still works. pluginCatalog: true, }, + /* + * How the admin plugin catalog treats plugins that are not published by + * the Etherpad project (see src/static/js/pluginfw/pluginTrust.ts): + * - 'label' (default): list them with a "Third-party" badge and ask for + * confirmation before installing; placeholder packages (0.0.0-* + * versions, no repository) only show up on an exact-name search. + * - 'hide': list official plugins only. + * - 'all': list everything, placeholders included. + * Installs from the command line are never affected. + */ + pluginCatalogThirdParty: 'label', /* * Skin name. * diff --git a/src/static/js/pluginfw/installer.ts b/src/static/js/pluginfw/installer.ts index 85179ac9f23..c7211be2327 100644 --- a/src/static/js/pluginfw/installer.ts +++ b/src/static/js/pluginfw/installer.ts @@ -30,6 +30,14 @@ import { PluginDeprecatedError, } from './pluginCatalogFilter'; import {InstallerTaskQueue} from './installerTasks'; +import { + hasRepositoryField, + isListedInCatalog, + isOfficialProvenance, + isPlaceholderPackage, + normalizeThirdPartyMode, + provenanceSource, +} from './pluginTrust'; import {findEtherpadRoot} from '../../../node/utils/AbsolutePaths'; const logger = log4js.getLogger('plugins'); @@ -170,7 +178,12 @@ export const uninstall = async (pluginName: string, cb:Function|null = null) => // promise forever — without it the finished:install socket event would never // fire and the admin UI would stay spinning indefinitely. const ENGINES_PREFLIGHT_TIMEOUT_MS = 5000; -type NpmVersionMeta = {engines?: {node?: string}, deprecated?: unknown}; +type NpmVersionMeta = { + engines?: {node?: string}, + deprecated?: unknown, + repository?: unknown, + dist?: {integrity?: unknown, attestations?: {url?: unknown}}, +}; const fetchPluginVersionMeta = async ( pluginName: string, version = 'latest', @@ -189,47 +202,95 @@ const fetchPluginVersionMeta = async ( } }; -// Deprecation lookups are cached by name@version because a published version -// is immutable apart from its deprecation flag, which changes maybe once in -// a package's lifetime. Without the cache the admin plugin page would hit -// the npm registry once per listed plugin on every catalog refresh. +/** + * Whether the given published version carries npm provenance from a + * repository in the ether GitHub org (see pluginTrust.ts). Only the + * registry's own attestations endpoint is consulted; a URL pointing anywhere + * else is ignored. Returns undefined when the lookup failed, so the caller + * does not cache a transient failure as "third-party". + */ +const fetchOfficialProvenance = async ( + name: string, + meta: NpmVersionMeta, + signal: AbortSignal, +): Promise => { + const url = meta.dist?.attestations?.url; + const version = (meta as any).version; + if (typeof url !== 'string' || typeof version !== 'string') return false; + if (!url.startsWith(`${npmRegistry}/-/npm/v1/attestations/`)) return false; + try { + const res = await fetch(url, {headers, signal}); + if (res.status === 404) return false; + if (!res.ok) return undefined; + const source = provenanceSource(await res.json(), + {name, version, integrity: meta.dist?.integrity}); + return isOfficialProvenance(source); + } catch (err) { + logger.debug(`npm provenance lookup for ${name}@${version} fell through: ${err}`); + return undefined; + } +}; + +/** What the catalog learns about one published version from npm. */ +export type PluginRegistryInfo = { + /** npm deprecation message, or null when not deprecated. */ + deprecated: string | null, + /** Whether the version's package.json names a repository. */ + hasRepository: boolean, + /** Built and published from an ether/* repository (npm provenance). */ + official: boolean, +}; + +// Lookups are cached by name@version because a published version is +// immutable apart from its deprecation flag, which changes maybe once in a +// package's lifetime. Without the cache the admin plugin page would hit the +// npm registry once per listed plugin on every catalog refresh. Provenance +// never changes for a published version, so it is cached separately and +// without expiry: the attestation fetch happens once per version. const DEPRECATION_TTL_MS = 12 * 60 * 60 * 1000; const DEPRECATION_SWEEP_BUDGET_MS = 15000; const DEPRECATION_CONCURRENCY = 8; const DEPRECATION_CACHE_MAX = 1000; -const deprecationCache = new Map(); +const registryInfoCache = new Map(); +const provenanceCache = new Map(); // Lookups that have been started but not finished, so two concurrent sweeps // (the admin page fires `getInstalled` and `search` together) join one // request per package instead of issuing two. `undefined` means the lookup -// failed, i.e. the deprecation state is unknown. -const deprecationInFlight = new Map>(); +// failed, i.e. the state is unknown. +const registryInfoInFlight = new Map>(); // Exported for tests; also lets an operator-triggered catalog reload pick up // a deprecation published in the last 12 hours. -export const clearDeprecationCache = () => deprecationCache.clear(); +export const clearDeprecationCache = () => { + registryInfoCache.clear(); + provenanceCache.clear(); +}; /** - * Looks up the npm deprecation notice for each of the given packages. + * Looks up deprecation, repository and provenance for each of the given + * packages. * * Fail-open by design: a package whose lookup fails (offline, npm blocked by * a firewall, 404, timeout, overall budget exceeded) is simply absent from - * the returned map, and the caller then treats it as not deprecated. An - * admin behind a firewall gets the full catalog, not an empty one. + * the returned map, and the caller then treats it as not deprecated and not + * a placeholder. An admin behind a firewall gets the full catalog, not an + * empty one. Unknown provenance is never treated as official. */ -export const fetchPluginDeprecations = async ( +export const fetchPluginRegistryInfo = async ( pkgs: ReadonlyArray<{name: string, version?: string}>, -): Promise> => { - const result = new Map(); +): Promise> => { + const result = new Map(); const pending: Array<{name: string, version: string, key: string}> = []; const now = Date.now(); - if (deprecationCache.size > DEPRECATION_CACHE_MAX) deprecationCache.clear(); + if (registryInfoCache.size > DEPRECATION_CACHE_MAX) registryInfoCache.clear(); + if (provenanceCache.size > DEPRECATION_CACHE_MAX) provenanceCache.clear(); for (const pkg of pkgs) { if (!pkg || typeof pkg.name !== 'string') continue; const version = typeof pkg.version === 'string' && pkg.version ? pkg.version : 'latest'; const key = `${pkg.name}@${version}`; - const cached = deprecationCache.get(key); + const cached = registryInfoCache.get(key); if (cached && cached.expires > now) { - result.set(pkg.name, cached.deprecated); + result.set(pkg.name, cached.info); } else { pending.push({name: pkg.name, version, key}); } @@ -240,16 +301,35 @@ export const fetchPluginDeprecations = async ( // on the remainder rather than making the admin page wait indefinitely. const budget = AbortSignal.timeout(DEPRECATION_SWEEP_BUDGET_MS); const lookup = (job: {name: string, version: string, key: string}) => { - const started = deprecationInFlight.get(job.key); + const started = registryInfoInFlight.get(job.key); if (started) return started; - const promise = (async () => { + const promise = (async (): Promise => { const meta = await fetchPluginVersionMeta(job.name, job.version, budget); if (meta === undefined) return undefined; // unknown -> not hidden - const deprecated = normalizeDeprecation(meta.deprecated); - deprecationCache.set(job.key, {deprecated, expires: Date.now() + DEPRECATION_TTL_MS}); - return deprecated; - })().finally(() => deprecationInFlight.delete(job.key)); - deprecationInFlight.set(job.key, promise); + const resolvedKey = typeof (meta as any).version === 'string' + ? `${job.name}@${(meta as any).version}` : job.key; + let official = provenanceCache.get(resolvedKey); + let cacheable = true; + if (official === undefined) { + const fetched = await fetchOfficialProvenance(job.name, meta, budget); + if (fetched === undefined) { + cacheable = false; + } else { + provenanceCache.set(resolvedKey, fetched); + } + official = fetched === true; + } + const info: PluginRegistryInfo = { + deprecated: normalizeDeprecation(meta.deprecated), + hasRepository: hasRepositoryField(meta.repository), + official, + }; + if (cacheable) { + registryInfoCache.set(job.key, {info, expires: Date.now() + DEPRECATION_TTL_MS}); + } + return info; + })().finally(() => registryInfoInFlight.delete(job.key)); + registryInfoInFlight.set(job.key, promise); return promise; }; let index = 0; @@ -257,19 +337,30 @@ export const fetchPluginDeprecations = async ( while (index < pending.length) { if (budget.aborted) return; const job = pending[index++]; - const deprecated = await lookup(job); - if (deprecated !== undefined) result.set(job.name, deprecated); + const info = await lookup(job); + if (info !== undefined) result.set(job.name, info); } }; await Promise.all( Array.from({length: Math.min(DEPRECATION_CONCURRENCY, pending.length)}, worker)); if (budget.aborted && result.size < pkgs.length) { - logger.warn('Plugin catalog: npm deprecation lookup timed out; ' + + logger.warn('Plugin catalog: npm metadata lookup timed out; ' + 'listing the plugins it could not check.'); } return result; }; +/** + * Looks up the npm deprecation notice for each of the given packages. Same + * fail-open contract as {@link fetchPluginRegistryInfo}. + */ +export const fetchPluginDeprecations = async ( + pkgs: ReadonlyArray<{name: string, version?: string}>, +): Promise> => { + const info = await fetchPluginRegistryInfo(pkgs); + return new Map([...info].map(([name, i]) => [name, i.deprecated])); +}; + export const install = async (pluginName: string, cb:Function|null = null) => { cb = wrapTaskCb(cb); logger.info(`Installing plugin ${pluginName}...`); @@ -364,13 +455,14 @@ const hideUninstallablePlugins = async ( entries: MapArrayType, ): Promise> => { const list = Object.values(entries) as unknown as CatalogEntry[]; - let deprecations = new Map(); + let registryInfo = new Map(); try { - deprecations = await fetchPluginDeprecations(list); + registryInfo = await fetchPluginRegistryInfo(list); } catch (err) { - logger.warn(`Plugin catalog: could not check npm deprecations (${err}); ` + + logger.warn(`Plugin catalog: could not check npm metadata (${err}); ` + 'listing all plugins.'); } + const deprecations = new Map([...registryInfo].map(([n, i]) => [n, i.deprecated])); const {kept, excluded, compatibilityIgnored} = filterCatalogEntries( entries as unknown as Record, deprecations); if (compatibilityIgnored) { @@ -385,7 +477,25 @@ const hideUninstallablePlugins = async ( logger.debug(`Plugin catalog: hiding ${name} (${exclusion.cause}): ${exclusion.detail}`); } } - return kept as unknown as MapArrayType; + // Classify what is left. `official` is always overwritten: the feed ships + // its own `official` flag, which core cannot verify and must not pass on. + const classified = kept as unknown as MapArrayType; + let official = 0; + let placeholders = 0; + for (const key of Object.keys(classified)) { + const entry = classified[key]; + if (!entry) continue; + const info = registryInfo.get(entry.name); + entry.official = info?.official === true; + entry.placeholder = !entry.official && + isPlaceholderPackage(entry.version, info?.hasRepository); + if (entry.official) official++; + if (entry.placeholder) placeholders++; + } + logger.info(`Plugin catalog: ${official} official plugin(s), ` + + `${Object.keys(classified).length - official} third-party ` + + `(${placeholders} placeholder package(s) listed only on exact-name search).`); + return classified; }; /** @@ -420,6 +530,8 @@ export const getInstalledPluginWarnings = async ( export const search = (searchTerm: string, maxCacheAge: number) => getAvailablePlugins(maxCacheAge).then( (results: MapArrayType) => { const res:MapArrayType = {}; + const mode = normalizeThirdPartyMode(settings.pluginCatalogThirdParty); + const rawTerm = searchTerm || ''; if (searchTerm) { searchTerm = searchTerm.toLowerCase(); @@ -429,6 +541,10 @@ export const search = (searchTerm: string, maxCacheAge: number) => getAvailableP // for every available plugin // TODO: Also search in keywords here! if (pluginName.indexOf(plugins.prefix) !== 0) continue; + // Third-party / placeholder policy (pluginTrust.ts). A placeholder is + // still found by its exact name so a developer can find the package + // they just published. + if (!isListedInCatalog(results[pluginName], mode, rawTerm)) continue; if (searchTerm && !~results[pluginName].name.toLowerCase().indexOf(searchTerm) && (typeof results[pluginName].description !== 'undefined' && diff --git a/src/static/js/pluginfw/pluginTrust.ts b/src/static/js/pluginfw/pluginTrust.ts new file mode 100644 index 00000000000..6a47aa16514 --- /dev/null +++ b/src/static/js/pluginfw/pluginTrust.ts @@ -0,0 +1,156 @@ +'use strict'; + +/** + * "Official" vs "third-party" for the admin plugin catalog. + * + * Anyone can publish an `ep_*` package to npm, and the plugin feed lists + * every one of them. Etherpad cannot review them all, so the catalog labels + * the ones the Etherpad project itself publishes as official and everything + * else as third-party. + * + * What makes a plugin official here is npm provenance, not anything the + * package says about itself. The `repository` field in package.json, the + * feed's own `official` flag and the npm maintainer list can all be set by + * whoever publishes the package (`npm owner add` needs no consent from the + * added user). A provenance attestation cannot: plugins in the ether GitHub + * org publish from GitHub Actions through npm trusted publishing, and npm + * only accepts the attestation after checking its Sigstore signature against + * the GitHub OIDC identity of the workflow that built the package. Core does + * not re-verify that signature; it trusts registry.npmjs.org over TLS, which + * is the same trust it already places in the tarball it installs. + * + * The attestation is accepted only when it is about this exact package: the + * in-toto subject must name `@` and carry the same sha512 as + * the version's `dist.integrity`. The build must come from a repository + * owned by the ether org, matched both by URL and by the org's numeric + * GitHub ID, so a renamed or re-registered org name does not inherit trust. + * + * Everything in this module is pure so it can be tested without a network. + */ + +export const OFFICIAL_GITHUB_ORG = 'ether'; +/** Numeric GitHub ID of the ether org (`gh api orgs/ether --jq .id`). */ +export const OFFICIAL_GITHUB_OWNER_ID = '181731'; +export const SLSA_PROVENANCE_V1 = 'https://slsa.dev/provenance/v1'; + +const officialRepoRe = + new RegExp(`^https://github\\.com/${OFFICIAL_GITHUB_ORG}/[A-Za-z0-9._-]+$`); + +/** True for `https://github.com/ether/`, nothing looser. */ +export const isOfficialRepository = (url: unknown): boolean => + typeof url === 'string' && officialRepoRe.test(url); + +/** Converts an SRI string (`sha512-`) to the hex digest in-toto uses. */ +export const sha512HexFromIntegrity = (integrity: unknown): string | null => { + if (typeof integrity !== 'string') return null; + const m = /^sha512-([A-Za-z0-9+/=]+)$/.exec(integrity.trim()); + if (!m) return null; + const hex = Buffer.from(m[1], 'base64').toString('hex'); + return hex.length === 128 ? hex : null; +}; + +const npmPurl = (name: string, version: string) => + `pkg:npm/${name.replace(/^@/, '%40')}@${version}`; + +/** + * Pulls the source repository out of an npm attestations document + * (`GET /-/npm/v1/attestations/@`), after checking that the + * SLSA provenance statement in it is about the given package version. + * + * @returns the source repository URL and owner ID, or null when the document + * holds no provenance for this exact package. + */ +export const provenanceSource = ( + attestations: unknown, + pkg: {name: string, version: string, integrity?: unknown}, +): {repository: string, ownerId: string | null} | null => { + const list = (attestations as any)?.attestations; + if (!Array.isArray(list)) return null; + const wantDigest = sha512HexFromIntegrity(pkg.integrity); + if (!wantDigest) return null; + const wantName = npmPurl(pkg.name, pkg.version); + for (const att of list) { + if (!att || att.predicateType !== SLSA_PROVENANCE_V1) continue; + const payload = att.bundle?.dsseEnvelope?.payload; + if (typeof payload !== 'string') continue; + let statement: any; + try { + statement = JSON.parse(Buffer.from(payload, 'base64').toString('utf8')); + } catch { + continue; + } + if (statement?.predicateType !== SLSA_PROVENANCE_V1) continue; + const subjects = Array.isArray(statement.subject) ? statement.subject : []; + const matches = subjects.some((s: any) => + s && s.name === wantName && s.digest?.sha512 === wantDigest); + if (!matches) continue; + const def = statement.predicate?.buildDefinition; + const repository = def?.externalParameters?.workflow?.repository; + if (typeof repository !== 'string') continue; + const ownerId = def?.internalParameters?.github?.repository_owner_id; + return {repository, ownerId: typeof ownerId === 'string' ? ownerId : null}; + } + return null; +}; + +/** Whether the given provenance makes a package official. */ +export const isOfficialProvenance = ( + source: {repository: string, ownerId: string | null} | null, +): boolean => !!source && isOfficialRepository(source.repository) && + source.ownerId === OFFICIAL_GITHUB_OWNER_ID; + +/** + * A package that is a name grab or a test upload rather than a plugin: a + * `0.0.0` pre-release version, or no `repository` at all. Such packages are + * left out of catalog browsing but are still found by an exact-name search, + * so a developer can find the package they just published. + * + * @param hasRepository `false` only when npm metadata was fetched and has no + * repository; `undefined` (lookup failed) does not count as a placeholder. + */ +export const isPlaceholderPackage = ( + version: unknown, + hasRepository?: boolean, +): boolean => (typeof version === 'string' && /^0\.0\.0(-|$)/.test(version.trim())) || + hasRepository === false; + +/** Whether npm version metadata names a source repository. */ +export const hasRepositoryField = (repository: unknown): boolean => { + if (typeof repository === 'string') return repository.trim() !== ''; + if (repository && typeof repository === 'object') { + const url = (repository as any).url; + return typeof url === 'string' && url.trim() !== ''; + } + return false; +}; + +/** + * `pluginCatalogThirdParty` setting: + * - `label` (default): list third-party plugins with a "Third-party" badge; + * leave placeholder packages out unless searched for by exact name. + * - `hide`: list official plugins only. + * - `all`: list everything, placeholders included (still labelled). + */ +export type ThirdPartyMode = 'label' | 'hide' | 'all'; +export const THIRD_PARTY_MODES: ReadonlyArray = ['label', 'hide', 'all']; + +export const normalizeThirdPartyMode = (raw: unknown): ThirdPartyMode => { + const v = typeof raw === 'string' ? raw.trim().toLowerCase() : ''; + return (THIRD_PARTY_MODES as ReadonlyArray).includes(v) ? v as ThirdPartyMode : 'label'; +}; + +/** + * Whether a classified catalog entry is listed for the given search. + * + * @param searchTerm what the admin typed (any case), or empty for browsing. + */ +export const isListedInCatalog = ( + entry: {name: string, official?: boolean, placeholder?: boolean}, + mode: ThirdPartyMode, + searchTerm = '', +): boolean => { + if (entry.official) return true; + if (mode === 'hide') return false; + if (mode === 'all' || !entry.placeholder) return true; + return searchTerm.trim().toLowerCase() === entry.name.toLowerCase(); +}; diff --git a/src/tests/backend/specs/pluginCatalog.ts b/src/tests/backend/specs/pluginCatalog.ts index c923dd6443d..0821fd719d5 100644 --- a/src/tests/backend/specs/pluginCatalog.ts +++ b/src/tests/backend/specs/pluginCatalog.ts @@ -8,7 +8,9 @@ import { getAvailablePlugins, getInstalledPluginWarnings, install, + search, } from '../../../static/js/pluginfw/installer'; +import {OFFICIAL_GITHUB_OWNER_ID} from '../../../static/js/pluginfw/pluginTrust'; import settings from '../../../node/utils/Settings'; /** @@ -70,10 +72,23 @@ describe(__filename, function () { type NpmBehaviour = (name: string, version: string) => unknown; - const stubFetch = (npm: NpmBehaviour) => sinon.stub(global, 'fetch') + type AttestationBehaviour = (name: string, version: string) => unknown; + + const stubFetch = ( + npm: NpmBehaviour, + {feedBody = feed as Record, attestations}: + {feedBody?: Record, attestations?: AttestationBehaviour} = {}, + ) => sinon.stub(global, 'fetch') .callsFake(async (input: any) => { const url = String(input); - if (url === feedUrl) return jsonResponse(feed) as any; + if (url === feedUrl) return jsonResponse(feedBody) as any; + const att = /\/-\/npm\/v1\/attestations\/(.+)@([^@]+)$/.exec(url); + if (att && url.startsWith(`${npmRegistry}/`)) { + const body = attestations ? attestations(att[1], att[2]) : undefined; + if (body instanceof Error) throw body; + if (body === undefined) return {ok: false, status: 404, statusText: 'Not Found'} as any; + return jsonResponse(body) as any; + } const m = url.startsWith(`${npmRegistry}/`) ? /\/([^/]+)\/([^/]+)$/.exec(url) : null; @@ -240,4 +255,127 @@ describe(__filename, function () { assert.equal(second.get('ep_stale'), 'gone'); }); }); + describe('official vs third-party (pluginTrust.ts)', function () { + // An SRI hash and the matching in-toto hex digest; any 64 bytes will do. + const bytes = Buffer.alloc(64, 7); + const integrity = `sha512-${bytes.toString('base64')}`; + const digest = bytes.toString('hex'); + + const provenance = (name: string, version: string, repository: string) => ({ + attestations: [{ + predicateType: 'https://slsa.dev/provenance/v1', + bundle: {dsseEnvelope: {payload: Buffer.from(JSON.stringify({ + _type: 'https://in-toto.io/Statement/v1', + subject: [{name: `pkg:npm/${name}@${version}`, digest: {sha512: digest}}], + predicateType: 'https://slsa.dev/provenance/v1', + predicate: {buildDefinition: { + externalParameters: {workflow: {repository}}, + internalParameters: {github: {repository_owner_id: OFFICIAL_GITHUB_OWNER_ID}}, + }}, + })).toString('base64')}}, + }], + }); + + const trustFeed = { + ep_align: {name: 'ep_align', description: 'Alignment', time: '2026-07-01', + version: '11.0.43', official: true, compatibility: 'compatible'}, + ep_liar: {name: 'ep_liar', description: 'Claims to be official', time: '2026-11-21', + version: '1.0.0', official: true, compatibility: 'compatible'}, + ep_community: {name: 'ep_community', description: 'A real third-party plugin', + time: '2026-01-01', version: '2.0.0', official: false, compatibility: 'compatible'}, + ep_nxs65012: {name: 'ep_nxs65012', description: '', time: '2026-11-21', + version: '0.0.0-stage', official: false, compatibility: 'compatible'}, + ep_norepo: {name: 'ep_norepo', description: 'no repository', time: '2026-11-21', + version: '1.0.0', official: false, compatibility: 'compatible'}, + }; + + const npmMeta = (name: string, version: string) => { + const base: any = {name, version, dist: {integrity}}; + if (name !== 'ep_norepo' && name !== 'ep_nxs65012') { + base.repository = {type: 'git', url: `git+https://github.com/ether/${name}.git`}; + } + if (name === 'ep_align' || name === 'ep_liar') { + base.dist.attestations = { + url: `${npmRegistry}/-/npm/v1/attestations/${name}@${version}`, + provenance: {predicateType: 'https://slsa.dev/provenance/v1'}, + }; + } + return base; + }; + + const attestations = (name: string, version: string) => (name === 'ep_align' + ? provenance(name, version, 'https://github.com/ether/ep_align') + // ep_liar declares an ether repository in package.json, but its + // provenance shows where it was really built. + : provenance(name, version, 'https://github.com/nx-zd/ep_liar')); + + let savedMode: string; + beforeEach(function () { + savedMode = settings.pluginCatalogThirdParty; + }); + afterEach(function () { + settings.pluginCatalogThirdParty = savedMode; + }); + + const names = (res: Record) => Object.keys(res).sort(); + + it('marks only plugins with ether provenance as official', async function () { + stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + const available = await getAvailablePlugins(false); + assert.equal(available.ep_align.official, true); + assert.equal(available.ep_liar.official, false, + 'the feed flag and package.json repository must not make a plugin official'); + assert.equal(available.ep_community.official, false); + assert.equal(available.ep_nxs65012.placeholder, true); + assert.equal(available.ep_norepo.placeholder, true); + assert.equal(available.ep_community.placeholder, false); + }); + + it('caches provenance, so a refresh does not refetch attestations', async function () { + const fetchStub = stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + await getAvailablePlugins(false); + const attCalls = () => fetchStub.getCalls() + .filter((c) => String(c.args[0]).includes('/-/npm/v1/attestations/')).length; + assert.equal(attCalls(), 2); + await getAvailablePlugins(false); + assert.equal(attCalls(), 2); + }); + + it('treats every plugin as third-party when npm is unreachable', async function () { + stubFetch(() => new Error('offline'), {feedBody: trustFeed}); + const available = await getAvailablePlugins(false); + for (const entry of Object.values(available)) assert.equal(entry.official, false); + // The 0.0.0 placeholder is still recognised from the feed alone; the + // repository check needs npm, so it fails open. + assert.equal(available.ep_nxs65012.placeholder, true); + assert.equal(available.ep_norepo.placeholder, false); + }); + + it('label (default): hides placeholders from browsing, keeps third-party', async function () { + settings.pluginCatalogThirdParty = 'label'; + stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + assert.deepEqual(names(await search('', 0)), ['ep_align', 'ep_community', 'ep_liar']); + assert.deepEqual(names(await search('nxs', 0)), []); + }); + + it('label: an exact-name search finds a placeholder', async function () { + settings.pluginCatalogThirdParty = 'label'; + stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + assert.deepEqual(names(await search('ep_nxs65012', 0)), ['ep_nxs65012']); + assert.deepEqual(names(await search('EP_NOREPO', 0)), ['ep_norepo']); + }); + + it('hide: lists official plugins only', async function () { + settings.pluginCatalogThirdParty = 'hide'; + stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + assert.deepEqual(names(await search('', 0)), ['ep_align']); + assert.deepEqual(names(await search('ep_community', 0)), []); + }); + + it('all: lists everything', async function () { + settings.pluginCatalogThirdParty = 'all'; + stubFetch(npmMeta, {feedBody: trustFeed, attestations}); + assert.deepEqual(names(await search('', 0)), Object.keys(trustFeed).sort()); + }); + }); }); diff --git a/src/tests/backend/specs/pluginTrust.ts b/src/tests/backend/specs/pluginTrust.ts new file mode 100644 index 00000000000..e8c4953e24c --- /dev/null +++ b/src/tests/backend/specs/pluginTrust.ts @@ -0,0 +1,210 @@ +'use strict'; + +import {strict as assert} from 'assert'; +import { + hasRepositoryField, + isListedInCatalog, + isOfficialProvenance, + isOfficialRepository, + isPlaceholderPackage, + normalizeThirdPartyMode, + OFFICIAL_GITHUB_OWNER_ID, + provenanceSource, + sha512HexFromIntegrity, + SLSA_PROVENANCE_V1, +} from '../../../static/js/pluginfw/pluginTrust'; + +// "Official" in the admin plugin catalog must not be something a publisher +// can claim for themselves. These tests pin the classification: only an npm +// provenance attestation for the exact package version, built in a +// repository owned by the ether GitHub org, makes a plugin official. + +// Real values from ep_align@11.0.58 on registry.npmjs.org. +const INTEGRITY = + 'sha512-gaS0jGRGYJdYBAU3cc0M2ah6tTUjmF/L3BYRPsWSrNDdC+VOl9UCSd9qSvdWOowXW4jHDtGUVUZTmhH/sXcb8w=='; +const DIGEST = '81a4b48c644660975804053771cd0cd9a87ab53523985fcbdc16113ec592acd0' + + 'dd0be54e97d50249df6a4af7563a8c175b88c70ed1945546539a11ffb1771bf3'; + +const makeAttestations = ({ + name = 'ep_align', + version = '11.0.58', + digest = DIGEST, + repository = 'https://github.com/ether/ep_align', + ownerId = OFFICIAL_GITHUB_OWNER_ID, + predicateType = SLSA_PROVENANCE_V1, +}: Partial> = {}) => { + const statement = { + _type: 'https://in-toto.io/Statement/v1', + subject: [{name: `pkg:npm/${name}@${version}`, digest: {sha512: digest}}], + predicateType, + predicate: { + buildDefinition: { + externalParameters: {workflow: {repository, ref: 'refs/heads/main'}}, + internalParameters: {github: {repository_owner_id: ownerId}}, + }, + }, + }; + return { + attestations: [ + {predicateType: 'https://github.com/npm/attestation/tree/main/specs/publish/v0.1', + bundle: {dsseEnvelope: {payload: Buffer.from('{}').toString('base64')}}}, + {predicateType, + bundle: {dsseEnvelope: {payload: Buffer.from(JSON.stringify(statement)).toString('base64')}}}, + ], + }; +}; + +describe(__filename, function () { + const pkg = {name: 'ep_align', version: '11.0.58', integrity: INTEGRITY}; + + describe('isOfficialRepository', function () { + it('accepts a repository in the ether org', function () { + assert.equal(isOfficialRepository('https://github.com/ether/ep_align'), true); + }); + for (const url of [ + 'https://github.com/etherx/ep_align', + 'https://github.com/ether/ep_align/../../evil/x', + 'https://github.com/ether/ep_align.git?x=https://github.com/ether/', + 'https://gitlab.com/ether/ep_align', + 'git+https://github.com/ether/ep_align.git', + 'https://github.com/ether', + 'https://github.com/nx-zd/ep_nxs65012', + undefined, + ]) { + it(`rejects ${url}`, function () { + assert.equal(isOfficialRepository(url), false); + }); + } + }); + + describe('sha512HexFromIntegrity', function () { + it('converts an SRI hash to the hex digest in-toto uses', function () { + assert.equal(sha512HexFromIntegrity(INTEGRITY), DIGEST); + }); + it('rejects anything that is not sha512', function () { + assert.equal(sha512HexFromIntegrity('sha1-abc'), null); + assert.equal(sha512HexFromIntegrity(undefined), null); + }); + }); + + describe('provenanceSource / isOfficialProvenance', function () { + it('treats a matching ether provenance attestation as official', function () { + const source = provenanceSource(makeAttestations(), pkg); + assert.deepEqual(source, + {repository: 'https://github.com/ether/ep_align', ownerId: OFFICIAL_GITHUB_OWNER_ID}); + assert.equal(isOfficialProvenance(source), true); + }); + + it('is third-party when the package has no provenance at all', function () { + assert.equal(provenanceSource(undefined, pkg), null); + assert.equal(provenanceSource({attestations: []}, pkg), null); + assert.equal(isOfficialProvenance(null), false); + }); + + it('is third-party when the build came from another org', function () { + const source = provenanceSource( + makeAttestations({repository: 'https://github.com/nx-zd/ep_align'}), pkg); + assert.equal(isOfficialProvenance(source), false); + }); + + it('is third-party when the repo URL says ether but the owner ID does not', function () { + // A re-registered or renamed "ether" org would carry a different ID. + const source = provenanceSource(makeAttestations({ownerId: '999'}), pkg); + assert.equal(isOfficialProvenance(source), false); + }); + + it('ignores an attestation copied from another package', function () { + assert.equal(provenanceSource(makeAttestations(), + {...pkg, name: 'ep_nxs65012'}), null); + }); + + it('ignores an attestation for another version', function () { + assert.equal(provenanceSource(makeAttestations(), {...pkg, version: '11.0.59'}), null); + }); + + it('ignores an attestation whose digest does not match the tarball', function () { + assert.equal(provenanceSource(makeAttestations({digest: 'ab'.repeat(64)}), pkg), null); + assert.equal(provenanceSource(makeAttestations(), {...pkg, integrity: undefined}), null); + }); + + it('ignores attestations that are not SLSA provenance', function () { + assert.equal(provenanceSource( + makeAttestations({predicateType: 'https://example.com/other'}), pkg), null); + }); + + it('survives a garbage payload', function () { + assert.equal(provenanceSource({attestations: [ + {predicateType: SLSA_PROVENANCE_V1, bundle: {dsseEnvelope: {payload: '!!!'}}}, + ]}, pkg), null); + }); + }); + + describe('isPlaceholderPackage', function () { + it('flags 0.0.0 pre-release versions', function () { + assert.equal(isPlaceholderPackage('0.0.0-stage'), true); + assert.equal(isPlaceholderPackage('0.0.0'), true); + }); + it('flags a package npm shows without a repository', function () { + assert.equal(isPlaceholderPackage('1.2.3', false), true); + }); + it('does not flag a real release, or one whose metadata is unknown', function () { + assert.equal(isPlaceholderPackage('0.0.1', true), false); + assert.equal(isPlaceholderPackage('0.0.10'), false); + assert.equal(isPlaceholderPackage('1.2.3', undefined), false); + }); + }); + + describe('hasRepositoryField', function () { + it('accepts the string and object forms', function () { + assert.equal(hasRepositoryField('github:ether/ep_align'), true); + assert.equal(hasRepositoryField({type: 'git', url: 'git+https://x/y.git'}), true); + }); + it('rejects missing or empty repositories', function () { + for (const v of [undefined, null, '', ' ', {}, {url: ''}]) { + assert.equal(hasRepositoryField(v), false, JSON.stringify(v)); + } + }); + }); + + describe('normalizeThirdPartyMode', function () { + it('accepts the documented values in any case', function () { + assert.equal(normalizeThirdPartyMode('hide'), 'hide'); + assert.equal(normalizeThirdPartyMode(' ALL '), 'all'); + assert.equal(normalizeThirdPartyMode('label'), 'label'); + }); + it('falls back to label for anything else', function () { + assert.equal(normalizeThirdPartyMode(undefined), 'label'); + assert.equal(normalizeThirdPartyMode('nope'), 'label'); + assert.equal(normalizeThirdPartyMode(true), 'label'); + }); + }); + + describe('isListedInCatalog', function () { + const official = {name: 'ep_align', official: true, placeholder: false}; + const thirdParty = {name: 'ep_mypads', official: false, placeholder: false}; + const placeholder = {name: 'ep_nxs65012', official: false, placeholder: true}; + + it('label: lists official and third-party, hides placeholders from browsing', function () { + assert.equal(isListedInCatalog(official, 'label'), true); + assert.equal(isListedInCatalog(thirdParty, 'label'), true); + assert.equal(isListedInCatalog(placeholder, 'label'), false); + assert.equal(isListedInCatalog(placeholder, 'label', 'nxs'), false); + }); + + it('label: an exact-name search still finds a placeholder', function () { + assert.equal(isListedInCatalog(placeholder, 'label', 'EP_NXS65012 '), true); + }); + + it('hide: lists official plugins only', function () { + assert.equal(isListedInCatalog(official, 'hide'), true); + assert.equal(isListedInCatalog(thirdParty, 'hide'), false); + assert.equal(isListedInCatalog(placeholder, 'hide', 'ep_nxs65012'), false); + }); + + it('all: lists everything', function () { + assert.equal(isListedInCatalog(placeholder, 'all'), true); + assert.equal(isListedInCatalog(thirdParty, 'all'), true); + }); + }); +}); diff --git a/src/tests/frontend-new/admin-spec/admin_plugin_trust.spec.ts b/src/tests/frontend-new/admin-spec/admin_plugin_trust.spec.ts new file mode 100644 index 00000000000..88eeb3fa5fa --- /dev/null +++ b/src/tests/frontend-new/admin-spec/admin_plugin_trust.spec.ts @@ -0,0 +1,118 @@ +import {expect, Page, test} from "@playwright/test"; +import {loginToAdmin} from "../helper/adminhelper"; + +// The admin catalog labels plugins published by the Etherpad project as +// "Official" and everything else as "Third-party", and asks for confirmation +// before installing a third-party plugin. Which plugin is which is decided on +// the server (pluginTrust.ts, covered by the backend specs); this spec checks +// what the admin sees. The live feed changes daily, so the search results are +// replaced with a fixture on the socket, and `install` events are recorded and +// swallowed so nothing is ever actually installed. + +const NS = '/pluginfw/installer'; +const PREFIX = `42${NS},`; + +const fixture = [ + {name: 'ep_fixture_official', description: 'Official fixture plugin', + version: '1.0.0', time: '2026-11-01', official: true}, + {name: 'ep_fixture_community', description: 'Third-party fixture plugin', + version: '2.0.0', time: '2026-11-02', official: false}, +]; + +// Splits a socket.io event frame for the installer namespace into its +// optional ack id and its [event, ...args] payload. +const parseFrame = (msg: string | Buffer) => { + if (typeof msg !== 'string' || !msg.startsWith(PREFIX)) return null; + const m = /^(\d*)(\[.*)$/s.exec(msg.slice(PREFIX.length)); + if (!m) return null; + return {ack: m[1], payload: JSON.parse(m[2]) as unknown[]}; +}; + +const useFixtureCatalog = async (page: Page) => { + const installs: string[] = []; + await page.routeWebSocket(/\/socket\.io\//, (ws) => { + const server = ws.connectToServer(); + ws.onMessage((msg) => { + const frame = parseFrame(msg); + if (frame && frame.payload[0] === 'install') { + installs.push(String(frame.payload[1])); + return; + } + server.send(msg); + }); + server.onMessage((msg) => { + const frame = parseFrame(msg); + if (frame && frame.payload[0] === 'results:search') { + const data = frame.payload[1] as {results: unknown[]}; + data.results = fixture; + ws.send(`${PREFIX}${frame.ack}${JSON.stringify(frame.payload)}`); + return; + } + ws.send(msg); + }); + }); + return installs; +}; + +test.describe('Plugin catalog: official and third-party plugins', () => { + let installs: string[]; + + test.beforeEach(async ({page}) => { + installs = await useFixtureCatalog(page); + await loginToAdmin(page, 'admin', 'changeme1'); + await page.goto('http://localhost:9001/admin/plugins'); + await page.waitForSelector('.pm-search-input'); + await expect(page.locator('table tbody tr')).toHaveCount(fixture.length, {timeout: 30000}); + }); + + const row = (page: Page, name: string) => + page.locator('table tbody tr').filter({hasText: name}); + + test('labels official and third-party plugins', async ({page}) => { + await expect(row(page, 'ep_fixture_official').locator('.pm-tag--official')) + .toHaveText('Official'); + await expect(row(page, 'ep_fixture_official').locator('.pm-tag--third-party')) + .toHaveCount(0); + await expect(row(page, 'ep_fixture_community').locator('.pm-tag--third-party')) + .toHaveText('Third-party'); + await expect(row(page, 'ep_fixture_community').locator('.pm-tag--third-party')) + .toHaveAttribute('title', 'Not maintained by the Etherpad project. Plugins run code on your server.'); + }); + + test('installs an official plugin with one click', async ({page}) => { + await row(page, 'ep_fixture_official').getByRole('button', {name: 'Install'}).click(); + await expect(page.getByTestId('third-party-confirm')).toHaveCount(0); + await expect.poll(() => installs).toEqual(['ep_fixture_official']); + }); + + test('asks before installing a third-party plugin, and cancel installs nothing', + async ({page}) => { + await row(page, 'ep_fixture_community').getByRole('button', {name: 'Install'}).click(); + const dialog = page.getByTestId('third-party-confirm'); + await expect(dialog).toBeVisible(); + await expect(dialog.getByRole('heading')).toHaveText('Install a third-party plugin?'); + await expect(dialog).toContainText( + 'ep_fixture_community is not maintained by the Etherpad project'); + await expect(dialog).toContainText('Plugins run code on your server'); + await dialog.getByRole('button', {name: 'Cancel'}).click(); + await expect(dialog).toHaveCount(0); + await expect(row(page, 'ep_fixture_community')).toHaveCount(1); + expect(installs).toEqual([]); + }); + + test('Escape dismisses the confirmation without installing', async ({page}) => { + await row(page, 'ep_fixture_community').getByRole('button', {name: 'Install'}).click(); + await expect(page.getByTestId('third-party-confirm')).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(page.getByTestId('third-party-confirm')).toHaveCount(0); + expect(installs).toEqual([]); + }); + + test('confirming installs the third-party plugin', async ({page}) => { + await row(page, 'ep_fixture_community').getByRole('button', {name: 'Install'}).click(); + const dialog = page.getByTestId('third-party-confirm'); + await dialog.getByRole('button', {name: 'Install'}).click(); + await expect(dialog).toHaveCount(0); + await expect.poll(() => installs).toEqual(['ep_fixture_community']); + }); +}); diff --git a/src/tests/frontend-new/admin-spec/adminupdateplugins.spec.ts b/src/tests/frontend-new/admin-spec/adminupdateplugins.spec.ts index 9056dc4f22d..deceba9e689 100644 --- a/src/tests/frontend-new/admin-spec/adminupdateplugins.spec.ts +++ b/src/tests/frontend-new/admin-spec/adminupdateplugins.spec.ts @@ -49,6 +49,13 @@ test.describe('Plugins page', ()=> { // Install button is in the last table cell await pluginRow.locator('td').last().locator('button').first().click() + // ep_set_title_on_pad is an official plugin and installs with one + // click, but if npm provenance could not be checked it is shown as + // third-party and the confirmation dialog appears first. + const confirm = page.getByTestId('third-party-confirm') + if (await confirm.waitFor({state: 'visible', timeout: 2000}).then(() => true, () => false)) { + await confirm.locator('.pm-btn-primary').click() + } await page.waitForSelector('.pm-installed') // Installed plugins are now in .pm-installed-row flex items (not a table). From a448b8a56433b78d40d46c37adedffc03b09c157 Mon Sep 17 00:00:00 2001 From: John McLear Date: Sat, 21 Nov 2026 13:22:13 +0000 Subject: [PATCH 2/3] test(admin): avoid the regex s flag in the plugin trust spec Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TcYAoDMav4BPPE9JrMtSvw --- src/tests/frontend-new/admin-spec/admin_plugin_trust.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/frontend-new/admin-spec/admin_plugin_trust.spec.ts b/src/tests/frontend-new/admin-spec/admin_plugin_trust.spec.ts index 88eeb3fa5fa..208f652fe29 100644 --- a/src/tests/frontend-new/admin-spec/admin_plugin_trust.spec.ts +++ b/src/tests/frontend-new/admin-spec/admin_plugin_trust.spec.ts @@ -23,7 +23,7 @@ const fixture = [ // optional ack id and its [event, ...args] payload. const parseFrame = (msg: string | Buffer) => { if (typeof msg !== 'string' || !msg.startsWith(PREFIX)) return null; - const m = /^(\d*)(\[.*)$/s.exec(msg.slice(PREFIX.length)); + const m = /^(\d*)(\[[\s\S]*)$/.exec(msg.slice(PREFIX.length)); if (!m) return null; return {ack: m[1], payload: JSON.parse(m[2]) as unknown[]}; }; From 1574219a6c5bea41375447c4d56f96ee94e91cc0 Mon Sep 17 00:00:00 2001 From: John McLear Date: Sat, 21 Nov 2026 13:34:01 +0000 Subject: [PATCH 3/3] fix(admin): address review of the official-plugin catalog - Installs from the catalog carry the version that was classified, and the server installs exactly that version, so an Official label cannot cover a newer, unchecked release. The socket still accepts a bare name. - Updates of installed plugins go through the same confirmation, using the catalog version and its classification; unknown means third-party. - getAvailable applies pluginCatalogThirdParty like search does. - Provenance is fetched in its own sweep with its own time budget, after the metadata sweep. A catalog with unchecked provenance is reused for at most a minute so the next search retries. - The deprecation-only lookup for installed plugins no longer fetches attestations. - Warn when provenance could not be checked, and in hide mode say why the list may be empty; document that hide needs registry.npmjs.org. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01TcYAoDMav4BPPE9JrMtSvw --- admin/src/pages/HomePage.tsx | 31 ++- admin/src/pages/Plugin.ts | 4 + doc/plugins.adoc | 6 +- doc/plugins.md | 6 +- settings.json.template | 4 +- src/node/hooks/express/adminplugins.ts | 36 ++- src/node/types/PackageInfo.ts | 2 + src/node/utils/Settings.ts | 3 +- src/static/js/pluginfw/installer.ts | 252 ++++++++++++------ src/tests/backend/specs/pluginCatalog.ts | 80 ++++++ .../admin-spec/admin_plugin_trust.spec.ts | 10 +- 11 files changed, 330 insertions(+), 104 deletions(-) diff --git a/admin/src/pages/HomePage.tsx b/admin/src/pages/HomePage.tsx index 3227c60bdaa..a9ab98e995d 100644 --- a/admin/src/pages/HomePage.tsx +++ b/admin/src/pages/HomePage.tsx @@ -26,7 +26,8 @@ export const HomePage = () => { }) const [searchTerm, setSearchTerm] = useState('') // Third-party plugin awaiting the admin's confirmation before install. - const [confirmInstall, setConfirmInstall] = useState(null) + const [confirmInstall, setConfirmInstall] = + useState<{name: string, version?: string} | null>(null) const {t} = useTranslation() const updatableCount = useMemo( @@ -143,19 +144,23 @@ export const HomePage = () => { setInstalledPlugins(installedPlugins.filter(i => i.name !== pluginName)) } - const installPlugin = (pluginName: string) => { - pluginsSocket!.emit('install', pluginName) + // With a version, the server installs exactly that release: the one the + // catalog showed and classified, not whatever is latest by then. + const installPlugin = (pluginName: string, version?: string) => { + pluginsSocket!.emit('install', version ? {name: pluginName, version} : pluginName) setPlugins(plugins.filter(p => p.name !== pluginName)) } // Official plugins install with one click. A third-party plugin runs code // the Etherpad project has not reviewed, so the admin confirms first; the // extra, deliberate click also blunts clickjacking of the Install button. - const requestInstall = (plugin: PluginDef) => { - if (plugin.official) { - installPlugin(plugin.name) + // Updates go through here too; an update whose target version could not + // be classified is treated as third-party. + const requestInstall = (plugin: {name: string, version?: string, official?: boolean}) => { + if (plugin.official === true) { + installPlugin(plugin.name, plugin.version) } else { - setConfirmInstall(plugin.name) + setConfirmInstall({name: plugin.name, version: plugin.version}) } } @@ -177,7 +182,7 @@ export const HomePage = () => { - {t('admin_plugins.third_party_confirm_body', {plugin: confirmInstall ?? ''})} + {t('admin_plugins.third_party_confirm_body', {plugin: confirmInstall?.name ?? ''})}
@@ -188,9 +193,9 @@ export const HomePage = () => {