feat: add plugin application runtime and unified instance authorization

This commit is contained in:
illusia committed 2026-11-03 20:13:01 +08:00
1 parent 8bca848c21
commit 3430a8a753
80 files changed
+2133 -1004

No files matched your search

@@ -0,0 +1,45 @@
<template>
<Teleport to="body">
<dialog ref="dialog" class="ws-instance-authorization" @cancel.prevent="cancel" @close="authorizationRequested = false">
<form @submit.prevent="save">
<div class="ws-authorization-mark" aria-hidden="true">◈</div>
<h2>{{ copy.title }}</h2>
<p>{{ copy.description }}</p>
<p>{{ copy.alternative }}</p>
<label><input v-model="checked" type="checkbox" /><span>{{ copy.choice }}</span></label>
<footer>
<button type="button" @click="decline">{{ copy.decline }}</button>
<button class="ws-authorization-primary" type="submit" :disabled="firstVisit && !checked">{{ firstVisit ? copy.accept : copy.save }}</button>
</footer>
</form>
</dialog>
</Teleport>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import type { SiteLanguage } from '../../../src/site-copy.js';
import { authorizationDecision, authorizationLanguage, authorizationRequested, setInstanceAuthorization } from '../services/instance-authorization.js';
import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
const props = defineProps<{ language: SiteLanguage }>();
const dialog = ref<HTMLDialogElement | null>(null), checked = ref(false), firstVisit = ref(false);
const copy = computed(() => instanceAuthorizationCopy[props.language]);
watch(() => props.language, value => { authorizationLanguage.value = value; }, { immediate: true });
watch([dialog, authorizationRequested, authorizationDecision], () => {
if (!dialog.value || dialog.value.open || (authorizationDecision.value !== null && !authorizationRequested.value)) return;
firstVisit.value = authorizationDecision.value === null;
checked.value = authorizationDecision.value === true;
dialog.value.showModal();
}, { flush: 'post' });
function finish() { authorizationRequested.value = false; dialog.value?.close(); }
function save() { if (firstVisit.value && !checked.value) return; setInstanceAuthorization(checked.value); finish(); }
function decline() { setInstanceAuthorization(false); finish(); }
function cancel() { if (firstVisit.value) decline(); else finish(); }
onBeforeUnmount(() => dialog.value?.close());
</script>
<style>
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid #dbe3f1;border-radius:20px;background:#fff;color:#25324b;font:14px/1.75 system-ui,-apple-system,"Segoe UI",sans-serif;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto}
.ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:#202e49}.ws-instance-authorization p{margin:12px 0;color:#526079}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:#edf0ff;color:#5265df;font-size:28px}
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:#f4f6fc;border:1px solid #dce3f3;border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:#5265df}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:42px;padding:9px 16px;border:1px solid #d9e1ef;border-radius:10px;background:#f4f6fc;color:#43516d;font:600 14px/1.5 system-ui;cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:#5265df;color:#fff;border-color:#5265df}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid #5265df;outline-offset:3px}
@media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
</style>
+141 -89
View File
@@ -1,111 +1,163 @@
<template>
<Teleport to="body">
<button v-if="connected" class="ws-plugin-launcher" type="button" @click="show">◈ {{ tr('title') }}</button>
<dialog ref="dialog" class="ws-plugin-dialog" :data-plugin-theme="theme" @close="closed" @cancel="closed">
<header><strong>{{ current?.manifest.name ?? tr('title') }}</strong><button type="button" @click="dialog?.close()">{{ tr('close') }}</button></header>
<p v-if="error" role="alert" class="ws-plugin-error">{{ error }}</p>
<template v-if="!current">
<div class="ws-plugin-toolbar"><button type="button" :disabled="busy" @click="refresh">{{ busy ? tr('loading') : tr('refresh') }}</button></div>
<p>{{ tr('enableNote') }}</p><p v-if="!busy && !available.length">{{ tr('empty') }}</p>
<section v-for="entry in available" :key="entry.manifest.id" class="ws-plugin-entry">
<div><strong>{{ entry.manifest.name }}</strong><small>{{ entry.scope === 'server' ? tr('server') : tr('instance') }} · {{ entry.manifest.version }}</small><p>{{ entry.manifest.description }}</p></div>
<button type="button" :disabled="busy" @click="launch(entry.manifest.id)">{{ tr('open') }}</button>
</section>
</template>
<template v-else>
<div class="ws-plugin-toolbar"><button type="button" @click="stop">← {{ tr('back') }}</button><small>{{ tr('permission') }}: {{ current.manifest.permissions.join(', ') }}</small></div>
<iframe ref="frame" :key="channel" :title="current.manifest.name" :srcdoc="documentSource" sandbox="allow-scripts" allow="fullscreen" referrerpolicy="no-referrer" @load="sendContext"></iframe>
</template>
</dialog>
<div v-if="thirdPartyAllowed && connected && sessionToken" class="ws-plugin-overlay" :data-plugin-theme="theme">
<button ref="launcher" class="ws-plugin-launcher" :style="launcherPosition" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="visible" @pointerdown="startLauncherDrag" @lostpointercapture="endDrag" @click="toggle">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
<span>{{ tr('title') }}</span><i v-if="current" />
</button>
<section v-show="visible" ref="windowElement" class="ws-plugin-window" :class="{ 'is-maximized': maximized, 'is-dragging': dragging }" :style="position" role="dialog" :aria-label="current && appView ? current.manifest.name : tr('title')" tabindex="-1" @keydown.esc.stop="minimize">
<header class="ws-plugin-titlebar" @pointerdown="startDrag" @lostpointercapture="endDrag" @dblclick="toggleMaximize">
<span class="ws-plugin-mark" aria-hidden="true">◈</span>
<div class="ws-plugin-window-title"><strong>{{ current && appView ? current.manifest.name : tr('title') }}</strong><small>WebSpeak</small></div>
<div class="ws-plugin-window-controls" @pointerdown.stop @dblclick.stop>
<button type="button" :title="ui.minimize" :aria-label="ui.minimize" @click="minimize"><svg viewBox="0 0 24 24"><path d="M5 17h14" /></svg></button>
<button type="button" :title="maximized ? ui.restore : ui.maximize" :aria-label="maximized ? ui.restore : ui.maximize" @click="toggleMaximize"><svg viewBox="0 0 24 24"><path :d="maximized ? 'M8 4h12v12M4 8h12v12H4z' : 'M5 5h14v14H5z'" /></svg></button>
<button class="ws-plugin-close" type="button" :title="tr('close')" :aria-label="tr('close')" @click="close"><svg viewBox="0 0 24 24"><path d="m6 6 12 12M18 6 6 18" /></svg></button>
</div>
</header>
<nav class="ws-plugin-navigation" :aria-label="tr('title')">
<button type="button" :class="{ active: !appView }" @click="appView = false">{{ ui.workspace }}</button>
<button v-if="current" type="button" :class="{ active: appView }" @click="appView = true">{{ current.manifest.name }}</button>
<span v-if="current && appView" class="ws-plugin-version">v{{ current.manifest.version }}</span>
</nav>
<p v-if="error" role="alert" class="ws-plugin-error">{{ error }}</p>
<div v-show="!appView" class="ws-plugin-library">
<div class="ws-plugin-library-heading"><div><h2>{{ tr('title') }}</h2><span>{{ available.length }} {{ ui.count }}</span></div><button type="button" :disabled="busy" @click="refresh">{{ busy ? tr('loading') : tr('refresh') }}</button></div>
<input v-model="search" class="ws-plugin-search" type="search" :placeholder="ui.search" :aria-label="ui.search" />
<p v-if="!busy && !filtered.length" class="ws-plugin-empty">{{ available.length ? ui.noResults : tr('empty') }}</p>
<div class="ws-plugin-grid">
<article v-for="entry in filtered" :key="entry.manifest.id" class="ws-plugin-entry">
<div class="ws-plugin-app-mark" aria-hidden="true">{{ entry.manifest.name.slice(0, 1).toUpperCase() }}</div>
<div class="ws-plugin-entry-copy"><h3>{{ entry.manifest.name }}</h3><small>v{{ entry.manifest.version }} · {{ entry.scope === 'server' ? tr('server') : tr('instance') }}</small><p>{{ entry.manifest.description }}</p></div>
<p v-if="entry.runtime.state === 'failed'" class="ws-plugin-entry-error">{{ entry.runtime.error }}</p>
<button type="button" :disabled="busy || entry.runtime.state === 'failed'" @click="launch(entry.manifest.id)">{{ tr('open') }} <span aria-hidden="true">↗</span></button>
</article>
</div>
</div>
<div v-show="appView && current" class="ws-plugin-browser">
<iframe v-if="current" ref="frame" :key="current.id" :title="current.manifest.name" :src="current.url" :allow="browserFeatures" referrerpolicy="no-referrer"></iframe>
</div>
<div v-if="dragging" class="ws-plugin-drag-shield" />
</section>
</div>
</Teleport>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
import { parsePluginPackage, pluginRecord, parsePluginJson, type PluginManifest, type PluginScope, type PluginRoomSnapshot } from '../../../src/shared/plugins.js';
import { pluginFrameDocument } from '../services/plugin-frame.js';
import type { PluginTransport } from '../services/plugin-transport.js';
import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
import { createPluginAppClient, type AvailablePluginApp, type PluginAppClient } from '../services/plugin-app-client.js';
import { type PluginAppLaunch, pluginRecord } from '../../../src/shared/plugins.js';
import { pluginTranslations, type PluginTextKey } from '../i18n/plugins.js';
import { pluginWindowTranslations } from '../i18n/plugin-window.js';
import type { SiteLanguage } from '../../../src/site-copy.js';
const props = defineProps<{ transport: PluginTransport; connected: boolean; language: SiteLanguage }>();
import { thirdPartyAllowed } from '../services/instance-authorization.js';
const props = defineProps<{ sessionToken: string; gatewayUrl: string; connected: boolean; language: SiteLanguage }>();
const tr = (key: PluginTextKey) => pluginTranslations[props.language][key];
const dialog = ref<HTMLDialogElement | null>(null), frame = ref<HTMLIFrameElement | null>(null);
const available = shallowRef<{ manifest: PluginManifest; scope: PluginScope }[]>([]);
const current = shallowRef<ReturnType<typeof parsePluginPackage> | null>(null);
const documentSource = ref(''), channel = ref(''), theme = ref<'light'|'dark'>('light');
const busy = ref(false), error = ref(''); let epoch = 0, openingId: string | undefined, context: Record<string,unknown> = {}, observer: MutationObserver | undefined;
const inFlight = new Set<number>();
const pluginId = computed(() => current.value?.manifest.id);
const ui = computed(() => pluginWindowTranslations[props.language]);
const windowElement = ref<HTMLElement | null>(null), launcher = ref<HTMLButtonElement | null>(null), frame = ref<HTMLIFrameElement | null>(null);
const available = shallowRef<AvailablePluginApp[]>([]), current = shallowRef<PluginAppLaunch | null>(null);
const busy = ref(false), error = ref(''), theme = ref<'light' | 'dark'>('light');
const visible = ref(false), maximized = ref(false), appView = ref(false), dragging = ref(false), search = ref('');
const position = ref<Record<string, string>>({});
const launcherPosition = ref<Record<string, string>>({});
const filtered = computed(() => available.value.filter(entry => `${entry.manifest.name} ${entry.manifest.description}`.toLocaleLowerCase().includes(search.value.trim().toLocaleLowerCase())));
let epoch = 0, pending: AbortController | undefined, opening: { client: PluginAppClient; key: string } | undefined, observer: MutationObserver | undefined;
let drag: { id: number; x: number; y: number; left: number; top: number; handle: HTMLElement; kind: 'window' | 'launcher'; moved: boolean } | undefined;
let suppressLauncherClick = false, resizeObserver: ResizeObserver | undefined;
const browserFeatures = computed(() => {
const policy = (document as Document & { featurePolicy?: { features(): string[] } }).featurePolicy;
const features = policy?.features() ?? ['fullscreen', 'autoplay', 'camera', 'microphone', 'display-capture', 'clipboard-read', 'clipboard-write', 'geolocation', 'screen-wake-lock'];
return features.filter(feature => /^[a-z0-9-]+$/.test(feature)).map(feature => feature + ' *').join('; ');
});
function detectTheme() {
const root = document.querySelector('.ws-skin-root');
const color = root ? getComputedStyle(root).color.match(/[\d.]+/g)?.map(Number) : null;
theme.value = color && color.length >= 3 ? (color[0]*.2126+color[1]*.7152+color[2]*.0722 > 140 ? 'dark':'light') : matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';
const style = getComputedStyle(root ?? document.documentElement);
if (style.colorScheme === 'dark' || style.colorScheme === 'light') { theme.value = style.colorScheme; return; }
const color = root ? style.color.match(/[\d.]+/g)?.map(Number) : null;
theme.value = color && color.length >= 3 ? (color[0] * .2126 + color[1] * .7152 + color[2] * .0722 > 140 ? 'dark' : 'light') : matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function send(value: object) { frame.value?.contentWindow?.postMessage({ channel: channel.value, ...value }, '*'); }
function sendContext() { send({ type: 'context', context: { ...context, language: props.language, theme: theme.value } }); }
function client() { return createPluginAppClient(props.gatewayUrl, props.sessionToken); }
async function refresh() {
const owner = ++epoch; busy.value = true; error.value = '';
try {
const result = await props.transport.request('list');
if (owner !== epoch) return;
if (!Array.isArray(result) || result.length > 50) throw new Error('PLUGIN_INVALID_RESPONSE');
available.value = result.map(v => { if (!pluginRecord(v)) throw new Error('PLUGIN_INVALID_RESPONSE');
const manifest = v.manifest; if (!pluginRecord(manifest) || typeof manifest.id !== 'string' || typeof manifest.name !== 'string' || (v.scope !== 'server' && v.scope !== 'instance')) throw new Error('PLUGIN_INVALID_RESPONSE');
return { manifest: manifest as unknown as PluginManifest, scope: v.scope }; });
} catch (e) { if (owner === epoch) error.value = `${tr('error')}: ${e instanceof Error ? e.message : ''}`; }
finally { if (owner === epoch) busy.value = false; }
if (!thirdPartyAllowed.value) return;
const owner = ++epoch; pending?.abort(); const controller = new AbortController(); pending = controller; busy.value = true; error.value = '';
try { const entries = await client().list(controller.signal); if (owner === epoch) available.value = entries; }
catch (e) { if (owner === epoch && !controller.signal.aborted) error.value = `${tr('error')}: ${e instanceof Error ? e.message : ''}`; }
finally { if (owner === epoch) { busy.value = false; pending = undefined; } }
}
function show() { detectTheme(); dialog.value?.showModal(); void refresh(); }
function toggle() {
if (suppressLauncherClick) { suppressLauncherClick = false; return; }
if (visible.value) { minimize(); return; }
detectTheme(); visible.value = true;
if (!current.value) { appView.value = false; void refresh(); }
void nextTick(() => { fitWindow(); windowElement.value?.focus(); });
}
function minimize() { endDrag(); visible.value = false; launcher.value?.focus(); }
function close() { stop(); error.value = ''; available.value = []; search.value = ''; minimize(); }
function stop() {
const id = pluginId.value ?? openingId; ++epoch; openingId = undefined; inFlight.clear(); current.value = null; documentSource.value = ''; context = {}; channel.value = ''; busy.value = false;
if (id) void props.transport.request('close', { pluginId: id }).catch(() => undefined);
++epoch; pending?.abort(); pending = undefined; const old = opening; opening = undefined; current.value = null; appView.value = false; busy.value = false;
if (old) void old.client.cancelOpen(old.key).catch(() => undefined);
}
function closed() { stop(); error.value = ''; available.value = []; }
async function launch(id: string) {
const owner = ++epoch; openingId = id; busy.value = true; error.value = '';
if (!thirdPartyAllowed.value) return;
if (current.value?.manifest.id === id) { appView.value = true; return; }
stop(); const owner = ++epoch, controller = new AbortController(), service = client(), key = crypto.randomUUID(); pending = controller; opening = { client: service, key }; busy.value = true; error.value = '';
try {
const result = await props.transport.request('open', { pluginId: id });
// stop() queues the close after this open on the same ordered socket.
// A late response must never close a newer opening of the same plugin.
const app = await service.open(id, { openId: key, theme: theme.value, language: props.language }, controller.signal);
if (owner !== epoch) return;
if (!pluginRecord(result) || !pluginRecord(result.snapshot)) throw new Error('PLUGIN_INVALID_RESPONSE');
const pack = parsePluginPackage(result.package);
if (pack.manifest.id !== id) throw new Error('PLUGIN_INVALID_RESPONSE');
current.value = pack; context = { config: result.config, self: result.self, scope: result.scope, snapshot: result.snapshot };
channel.value = crypto.randomUUID(); documentSource.value = pluginFrameDocument(pack, channel.value);
} catch (e) { if (owner === epoch) error.value = `${tr('error')}: ${e instanceof Error ? e.message : ''}`; }
finally { if (owner === epoch) { openingId = undefined; busy.value = false; } }
if (new URL(app.url).origin === location.origin) throw new Error('PLUGIN_SEPARATE_ORIGIN_REQUIRED');
current.value = app; appView.value = true;
} catch (e) {
if (owner === epoch) { const old = opening; opening = undefined; if (old) void old.client.cancelOpen(old.key).catch(() => undefined); if (!controller.signal.aborted) error.value = `${tr('error')}: ${e instanceof Error ? e.message : ''}`; }
} finally { if (owner === epoch) { busy.value = false; pending = undefined; } }
}
async function receive(event: MessageEvent) {
if (!frame.value || event.source !== frame.value.contentWindow || !pluginRecord(event.data) || event.data.channel !== channel.value || !current.value) return;
const value = event.data;
if (value.type === 'ready') { sendContext(); return; }
if (value.type !== 'request' || !Number.isSafeInteger(value.id) || inFlight.has(value.id as number) || inFlight.size >= 8) return;
const id = value.id as number, owner = epoch, plugin = pluginId.value!; inFlight.add(id);
try {
let result: unknown;
if (value.method === 'room.snapshot') result = await props.transport.request('snapshot', { pluginId: plugin });
else if (value.method === 'room.update' && pluginRecord(value.args) && Number.isSafeInteger(value.args.revision)) {
result = await props.transport.request('update', { pluginId: plugin, revision: value.args.revision as number, state: parsePluginJson(value.args.state) });
} else throw new Error('PLUGIN_PERMISSION_DENIED');
if (owner === epoch) send({ type: 'reply', id, result });
} catch (e) { if (owner === epoch) send({ type: 'reply', id, error: e instanceof Error ? e.message : 'PLUGIN_FAILED' }); }
finally { if (owner === epoch) inFlight.delete(id); }
function message(event: MessageEvent) {
if (!current.value || event.source !== frame.value?.contentWindow || event.origin !== new URL(current.value.url).origin || !pluginRecord(event.data)) return;
if (event.data.type === 'webspeak-app-closed' && event.data.id === current.value.id) { stop(); error.value = tr('context'); }
}
const unsubscribe = props.transport.subscribe(message => {
if (message.type === 'pluginReset') { stop(); available.value = []; dialog.value?.close(); return; }
if (message.type !== 'pluginEvent' || message.pluginId !== pluginId.value) return;
if (!message.snapshot) { stop(); error.value = tr('context'); return; }
context.snapshot = message.snapshot as PluginRoomSnapshot; send({ type: 'snapshot', snapshot: message.snapshot });
function appearance() { if (current.value && opening) void opening.client.appearance(current.value.id, theme.value, props.language).catch(() => undefined); }
function fitWindow() {
if (launcher.value && launcherPosition.value.left) {
const box = launcher.value.getBoundingClientRect();
launcherPosition.value = { left: `${Math.max(8, Math.min(box.left, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(box.top, innerHeight - box.height - 8))}px`, right: 'auto', bottom: 'auto' };
}
if (!visible.value || maximized.value || !windowElement.value) return;
const box = windowElement.value.getBoundingClientRect();
position.value = { left: `${Math.max(8, Math.min(box.left, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(box.top, innerHeight - box.height - 8))}px`, transform: 'none' };
}
function toggleMaximize() { endDrag(); maximized.value = !maximized.value; if (!maximized.value) void nextTick(fitWindow); }
function startDrag(event: PointerEvent) {
if (event.button !== 0 || maximized.value || (event.target as HTMLElement).closest('button')) return;
const box = windowElement.value?.getBoundingClientRect(); if (!box) return;
event.preventDefault(); const handle = event.currentTarget as HTMLElement;
drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: box.left, top: box.top, handle, kind: 'window', moved: false }; dragging.value = true;
handle.setPointerCapture(event.pointerId);
}
function startLauncherDrag(event: PointerEvent) {
if (event.button !== 0 || !launcher.value) return;
const box = launcher.value.getBoundingClientRect(); suppressLauncherClick = false;
drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: box.left, top: box.top, handle: launcher.value, kind: 'launcher', moved: false };
launcher.value.setPointerCapture(event.pointerId);
}
function moveDrag(event: PointerEvent) {
if (!drag || drag.id !== event.pointerId) return;
const target = drag.kind === 'launcher' ? launcher.value : windowElement.value; if (!target) return;
if (Math.hypot(event.clientX - drag.x, event.clientY - drag.y) < 5 && !drag.moved) return;
drag.moved = true; const box = target.getBoundingClientRect();
const next = { left: `${Math.max(8, Math.min(drag.left + event.clientX - drag.x, innerWidth - box.width - 8))}px`, top: `${Math.max(8, Math.min(drag.top + event.clientY - drag.y, innerHeight - box.height - 8))}px`, transform: 'none' };
if (drag.kind === 'launcher') launcherPosition.value = { ...next, right: 'auto', bottom: 'auto' }; else position.value = next;
}
function endDrag() {
const old = drag; drag = undefined; dragging.value = false;
if (old?.kind === 'launcher' && old.moved) suppressLauncherClick = true;
if (old?.handle.hasPointerCapture(old.id)) old.handle.releasePointerCapture(old.id);
}
watch(windowElement, element => { resizeObserver?.disconnect(); if (element) { resizeObserver = new ResizeObserver(fitWindow); resizeObserver.observe(element); } });
watch(() => [props.sessionToken, props.gatewayUrl, props.connected] as const, close);
watch(thirdPartyAllowed, allowed => { if (!allowed) close(); }, { flush: 'sync' });
watch(() => props.language, appearance); watch(theme, appearance);
onMounted(() => {
detectTheme(); window.addEventListener('message', message); window.addEventListener('resize', fitWindow); window.addEventListener('pointermove', moveDrag); window.addEventListener('pointerup', endDrag); window.addEventListener('pointercancel', endDrag); window.addEventListener('blur', endDrag);
observer = new MutationObserver(detectTheme); observer.observe(document.documentElement, { attributes: true, subtree: true, attributeFilter: ['data-ws-skin', 'data-theme'] });
});
watch(() => props.language, sendContext);
watch(theme, sendContext);
watch(() => props.connected, connected => { if (!connected) { closed(); dialog.value?.close(); } });
onMounted(() => { window.addEventListener('message', receive); observer = new MutationObserver(detectTheme); observer.observe(document.documentElement, { attributes: true, subtree: true, attributeFilter:['data-ws-skin','data-theme'] }); });
onBeforeUnmount(() => { unsubscribe(); stop(); observer?.disconnect(); window.removeEventListener('message', receive); dialog.value?.close(); });
onBeforeUnmount(() => { stop(); endDrag(); observer?.disconnect(); resizeObserver?.disconnect(); window.removeEventListener('message', message); window.removeEventListener('resize', fitWindow); window.removeEventListener('pointermove', moveDrag); window.removeEventListener('pointerup', endDrag); window.removeEventListener('pointercancel', endDrag); window.removeEventListener('blur', endDrag); });
</script>
<style>
.ws-plugin-launcher{all:initial;position:fixed;right:16px;top:88px;z-index:10000;font:600 14px system-ui;cursor:pointer;background:#184b48;color:white;border:1px solid #4d827e;border-radius:24px;padding:10px 16px;box-shadow:0 4px 20px #0003}
.ws-plugin-dialog{box-sizing:border-box;width:min(960px,calc(100vw - 24px));max-height:calc(100dvh - 32px);padding:20px;border:1px solid #b6c9c7;border-radius:16px;background:#fff;color:#182e2d;font:15px/1.5 system-ui;overflow:auto}
.ws-plugin-dialog[data-plugin-theme="dark"]{background:#20242b;color:#ecf2f1;border-color:#4a525d}.ws-plugin-dialog::backdrop{background:#0009}.ws-plugin-dialog header,.ws-plugin-toolbar,.ws-plugin-entry{display:flex;align-items:center;gap:12px;justify-content:space-between}.ws-plugin-dialog header strong{font-size:20px}.ws-plugin-dialog button{font:inherit;cursor:pointer;border:1px solid #779c98;border-radius:8px;padding:8px 12px;background:#e5f3f0;color:#153f3b}.ws-plugin-dialog button:disabled{opacity:.5;cursor:wait}.ws-plugin-dialog iframe{display:block;width:100%;height:min(620px,68dvh);border:1px solid #779c98;border-radius:8px;background:transparent}.ws-plugin-toolbar{margin:14px 0;flex-wrap:wrap}.ws-plugin-entry{border-top:1px solid #779c9866;padding:16px 0}.ws-plugin-entry small{display:block;opacity:.7}.ws-plugin-entry p{margin:6px 0}.ws-plugin-error{color:#c73131;overflow-wrap:anywhere}
@media(max-width:600px){.ws-plugin-launcher{top:72px;right:8px;padding:8px 12px}.ws-plugin-dialog{padding:14px}.ws-plugin-entry{align-items:start}.ws-plugin-dialog iframe{height:65dvh}}
</style>
<style src="../styles/plugin-overlay.css"></style>
+6 -6
View File
@@ -20,6 +20,7 @@ import { parseSkinExtensionUiInput } from "../../../src/shared/skin-extension-ui
import { approveSkinPluginComponents, getMissingSkinPluginApprovals, isSkinPluginComponentApproved, revokeSkinPluginApprovals } from "../services/skin-plugin-approval.js";
import { createSkinPluginAssetUrlCache } from "../services/skin-plugin-asset-urls.js";
import { PROMPT_FOR_SKIN_PERMISSIONS } from "../services/skin-permission-policy.js";
import { canUseSkin, openInstanceAuthorization } from '../services/instance-authorization.js';
import { useSkinEditorMode } from "../services/skin-editor-mode.js";
type Scalar = string | number | boolean;
@@ -108,14 +109,14 @@ export default defineComponent({
const matchingComponents = computed(() => validatedDocument.value.components.filter((component) => component.page === props.page));
const pendingApproval = computed(() => {
refresh.value;
return denied.value ? [] : getMissingSkinPluginApprovals(props.skinId, props.skinVersion, { ...validatedDocument.value, components: matchingComponents.value });
return denied.value || !canUseSkin(props.skinId) ? [] : getMissingSkinPluginApprovals(props.skinId, props.skinVersion, { ...validatedDocument.value, components: matchingComponents.value });
});
const accessComponents = computed(() => pendingApproval.value.length
? pendingApproval.value
: matchingComponents.value.filter((component) => component.permissions.length > 0));
const activeComponents = computed(() => {
refresh.value;
return matchingComponents.value.filter((component) => isSkinPluginComponentApproved(props.skinId, props.skinVersion, component));
return canUseSkin(props.skinId) ? matchingComponents.value.filter((component) => isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)) : [];
});
const surfaceCandidate = computed(() => activeComponents.value.find((component) => component.mode === "surface") ?? null);
const activeSurface = computed(() => surfaceSuppressed.value ? null : surfaceCandidate.value);
@@ -220,7 +221,7 @@ export default defineComponent({
function dispatch(component: SkinPluginComponent, actionId: string, context: SafeContext, state: Record<string, Scalar>): void {
const definition = component.actions[actionId];
if (!definition || !isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)) return;
if (!definition || !canUseSkin(props.skinId) || !isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)) return;
const args = resolveActionArgs(definition, context, state);
if (definition.type === "ui.setState") {
if (typeof args.key === "string" && component.state && Object.hasOwn(component.state, args.key) && "value" in args) {
@@ -244,7 +245,7 @@ export default defineComponent({
}
function dispatchRuntimeCallback(component: SkinPluginComponent, handlerId: string, eventName: string, event: Event, state: Record<string, Scalar>): void {
if (!component.runtimeCallbacks) return;
if (!canUseSkin(props.skinId) || !component.runtimeCallbacks) return;
const callbackEvent: Record<string, unknown> = { componentId: component.id, handlerId, eventName };
if (typeof KeyboardEvent !== "undefined" && event instanceof KeyboardEvent) callbackEvent.key = event.key;
const mayReadUserInput = props.extensionPermissions.includes("ui.input.read");
@@ -419,8 +420,7 @@ export default defineComponent({
}
function openAccessManager(): void {
denied.value = false;
manageOpen.value = true;
openInstanceAuthorization();
}
function closeOrDisable(): void {
+11 -1
View File
@@ -8,6 +8,7 @@ import { SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS } from "../../../src/shared/skin-r
import SkinPluginOutlet from "./SkinPluginOutlet.js";
import { approveSkinRuntimePlugin, getSkinRuntimePluginApproval, revokeSkinRuntimePluginApprovals } from "../services/skin-runtime-plugin-approval.js";
import { PROMPT_FOR_SKIN_PERMISSIONS } from "../services/skin-permission-policy.js";
import { canUseSkin, openInstanceAuthorization } from '../services/instance-authorization.js';
import { useSkinEditorMode } from "../services/skin-editor-mode.js";
import { createSkinRuntimePluginSession } from "../services/skin-runtime-plugin-session.js";
import { createSkinRuntimePluginWasmSandbox } from "../services/skin-runtime-plugin-wasm.js";
@@ -63,6 +64,7 @@ function createRun(
skinVersion,
plugin,
approval,
signal: abortController.signal,
files,
uiInput: input,
context,
@@ -133,6 +135,7 @@ export default defineComponent({
const pagePlugins = computed(() => props.plugins?.plugins.filter((plugin) => plugin.page === props.page) ?? []);
const approved = (plugin: SkinRuntimePlugin): SkinRuntimePluginApproval | null => {
if (!canUseSkin(props.skinId)) return null;
const digest = digests.value[plugin.id];
if (!digest) return null;
const memoryGrant = inMemoryApprovals.get(plugin.id);
@@ -243,6 +246,7 @@ export default defineComponent({
await handler(action.args);
},
onOutput: () => {
if (!canUseSkin(props.skinId) || disposed || sessions.get(plugin.id) !== session) return;
installStyle(plugin);
outputs.value = { ...outputs.value, [plugin.id]: session.output };
digestErrors.value = { ...digestErrors.value, [plugin.id]: "" };
@@ -257,6 +261,7 @@ export default defineComponent({
function reconcile(): void {
if (disposed) return;
if (!canUseSkin(props.skinId)) { stopAll('instance-authorization-revoked'); return; }
const currentIds = new Set(pagePlugins.value.map((plugin) => plugin.id));
for (const pluginId of [...sessions.keys()]) if (!currentIds.has(pluginId)) stopPlugin(pluginId, "page-changed");
for (const plugin of pagePlugins.value) {
@@ -266,6 +271,7 @@ export default defineComponent({
}
function approvePending(): void {
if (!canUseSkin(props.skinId)) return;
for (const plugin of pending.value) {
const digest = digests.value[plugin.id];
if (!digest) continue;
@@ -294,7 +300,7 @@ export default defineComponent({
}
function openManager(): void {
managerOpen.value = true;
openInstanceAuthorization();
}
function dispatch(pluginId: string, value: unknown): void {
@@ -342,6 +348,10 @@ export default defineComponent({
}, { immediate: true });
watch(() => [props.page, digests.value, revision.value], reconcile, { deep: true });
watch(() => canUseSkin(props.skinId), allowed => {
if (!allowed) { stopAll('instance-authorization-revoked'); managerOpen.value = false; }
else approvePending();
}, { flush: 'sync' });
watch(editorMode.isEnabled, (enabled) => { if (!enabled) managerOpen.value = false; });
watch(() => props.context, () => {
if (disposed) return;
+10 -1
View File
@@ -35,6 +35,9 @@
<span>{{ option.label }}</span>
<Icon v-if="modelValue === option.value" name="check" :size="14" />
</button>
<button type="button" class="skin-option skin-authorization" role="option" :aria-selected="false" @click="authorization">
<Icon name="shield" :size="16" /><span>{{ authorizationCopy.menu }}</span><small>{{ thirdPartyAllowed ? authorizationCopy.enabled : authorizationCopy.disabled }}</small>
</button>
</div>
</div>
</template>
@@ -42,6 +45,8 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import Icon from "./Icon.vue";
import { authorizationLanguage, canUseSkin, openInstanceAuthorization, thirdPartyAllowed } from '../services/instance-authorization.js';
import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
export interface SkinOption {
value: string;
@@ -60,7 +65,9 @@ const emit = defineEmits<{
change: [value: string];
}>();
const options = computed(() => props.options);
const options = computed(() => props.options.filter(option => canUseSkin(option.value)));
const authorizationCopy = computed(() => instanceAuthorizationCopy[authorizationLanguage.value]);
function authorization() { close(); openInstanceAuthorization(); }
const selectedOption = computed(() => options.value.find((option) => option.value === props.modelValue) ?? options.value[0] ?? {
value: props.modelValue,
label: props.menuLabel,
@@ -92,6 +99,8 @@ onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerD
flex: 0 0 auto;
color: var(--text-muted);
}
.skin-authorization{margin-top:6px;border-top:1px solid #8bdad8!important}
.skin-authorization small{margin-left:auto;font-size:10px;opacity:.75}
.skin-trigger {
display: inline-flex;
+10 -7
View File
@@ -1,14 +1,16 @@
<template>
<section class="page-content plugin-admin">
<header class="plugin-hero">
<div><span class="plugin-eyebrow"><Icon name="grid" :size="14" /> EXTENSIONS</span><h2>{{ tr('store') }}</h2><p>{{ tr('lead') }}</p><div class="plugin-metrics"><span><b>{{ model.catalog.value?.entries.length ?? '—' }}</b>{{ text('available') }}</span><i></i><span><b>{{ model.installed.value.length }}</b>{{ tr('installed') }}</span><i></i><span><b>{{ enabledCount }}</b>{{ text('active') }}</span></div></div>
<div><span class="plugin-eyebrow"><Icon name="grid" :size="14" /> APPS</span><h2>{{ tr('store') }}</h2><p>{{ tr('lead') }}</p><div class="plugin-metrics"><span><b>{{ model.catalog.value?.entries.length ?? '—' }}</b>{{ text('available') }}</span><i></i><span><b>{{ model.installed.value.length }}</b>{{ tr('installed') }}</span><i></i><span><b>{{ enabledCount }}</b>{{ text('active') }}</span></div></div>
<div class="plugin-hero-art" aria-hidden="true"><i></i><i></i><i></i><i></i><b>+</b></div>
</header>
<details class="plugin-runtime-settings"><summary><Icon name="server" :size="16" />{{ tr('runtime') }}<span class="plugin-status" :class="{active:model.runtime.value?.available}"><i></i>{{ tr(model.runtime.value?.available?'running':'stopped') }} · {{ model.runtime.value?.port ?? '—' }}</span></summary><p>{{ tr('originHelp') }}</p><form @submit.prevent="model.saveRuntime"><label>{{ tr('origin') }}<input v-model="model.origin.value" type="url" placeholder="https://apps.example.com" :disabled="model.busy.value" /></label><button class="plugin-button primary" type="submit" :disabled="model.busy.value || !model.runtime.value">{{ tr('save') }}</button></form></details>
<div class="plugin-toolbar">
<nav class="plugin-tabs" :aria-label="tr('store')"><button type="button" :aria-current="tab==='store'?'page':undefined" @click="tab='store'"><Icon name="compass" :size="16" />{{ text('discover') }}</button><button type="button" :aria-current="tab==='installed'?'page':undefined" @click="tab='installed'"><Icon name="grid" :size="16" />{{ tr('installed') }}<span>{{ model.installed.value.length }}</span></button></nav>
<div class="plugin-tools"><label class="plugin-search"><Icon name="search" :size="16" /><input v-model="search" type="search" :aria-label="text('search')" :placeholder="text('search')" /></label><button class="plugin-refresh" type="button" :disabled="model.busy.value" :title="tr('refresh')" :aria-label="tr('refresh')" @click="model.load"><Icon name="refresh" :size="17" /></button></div>
</div>
<p v-if="model.error.value" class="plugin-feedback is-error" role="alert"><Icon name="info" :size="17" />{{ tr('error') }}: {{ model.error.value }}</p>
<p v-if="tab==='store' && model.catalogError.value" class="plugin-feedback is-error" role="alert"><Icon name="info" :size="17" />{{ tr('catalogError') }} · {{ model.catalogError.value }}</p>
<p v-if="notice" class="plugin-feedback" role="status"><Icon name="check" :size="17" />{{ notice }}</p>
<div class="plugin-section-heading"><div><h3>{{ tab==='store'?text('discover'):tr('installed') }}</h3><span v-if="tab==='store'" class="plugin-source"><i></i>{{ text('source') }}</span></div><a v-if="tab==='store'" :href="PLUGIN_STORE_REPOSITORY" target="_blank" rel="noopener noreferrer"><Icon name="github" :size="16" />GitHub ↗</a><button v-else class="plugin-button" type="button" :disabled="model.busy.value" @click="fileInput?.click()"><Icon name="share" :size="15" />{{ tr('upload') }}</button></div>
<input ref="fileInput" class="plugin-file-input" type="file" accept=".wplugin,application/json" @change="upload" />
@@ -16,21 +18,21 @@
<div v-if="tab==='store'" class="plugin-store-grid">
<article v-for="entry in catalogEntries" :key="entry.id" class="plugin-market-card">
<div class="plugin-card-visual"><div class="plugin-card-symbol"><Icon name="grid" :size="38" /></div><span>API {{ entry.manifest?.apiVersion ?? '—' }}</span><i aria-hidden="true"></i></div>
<div class="plugin-card-body"><div class="plugin-card-title"><h4>{{ entry.manifest?.name ?? entry.id }}</h4><small>v{{ entry.manifest?.version ?? '—' }}</small></div><p class="plugin-author">{{ entry.manifest?.author }} · {{ entry.manifest?.license }}</p><p class="plugin-description">{{ entry.manifest?.description }}</p><div class="plugin-tags"><span v-for="scope in entry.manifest?.scopes" :key="scope"><Icon name="server" :size="12" />{{ tr(scope) }}</span></div><div class="plugin-permissions"><span v-for="permission in entry.manifest?.permissions" :key="permission"><Icon name="check" :size="12" />{{ text(permission==='room.read'?'read':'write') }}</span></div><p v-if="entry.error" class="is-error">{{ entry.error }}</p></div>
<div class="plugin-card-body"><div class="plugin-card-title"><h4>{{ entry.manifest?.name ?? entry.id }}</h4><small>v{{ entry.manifest?.version ?? '—' }}</small></div><p class="plugin-author">{{ entry.manifest?.author }} · {{ entry.manifest?.license }}</p><p class="plugin-description">{{ entry.manifest?.description }}</p><div class="plugin-tags"><span v-for="scope in entry.manifest?.scopes" :key="scope"><Icon name="server" :size="12" />{{ tr(scope) }}</span></div><div class="plugin-permissions"><span>{{ tr('client') }}</span><span v-if="entry.manifest?.server">{{ tr('backend') }}</span></div><p v-if="entry.error" class="is-error">{{ entry.error }}</p></div>
<footer><a :href="entry.repository" target="_blank" rel="noopener noreferrer" :aria-label="`${entry.manifest?.name ?? entry.id} · GitHub`"><Icon name="github" :size="16" />GitHub ↗</a><button class="plugin-button primary" type="button" :disabled="model.busy.value || !entry.manifest || !!entry.error" @click="install(entry)"><Icon name="download" :size="15" />{{ installLabel(entry) }}</button></footer>
</article>
</div>
<div v-else class="plugin-installed-list">
<article v-for="plugin in installedEntries" :key="plugin.manifest.id" class="plugin-installed-card">
<header><div class="plugin-installed-icon"><Icon name="grid" :size="23" /></div><div class="plugin-installed-name"><h4>{{ plugin.manifest.name }}</h4><p>v{{ plugin.manifest.version }} · {{ plugin.manifest.author }}</p></div><span class="plugin-status" :class="{active:plugin.settings.enabled}"><i></i>{{ text(plugin.settings.enabled?'active':'inactive') }}</span></header>
<p class="plugin-description">{{ plugin.manifest.description }}</p><div class="plugin-installed-meta"><span><Icon name="server" :size="13" />{{ tr(plugin.settings.scope) }}</span><span>{{ plugin.manifest.license }}</span><span>API {{ plugin.manifest.apiVersion }}</span></div>
<header><div class="plugin-installed-icon"><Icon name="grid" :size="23" /></div><div class="plugin-installed-name"><h4>{{ plugin.manifest.name }}</h4><p>v{{ plugin.manifest.version }} · {{ plugin.manifest.author }}</p></div><span class="plugin-status" :class="{active:plugin.settings.enabled}"><i></i>{{ tr(plugin.runtime?.state ?? 'disabled') }}</span></header>
<p class="plugin-description">{{ plugin.manifest.description }}</p><p v-if="plugin.runtime?.error" class="is-error" role="alert">{{ plugin.runtime.error }}</p><div class="plugin-installed-meta"><span><Icon name="server" :size="13" />{{ tr(plugin.settings.scope) }}</span><span>{{ plugin.manifest.license }}</span><span>API {{ plugin.manifest.apiVersion }}</span></div>
<details :open="expanded===plugin.manifest.id" @toggle="onToggle($event,plugin.manifest.id)"><summary><Icon name="settings" :size="16" />{{ text('configure') }}<Icon class="plugin-chevron" name="chevron-down" :size="15" /></summary><fieldset :disabled="model.busy.value">
<div class="plugin-enable-row"><div><strong>{{ tr('enabled') }}</strong><p>{{ text('review') }}</p></div><label class="plugin-switch"><input v-model="model.drafts[plugin.manifest.id].enabled" type="checkbox" :aria-label="tr('enabled')" /><span></span></label></div>
<div class="plugin-permissions"><span v-for="permission in plugin.manifest.permissions" :key="permission"><Icon name="shield" :size="13" />{{ text(permission==='room.read'?'read':'write') }}</span></div>
<label class="plugin-trust"><input v-model="model.drafts[plugin.manifest.id].trusted" type="checkbox" />{{ tr('trust') }}</label><p class="plugin-trust-note">{{ tr('enableNote') }}</p>
<label>{{ tr('scope') }}<select v-model="model.drafts[plugin.manifest.id].scope"><option v-for="scope in plugin.manifest.scopes" :key="scope" :value="scope">{{ tr(scope) }}</option></select></label>
<label v-if="model.drafts[plugin.manifest.id].scope==='server'">{{ tr('targets') }}<textarea v-model="model.drafts[plugin.manifest.id].targets" rows="3" maxlength="15000" placeholder="voice.example.com:9987"></textarea></label>
<details class="plugin-advanced"><summary>{{ text('advanced') }}<Icon name="chevron-down" :size="14" /></summary><label>{{ tr('config') }}<textarea v-model="model.drafts[plugin.manifest.id].config" rows="5" maxlength="8192" spellcheck="false"></textarea></label></details>
<div class="plugin-settings-actions"><button class="plugin-button danger" type="button" @click="remove(plugin)"><Icon name="trash" :size="14" />{{ tr('remove') }}</button><button class="plugin-button primary" type="button" @click="save(plugin)"><Icon name="check" :size="15" />{{ tr('save') }}</button></div>
<details class="plugin-advanced"><summary>{{ text('advanced') }}<Icon name="chevron-down" :size="14" /></summary><label>{{ tr('config') }}<textarea v-model="model.drafts[plugin.manifest.id].config" rows="5" maxlength="65536" spellcheck="false"></textarea></label><template v-if="plugin.manifest.server"><label>{{ tr('privateConfig') }}<small>{{ tr(plugin.settings.hasServerConfig?'secretSaved':'secretEmpty') }}</small><select v-model="model.drafts[plugin.manifest.id].serverConfigAction"><option value="keep">{{ tr('keep') }}</option><option value="replace">{{ tr('replace') }}</option><option value="remove">{{ tr('erase') }}</option></select><textarea v-if="model.drafts[plugin.manifest.id].serverConfigAction==='replace'" v-model="model.drafts[plugin.manifest.id].serverConfig" rows="5" maxlength="65536" spellcheck="false" autocomplete="off" autocapitalize="off" autocorrect="off"></textarea></label></template></details>
<div class="plugin-settings-actions"><button v-if="plugin.manifest.server" class="plugin-button" type="button" :disabled="!plugin.settings.enabled" @click="model.restart(plugin)">{{ tr('restart') }}</button><button class="plugin-button danger" type="button" @click="remove(plugin)"><Icon name="trash" :size="14" />{{ tr('remove') }}</button><button class="plugin-button primary" type="button" @click="save(plugin)"><Icon name="check" :size="15" />{{ tr('save') }}</button></div>
</fieldset></details>
</article>
</div>
@@ -80,4 +82,5 @@ section.page-content.plugin-admin{display:grid;grid-template-columns:minmax(0,1f
.plugin-installed-card fieldset>label,.plugin-advanced label{display:grid;gap:8px;color:var(--admin-muted);font-size:11px}.plugin-installed-card textarea,.plugin-installed-card select{width:100%;min-width:0;max-width:100%;border:1px solid var(--admin-border);padding:10px 12px;border-radius:8px;background:var(--admin-field);color:var(--admin-text);font-size:12px}.plugin-installed-card textarea{resize:vertical;line-height:1.7}.plugin-advanced{border:1px solid var(--admin-border);border-radius:9px;padding:0 12px}.plugin-advanced summary{display:flex;align-items:center;justify-content:space-between;font-size:11px;color:var(--admin-muted);padding:12px 0;cursor:pointer}.plugin-advanced label{padding-bottom:12px}.plugin-advanced textarea{font-family:ui-monospace,monospace}.plugin-settings-actions{display:flex;justify-content:space-between;gap:12px;padding-top:4px}.plugin-scope-help{margin-top:8px;border-top:1px solid var(--admin-border);padding-top:20px;color:var(--admin-muted);font-size:11px}.plugin-scope-help summary{display:flex;gap:8px;align-items:center;cursor:pointer;width:fit-content}.plugin-scope-help p{line-height:1.8;margin-top:12px;max-width:850px}.plugin-empty{display:grid;justify-items:center;gap:16px;padding:60px 20px;color:var(--admin-muted);text-align:center;border:1px dashed var(--admin-border);border-radius:16px}.plugin-empty h4{font-size:14px}.plugin-admin :is(button,a,input,textarea,select,summary):focus-visible{outline:3px solid color-mix(in srgb,var(--admin-accent) 35%,transparent);outline-offset:3px}
@media(max-width:1100px){.plugin-hero-art{width:100px;flex-basis:100px;margin-right:0}.plugin-hero{padding:26px}.plugin-tools{flex:1;justify-content:end}.plugin-search{flex:1;max-width:320px}.plugin-search input{width:100%}}
@media(max-width:600px){.plugin-admin{gap:18px}.plugin-hero{padding:24px 20px;border-radius:16px}.plugin-hero h2{font-size:25px}.plugin-hero p{font-size:12px}.plugin-hero-art{position:absolute;width:110px;right:-28px;top:-35px;opacity:.12}.plugin-metrics{gap:12px}.plugin-metrics>span{gap:6px;font-size:10px}.plugin-metrics b{font-size:18px}.plugin-tabs,.plugin-tools{width:100%}.plugin-tabs button{flex:1;justify-content:center;padding:8px 10px}.plugin-search{max-width:none}.plugin-section-heading>div{gap:8px}.plugin-section-heading h3{font-size:14px}.plugin-source{font-size:9px}.plugin-card-body{padding:18px}.plugin-market-card{max-width:none}.plugin-installed-card>header{padding:18px 16px 12px;flex-wrap:wrap;gap:10px}.plugin-installed-icon{width:40px;height:40px}.plugin-installed-name h4{font-size:13px}.plugin-status{font-size:9px}.plugin-installed-card>.plugin-description,.plugin-installed-meta{padding-left:16px;padding-right:16px}.plugin-installed-card>details>summary{padding:14px 16px}.plugin-installed-card fieldset{padding:4px 16px 16px}.plugin-enable-row{padding:12px}}
.plugin-runtime-settings{border:1px solid var(--admin-border);border-radius:14px;background:var(--admin-surface);padding:18px}.plugin-runtime-settings>summary{display:flex;align-items:center;gap:12px;cursor:pointer;font-weight:650}.plugin-runtime-settings>p{margin:16px 0;color:var(--admin-muted);font-size:12px;line-height:1.7}.plugin-runtime-settings form{display:flex;align-items:end;gap:14px;flex-wrap:wrap}.plugin-runtime-settings label{display:grid;flex:1;gap:8px;font-size:12px;min-width:min(100%,260px)}.plugin-runtime-settings input{width:100%;box-sizing:border-box;border:1px solid var(--admin-border);border-radius:9px;padding:10px;background:var(--admin-raised);color:var(--admin-text)}.plugin-trust{display:flex!important;align-items:start!important;gap:10px!important;font-weight:650}.plugin-trust input{width:auto!important;margin-top:3px;flex:none}.plugin-trust-note{font-size:12px;color:var(--admin-muted);line-height:1.7}.plugin-advanced label>small{color:var(--admin-muted);font-weight:400}.plugin-settings-actions{flex-wrap:wrap}
</style>
+42 -49
View File
@@ -1,54 +1,47 @@
import { reactive, ref, shallowRef } from "vue";
import { createAdminRequests } from "../services/admin-requests.js";
import { isAdminRequestCancelled, type AdminApi } from "../services/admin-api.js";
import { parsePluginPackage, PLUGIN_LIMIT_BYTES, type InstalledPlugin, type PluginCatalog, type PluginStoreEntry } from "../../../src/shared/plugins.js";
import { reactive, ref, shallowRef } from 'vue';
import { createAdminRequests } from '../services/admin-requests.js';
import { isAdminRequestCancelled, type AdminApi } from '../services/admin-api.js';
import { parsePluginPackage, PLUGIN_LIMIT_BYTES, type InstalledPlugin, type PluginCatalog, type PluginStoreEntry, type PluginRuntimeSettings, type PluginSettingsInput } from '../../../src/shared/plugins.js';
export function useAdminPlugins(api: AdminApi) {
const installed = shallowRef<InstalledPlugin[]>([]), catalog = shallowRef<PluginCatalog | null>(null);
const busy = ref(false), error = ref(''), requests = createAdminRequests();
const drafts = reactive<Record<string, { enabled: boolean; scope: 'server'|'instance'; targets: string; config: string }>>({});
function apply(records: InstalledPlugin[]) {
installed.value = records;
for (const record of records) if (!drafts[record.manifest.id]) drafts[record.manifest.id] = {
enabled: record.settings.enabled, scope: record.settings.scope, targets: record.settings.targets.join('\n'), config: JSON.stringify(record.settings.config, null, 2),
};
for (const id of Object.keys(drafts)) if (!records.some(r => r.manifest.id === id)) delete drafts[id];
const installed=shallowRef<InstalledPlugin[]>([]),catalog=shallowRef<PluginCatalog|null>(null),runtime=shallowRef<PluginRuntimeSettings|null>(null);
const origin=ref(''),busy=ref(false),error=ref(''),catalogError=ref(''),requests=createAdminRequests();
const drafts=reactive<Record<string,{enabled:boolean;trusted:boolean;scope:'server'|'instance';targets:string;config:string;serverConfigAction:'keep'|'replace'|'remove';serverConfig:string}>>({});
function apply(records:InstalledPlugin[]){
installed.value=records;
for(const record of records)if(!drafts[record.manifest.id])drafts[record.manifest.id]={enabled:record.settings.enabled,trusted:record.settings.trusted,scope:record.settings.scope,targets:record.settings.targets.join('\n'),config:JSON.stringify(record.settings.config,null,2),serverConfigAction:'keep',serverConfig:''};
for(const id of Object.keys(drafts))if(!records.some(r=>r.manifest.id===id))delete drafts[id];
}
async function work(run: (signal: AbortSignal, current: () => boolean) => Promise<void>) {
if (busy.value) return;
const request = requests.begin('plugins'); busy.value = true; error.value = '';
const timer = setTimeout(() => { if (request.isCurrent()) { error.value='PLUGIN_TIMEOUT'; requests.cancel('plugins'); busy.value=false; } }, 90_000);
try { await run(request.signal, request.isCurrent); }
catch (e) { if (request.isCurrent() && !isAdminRequestCancelled(e)) error.value = e instanceof Error ? e.message : 'PLUGIN_FAILED'; }
finally { clearTimeout(timer); if (request.isCurrent()) busy.value = false; request.finish(); }
async function work(run:(signal:AbortSignal,current:()=>boolean)=>Promise<void>){
if(busy.value)return;const request=requests.begin('plugins');busy.value=true;error.value='';
const timer=setTimeout(()=>{if(request.isCurrent()){error.value='PLUGIN_TIMEOUT';requests.cancel('plugins');busy.value=false;}},90_000);
try{await run(request.signal,request.isCurrent);}catch(e){if(request.isCurrent()&&!isAdminRequestCancelled(e))error.value=e instanceof Error?e.message:'PLUGIN_FAILED';}
finally{clearTimeout(timer);if(request.isCurrent())busy.value=false;request.finish();}
}
function load() { return work(async (signal, current) => {
const result = await api.plugins(signal); if (current()) apply(result.plugins);
// Installed packages remain manageable even when GitHub is unavailable.
const store = await api.pluginStore(signal); if (current()) catalog.value = store;
}); }
async function install(entry: PluginStoreEntry) {
return work(async (signal, current) => {
const result = await api.installPlugin({ id: entry.id, revision: entry.revision, installedRevision: installed.value.find(p => p.manifest.id === entry.id)?.revision ?? null }, signal);
if (current()) { delete drafts[entry.id]; apply([...installed.value.filter(p => p.manifest.id !== entry.id), result.plugin]); }
});
}
function save(record: InstalledPlugin) {
return work(async (signal, current) => {
const draft = drafts[record.manifest.id], captured = JSON.stringify(draft);
const settings = { enabled: draft.enabled, scope: draft.scope, targets: draft.targets.split(/\r?\n/).map(t => t.trim()).filter(Boolean), config: JSON.parse(draft.config) };
const result = await api.configurePlugin(record.manifest.id, record.revision, settings, signal);
if (current()) { if (JSON.stringify(drafts[record.manifest.id]) === captured) delete drafts[record.manifest.id]; apply(installed.value.map(p => p.manifest.id === record.manifest.id ? result.plugin : p)); }
});
}
function remove(record: InstalledPlugin) { return work(async (signal, current) => { await api.removePlugin(record.manifest.id, record.revision, signal); if (current()) apply(installed.value.filter(p => p.manifest.id !== record.manifest.id)); }); }
function upload(file: File) { return work(async (signal, current) => {
if (file.size > PLUGIN_LIMIT_BYTES) throw new Error('PLUGIN_TOO_LARGE');
const pack = parsePluginPackage(JSON.parse(await file.text())); if (!current()) return;
const result = await api.uploadPlugin(pack, installed.value.find(p => p.manifest.id === pack.manifest.id)?.revision ?? null, signal);
if (current()) { delete drafts[pack.manifest.id]; apply([...installed.value.filter(p => p.manifest.id !== pack.manifest.id), result.plugin]); }
}); }
function cancelRequests() { requests.reset(); busy.value = false; }
function reset() { cancelRequests(); installed.value = []; catalog.value = null; error.value = ''; for (const id of Object.keys(drafts)) delete drafts[id]; }
return { installed, catalog, busy, error, drafts, load, install, save, remove, upload, cancelRequests, reset };
function load(){return work(async(signal,current)=>{
const records=await api.plugins(signal);if(current())apply(records.plugins);
const settings=await api.pluginRuntime(signal);if(current()){runtime.value=settings.runtime;origin.value=settings.runtime.publicOrigin;}
try{const store=await api.pluginStore(signal);if(current()){catalog.value=store;catalogError.value='';}}catch(e){if(current()&&!isAdminRequestCancelled(e)){catalog.value=null;catalogError.value=e instanceof Error?e.message:'PLUGIN_STORE_UNAVAILABLE';}}
});}
function install(entry:PluginStoreEntry){return work(async(signal,current)=>{
const result=await api.installPlugin({id:entry.id,revision:entry.revision,installedRevision:installed.value.find(p=>p.manifest.id===entry.id)?.revision??null},signal);
if(current()){delete drafts[entry.id];apply([...installed.value.filter(p=>p.manifest.id!==entry.id),result.plugin]);}
});}
function save(record:InstalledPlugin){return work(async(signal,current)=>{
const draft=drafts[record.manifest.id],captured=JSON.stringify(draft);
const settings:PluginSettingsInput={enabled:draft.enabled,trusted:draft.trusted,scope:draft.scope,targets:draft.targets.split(/\r?\n/).map(t=>t.trim()).filter(Boolean),config:JSON.parse(draft.config),serverConfigAction:draft.serverConfigAction,...(draft.serverConfigAction==='replace'?{serverConfig:JSON.parse(draft.serverConfig)}:{})};
const result=await api.configurePlugin(record.manifest.id,record.revision,settings,signal);
if(current()){if(JSON.stringify(drafts[record.manifest.id])===captured)delete drafts[record.manifest.id];apply(installed.value.map(p=>p.manifest.id===record.manifest.id?result.plugin:p));}
});}
function restart(record:InstalledPlugin){return work(async(signal,current)=>{const result=await api.restartPlugin(record.manifest.id,record.revision,signal);if(current())apply(installed.value.map(p=>p.manifest.id===record.manifest.id?result.plugin:p));});}
function saveRuntime(){return work(async(signal,current)=>{if(!runtime.value)return;const captured=origin.value,result=await api.configurePluginRuntime(captured,runtime.value.revision,signal);if(current()){runtime.value=result.runtime;if(origin.value===captured)origin.value=result.runtime.publicOrigin;}});}
function remove(record:InstalledPlugin){return work(async(signal,current)=>{await api.removePlugin(record.manifest.id,record.revision,signal);if(current())apply(installed.value.filter(p=>p.manifest.id!==record.manifest.id));});}
function upload(file:File){return work(async(signal,current)=>{
if(file.size>PLUGIN_LIMIT_BYTES)throw new Error('PLUGIN_TOO_LARGE');const pack=parsePluginPackage(JSON.parse(await file.text()));if(!current())return;
const result=await api.uploadPlugin(pack,installed.value.find(p=>p.manifest.id===pack.manifest.id)?.revision??null,signal);
if(current()){delete drafts[pack.manifest.id];apply([...installed.value.filter(p=>p.manifest.id!==pack.manifest.id),result.plugin]);}
});}
function cancelRequests(){requests.reset();busy.value=false;for(const draft of Object.values(drafts)){draft.serverConfig='';draft.serverConfigAction='keep';}}
function reset(){cancelRequests();installed.value=[];catalog.value=null;runtime.value=null;origin.value='';error.value='';catalogError.value='';for(const id of Object.keys(drafts))delete drafts[id];}
return {installed,catalog,runtime,origin,busy,error,catalogError,drafts,load,install,save,restart,saveRuntime,remove,upload,cancelRequests,reset};
}
+20 -3
View File
@@ -1,4 +1,5 @@
import { onScopeDispose, ref, shallowRef, type Ref } from "vue";
import { computed, onScopeDispose, ref, shallowRef, watch, type Ref } from "vue";
import { canUseSkin, thirdPartyAllowed } from '../services/instance-authorization.js';
import { listInstalledSkins, loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
import { BUILTIN_SKIN_CATALOG, getPublicDefaultSkinId, isPublicSkinEnabled, listPublicSkins, type SkinCatalogEntry } from "../services/skin-catalog.js";
import { activateSkin, BUILTIN_DARK_SKIN, BUILTIN_LIGHT_SKIN, clearCustomSkinStyle, getStoredSkinId } from "../services/skin-runtime.js";
@@ -19,7 +20,8 @@ const fallbackId = () => isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUI
/** One page owns initialization, choices and their late responses, including persistence. */
export function usePublicSkin(options: PublicSkinOptions = {}) {
const activeSkin = options.activeSkin ?? shallowRef<InstalledSkin | null>(null);
const stored = getStoredSkinId();
const candidate = getStoredSkinId();
const stored = candidate && canUseSkin(candidate) ? candidate : null;
const activeSkinId = ref(stored ?? fallbackId());
const skinReady = ref(Boolean(stored && builtin(stored)));
const skinLoadError = shallowRef<{ skinId: string } | null>(null);
@@ -37,6 +39,7 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
async function apply(id: string, operation: ReturnType<typeof createSkinOperation>, persist = true, updateTheme = false, clearLoadError = true) {
operation.check();
if (!canUseSkin(id)) id = fallbackId();
const entry = catalogSkins.value.find(skin => skin.id === id);
const skin = await operation.wait(activateSkin(id, entry?.version, options.appVersion?.(), { signal: operation.signal }));
if (!owns(operation)) return;
@@ -119,5 +122,19 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
await select(fallbackId());
}
return { activeSkin, activeSkinId, skinReady, skinLoadError, installedSkins, catalogSkins, initialize, select, cancel, reset, switchToBuiltIn, switchToBuiltInAfterLoadError };
watch(thirdPartyAllowed, allowed => {
if (disposed) return;
if (allowed) { void initialize(); return; }
cancel();
activeSkin.value = null;
skinLoadError.value = null;
clearCustomSkinStyle();
activeSkinId.value = fallbackId();
skinReady.value = true;
void select(fallbackId());
}, { flush: 'sync' });
return { activeSkin, activeSkinId, skinReady, skinLoadError,
installedSkins: computed(() => installedSkins.value.filter(skin => canUseSkin(skin.id))),
catalogSkins: computed(() => catalogSkins.value.filter(skin => canUseSkin(skin.id))),
initialize, select, cancel, reset, switchToBuiltIn, switchToBuiltInAfterLoadError };
}
+4 -5
View File
@@ -7,7 +7,6 @@ import { createAccompaniment, type AccompanimentErrorCode } from "../voice/accom
import { createWebRtcTransport } from "../voice/webrtc-transport.js";
import { createVoiceConnection } from "../voice/connection.js";
import { createVoiceCommands } from "../voice/commands.js";
import { createPluginTransport } from "../services/plugin-transport.js";
import { createVoiceSessionState } from "../voice/session-state.js";
import { applySavedMemberVolumes } from "../voice/member-volume-preferences.js";
import { createAudioDiagnostics, type AudioPermission, type VoiceAudioStatusSample } from "../voice/audio-diagnostics.js";
@@ -201,7 +200,7 @@ export function useVoiceWebSocket() {
const ws = shallowRef<WebSocket | null>(null);
const serverInfo = shallowRef<VoiceServerInfo | null>(null);
const state = reactive<VoiceState>({ connected: false, connecting: false, reconnecting: false, reconnectAttempt: 0, reconnectFailed: false, tsClientId: 0, error: "", errorCode: "", microphoneError: "", microphoneErrorCode: "", audioNotice: "", audioNoticeCode: "", channelSwitchedChannelId: "" });
const plugins = createPluginTransport(() => ws.value, () => state.connected);
const pluginSession = ref("");
const sessionState = createVoiceSessionState({
selfId: () => state.tsClientId,
onMemberRemoved(id) {
@@ -1025,7 +1024,7 @@ export function useVoiceWebSocket() {
/** All ways a session ends release the same owned media and pending work. */
function releaseSessionResources(sendScreenStop = false): void {
plugins.reset();
pluginSession.value = "";
chatGeneration++;
inputDeviceGeneration++;
outputDeviceGeneration++;
@@ -1046,7 +1045,6 @@ export function useVoiceWebSocket() {
}
function handleMessage(raw: unknown): void {
if (plugins.receive(raw)) return;
const msg = parseServerMessage(raw);
if (!msg || screenShare.handleMessage(msg) || sessionState.receive(msg)) return;
switch (msg.type) {
@@ -1069,6 +1067,7 @@ export function useVoiceWebSocket() {
state.errorCode = "";
state.channelSwitchedChannelId = "";
state.tsClientId = Number(msg.tsClientId) || 0;
pluginSession.value = msg.pluginSession ?? "";
// The mute preference is local to the browser, while TeamSpeak shows
// the gateway's own client_input_muted flag to other clients. Send it
// as soon as the session is ready so a muted reconnect is visible to
@@ -1420,7 +1419,7 @@ export function useVoiceWebSocket() {
}
return {
plugins,
pluginSession,
...screenShare.api,
ws,
state,
@@ -1,5 +1,6 @@
import { computed, reactive, ref, type Ref } from "vue";
import { DEFAULT_TEAM_SPEAK_PORT, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
import { APP_VERSION } from "../services/app-version.js";
import type { Language } from "../i18n/web-client.js";
interface RelayOption {
@@ -28,7 +29,7 @@ export function useWebClientPublicConfig({
const initialized = ref(false);
const mobileMode = ref(false);
const siteName = ref("WebSpeak");
const appVersion = ref("0.2.7");
const appVersion = ref(APP_VERSION);
const visitorNumber = ref<number | null>(null);
const visitorTotal = ref<number | null>(null);
const accelerationRelays = ref<RelayOption[]>([]);
+15
View File
@@ -0,0 +1,15 @@
import type { SiteLanguage } from '../../../src/site-copy.js';
const en = {
menu: 'Authorization', title: 'Skins & plugins',
description: 'To provide customization and plugin features, third-party skins and plugins supplied by this WebSpeak instance may access information displayed in your channels, such as member names, channel details and chat messages. Connection credentials are excluded. Each WebSpeak instance is maintained by its own service provider.',
choice: 'I allow this instance’s third-party skins and plugins to use this information.',
alternative: 'If you decline, you can still use the three official skins: Day, Night and ILLUSIA. Other skins (including KAAK) and plugins will be hidden. You can change this choice in the skin menu at any time.',
accept: 'Agree and continue', decline: 'Use official skins only', save: 'Save', enabled: 'On', disabled: 'Off',
};
export const instanceAuthorizationCopy: Record<SiteLanguage, typeof en> = {
en,
zh: { menu: '授权', title: '皮肤与插件授权', description: '为了正常提供美化与插件功能,当前 WebSpeak 实例提供的第三方皮肤及插件可能需要读取频道中显示的信息,例如成员昵称、频道信息和聊天内容,不包括连接凭据。每个 WebSpeak 实例由各自的服务提供者维护。', choice: '我同意当前实例提供的第三方皮肤与插件使用上述信息。', alternative: '若不同意,仍可使用日间、夜间、ILLUSIA 三款官方皮肤;其他皮肤(包括 KAAK)及插件将被隐藏。你可以随时在皮肤菜单的“授权”中更改选择。', accept: '同意并继续', decline: '仅使用官方皮肤', save: '保存', enabled: '已开启', disabled: '已关闭' },
de: { menu: 'Berechtigung', title: 'Designs & Plugins', description: 'Designs und Plugins von Drittanbietern dieser WebSpeak-Instanz können für ihre Funktionen auf angezeigte Kanalinformationen zugreifen, etwa Mitgliedsnamen, Kanaldetails und Chatnachrichten. Verbindungszugangsdaten sind ausgeschlossen. Jede Instanz wird von ihrem eigenen Dienstanbieter betrieben.', choice: 'Ich erlaube den Designs und Plugins dieser Instanz die Nutzung dieser Informationen.', alternative: 'Ohne Zustimmung bleiben die drei offiziellen Designs Tag, Nacht und ILLUSIA verfügbar. Andere Designs (einschließlich KAAK) und Plugins werden ausgeblendet. Die Auswahl lässt sich jederzeit im Designmenü ändern.', accept: 'Zustimmen und fortfahren', decline: 'Nur offizielle Designs', save: 'Speichern', enabled: 'An', disabled: 'Aus' },
ru: { menu: 'Разрешение', title: 'Темы и плагины', description: 'Сторонние темы и плагины этого экземпляра WebSpeak могут использовать сведения, отображаемые в каналах: имена участников, данные каналов и сообщения чата. Учётные данные подключения исключены. Каждый экземпляр обслуживает собственный поставщик услуг.', choice: 'Я разрешаю сторонним темам и плагинам этого экземпляра использовать эти сведения.', alternative: 'Без согласия доступны три официальные темы: дневная, ночная и ILLUSIA. Другие темы (включая KAAK) и плагины будут скрыты. Выбор можно изменить в меню тем.', accept: 'Разрешить и продолжить', decline: 'Только официальные темы', save: 'Сохранить', enabled: 'Включено', disabled: 'Выключено' },
ja: { menu: '許可', title: 'スキンとプラグイン', description: 'この WebSpeak インスタンスが提供するサードパーティ製スキンとプラグインは、機能の提供のためにメンバー名、チャンネル情報、チャットなどの表示情報を利用する場合があります。接続用の認証情報は含まれません。各インスタンスはそれぞれのサービス提供者が管理しています。', choice: 'このインスタンスのスキンとプラグインによる上記情報の利用に同意します。', alternative: '同意しない場合も、公式の昼・夜・ILLUSIA の3つのスキンを使用できます。その他のスキン(KAAK を含む)とプラグインは非表示になります。スキンメニューからいつでも変更できます。', accept: '同意して続ける', decline: '公式スキンのみ使用', save: '保存', enabled: '有効', disabled: '無効' },
};
+5 -5
View File
@@ -1,10 +1,10 @@
import type { SiteLanguage } from '../../../src/site-copy.js';
const en={available:'Available plugins',discover:'Discover',search:'Search plugins or authors',active:'Enabled',inactive:'Disabled',configure:'Configure plugin',advanced:'Advanced configuration',add:'Install plugin',update:'Update',reinstall:'Reinstall',empty:'No matching plugins',read:'Read shared room',write:'Update shared room',review:'Review permissions before enabling',installedNotice:'Installed. Review settings and enable the plugin.',source:'Distributed through GitHub',scopeHelp:'About plugin scopes'};
const en={available:'Available plugins',discover:'Discover',search:'Search plugins or authors',active:'Enabled',inactive:'Disabled',configure:'Configure plugin',advanced:'Advanced configuration',add:'Install plugin',update:'Update',reinstall:'Reinstall',empty:'No matching plugins',review:'Review the source and dependencies before enabling',installedNotice:'Installed. Review settings and enable the plugin.',source:'Distributed through GitHub',scopeHelp:'About plugin scopes'};
export type PluginStoreTextKey=keyof typeof en;
export const pluginStoreTranslations:Record<SiteLanguage,Record<PluginStoreTextKey,string>>={
en,
zh:{available:'可用插件',discover:'发现插件',search:'搜索插件名称或作者',active:'已启用',inactive:'未启用',configure:'配置插件',advanced:'高级配置',add:'安装插件',update:'更新插件',reinstall:'重新安装',empty:'没有找到匹配的插件',read:'读取共享房间',write:'更新共享房间',review:'启用前请检查插件权限',installedNotice:'安装成功,请检查设置后启用插件。',source:'通过 GitHub 分发',scopeHelp:'了解插件作用域'},
de:{available:'Verfügbare Plugins',discover:'Entdecken',search:'Plugins oder Autoren suchen',active:'Aktiviert',inactive:'Deaktiviert',configure:'Plugin konfigurieren',advanced:'Erweiterte Konfiguration',add:'Plugin installieren',update:'Aktualisieren',reinstall:'Neu installieren',empty:'Keine passenden Plugins',read:'Gemeinsamen Raum lesen',write:'Gemeinsamen Raum ändern',review:'Berechtigungen vor dem Aktivieren prüfen',installedNotice:'Installiert. Einstellungen prüfen und Plugin aktivieren.',source:'Verteilung über GitHub',scopeHelp:'Geltungsbereiche verstehen'},
ru:{available:'Доступные плагины',discover:'Обзор',search:'Поиск плагинов или авторов',active:'Включён',inactive:'Выключен',configure:'Настроить плагин',advanced:'Дополнительные настройки',add:'Установить плагин',update:'Обновить',reinstall:'Переустановить',empty:'Подходящих плагинов нет',read:'Чтение общей комнаты',write:'Изменение общей комнаты',review:'Проверьте разрешения перед включением',installedNotice:'Установлено. Проверьте настройки и включите плагин.',source:'Распространение через GitHub',scopeHelp:'Области действия плагинов'},
ja:{available:'利用可能',discover:'見つける',search:'プラグイン名・作者を検索',active:'有効',inactive:'無効',configure:'プラグイン設定',advanced:'詳細設定',add:'インストール',update:'更新',reinstall:'再インストール',empty:'一致するプラグインがありません',read:'共有ルームの読み取り',write:'共有ルームの更新',review:'有効化する前に権限を確認してください',installedNotice:'インストールしました。設定を確認して有効にしてください。',source:'GitHub で配布',scopeHelp:'スコープについて'},
zh:{available:'可用插件',discover:'发现插件',search:'搜索插件名称或作者',active:'已启用',inactive:'未启用',configure:'配置插件',advanced:'高级配置',add:'安装插件',update:'更新插件',reinstall:'重新安装',empty:'没有找到匹配的插件',review:'启用前请审核源码和依赖',installedNotice:'安装成功,请检查设置后启用插件。',source:'通过 GitHub 分发',scopeHelp:'了解插件作用域'},
de:{available:'Verfügbare Plugins',discover:'Entdecken',search:'Plugins oder Autoren suchen',active:'Aktiviert',inactive:'Deaktiviert',configure:'Plugin konfigurieren',advanced:'Erweiterte Konfiguration',add:'Plugin installieren',update:'Aktualisieren',reinstall:'Neu installieren',empty:'Keine passenden Plugins',review:'Quellcode und Abhängigkeiten vor der Aktivierung prüfen',installedNotice:'Installiert. Einstellungen prüfen und Plugin aktivieren.',source:'Verteilung über GitHub',scopeHelp:'Geltungsbereiche verstehen'},
ru:{available:'Доступные плагины',discover:'Обзор',search:'Поиск плагинов или авторов',active:'Включён',inactive:'Выключен',configure:'Настроить плагин',advanced:'Дополнительные настройки',add:'Установить плагин',update:'Обновить',reinstall:'Переустановить',empty:'Подходящих плагинов нет',review:'Проверьте код и зависимости перед включением',installedNotice:'Установлено. Проверьте настройки и включите плагин.',source:'Распространение через GitHub',scopeHelp:'Области действия плагинов'},
ja:{available:'利用可能',discover:'見つける',search:'プラグイン名・作者を検索',active:'有効',inactive:'無効',configure:'プラグイン設定',advanced:'詳細設定',add:'インストール',update:'更新',reinstall:'再インストール',empty:'一致するプラグインがありません',review:'有効化する前にコードと依存関係を確認してください',installedNotice:'インストールしました。設定を確認して有効にしてください。',source:'GitHub で配布',scopeHelp:'スコープについて'},
};
+10
View File
@@ -0,0 +1,10 @@
import type { SiteLanguage } from '../../../src/site-copy.js';
const en = { minimize: 'Minimize', maximize: 'Maximize', restore: 'Restore', search: 'Find a plugin…', resume: 'Return to app', workspace: 'Application library', count: 'available', move: 'Drag to move', noResults: 'No matching plugins' };
export const pluginWindowTranslations: Record<SiteLanguage, typeof en> = {
en,
zh: { minimize: '最小化', maximize: '最大化', restore: '还原', search: '搜索插件…', resume: '返回应用', workspace: '应用库', count: '个可用', move: '拖动窗口', noResults: '没有匹配的插件' },
de: { minimize: 'Minimieren', maximize: 'Maximieren', restore: 'Wiederherstellen', search: 'Plugin suchen…', resume: 'Zur Anwendung', workspace: 'Anwendungen', count: 'verfügbar', move: 'Zum Verschieben ziehen', noResults: 'Keine passenden Plugins' },
ru: { minimize: 'Свернуть', maximize: 'Развернуть', restore: 'Восстановить', search: 'Найти плагин…', resume: 'Вернуться к приложению', workspace: 'Библиотека приложений', count: 'доступно', move: 'Перетащите окно', noResults: 'Плагины не найдены' },
ja: { minimize: '最小化', maximize: '最大化', restore: '元に戻す', search: 'プラグインを検索…', resume: 'アプリに戻る', workspace: 'アプリライブラリ', count: '件利用可能', move: 'ドラッグして移動', noResults: '一致するプラグインはありません' },
};
+239 -11
View File
@@ -1,17 +1,245 @@
import type { SiteLanguage } from "../../../src/site-copy.js";
const en = {
title: "Plugins", store: "Plugin store", installed: "Installed plugins", refresh: "Refresh", install: "Install / update", upload: "Import .wplugin", remove: "Remove", save: "Save settings",
server: "Server plugin", instance: "WebSpeak instance plugin", targets: "TS server targets (one host:port per line)", config: "Public configuration (JSON; never enter secrets)", enabled: "Enable plugin",
lead: "Install from GitHub, review permissions, then enable. Updates are disabled until reviewed again.", empty: "No plugins available", open: "Open", close: "Close", back: "Back to plugins", permission: "Permissions", scope: "Scope", source: "Distribution repository",
loading: "Loading…", error: "Plugin operation failed", removed: "Remove this plugin? Its active rooms will close.", context: "The connection, channel or plugin changed. Open the plugin again.",
note: "Server plugins share a room within each channel of the configured TS server. Instance plugins share a room across all connected users on this WebSpeak gateway.",
enableNote: "Opening a plugin runs third-party browser code in an isolated panel. Public configuration and room state are visible to participants.",
"panelNote":"Applications reviewed and enabled by this instance’s administrator. Browser permission prompts still apply.",
"catalogError":"The application catalog is unavailable or requires API v2. Local import remains available.",
"title": "Plugins",
"store": "Plugin store",
"installed": "Installed plugins",
"refresh": "Refresh",
"install": "Install / update",
"upload": "Import .wplugin",
"remove": "Remove",
"save": "Save settings",
"server": "TS server scope",
"instance": "WebSpeak instance scope",
"targets": "Allowed TS targets (one host:port per line)",
"config": "Public configuration (JSON; visible to users)",
"enabled": "Enable plugin",
"lead": "Reviewed applications with standard browser capabilities and optional Node services. Updates require renewed trust.",
"empty": "No plugins available",
"open": "Open",
"close": "Close",
"back": "Back to plugins",
"scope": "Scope",
"source": "Distribution repository",
"loading": "Loading…",
"error": "Plugin operation failed",
"removed": "Remove this application? Open sessions will close; its backend data is retained.",
"context": "The connection or application changed. Open it again.",
"note": "Scope controls admission and supplies a context key. Authors implement their own collaboration and routes. Server scope follows the actual TS target and channel; instance scope spans this gateway.",
"enableNote": "These are trusted applications on a separate origin. Node backends run with the WebSpeak service account’s OS privileges. Review the source and dependencies before enabling.",
"runtime": "Application runtime",
"origin": "Public runtime origin",
"originHelp": "Use a separate HTTPS origin, such as https://apps.example.com, proxying to the runtime port. Blank enables local automatic addressing only.",
"trust": "I have reviewed and trust this application and its dependencies",
"privateConfig": "Private backend configuration (JSON; encrypted at rest)",
"keep": "Keep existing secret configuration",
"replace": "Replace secret configuration",
"erase": "Remove secret configuration",
"secretSaved": "Private configuration is stored",
"secretEmpty": "No private configuration stored",
"restart": "Restart backend",
"client": "Browser application",
"backend": "Node backend",
"disabled": "Disabled",
"stopped": "Stopped",
"starting": "Starting",
"running": "Running",
"failed": "Failed"
};
export type PluginTextKey = keyof typeof en;
export const pluginTranslations: Record<SiteLanguage, Record<PluginTextKey,string>> = {
en,
zh: { title:"插件功能",store:"插件商店",installed:"已安装插件",refresh:"刷新",install:"安装 / 更新",upload:"导入 .wplugin",remove:"移除",save:"保存设置",server:"服务器插件",instance:"WebSpeak 实例插件",targets:"TS 服务器地址(每行一个 host:port)",config:"公开配置(JSON;请勿填入任何密钥)",enabled:"启用插件",lead:"从 GitHub 安装,审查权限后启用。更新后须重新审查并启用。",empty:"暂无可用插件",open:"打开",close:"关闭",back:"返回插件列表",permission:"权限",scope:"作用域",source:"分发仓库",loading:"加载中…",error:"插件操作失败",removed:"移除此插件?正在使用的插件房间将关闭。",context:"连接、频道或插件发生变化,请重新打开插件。",note:"服务器插件在指定 TS 服务器的每个频道内共享房间;实例插件在当前 WebSpeak 网关的所有已连接用户间共享房间。",enableNote:"打开插件会在隔离面板中执行第三方浏览器代码。公开配置和房间状态对参与者可见。" },
de: {title:"Plugins",store:"Plugin-Store",installed:"Installierte Plugins",refresh:"Aktualisieren",install:"Installieren / aktualisieren",upload:".wplugin importieren",remove:"Entfernen",save:"Einstellungen speichern",server:"Server-Plugin",instance:"WebSpeak-Instanz-Plugin",targets:"TS-Server (host:port, eine Adresse pro Zeile)",config:"Öffentliche Konfiguration (JSON; keine Geheimnisse)",enabled:"Plugin aktivieren",lead:"Von GitHub installieren, Berechtigungen prüfen und aktivieren. Updates erfordern erneute Aktivierung.",empty:"Keine Plugins verfügbar",open:"Öffnen",close:"Schließen",back:"Zur Plugin-Liste",permission:"Berechtigungen",scope:"Geltungsbereich",source:"Verteilungsrepository",loading:"Wird geladen…",error:"Plugin-Vorgang fehlgeschlagen",removed:"Plugin entfernen? Aktive Räume werden geschlossen.",context:"Verbindung, Kanal oder Plugin geändert. Plugin erneut öffnen.",note:"Server-Plugins teilen Räume pro Kanal des konfigurierten TS-Servers. Instanz-Plugins teilen einen Raum mit allen verbundenen Nutzern dieses Gateways.",enableNote:"Plugins führen fremden Browsercode in einem isolierten Bereich aus. Öffentliche Konfiguration und Raumzustand sind für Teilnehmer sichtbar."},
ru: {title:"Плагины",store:"Магазин плагинов",installed:"Установленные плагины",refresh:"Обновить",install:"Установить / обновить",upload:"Импорт .wplugin",remove:"Удалить",save:"Сохранить настройки",server:"Плагин сервера",instance:"Плагин экземпляра WebSpeak",targets:"Адреса TS (host:port, по одному в строке)",config:"Публичные настройки (JSON; без секретов)",enabled:"Включить плагин",lead:"Установите из GitHub, проверьте разрешения и включите. После обновления требуется повторное включение.",empty:"Нет доступных плагинов",open:"Открыть",close:"Закрыть",back:"К списку плагинов",permission:"Разрешения",scope:"Область действия",source:"Репозиторий распространения",loading:"Загрузка…",error:"Ошибка операции плагина",removed:"Удалить плагин? Активные комнаты закроются.",context:"Соединение, канал или плагин изменились. Откройте плагин снова.",note:"Плагины сервера создают общую комнату в каждом канале указанного TS-сервера. Плагины экземпляра объединяют всех подключённых пользователей шлюза.",enableNote:"Плагин выполняет сторонний код в изолированной панели. Публичные настройки и состояние комнаты видны участникам."},
ja: {title:"プラグイン",store:"プラグインストア",installed:"インストール済み",refresh:"更新",install:"インストール / 更新",upload:".wplugin を読み込む",remove:"削除",save:"設定を保存",server:"サーバープラグイン",instance:"WebSpeak インスタンスプラグイン",targets:"TS サーバー(1行に host:port を1つ)",config:"公開設定(JSON、秘密情報を入力しないでください)",enabled:"有効にする",lead:"GitHub からインストールし、権限を確認して有効にします。更新後は再度有効化してください。",empty:"利用できるプラグインがありません",open:"開く",close:"閉じる",back:"一覧に戻る",permission:"権限",scope:"スコープ",source:"配布リポジトリ",loading:"読み込み中…",error:"プラグイン操作に失敗しました",removed:"削除しますか?使用中のルームは閉じられます。",context:"接続、チャンネルまたはプラグインが変更されました。開き直してください。",note:"サーバープラグインは指定 TS サーバーのチャンネルごとに共有します。インスタンスプラグインは同じゲートウェイの接続ユーザー全員で共有します。",enableNote:"隔離パネルでサードパーティーコードを実行します。公開設定とルーム状態は参加者に見えます。"},
en,
zh:{
"panelNote":"这里只显示实例管理员已审核并启用的应用,使用时仍需遵守浏览器的权限提示。",
"catalogError":"应用目录暂不可用或需要升级为 API v2,仍可导入本地应用包。",
"title": "插件功能",
"store": "插件商店",
"installed": "已安装插件",
"refresh": "刷新",
"install": "安装 / 更新",
"upload": "导入 .wplugin",
"remove": "移除",
"save": "保存设置",
"server": "TS 服务器范围",
"instance": "WebSpeak 实例范围",
"targets": "允许的 TS 地址(每行一个 host:port)",
"config": "公开配置(JSON;用户可见)",
"enabled": "启用插件",
"lead": "经审核的应用,可使用标准浏览器能力和可选的 Node 服务。更新后需要重新信任。",
"empty": "暂无可用插件",
"open": "打开",
"close": "关闭",
"back": "返回插件列表",
"scope": "作用域",
"source": "分发仓库",
"loading": "加载中…",
"error": "插件操作失败",
"removed": "移除此应用?已打开的会话将关闭,后端数据会保留。",
"context": "连接或应用已变化,请重新打开。",
"note": "作用域负责准入并提供上下文标识,协作逻辑和路由由作者编写。服务器范围跟随实际 TS 目标和频道;实例范围覆盖当前网关。",
"enableNote": "插件是运行于独立源的受信任应用。Node 后端拥有 WebSpeak 服务账户的操作系统权限。启用前请审核源码和依赖。",
"runtime": "应用运行时",
"origin": "运行时公开源地址",
"originHelp": "配置独立的 HTTPS 源,如 https://apps.example.com,并反向代理到运行时端口。留空仅支持本地自动地址。",
"trust": "我已审核并信任此应用及其依赖",
"privateConfig": "后端私密配置(JSON;加密存储)",
"keep": "保留现有私密配置",
"replace": "替换私密配置",
"erase": "删除私密配置",
"secretSaved": "已保存私密配置",
"secretEmpty": "尚无私密配置",
"restart": "重启后端",
"client": "浏览器应用",
"backend": "Node 后端",
"disabled": "未启用",
"stopped": "已停止",
"starting": "启动中",
"running": "运行中",
"failed": "失败"
},
de:{
"panelNote":"Von der Instanzadministration geprüfte und aktivierte Anwendungen. Browser-Berechtigungsabfragen gelten weiterhin.",
"catalogError":"Der Katalog ist nicht verfügbar oder benötigt API v2. Lokaler Import bleibt möglich.",
"title": "Plugins",
"store": "Plugin-Store",
"installed": "Installierte Plugins",
"refresh": "Aktualisieren",
"install": "Installieren / aktualisieren",
"upload": ".wplugin importieren",
"remove": "Entfernen",
"save": "Einstellungen speichern",
"server": "TS-Server-Bereich",
"instance": "WebSpeak-Instanz-Bereich",
"targets": "Erlaubte TS-Ziele (host:port pro Zeile)",
"config": "Öffentliche Konfiguration (JSON; für Nutzer sichtbar)",
"enabled": "Plugin aktivieren",
"lead": "Geprüfte Anwendungen mit Browserfunktionen und optionalen Node-Diensten. Updates erfordern erneutes Vertrauen.",
"empty": "Keine Plugins verfügbar",
"open": "Öffnen",
"close": "Schließen",
"back": "Zur Plugin-Liste",
"scope": "Bereich",
"source": "Verteilungsrepository",
"loading": "Wird geladen…",
"error": "Plugin-Vorgang fehlgeschlagen",
"removed": "Anwendung entfernen? Sitzungen werden geschlossen; Backend-Daten bleiben erhalten.",
"context": "Verbindung oder Anwendung geändert. Erneut öffnen.",
"note": "Der Bereich steuert den Zugang und liefert einen Kontextschlüssel. Zusammenarbeit und Routen implementiert der Autor. Server-Bereiche folgen TS-Ziel und Kanal; Instanz-Bereiche gelten für dieses Gateway.",
"enableNote": "Vertrauenswürdige Anwendungen auf einer separaten Origin. Node-Backends haben die Betriebssystemrechte des WebSpeak-Dienstkontos. Quellcode und Abhängigkeiten vor der Aktivierung prüfen.",
"runtime": "Anwendungslaufzeit",
"origin": "Öffentliche Runtime-Origin",
"originHelp": "Separate HTTPS-Origin, z. B. https://apps.example.com, auf den Runtime-Port weiterleiten. Leer nur für lokale automatische Adressen.",
"trust": "Ich habe diese Anwendung und ihre Abhängigkeiten geprüft und vertraue ihnen",
"privateConfig": "Private Backend-Konfiguration (JSON; verschlüsselt gespeichert)",
"keep": "Vorhandene private Konfiguration behalten",
"replace": "Private Konfiguration ersetzen",
"erase": "Private Konfiguration löschen",
"secretSaved": "Private Konfiguration gespeichert",
"secretEmpty": "Keine private Konfiguration gespeichert",
"restart": "Backend neu starten",
"client": "Browseranwendung",
"backend": "Node-Backend",
"disabled": "Deaktiviert",
"stopped": "Gestoppt",
"starting": "Startet",
"running": "Läuft",
"failed": "Fehlgeschlagen"
},
ru:{
"panelNote":"Приложения проверены и включены администратором экземпляра. Разрешения браузера по-прежнему применяются.",
"catalogError":"Каталог недоступен или требует API v2. Локальный импорт по-прежнему доступен.",
"title": "Плагины",
"store": "Магазин плагинов",
"installed": "Установленные плагины",
"refresh": "Обновить",
"install": "Установить / обновить",
"upload": "Импорт .wplugin",
"remove": "Удалить",
"save": "Сохранить настройки",
"server": "Область TS-сервера",
"instance": "Область экземпляра WebSpeak",
"targets": "Разрешённые адреса TS (host:port, по одному в строке)",
"config": "Публичные настройки (JSON; видны пользователям)",
"enabled": "Включить плагин",
"lead": "Проверенные приложения с возможностями браузера и необязательными сервисами Node. Обновления требуют повторного доверия.",
"empty": "Нет доступных плагинов",
"open": "Открыть",
"close": "Закрыть",
"back": "К списку плагинов",
"scope": "Область действия",
"source": "Репозиторий распространения",
"loading": "Загрузка…",
"error": "Ошибка операции плагина",
"removed": "Удалить приложение? Сеансы закроются; данные сервиса сохранятся.",
"context": "Соединение или приложение изменились. Откройте снова.",
"note": "Область определяет доступ и ключ контекста. Автор реализует совместную работу и маршруты. Область сервера следует фактическому адресу TS и каналу, экземпляра — всему шлюзу.",
"enableNote": "Это доверенные приложения на отдельном источнике. Сервисы Node обладают правами учётной записи WebSpeak в ОС. До включения проверьте код и зависимости.",
"runtime": "Среда приложений",
"origin": "Публичный источник среды",
"originHelp": "Отдельный HTTPS-источник, например https://apps.example.com, с проксированием на порт среды. Пустое поле — только для локальных адресов.",
"trust": "Я проверил приложение и зависимости и доверяю им",
"privateConfig": "Приватные настройки сервиса (JSON; хранятся зашифрованными)",
"keep": "Сохранить текущие приватные настройки",
"replace": "Заменить приватные настройки",
"erase": "Удалить приватные настройки",
"secretSaved": "Приватные настройки сохранены",
"secretEmpty": "Приватных настроек нет",
"restart": "Перезапустить сервис",
"client": "Браузерное приложение",
"backend": "Сервис Node",
"disabled": "Выключен",
"stopped": "Остановлен",
"starting": "Запускается",
"running": "Работает",
"failed": "Ошибка"
},
ja:{
"panelNote":"インスタンス管理者が審査して有効にしたアプリです。ブラウザーの権限確認は引き続き必要です。",
"catalogError":"カタログが利用できないか API v2 が必要です。ローカル読み込みは利用できます。",
"title": "プラグイン",
"store": "プラグインストア",
"installed": "インストール済み",
"refresh": "更新",
"install": "インストール / 更新",
"upload": ".wplugin を読み込む",
"remove": "削除",
"save": "設定を保存",
"server": "TS サーバー範囲",
"instance": "WebSpeak インスタンス範囲",
"targets": "許可する TS アドレス(1行に host:port)",
"config": "公開設定(JSON、ユーザーに公開)",
"enabled": "有効にする",
"lead": "標準ブラウザー機能と任意の Node サービスを使う審査済みアプリです。更新後は再度信頼を確認します。",
"empty": "利用できるプラグインがありません",
"open": "開く",
"close": "閉じる",
"back": "一覧に戻る",
"scope": "範囲",
"source": "配布リポジトリ",
"loading": "読み込み中…",
"error": "プラグイン操作に失敗しました",
"removed": "削除しますか?セッションは閉じますが、バックエンドのデータは保持します。",
"context": "接続またはアプリが変わりました。開き直してください。",
"note": "範囲はアクセスとコンテキストキーを提供します。共同作業やルートは作者が実装します。サーバー範囲は実際の TS 接続先とチャンネル、インスタンス範囲は現在のゲートウェイに適用します。",
"enableNote": "別オリジンで動く信頼済みアプリです。Node バックエンドは WebSpeak サービスアカウントの OS 権限で動作します。有効化前にコードと依存関係を確認してください。",
"runtime": "アプリ実行環境",
"origin": "公開ランタイムオリジン",
"originHelp": "https://apps.example.com のような別 HTTPS オリジンを実行ポートへ転送します。空欄はローカル自動アドレス専用です。",
"trust": "アプリと依存関係を審査し、信頼します",
"privateConfig": "バックエンドの秘密設定(JSON、暗号化して保存)",
"keep": "現在の秘密設定を保持",
"replace": "秘密設定を置換",
"erase": "秘密設定を削除",
"secretSaved": "秘密設定を保存済み",
"secretEmpty": "秘密設定なし",
"restart": "バックエンドを再起動",
"client": "ブラウザーアプリ",
"backend": "Node バックエンド",
"disabled": "無効",
"stopped": "停止",
"starting": "起動中",
"running": "動作中",
"failed": "失敗"
}
};
+5 -2
View File
@@ -1,7 +1,7 @@
import { adminResponses, type AdminResponseReader } from "../../../src/shared/admin-responses.js";
import type { AdminSettingsInput, ManagedInviteInput, TsAdminSettingsInput, TsAdminActionRequest } from "../../../src/shared/admin-inputs.js";
import type { SkinStoreInstallInput } from "../../../src/shared/skin-store.js";
import { pluginResponses, type PluginPackage, type PluginSettings } from "../../../src/shared/plugins.js";
import { pluginResponses, type PluginPackage, type PluginSettingsInput } from "../../../src/shared/plugins.js";
export class AdminApiError extends Error {
constructor(readonly code: string, readonly status = 0, message = code) {
@@ -103,9 +103,12 @@ export function createAdminApi(options: AdminApiOptions) {
invalidate() { generation++; for (const controller of pending) controller.abort(); },
plugins: (signal?: AbortSignal) => request("/plugins", pluginResponses.installed, "GET", undefined, true, signal),
pluginStore: (signal?: AbortSignal) => request("/plugins/store", pluginResponses.catalog, "GET", undefined, true, signal),
pluginRuntime: (signal?: AbortSignal) => request("/plugins/runtime", pluginResponses.runtime, "GET", undefined, true, signal),
configurePluginRuntime: (publicOrigin: string, revision: string, signal?: AbortSignal) => request("/plugins/runtime", pluginResponses.runtime, "PUT", { publicOrigin, revision }, true, signal),
restartPlugin: (id: string, revision: string, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}/restart`, pluginResponses.saved, "POST", { revision }, true, signal),
installPlugin: (body: { id: string; revision: string; installedRevision: string | null }, signal?: AbortSignal) => request("/plugins/store/install", pluginResponses.saved, "POST", body, true, signal),
uploadPlugin: (pack: PluginPackage, installedRevision: string | null, signal?: AbortSignal) => request("/plugins/upload", pluginResponses.saved, "POST", { package: pack, installedRevision }, true, signal),
configurePlugin: (id: string, revision: string, settings: PluginSettings, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}/settings`, pluginResponses.saved, "PUT", { revision, settings }, true, signal),
configurePlugin: (id: string, revision: string, settings: PluginSettingsInput, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}/settings`, pluginResponses.saved, "PUT", { revision, settings }, true, signal),
removePlugin: (id: string, revision: string, signal?: AbortSignal) => request(`/plugins/${encodeURIComponent(id)}`, adminResponses.ok, "DELETE", { revision }, true, signal),
session: (signal?: AbortSignal) => request("/session", adminResponses.session, "GET", undefined, true, signal),
login: (username: string, password: string, signal?: AbortSignal) => request("/login", adminResponses.login, "POST", { username, password }, false, signal),
+4
View File
@@ -0,0 +1,4 @@
import appPackage from "../../../package.json";
// Available before the public config request completes, including on the demo page.
export const APP_VERSION = appPackage.version;
@@ -0,0 +1,39 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createInstanceAuthorization, INSTANCE_AUTHORIZATION_KEY, canUseSkin, setInstanceAuthorization } from './instance-authorization.js';
function storage() {
const values = new Map<string, string>();
return { values, getItem: (key: string) => values.get(key) ?? null, setItem: (key: string, value: string) => { values.set(key, value); } };
}
test('new instances require an explicit decision; legacy package approvals do not imply consent', () => {
const data = storage(); data.values.set('webspeak:skin-plugin-approvals', '{"grants":{"old":true}}');
const state = createInstanceAuthorization(data);
assert.equal(state.decision.value, null); assert.equal(state.allowed.value, false);
state.set(false); assert.equal(createInstanceAuthorization(data).decision.value, false);
state.set(true); assert.equal(createInstanceAuthorization(data).allowed.value, true);
assert.deepEqual([...data.values.keys()].sort(), [INSTANCE_AUTHORIZATION_KEY, 'webspeak:skin-plugin-approvals'].sort());
});
test('separate instance storage stays independent; revocation and clearing propagate on reload', () => {
const first = storage(), second = storage(), tab = createInstanceAuthorization(first), otherTab = createInstanceAuthorization(first);
tab.set(true); otherTab.reload(); assert.equal(otherTab.allowed.value, true);
assert.equal(createInstanceAuthorization(second).decision.value, null);
tab.set(false); otherTab.reload(); assert.equal(otherTab.allowed.value, false);
first.values.clear(); otherTab.reload(); assert.equal(otherTab.decision.value, null);
});
test('malformed or inaccessible storage never grants access; explicit choices survive in memory', () => {
const data = storage();
for (const value of ['true', '{}', '{"schemaVersion":1,"allowed":"true"}', '{"schemaVersion":2,"allowed":true}', 'broken']) {
data.setItem(INSTANCE_AUTHORIZATION_KEY, value); assert.equal(createInstanceAuthorization(data).allowed.value, false);
}
const unavailable = createInstanceAuthorization({ getItem() { throw Error(); }, setItem() { throw Error(); } });
assert.equal(unavailable.allowed.value, false); unavailable.set(true); assert.equal(unavailable.allowed.value, true);
unavailable.set(false); assert.equal(unavailable.allowed.value, false);
});
test('only the three official IDs bypass consent, including when KAAK is shipped as built-in', () => {
setInstanceAuthorization(false);
for (const id of ['builtin.light', 'builtin.dark', 'community.illusia-voice']) assert.equal(canUseSkin(id), true);
for (const id of ['community.kaak-voice', 'community.discord-voice', 'builtin.other']) assert.equal(canUseSkin(id), false);
setInstanceAuthorization(true); assert.equal(canUseSkin('community.kaak-voice'), true);
setInstanceAuthorization(false);
});
@@ -0,0 +1,42 @@
import { computed, readonly, ref } from 'vue';
import type { SiteLanguage } from '../../../src/site-copy.js';
export const INSTANCE_AUTHORIZATION_KEY = 'webspeak:instance-authorization:v1';
export const OFFICIAL_SKIN_IDS = new Set(['builtin.light', 'builtin.dark', 'community.illusia-voice']);
type AuthorizationStorage = Pick<Storage, 'getItem' | 'setItem'>;
/** A decision belongs to this browser origin, never to a skin package or a TS account. */
export function createInstanceAuthorization(storage: AuthorizationStorage) {
function read(): boolean | null {
try {
const value = JSON.parse(storage.getItem(INSTANCE_AUTHORIZATION_KEY) ?? 'null');
return value?.schemaVersion === 1 && typeof value.allowed === 'boolean' ? value.allowed : null;
} catch { return null; }
}
const decision = ref<boolean | null>(read());
return {
decision: readonly(decision),
allowed: computed(() => decision.value === true),
set(allowed: boolean) {
// Notify consumers synchronously so revocation also retires in-flight loads.
decision.value = allowed;
try { storage.setItem(INSTANCE_AUTHORIZATION_KEY, JSON.stringify({ schemaVersion: 1, allowed })); } catch { /* Keep this page's explicit decision when storage is unavailable. */ }
},
reload() { decision.value = read(); },
};
}
const store = createInstanceAuthorization({
getItem: key => typeof window === 'undefined' ? null : window.localStorage.getItem(key),
setItem: (key, value) => { if (typeof window !== 'undefined') window.localStorage.setItem(key, value); },
});
export const authorizationDecision = store.decision;
export const thirdPartyAllowed = store.allowed;
export const authorizationRequested = ref(false);
export const authorizationLanguage = ref<SiteLanguage>('zh');
export const setInstanceAuthorization = store.set;
export const canUseSkin = (id: string) => OFFICIAL_SKIN_IDS.has(id) || thirdPartyAllowed.value;
export function openInstanceAuthorization() { authorizationRequested.value = true; }
if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') window.addEventListener('storage', event => {
if (event.key === INSTANCE_AUTHORIZATION_KEY || event.key === null) store.reload();
});
@@ -0,0 +1,29 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createPluginAppClient } from './plugin-app-client.js';
const token='a'.repeat(43),id='b'.repeat(43);
const manifest={apiVersion:2,id:'test.app',name:'Test',version:'1.0.0',author:'Test',license:'MIT',description:'App',scopes:['instance'],client:{entry:'client/index.html'}};
test('plugin control uses the connected gateway origin and never sends its voice query or cookies',async()=>{
const seen:Array<{url:string;init:RequestInit|undefined}>=[];
const client=createPluginAppClient('wss://relay.example/voice?credential=private',token,async(url,init)=>{seen.push({url:String(url),init});return Response.json({plugins:[{manifest,scope:'instance',runtime:{state:'client'}}]});});
assert.equal((await client.list())[0].manifest.id,'test.app');assert.equal(seen[0].url,'https://relay.example/api/plugins');assert.equal(seen[0].init?.credentials,'omit');assert.equal(new Headers(seen[0].init?.headers).get('authorization'),'Bearer '+token);
assert.throws(()=>createPluginAppClient('https://x','invalid'));assert.throws(()=>createPluginAppClient('https://user:secret@example.com',token));
});
test('launch validation rejects mismatched IDs, unsafe URLs and invalid runtime responses',async()=>{
for(const value of [{id,url:`https://apps.example/apps/${id}/client/index.html`,manifest:{...manifest,id:'another.app'}},{id,url:`https://user:secret@apps.example/apps/${id}/client/index.html`,manifest},{id,url:'javascript:alert(1)',manifest},{id,url:`https://apps.example/apps/${id}/client/index.html?ticket=x`,manifest}]){
const client=createPluginAppClient('http://localhost:3040',token,async()=>Response.json(value));await assert.rejects(client.open('test.app',{openId:'operation-123',theme:'light',language:'en'}));
}
const client=createPluginAppClient('http://localhost:3040',token,async()=>Response.json({plugins:[{manifest,scope:'anything',runtime:{state:'unknown'}}]}));await assert.rejects(client.list());
});
test('control requests time out through response body parsing and support caller cancellation',async()=>{
const slow:typeof fetch=async(_url,init)=>new Promise((_resolve,reject)=>init?.signal?.addEventListener('abort',()=>reject(new Error('aborted'))));
const client=createPluginAppClient('http://localhost:3040',token,slow,15);await assert.rejects(client.list(),/PLUGIN_TIMEOUT/);
const controller=new AbortController(),request=client.list(controller.signal);controller.abort();await assert.rejects(request,/PLUGIN_REQUEST_CANCELLED/);
const body:typeof fetch=async(_url,init)=>({ok:true,json:()=>new Promise((_resolve,reject)=>init?.signal?.addEventListener('abort',()=>reject(new Error('aborted'))))}) as Response;
await assert.rejects(createPluginAppClient('http://localhost:3040',token,body,15).list(),/PLUGIN_TIMEOUT/);
});
test('pending open cancellation remains a separate operation and status errors are bounded codes',async()=>{
const requests:string[]=[];const client=createPluginAppClient('http://localhost:3040',token,async(url,init)=>{requests.push(`${init?.method} ${url}`);return Response.json({ok:true});});
await client.cancelOpen('operation-123');assert.match(requests[0],/^DELETE .*\/opening\/operation-123$/);
await assert.rejects(createPluginAppClient('http://localhost:3040',token,async()=>Response.json({code:'<secret error body>'},{status:500})).list(),/PLUGIN_RUNTIME_FAILED/);
});
+40
View File
@@ -0,0 +1,40 @@
import { parsePluginManifest, pluginAssert, pluginRecord, type PluginManifest, type PluginAppLaunch, type PluginScope, type PluginRuntimeStatus } from '../../../src/shared/plugins.js';
export interface AvailablePluginApp { manifest: PluginManifest; scope: PluginScope; runtime: PluginRuntimeStatus }
export function createPluginAppClient(gatewayUrl:string,token:string,fetcher:typeof fetch=fetch,timeoutMs=15000){
pluginAssert(/^[A-Za-z0-9_-]{43}$/.test(token),'PLUGIN_NOT_CONNECTED');
const gateway=new URL(gatewayUrl);pluginAssert(['ws:','wss:','http:','https:'].includes(gateway.protocol)&&!gateway.username&&!gateway.password);
gateway.protocol=gateway.protocol==='wss:'||gateway.protocol==='https:'?'https:':'http:';
const base=gateway.origin+'/api/plugins';
async function request(route:string,method='GET',body?:unknown,signal?:AbortSignal):Promise<unknown>{
const controller=new AbortController();let timedOut=false;
const abort=()=>controller.abort();if(signal?.aborted)abort();else signal?.addEventListener('abort',abort,{once:true});
const timer=setTimeout(()=>{timedOut=true;controller.abort();},timeoutMs);
try{
const response=await fetcher(base+route,{method,headers:{authorization:'Bearer '+token,...(body===undefined?{}:{'content-type':'application/json'})},credentials:'omit',redirect:'error',signal:controller.signal,...(body===undefined?{}:{body:JSON.stringify(body)})});
const value:unknown=await response.json();
if(!response.ok)throw new Error(pluginRecord(value)&&typeof value.code==='string'&&/^[A-Z0-9_]{1,80}$/.test(value.code)?value.code:'PLUGIN_RUNTIME_FAILED');
return value;
}catch(error){if(timedOut)throw new Error('PLUGIN_TIMEOUT');if(signal?.aborted)throw new Error('PLUGIN_REQUEST_CANCELLED');throw error;}
finally{clearTimeout(timer);signal?.removeEventListener('abort',abort);}
}
return {
async list(signal?:AbortSignal):Promise<AvailablePluginApp[]>{
const value=await request('','GET',undefined,signal);pluginAssert(pluginRecord(value)&&Array.isArray(value.plugins)&&value.plugins.length<=50,'PLUGIN_INVALID_RESPONSE');
return value.plugins.map(entry=>{
pluginAssert(pluginRecord(entry)&&(entry.scope==='server'||entry.scope==='instance')&&pluginRecord(entry.runtime)&&['disabled','client','stopped','starting','running','failed'].includes(String(entry.runtime.state)),'PLUGIN_INVALID_RESPONSE');
return {manifest:parsePluginManifest(entry.manifest),scope:entry.scope,runtime:{state:entry.runtime.state as PluginRuntimeStatus['state'],...(typeof entry.runtime.error==='string'?{error:entry.runtime.error}:{})}};
});
},
async open(id:string,options:{openId:string;theme:'light'|'dark';language:string},signal?:AbortSignal):Promise<PluginAppLaunch>{
const value=await request('/'+encodeURIComponent(id)+'/open','POST',options,signal);
pluginAssert(pluginRecord(value)&&typeof value.id==='string'&&/^[A-Za-z0-9_-]{43}$/.test(value.id)&&typeof value.url==='string','PLUGIN_INVALID_RESPONSE');
const manifest=parsePluginManifest(value.manifest),url=new URL(value.url);
pluginAssert(manifest.id===id&&['http:','https:'].includes(url.protocol)&&!url.username&&!url.password&&url.pathname==='/apps/'+value.id+'/'+manifest.client.entry&&!url.hash&&!url.search,'PLUGIN_INVALID_RESPONSE');
return {id:value.id,url:url.href,manifest};
},
cancelOpen:(openId:string)=>request('/opening/'+encodeURIComponent(openId),'DELETE'),
appearance:(id:string,theme:'light'|'dark',language:string)=>request('/apps/'+encodeURIComponent(id),'PATCH',{theme,language}),
};
}
export type PluginAppClient=ReturnType<typeof createPluginAppClient>;
-32
View File
@@ -1,32 +0,0 @@
import { type PluginPackage } from "../../../src/shared/plugins.js";
/** The SDK never receives a voice socket, TS identity, cookie, or admin API. */
export function pluginFrameDocument(pack: PluginPackage, channel: string): string {
const escape = (source: string, tag: string) => source.replace(new RegExp(`</${tag}`, "gi"), `<\\/${tag}`);
const bootstrap = `(() => {
const channel = ${JSON.stringify(channel)};
const pending = new Map(), listeners = new Set(); let sequence = 0, context;
const send = value => parent.postMessage({channel,...value}, '*');
const ready = new Promise(resolve => window.addEventListener('message', function receive(event) {
if(event.source !== parent || event.data?.channel !== channel) return;
const m = event.data;
if(m.type === 'context') { context=m.context; document.documentElement.dataset.theme=context.theme;
document.getElementById('plugin-light').media=context.theme==='dark'?'not all':'all';
document.getElementById('plugin-dark').media=context.theme==='dark'?'all':'not all'; resolve(context); }
if(m.type === 'snapshot') for(const fn of listeners) { try {fn(m.snapshot);} catch {} }
if(m.type === 'reply') { const task=pending.get(m.id); if(task) {pending.delete(m.id); clearTimeout(task.timer); m.error?task.reject(new Error(m.error)):task.resolve(m.result);} }
}));
const request = (method,args) => new Promise((resolve,reject) => {
if(pending.size>=16) return reject(new Error('PLUGIN_RATE_LIMITED'));
const id=++sequence, timer=setTimeout(()=>{pending.delete(id);reject(new Error('PLUGIN_TIMEOUT'));},12000);
pending.set(id,{resolve,reject,timer}); send({type:'request',id,method,args});
});
window.webspeak = Object.freeze({apiVersion:1,ready,
room:Object.freeze({snapshot:()=>request('room.snapshot'),update:(revision,state)=>request('room.update',{revision,state}),
subscribe(fn){listeners.add(fn); return ()=>listeners.delete(fn);}})});
send({type:'ready'});
})();`;
// Opaque origin + no same-origin, popups, forms, navigation, fetch, or nested frames.
const csp = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src https: data:; media-src https: http: blob:; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'";
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="${csp}"><script>${escape(bootstrap,"script")}</script><style>html,body{margin:0;min-height:100%;font:15px system-ui}*{box-sizing:border-box}body{padding:20px}html[data-theme="dark"]{color-scheme:dark}</style><style id="plugin-light">${escape(pack.styles.light,"style")}</style><style id="plugin-dark" media="not all">${escape(pack.styles.dark,"style")}</style></head><body>${pack.html}<script>${escape(pack.script,"script")}</script></body></html>`;
}
-26
View File
@@ -1,26 +0,0 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createPluginTransport } from './plugin-transport.js';
test('plugin requests correlate replies, reset pending work and release subscribers independently',async () => {
const sent:any[]=[];const socket={readyState:1,send:(v:string)=>sent.push(JSON.parse(v))} as unknown as WebSocket;
const transport=createPluginTransport(()=>socket,()=>true);
const result=transport.request('list');assert.equal(sent[0].type,'pluginRequest');
transport.receive({type:'pluginReply',requestId:sent[0].requestId,ok:true,result:[{id:'a'}]});
assert.deepEqual(await result,[{id:'a'}]);
const events:any[]=[];const off=transport.subscribe(m=>events.push(m));
transport.receive({type:'pluginEvent',pluginId:'a',snapshot:null});assert.equal(events.length,1);
const pending=transport.request('open',{pluginId:'a'});transport.reset();await assert.rejects(pending,/PLUGIN_NOT_CONNECTED/);
transport.receive({type:'pluginReply',requestId:sent[1].requestId,ok:true,result:{old:true}});assert.equal(events.at(-1).type,'pluginReset');
off();transport.reset();assert.equal(events.length,2);
});
test('server errors, disconnected sockets and request quotas do not leak promises',async () => {
const sent:any[]=[];let connected=false;const socket={readyState:1,send:(v:string)=>sent.push(JSON.parse(v))} as unknown as WebSocket;
const transport=createPluginTransport(()=>socket,()=>connected);
await assert.rejects(transport.request('list'),/PLUGIN_NOT_CONNECTED/);connected=true;
const failed=transport.request('snapshot',{pluginId:'a'});
transport.receive({type:'pluginReply',requestId:sent[0].requestId,ok:false,code:'PLUGIN_NOT_OPEN'});await assert.rejects(failed,/PLUGIN_NOT_OPEN/);
const pending=Array.from({length:16},()=>transport.request('list').catch(e=>e.message));
await assert.rejects(transport.request('list'),/PLUGIN_RATE_LIMITED/);transport.reset();
assert.ok((await Promise.all(pending)).every(v=>v==='PLUGIN_NOT_CONNECTED'));
});
-39
View File
@@ -1,39 +0,0 @@
import { pluginRecord, type PluginRequest, type PluginMessage } from "../../../src/shared/plugins.js";
/** Owns requests and event subscribers for one voice connection. */
export function createPluginTransport(socket: () => WebSocket | null, connected: () => boolean) {
let sequence = 0;
const pending = new Map<string, { finish(value?: unknown, error?: Error): void }>();
const listeners = new Set<(message: PluginMessage | { type: "pluginReset" }) => void>();
function emit(message: PluginMessage | { type: "pluginReset" }): void { for (const listener of [...listeners]) { try { listener(message); } catch { /* isolate presentation */ } } }
return {
request(action: PluginRequest["action"], fields: { pluginId?: string; revision?: number; state?: unknown } = {}): Promise<unknown> {
const ws = socket();
if (!connected() || ws?.readyState !== 1) return Promise.reject(new Error("PLUGIN_NOT_CONNECTED"));
if (pending.size >= 16) return Promise.reject(new Error("PLUGIN_RATE_LIMITED"));
const requestId = `plugin-${Date.now().toString(36)}-${++sequence}`;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => finish(undefined, new Error("PLUGIN_TIMEOUT")), 15_000);
const finish = (value?: unknown, error?: Error) => { if (!pending.delete(requestId)) return; clearTimeout(timer); error ? reject(error) : resolve(value); };
pending.set(requestId, { finish });
try { ws.send(JSON.stringify({ type: "pluginRequest", requestId, action, ...fields })); }
catch { finish(undefined, new Error("PLUGIN_NOT_CONNECTED")); }
});
},
receive(value: unknown): boolean {
if (!pluginRecord(value)) return false;
if (value.type === "pluginReply") {
if (typeof value.requestId === "string" && typeof value.ok === "boolean") pending.get(value.requestId)?.finish(value.result,
value.ok ? undefined : new Error(typeof value.code === "string" ? value.code.slice(0, 80) : "PLUGIN_FAILED"));
return true;
}
if (value.type === "pluginEvent" && typeof value.pluginId === "string" && (value.snapshot === null || pluginRecord(value.snapshot))) {
emit(value as unknown as PluginMessage); return true;
}
return false;
},
subscribe(listener: (message: PluginMessage | { type: "pluginReset" }) => void): () => void { listeners.add(listener); return () => listeners.delete(listener); },
reset(): void { for (const item of [...pending.values()]) item.finish(undefined, new Error("PLUGIN_NOT_CONNECTED")); emit({ type: "pluginReset" }); },
};
}
export type PluginTransport = ReturnType<typeof createPluginTransport>;
+3 -1
View File
@@ -1,5 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import test, { beforeEach } from "node:test";
import { setInstanceAuthorization } from './instance-authorization.js';
import { createRenderer, createSSRApp, defineComponent, h, nextTick, ref } from "vue";
import { renderToString } from "@vue/server-renderer";
import { parseSkinPluginDocument, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
@@ -11,6 +12,7 @@ import {
SkinExtensionUiOutputError,
} from "../../../src/shared/skin-extension-ui.js";
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
beforeEach(() => setInstanceAuthorization(true));
function outputDocument(componentId = "runtime-ui", root?: Record<string, unknown>, permissions: string[] = [], actions: Record<string, unknown> = {}, state?: Record<string, unknown>): string {
return JSON.stringify({
+2 -1
View File
@@ -1,2 +1,3 @@
/** Temporary development policy. Re-enable consent before public skin distribution. */
/** Per-package dialogs are replaced by the explicit, revocable instance authorization.
* Hosts must check canUseSkin before issuing/using internal manifest-bound grants. */
export const PROMPT_FOR_SKIN_PERMISSIONS = false;
@@ -51,7 +51,7 @@ export function getSkinRuntimePluginApproval(
return grant && isSkinRuntimePluginApproved(grant, skinId, skinVersion, plugin, digest) ? grant : null;
}
/** Called only by the host consent UI after a user explicitly approves this exact package. */
/** Internal digest-bound record. The host must first allow this skin through instance authorization. */
export function approveSkinRuntimePlugin(
skinId: string,
skinVersion: string,
@@ -35,6 +35,19 @@ async function approvedFiles(source = createSkinExtensionWasmPrefixByteImmediate
return { files, digest, approval: createSkinRuntimePluginApproval("community.sample", "2.0.0", plugin, digest) };
}
test('revocation while package bytes are being verified prevents worker startup', async () => {
const { files, approval } = await approvedFiles();
const controller = new AbortController(), original = files[plugin.entry];
class RevokedBlob extends Blob {
override async arrayBuffer(): Promise<ArrayBuffer> { controller.abort(); return super.arrayBuffer(); }
}
await assert.rejects(createSkinRuntimePluginWasmSandbox({
skinId: 'community.sample', skinVersion: '2.0.0', plugin, approval,
files: { [plugin.entry]: new RevokedBlob([original]) }, signal: controller.signal,
readSessionStatus: async () => ({ connected: true, channelName: 'Test', memberCount: 1 }),
}), { name: 'AbortError' });
});
test("Wasm plugin startup rechecks the exact digest approval before creating a Worker", async () => {
const { files, approval } = await approvedFiles();
const staleApproval = { ...approval, digest: "0".repeat(64) };
@@ -26,6 +26,7 @@ export class SkinRuntimePluginWasmError extends Error {
}
export interface SkinRuntimePluginWasmOptions {
signal?: AbortSignal;
skinId: string;
skinVersion: string;
plugin: SkinRuntimePlugin;
@@ -43,6 +44,7 @@ const WASM_PROTOTYPE_PERMISSIONS = new Set([...SKIN_RUNTIME_PLUGIN_DATA_PERMISSI
export async function createSkinRuntimePluginWasmSandbox(
options: SkinRuntimePluginWasmOptions,
): Promise<SkinExtensionWasmSandboxHandle> {
options.signal?.throwIfAborted();
const plugin = parseSkinRuntimePluginDocument({ schemaVersion: 1, plugins: [options.plugin] }).plugins[0];
if (plugin.runtime !== "wasm") throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_ENTRY_INVALID", "Only a Wasm plugin entry can use the bounded Wasm runner.");
@@ -52,6 +54,7 @@ export async function createSkinRuntimePluginWasmSandbox(
}
const digest = await computeSkinRuntimePluginDigest(plugin, options.files);
options.signal?.throwIfAborted();
let approval: SkinRuntimePluginApproval;
try { approval = parseSkinRuntimePluginApproval(options.approval); }
catch { throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_APPROVAL_INVALID", "The Wasm plugin does not have a valid local approval."); }
@@ -62,6 +65,7 @@ export async function createSkinRuntimePluginWasmSandbox(
const entry = options.files[plugin.entry];
if (!(entry instanceof Blob)) throw new SkinRuntimePluginWasmError("SKIN_EXTENSION_WASM_ENTRY_INVALID", "The approved Wasm entry is unavailable.");
const wasmBytes = new Uint8Array(await entry.arrayBuffer());
options.signal?.throwIfAborted();
const baseInput = parseSkinExtensionUiInput(options.uiInput ?? { schemaVersion: 1, state: {}, event: null });
const uiInput = parseSkinExtensionUiInput({
...baseInput,
+5 -1
View File
@@ -1,10 +1,12 @@
import { getInstalledSkin, saveInstalledSkin } from "./local-persistence.js";
import { APP_VERSION } from "./app-version.js";
import type { InstalledSkin } from "./skin-pack.js";
import { applyTheme, getBuiltinSkinCss, getStoredTheme, isDarkTheme } from "./theme.js";
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
import { getBundledSkinPackageUrl, isPublicSkinEnabled } from "./skin-catalog.js";
import { createSkinOperation, type SkinLoadOptions } from "./skin-operation.js";
import { setSkinLayoutPackage } from "./skin-layout-runtime.js";
import { canUseSkin } from './instance-authorization.js';
export const ACTIVE_SKIN_KEY = "webspeak:active-skin";
export const BUILTIN_LIGHT_SKIN = "builtin.light";
@@ -34,7 +36,7 @@ export async function activateStoredSkin(): Promise<InstalledSkin | null> {
return activateSkin(selectedId);
}
export async function activateSkin(id: string, expectedVersion?: string, appVersion = "0.2.7", options: SkinLoadOptions = {}): Promise<InstalledSkin | null> {
export async function activateSkin(id: string, expectedVersion?: string, appVersion = APP_VERSION, options: SkinLoadOptions = {}): Promise<InstalledSkin | null> {
// An already retired page must not cancel a newer page's activation.
options.signal?.throwIfAborted();
pendingActivation?.cancel();
@@ -51,6 +53,7 @@ export async function activateSkin(id: string, expectedVersion?: string, appVers
async function prepareAndActivate(id: string, expectedVersion: string | undefined, appVersion: string,
operation: ReturnType<typeof createSkinOperation>): Promise<InstalledSkin | null> {
operation.check();
if (!canUseSkin(id)) return fallBackToBuiltin();
if (id === BUILTIN_LIGHT_SKIN || id === BUILTIN_DARK_SKIN) {
removeCustomSkinStyle();
setSkinLayoutPackage(id, null);
@@ -92,6 +95,7 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine
const compiled = resolveSkinCssAssets(skin.css, skin.assets);
candidateUrls = compiled.objectUrls;
operation.check();
if (!canUseSkin(id)) { candidateUrls.forEach(url => URL.revokeObjectURL(url)); return fallBackToBuiltin(); }
// A community skin is a complete appearance choice, not an overlay on the
// previously selected day/night skin. Keep the document theme (used by the
// independent admin appearance) but give unstyled public parts a light,
+50
View File
@@ -0,0 +1,50 @@
.ws-plugin-overlay{--po-bg:#f5f7fc;--po-surface:#fff;--po-raised:#edf1f9;--po-line:#dae1ef;--po-text:#233049;--po-muted:#65728b;--po-accent:#5265df;--po-tint:#e9edff;position:fixed;inset:0;z-index:10000;pointer-events:none;color:var(--po-text);font:14px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;color-scheme:light;text-align:left}
.ws-plugin-overlay[data-plugin-theme="dark"]{--po-bg:#171c27;--po-surface:#202736;--po-raised:#2a3345;--po-line:#364158;--po-text:#edf2ff;--po-muted:#a5b1ca;--po-accent:#a4b0ff;--po-tint:#333e64;color-scheme:dark}
.ws-plugin-overlay *{box-sizing:border-box}
.ws-plugin-overlay button{appearance:none;display:inline-flex;align-items:center;justify-content:center;gap:8px;margin:0;min-width:0;width:auto;height:auto;font:inherit;letter-spacing:normal;text-transform:none;border:1px solid var(--po-line);border-radius:9px;padding:8px 14px;background:var(--po-surface);color:var(--po-text);box-shadow:none;cursor:pointer;white-space:normal}
.ws-plugin-overlay button:hover{background:var(--po-raised);border-color:var(--po-accent)}
.ws-plugin-overlay button:disabled{opacity:.5;cursor:wait}
.ws-plugin-overlay button:focus-visible,.ws-plugin-search:focus-visible{outline:2px solid var(--po-accent);outline-offset:3px}
.ws-plugin-overlay svg{display:block;width:19px;height:19px;flex:none;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
.ws-plugin-overlay .ws-plugin-launcher{position:absolute;pointer-events:auto;right:max(20px,env(safe-area-inset-right));bottom:calc(22px + env(safe-area-inset-bottom));padding:13px 18px;border:1px solid #ffffff35;border-radius:18px;background:#303f78;color:#fff;box-shadow:0 8px 30px #101a4240;font-weight:650;transition:background .15s,box-shadow .15s}
.ws-plugin-overlay .ws-plugin-launcher:hover{background:#405496;box-shadow:0 10px 35px #101a4260}
.ws-plugin-launcher i{width:7px;height:7px;border-radius:50%;background:#9ee7b5}
.ws-plugin-window{position:absolute;pointer-events:auto;left:50%;top:10dvh;transform:translateX(-50%);display:flex;flex-direction:column;width:min(1080px,calc(100vw - 32px));height:min(760px,80dvh);min-width:320px;min-height:240px;max-width:calc(100vw - 16px);max-height:calc(100dvh - 16px);overflow:hidden;resize:both;border:1px solid var(--po-line);border-radius:17px;background:var(--po-bg);box-shadow:0 30px 100px #080e3540,0 4px 20px #080e3520;isolation:isolate}
.ws-plugin-window:focus{outline:none}
.ws-plugin-window.is-maximized{inset:8px!important;width:calc(100vw - 16px)!important;height:calc(100dvh - 16px)!important;transform:none!important;resize:none}
.ws-plugin-titlebar{display:flex;align-items:center;gap:12px;flex:none;min-height:62px;margin:0;padding:8px 10px 8px 20px;border-bottom:1px solid var(--po-line);background:var(--po-surface);cursor:grab;touch-action:none;user-select:none}
.is-dragging .ws-plugin-titlebar{cursor:grabbing}
.ws-plugin-mark{display:grid;place-items:center;width:32px;height:32px;flex:none;border-radius:10px;background:var(--po-tint);color:var(--po-accent);font-size:23px}
.ws-plugin-window-title{display:flex;align-items:baseline;gap:12px;min-width:0;flex:1}
.ws-plugin-window-title strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:15px;font-weight:650}
.ws-plugin-window-title small{color:var(--po-muted);font-size:11px;flex:none}
.ws-plugin-window-controls{display:flex;gap:3px;flex:none}
.ws-plugin-overlay .ws-plugin-window-controls button{padding:9px;border:0;border-radius:8px;background:transparent;color:var(--po-muted)}
.ws-plugin-overlay .ws-plugin-window-controls button:hover{background:var(--po-raised);color:var(--po-text)}
.ws-plugin-overlay .ws-plugin-window-controls .ws-plugin-close:hover{background:#d44354;color:white}
.ws-plugin-navigation{display:flex;align-items:center;gap:6px;min-height:52px;flex:none;padding:8px 16px;border-bottom:1px solid var(--po-line);overflow-x:auto}
.ws-plugin-overlay .ws-plugin-navigation button{flex:none;padding:7px 12px;border:0;background:transparent;color:var(--po-muted);font-size:12px}
.ws-plugin-overlay .ws-plugin-navigation button.active{background:var(--po-tint);color:var(--po-accent);font-weight:650}
.ws-plugin-version{margin-left:auto;white-space:nowrap;color:var(--po-muted);font-size:11px}
.ws-plugin-library{flex:1;min-height:0;padding:26px;overflow:auto;overscroll-behavior:contain}
.ws-plugin-library-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:20px}
.ws-plugin-library-heading h2{margin:0 0 3px;color:var(--po-text);font-size:24px;font-weight:700;line-height:1.3}
.ws-plugin-library-heading span{font-size:12px;color:var(--po-muted)}
.ws-plugin-overlay .ws-plugin-search{display:block;width:100%;height:42px;margin:0 0 22px;padding:10px 14px;background:var(--po-surface);color:var(--po-text);font:inherit;border:1px solid var(--po-line);border-radius:10px;box-shadow:none}
.ws-plugin-search::placeholder{color:var(--po-muted)}
.ws-plugin-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,270px),1fr));align-items:start;gap:16px}
.ws-plugin-entry{display:grid;grid-template-columns:44px minmax(0,1fr);gap:14px;padding:20px;background:var(--po-surface);border:1px solid var(--po-line);border-radius:13px}
.ws-plugin-app-mark{display:grid;place-items:center;width:44px;height:44px;border-radius:13px;background:var(--po-tint);color:var(--po-accent);font-size:22px;font-weight:700}
.ws-plugin-entry h3{margin:0 0 4px;font-size:15px;font-weight:650;overflow-wrap:anywhere;color:var(--po-text)}
.ws-plugin-entry small{display:block;color:var(--po-muted);font-size:11px}
.ws-plugin-entry p{margin:12px 0 0;color:var(--po-muted);font-size:13px;overflow-wrap:anywhere}
.ws-plugin-overlay .ws-plugin-entry button{grid-column:1/-1;justify-content:space-between;width:100%;background:var(--po-tint);border-color:transparent;color:var(--po-accent);font-weight:600}
.ws-plugin-entry-error{grid-column:1/-1;color:#d1495b!important}
.ws-plugin-empty{text-align:center;color:var(--po-muted);padding:50px 12px}
.ws-plugin-error{flex:none;margin:0;padding:12px 20px;background:#dc50541a;color:#d1495b;overflow-wrap:anywhere;max-height:100px;overflow:auto}
.ws-plugin-browser{flex:1;min-height:0;display:flex;background:var(--po-surface)}
.ws-plugin-browser iframe{display:block;flex:1;width:100%;height:100%;min-height:0;border:0;border-radius:0;background:var(--po-surface)}
.ws-plugin-drag-shield{position:absolute;inset:62px 0 0;z-index:1;cursor:grabbing}
@media(max-width:600px){.ws-plugin-window{left:8px!important;top:8px!important;transform:none!important;width:calc(100vw - 16px)!important;height:calc(100dvh - 92px);min-width:0;resize:none;border-radius:13px}.ws-plugin-titlebar{padding-left:12px;gap:8px}.ws-plugin-window-title small{display:none}.ws-plugin-library{padding:18px}.ws-plugin-overlay .ws-plugin-launcher{bottom:calc(16px + env(safe-area-inset-bottom));right:12px;padding:12px 14px}.ws-plugin-library-heading h2{font-size:21px}.ws-plugin-entry{padding:16px}.ws-plugin-navigation{padding-inline:10px}}
@media(prefers-reduced-motion:reduce){.ws-plugin-overlay .ws-plugin-launcher{transition:none}}
.ws-plugin-launcher{touch-action:none;user-select:none}
+2
View File
@@ -58,11 +58,13 @@
<div v-if="poke" class="demo-poke" data-ws-part="demo.poke-notification" role="status"><Icon name="bell" :size="17" /><span><strong>msicbot</strong> {{ copy.pokedYou }}</span><button type="button" data-ws-part="demo.poke.dismiss" @click="poke = false"><Icon name="close" :size="14" /></button></div>
</div>
<SkinLoadRecoveryNotice :error="skinLoadError" :language="language" @use-built-in="switchToBuiltInAfterLoadError" />
<InstanceAuthorization :language="language" />
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import Icon from "../components/Icon.vue";
import InstanceAuthorization from '../components/InstanceAuthorization.vue';
import "../styles/skin-plugin.css";
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
+5 -2
View File
@@ -870,7 +870,7 @@
<div class="ws-skin-mount-slot" data-ws-skin-mount="voice.workspace.overlay"></div>
</div>
<PluginPanel :transport="plugins" :connected="voiceState.connected" :language="language" />
<PluginPanel :session-token="pluginSession" :gateway-url="pluginVoiceSocket?.url ?? ''" :connected="voiceState.connected" :language="language" />
<IdentityImportDialog
v-if="identityImportOpen"
v-model="identityImportText"
@@ -958,6 +958,7 @@
>
</div>
<SkinLoadRecoveryNotice :error="skinLoadError" :language="language" @use-built-in="switchToBuiltInAfterLoadError" />
<InstanceAuthorization :language="language" />
</template>
<script setup lang="ts">
@@ -1003,6 +1004,7 @@ import { useWebClientChannels, type TreeChannel } from "../composables/useWebCli
import { useWebClientConnection } from "../composables/useWebClientConnection.js";
import { useWebClientMembers } from "../composables/useWebClientMembers.js";
import PluginPanel from "../components/PluginPanel.vue";
import InstanceAuthorization from '../components/InstanceAuthorization.vue';
import { useVoiceWebSocket, type ChannelMember, type ChatMessage } from "../composables/useVoiceWebSocket.js";
import { useWebClientScreenShare } from "../composables/useWebClientScreenShare.js";
import { useWebClientPerformance } from "../composables/useWebClientPerformance.js";
@@ -1104,7 +1106,8 @@ const {
leaveScreenShare,
checkSupport,
clearError,
plugins,
pluginSession,
ws: pluginVoiceSocket,
measureVoiceAudioStatus,
} = useVoiceWebSocket();
const performance = useWebClientPerformance(computed(() => voiceState.connected), measureVoiceAudioStatus);
+17 -3
View File
@@ -337,7 +337,7 @@ export function createScreenShareController(transport: ScreenShareTransport) {
startScreenShareStatsPolling();
traceScreenShare("peer-created", { streamId, peerId, role });
if (role === "owner") {
// Match TeamSpeak's screen-share offer shape: video is MID 0, optional
// Match TeamSpeak's screen-share offer shape: video is MID 0,
// audio follows it, and a publisher only sends media.
const localTracks = [...(screenShareLocalStream?.getTracks() ?? [])];
localTracks.sort((left, right) => left.kind === right.kind ? 0 : left.kind === "video" ? -1 : 1);
@@ -347,6 +347,13 @@ export function createScreenShareController(transport: ScreenShareTransport) {
if (transceiver) transceiver.direction = "sendonly";
if (track.kind === "video") void configureScreenShareVideoSender(sender, track);
}
// The native receiver does not answer video-only offers. Window/monitor
// capture (or audio disabled by the user) often returns no audio track.
// Negotiate the required audio section without capturing a microphone,
// fabricating a track or claiming that shared audio is available.
if (peerId.startsWith("ts-viewer-") && !localTracks.some(track => track.kind === "audio")) {
peer.addTransceiver("audio", { direction: "sendonly" });
}
} else {
peer.addTransceiver("video", { direction: "recvonly" });
const stream = screenShareStreams.find((candidate) => candidate.streamId === streamId);
@@ -537,12 +544,19 @@ export function createScreenShareController(transport: ScreenShareTransport) {
await peer.setLocalDescription(offer);
if (!isCurrentPeer(peerId, peer)) return;
armScreenSharePeerTimer(peerId);
traceScreenShare("native-viewer-offer-ready", { streamId, peerId });
const sdp = peer.localDescription?.sdp ?? offer.sdp ?? "";
traceScreenShare("native-viewer-offer-ready", {
streamId, peerId,
hasAudioSection: /^m=audio\s/m.test(sdp),
hasVideoSection: /^m=video\s/m.test(sdp),
capturedAudio: (screenShareLocalStream?.getAudioTracks().length ?? 0) > 0,
displaySurface: screenShareLocalStream?.getVideoTracks()[0]?.getSettings().displaySurface ?? null,
});
sendScreenShareMessage({
type: "screenShareSignal",
streamId,
targetPeerId: peerId,
signal: { kind: "offer", sdp: peer.localDescription?.sdp ?? offer.sdp ?? "" },
signal: { kind: "offer", sdp },
});
} catch (error: unknown) {
traceScreenShare("native-viewer-offer-failed", { streamId, peerId, errorName: error instanceof Error ? error.name : "unknown" });