mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
feat(web): implement open skin layouts and migrate Illusia
This commit is contained in:
1 parent
58559cf839
commit
02441410a0
60 files changed
+6511
-50
No files matched your search
@@ -1,7 +1,12 @@
|
||||
<template>
|
||||
<router-view />
|
||||
<SkinLayoutEditor />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import SkinLayoutEditor from "./components/SkinLayoutEditor.vue";
|
||||
</script>
|
||||
|
||||
<style>
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div v-if="editor.available.value" class="skin-layout-editor" data-ws-layout-editor>
|
||||
<button
|
||||
class="skin-layout-trigger"
|
||||
type="button"
|
||||
:aria-expanded="editor.isOpen.value"
|
||||
aria-controls="skin-layout-panel"
|
||||
@click="editor.setOpen(!editor.isOpen.value)"
|
||||
>
|
||||
<span aria-hidden="true">⠿</span>
|
||||
{{ editor.labels.value.editButton }}
|
||||
</button>
|
||||
|
||||
<section
|
||||
v-if="editor.isOpen.value"
|
||||
id="skin-layout-panel"
|
||||
class="skin-layout-panel"
|
||||
role="dialog"
|
||||
aria-modal="false"
|
||||
:aria-label="editor.labels.value.title"
|
||||
>
|
||||
<header class="skin-layout-heading">
|
||||
<div>
|
||||
<h2>{{ editor.labels.value.title }}</h2>
|
||||
<p>{{ editor.labels.value.hint }}</p>
|
||||
</div>
|
||||
<button type="button" class="skin-layout-close" :aria-label="editor.labels.value.close" @click="editor.setOpen(false)">×</button>
|
||||
</header>
|
||||
|
||||
<label class="skin-layout-toggle">
|
||||
<input type="checkbox" :checked="editor.isEditing.value" @change="editor.setEditing(($event.target as HTMLInputElement).checked)" />
|
||||
<span>{{ editor.labels.value.editMode }}</span>
|
||||
</label>
|
||||
|
||||
<label class="skin-layout-toggle">
|
||||
<input type="checkbox" :checked="editor.focusPreviewEnabled.value" @change="editor.setFocusPreview(($event.target as HTMLInputElement).checked)" />
|
||||
<span>{{ editor.labels.value.focusPreview }}</span>
|
||||
</label>
|
||||
<ol v-if="editor.focusPreviewEnabled.value" class="skin-layout-focus-list" :aria-label="editor.labels.value.focusPreview">
|
||||
<li v-if="!editor.focusPreviewTargets.value.length" class="skin-layout-focus-empty">
|
||||
{{ editor.labels.value.focusPreviewEmpty }}
|
||||
</li>
|
||||
<li v-for="target in editor.focusPreviewTargets.value" :key="target.key" :class="{ 'is-small': !target.meetsTouchTarget }">
|
||||
<span class="skin-layout-focus-number" aria-hidden="true">{{ target.order }}</span>
|
||||
<span class="skin-layout-focus-name"><strong>{{ target.componentName }}</strong><small>{{ target.accessibleName || editor.labels.value.focusPreviewUnnamed }}</small></span>
|
||||
<span class="skin-layout-focus-size">{{ editor.labels.value.focusPreviewTargetSize.replace("{width}", String(Math.round(target.width))).replace("{height}", String(Math.round(target.height))) }}<small>{{ target.meetsTouchTarget ? editor.labels.value.focusPreviewTargetAdequate : editor.labels.value.focusPreviewTargetSmall }}</small></span>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<label class="skin-layout-field">
|
||||
<span>{{ editor.labels.value.component }}</span>
|
||||
<input v-model="editor.filter.value" type="search" :placeholder="editor.labels.value.filter" />
|
||||
<select :value="editor.selectedComponentId.value" @change="editor.selectComponent(($event.target as HTMLSelectElement).value)">
|
||||
<option v-for="component in editor.filteredComponents.value" :key="component.id" :value="component.id">{{ component.name }} ({{ component.id }})</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="skin-layout-toggle">
|
||||
<input type="checkbox" :checked="editor.selectedVisible.value" @change="editor.setVisible(($event.target as HTMLInputElement).checked)" />
|
||||
<span>{{ editor.labels.value.visible }}</span>
|
||||
</label>
|
||||
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.positionX }}</span><output>{{ Math.round(editor.selectedX.value) }} px</output></label>
|
||||
<input type="range" :min="editor.positionBoundsX.value.minimum" :max="editor.positionBoundsX.value.maximum" step="1" :value="editor.selectedX.value" @input="editor.setX(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.positionY }}</span><output>{{ Math.round(editor.selectedY.value) }} px</output></label>
|
||||
<input type="range" :min="editor.positionBoundsY.value.minimum" :max="editor.positionBoundsY.value.maximum" step="1" :value="editor.selectedY.value" @input="editor.setY(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.size }}</span><output>{{ Math.round(editor.selectedScale.value * 100) }}%</output></label>
|
||||
<input type="range" :min="editor.selectedSizeBounds.value.minScale" :max="editor.selectedSizeBounds.value.maxScale" step="0.05" :value="editor.selectedScale.value" @input="editor.setScale(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.width }}</span><output>{{ Math.round(editor.selectedWidth.value) }} px</output></label>
|
||||
<input type="range" :min="editor.selectedSizeBounds.value.minWidth" :max="editor.selectedSizeBounds.value.maxWidth" step="4" :value="editor.selectedWidth.value" @input="editor.setWidth(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.height }}</span><output>{{ Math.round(editor.selectedHeight.value) }} px</output></label>
|
||||
<input type="range" :min="editor.selectedSizeBounds.value.minHeight" :max="editor.selectedSizeBounds.value.maxHeight" step="4" :value="editor.selectedHeight.value" @input="editor.setHeight(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
|
||||
<div class="skin-layout-colors">
|
||||
<label><span>{{ editor.labels.value.foreground }}</span><input type="color" :value="editor.selectedForeground.value" @input="editor.setForeground(($event.target as HTMLInputElement).value)" /></label>
|
||||
<label><span>{{ editor.labels.value.background }}</span><input type="color" :value="editor.selectedBackground.value" @input="editor.setBackground(($event.target as HTMLInputElement).value)" /></label>
|
||||
<label><span>{{ editor.labels.value.border }}</span><input type="color" :value="editor.selectedBorder.value" @input="editor.setBorder(($event.target as HTMLInputElement).value)" /></label>
|
||||
</div>
|
||||
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.radius }}</span><output>{{ Math.round(editor.selectedRadius.value) }} px</output></label>
|
||||
<input type="range" min="0" max="64" step="1" :value="editor.selectedRadius.value" @input="editor.setRadius(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
|
||||
<div class="skin-layout-actions">
|
||||
<button type="button" :disabled="!editor.canUndo.value" @click="editor.undo">{{ editor.labels.value.undo }}</button>
|
||||
<button type="button" :disabled="!editor.canRedo.value" @click="editor.redo">{{ editor.labels.value.redo }}</button>
|
||||
</div>
|
||||
<div class="skin-layout-actions">
|
||||
<button type="button" @click="editor.resetComponent">{{ editor.labels.value.resetItem }}</button>
|
||||
<button type="button" @click="editor.resetAll">{{ editor.labels.value.resetAll }}</button>
|
||||
</div>
|
||||
<div class="skin-layout-actions">
|
||||
<button type="button" @click="editor.exportCurrent">{{ editor.labels.value.export }}</button>
|
||||
<button type="button" @click="importInput?.click()">{{ editor.labels.value.import }}</button>
|
||||
<input ref="importInput" class="skin-layout-file" type="file" accept="application/json,.json" @change="onImport" />
|
||||
</div>
|
||||
<p v-if="editor.statusMessage.value" class="skin-layout-status" role="status">{{ editor.statusMessage.value }}</p>
|
||||
<div v-if="editor.layoutWarnings.value.length" class="skin-layout-warning" role="status">
|
||||
<p v-for="warning in editor.layoutWarnings.value" :key="warning">{{ warning }}</p>
|
||||
<button type="button" @click="editor.ignoreLayoutWarnings">{{ editor.labels.value.ignoreWarnings }}</button>
|
||||
</div>
|
||||
<div v-if="editor.migrationRecovery.value" class="skin-layout-warning" role="status">
|
||||
<span>{{ editor.labels.value.migrationWarning(editor.migrationRecoveryCount.value) }}</span>
|
||||
<button type="button" @click="editor.exportRecovery">{{ editor.labels.value.exportRecovery }}</button>
|
||||
</div>
|
||||
<p class="skin-layout-context">{{ editor.context.value?.skinId }} · {{ editor.context.value?.page }} · {{ editor.context.value?.profile }}</p>
|
||||
</section>
|
||||
</div>
|
||||
<div v-if="editor.focusPreviewEnabled.value" class="skin-layout-focus-overlay" aria-hidden="true">
|
||||
<span
|
||||
v-for="target in editor.focusPreviewTargets.value"
|
||||
:key="target.key"
|
||||
class="skin-layout-focus-marker"
|
||||
:class="{ 'is-small': !target.meetsTouchTarget }"
|
||||
:style="{ left: `${target.left}px`, top: `${target.top}px`, width: `${target.width}px`, height: `${target.height}px` }"
|
||||
>{{ target.order }}</span>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import { useSkinLayoutEditor } from "../composables/useSkinLayoutEditor.js";
|
||||
|
||||
const editor = useSkinLayoutEditor();
|
||||
const importInput = ref<HTMLInputElement | null>(null);
|
||||
|
||||
async function onImport(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement;
|
||||
await editor.importFile(input.files?.[0]);
|
||||
input.value = "";
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.skin-layout-editor {
|
||||
position: fixed;
|
||||
z-index: 2147483000;
|
||||
right: 14px;
|
||||
bottom: 14px;
|
||||
color: #172033;
|
||||
font: 13px/1.45 Inter, ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
.skin-layout-editor button,
|
||||
.skin-layout-editor input,
|
||||
.skin-layout-editor select {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.skin-layout-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
min-height: 44px;
|
||||
padding: 0 14px;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 999px;
|
||||
color: #fff;
|
||||
background: #273449;
|
||||
box-shadow: 0 5px 22px #0f172a55;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.skin-layout-trigger span { font-size: 19px; line-height: 1; }
|
||||
|
||||
.skin-layout-panel {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 56px;
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
width: min(360px, calc(100vw - 24px));
|
||||
max-height: min(78vh, 720px);
|
||||
overflow: auto;
|
||||
padding: 16px;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 16px;
|
||||
background: #fff;
|
||||
box-shadow: 0 18px 60px #0f172a44;
|
||||
}
|
||||
|
||||
.skin-layout-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
|
||||
.skin-layout-heading h2 { margin: 0; font-size: 16px; }
|
||||
.skin-layout-heading p { margin: 5px 0 0; color: #475569; font-size: 12px; }
|
||||
.skin-layout-close { width: 32px; height: 32px; border-radius: 8px; color: #334155; background: #f1f5f9; font-size: 22px !important; cursor: pointer; }
|
||||
.skin-layout-toggle { display: flex; align-items: center; gap: 8px; min-height: 38px; }
|
||||
.skin-layout-field { display: grid; gap: 6px; }
|
||||
.skin-layout-field > span,
|
||||
.skin-layout-range label,
|
||||
.skin-layout-colors span { color: #475569; font-size: 12px; }
|
||||
.skin-layout-field input[type="search"],
|
||||
.skin-layout-field select { width: 100%; min-height: 36px; padding: 6px 9px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #fff; }
|
||||
.skin-layout-range { display: grid; gap: 3px; }
|
||||
.skin-layout-range label { display: flex; justify-content: space-between; gap: 8px; }
|
||||
.skin-layout-range output { color: #172033; font-variant-numeric: tabular-nums; }
|
||||
.skin-layout-range input { width: 100%; accent-color: #4f46e5; }
|
||||
.skin-layout-colors { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
|
||||
.skin-layout-colors label { display: grid; gap: 4px; }
|
||||
.skin-layout-colors input { width: 100%; height: 34px; padding: 2px; border: 1px solid #cbd5e1; border-radius: 7px; background: #fff; }
|
||||
.skin-layout-actions { display: flex; flex-wrap: wrap; gap: 7px; }
|
||||
.skin-layout-actions button { min-height: 36px; padding: 0 10px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #f8fafc; cursor: pointer; }
|
||||
.skin-layout-actions button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.skin-layout-file { display: none; }
|
||||
.skin-layout-status { margin: 0; color: #4338ca; }
|
||||
.skin-layout-warning { margin: 0; padding: 8px 10px; border: 1px solid #fcd34d; border-radius: 8px; color: #854d0e; background: #fffbeb; }
|
||||
.skin-layout-warning button { min-height: 32px; margin-top: 6px; padding: 0 9px; border: 1px solid #d97706; border-radius: 7px; color: #78350f; background: #fff; cursor: pointer; }
|
||||
.skin-layout-context { margin: 0; color: #64748b; font-size: 11px; overflow-wrap: anywhere; }
|
||||
.skin-layout-editor :focus-visible { outline: 2px solid #4f46e5; outline-offset: 2px; }
|
||||
.skin-layout-focus-list { display: grid; gap: 6px; max-height: 220px; overflow: auto; margin: 0; padding: 0; list-style: none; }
|
||||
.skin-layout-focus-list > li { display: flex; align-items: flex-start; gap: 8px; min-width: 0; padding: 7px; border: 1px solid #86efac; border-radius: 8px; background: #f0fdf4; }
|
||||
.skin-layout-focus-list > li.is-small { border-color: #fca5a5; background: #fef2f2; }
|
||||
.skin-layout-focus-list .skin-layout-focus-empty { border-color: #cbd5e1; background: #f8fafc; color: #475569; }
|
||||
.skin-layout-focus-number { display: grid; place-items: center; flex: 0 0 22px; width: 22px; height: 22px; border-radius: 50%; color: #fff; background: #15803d; font-weight: 700; }
|
||||
.is-small .skin-layout-focus-number { background: #b91c1c; }
|
||||
.skin-layout-focus-name, .skin-layout-focus-size { display: grid; min-width: 0; gap: 2px; overflow-wrap: anywhere; }
|
||||
.skin-layout-focus-name { flex: 1; }
|
||||
.skin-layout-focus-name small, .skin-layout-focus-size small { color: #475569; font-size: 10px; }
|
||||
.skin-layout-focus-size { flex: 0 0 auto; text-align: right; }
|
||||
.skin-layout-focus-overlay { position: fixed; z-index: 2147482999; inset: 0; pointer-events: none; }
|
||||
.skin-layout-focus-marker { position: fixed; box-sizing: border-box; display: grid; place-items: start; padding: 0 2px; border: 2px solid #15803d; border-radius: 3px; color: #fff; background: #15803d40; font: 700 11px/16px ui-sans-serif, system-ui, sans-serif; }
|
||||
.skin-layout-focus-marker.is-small { border-color: #b91c1c; background: #b91c1c40; }
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.skin-layout-editor { right: 10px; bottom: 10px; }
|
||||
.skin-layout-panel { max-height: 72vh; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,52 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<section v-if="error" class="skin-load-recovery" role="alert">
|
||||
<p>{{ labels.skinLoadError(error.skinId) }}</p>
|
||||
<button type="button" @click="$emit('use-built-in')">{{ labels.skinUseBuiltIn }}</button>
|
||||
</section>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import type { Language } from "../i18n/web-client.js";
|
||||
import { resolveSkinLayoutLanguage, skinLayoutLabels } from "../i18n/skin-layout.js";
|
||||
|
||||
defineEmits<{ "use-built-in": [] }>();
|
||||
|
||||
const props = defineProps<{
|
||||
error: { skinId: string } | null;
|
||||
language: Language;
|
||||
}>();
|
||||
const labels = computed(() => skinLayoutLabels[resolveSkinLayoutLanguage(props.language)]);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.skin-load-recovery {
|
||||
position: fixed;
|
||||
z-index: 2147482500;
|
||||
top: max(12px, env(safe-area-inset-top));
|
||||
left: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
width: min(720px, calc(100vw - 24px));
|
||||
padding: 10px 12px;
|
||||
transform: translateX(-50%);
|
||||
border: 1px solid #f59e0b;
|
||||
border-radius: 12px;
|
||||
color: #78350f;
|
||||
background: #fffbeb;
|
||||
box-shadow: 0 8px 28px #0f172a33;
|
||||
font: 14px/1.45 ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
.skin-load-recovery p { flex: 1; min-width: 0; margin: 0; overflow-wrap: anywhere; }
|
||||
.skin-load-recovery button { flex: 0 0 auto; min-height: 44px; max-width: 100%; padding: 7px 10px; border: 1px solid #b45309; border-radius: 8px; color: #78350f; background: #fff; cursor: pointer; white-space: normal; }
|
||||
.skin-load-recovery button:focus-visible { outline: 3px solid #1d4ed8; outline-offset: 2px; }
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.skin-load-recovery { align-items: stretch; flex-direction: column; gap: 7px; }
|
||||
.skin-load-recovery button { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
@@ -22,6 +22,7 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
|
||||
const stored = getStoredSkinId();
|
||||
const activeSkinId = ref(stored ?? fallbackId());
|
||||
const skinReady = ref(Boolean(stored && builtin(stored)));
|
||||
const skinLoadError = shallowRef<{ skinId: string } | null>(null);
|
||||
const installedSkins = ref<InstalledSkin[]>([]);
|
||||
const catalogSkins = ref<SkinCatalogEntry[]>([...BUILTIN_SKIN_CATALOG]);
|
||||
let current: ReturnType<typeof createSkinOperation> | undefined;
|
||||
@@ -34,34 +35,38 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
|
||||
}
|
||||
onScopeDispose(() => { disposed = true; cancel(); });
|
||||
|
||||
async function apply(id: string, operation: ReturnType<typeof createSkinOperation>, persist = true, updateTheme = false) {
|
||||
async function apply(id: string, operation: ReturnType<typeof createSkinOperation>, persist = true, updateTheme = false, clearLoadError = true) {
|
||||
operation.check();
|
||||
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;
|
||||
if (!builtin(id) && !skin) throw new Error("The selected skin could not be activated.");
|
||||
activeSkin.value = skin;
|
||||
activeSkinId.value = skin?.id ?? (builtin(id) ? id : fallbackId());
|
||||
if (clearLoadError) skinLoadError.value = null;
|
||||
const mode = activeSkinId.value === BUILTIN_LIGHT_SKIN ? "light"
|
||||
: activeSkinId.value === BUILTIN_DARK_SKIN ? "dark" : isDarkTheme(getStoredTheme()) ? "dark" : "light";
|
||||
if (options.themeMode && updateTheme) {
|
||||
options.themeMode.value = mode;
|
||||
saveTheme(mode);
|
||||
saveTheme(mode, { preserveCustomSkins: !builtin(activeSkinId.value) });
|
||||
}
|
||||
if (persist) void saveLocalPreferences({ schemaVersion: 1, skinId: activeSkinId.value,
|
||||
...(options.themeMode && updateTheme ? { theme: mode } : {}) }, operation.signal).catch(() => undefined);
|
||||
}
|
||||
async function recover(error: unknown, operation: ReturnType<typeof createSkinOperation>) {
|
||||
async function recover(error: unknown, operation: ReturnType<typeof createSkinOperation>, failedSkinId: string) {
|
||||
if (!owns(operation) || (error as { name?: string })?.name === "AbortError") return;
|
||||
if (!builtin(failedSkinId)) skinLoadError.value = { skinId: failedSkinId };
|
||||
// Retire every stage of the old operation before installing a fallback.
|
||||
operation.cancel();
|
||||
const fallback = begin();
|
||||
try { await apply(fallbackId(), fallback, false); }
|
||||
try { await apply(fallbackId(), fallback, false, false, false); }
|
||||
catch { /* A newer selection or page can retire the fallback as well. */ }
|
||||
finally { if (owns(fallback)) skinReady.value = true; fallback.finish(); }
|
||||
}
|
||||
async function initialize() {
|
||||
if (disposed) return;
|
||||
const operation = begin();
|
||||
let requestedSkinId = fallbackId();
|
||||
try {
|
||||
const [preferences, installed, available] = await operation.wait(Promise.all([
|
||||
loadLocalPreferences(), listInstalledSkins(), listPublicSkins({ signal: operation.signal }),
|
||||
@@ -74,8 +79,9 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
|
||||
}
|
||||
// Only an explicit user choice overrides the instance default.
|
||||
const choice = readChoice();
|
||||
await apply(choice && isPublicSkinEnabled(choice) ? choice : getPublicDefaultSkinId(), operation);
|
||||
} catch (error) { await recover(error, operation); }
|
||||
requestedSkinId = choice && isPublicSkinEnabled(choice) ? choice : getPublicDefaultSkinId();
|
||||
await apply(requestedSkinId, operation);
|
||||
} catch (error) { await recover(error, operation, requestedSkinId); }
|
||||
finally { if (owns(operation)) skinReady.value = true; operation.finish(); }
|
||||
}
|
||||
async function select(id: string) {
|
||||
@@ -84,12 +90,13 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
|
||||
try {
|
||||
try { localStorage.setItem("webspeak:skin-choice", id); } catch { /* Optional storage. */ }
|
||||
await apply(id, operation, true, true);
|
||||
} catch (error) { await recover(error, operation); }
|
||||
} catch (error) { await recover(error, operation, id); }
|
||||
finally { if (owns(operation)) skinReady.value = true; operation.finish(); }
|
||||
}
|
||||
async function reset() {
|
||||
if (disposed) return;
|
||||
const operation = begin();
|
||||
skinLoadError.value = null;
|
||||
clearCustomSkinStyle();
|
||||
activeSkin.value = null;
|
||||
installedSkins.value = [];
|
||||
@@ -104,5 +111,10 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
|
||||
catch { /* Reset remains usable even if refreshing the optional catalog fails. */ }
|
||||
finally { operation.finish(); }
|
||||
}
|
||||
return { activeSkin, activeSkinId, skinReady, installedSkins, catalogSkins, initialize, select, cancel, reset };
|
||||
async function switchToBuiltInAfterLoadError(): Promise<void> {
|
||||
if (!skinLoadError.value) return;
|
||||
await select(fallbackId());
|
||||
}
|
||||
|
||||
return { activeSkin, activeSkinId, skinReady, skinLoadError, installedSkins, catalogSkins, initialize, select, cancel, reset, switchToBuiltInAfterLoadError };
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, shallowRef } from "vue";
|
||||
import {
|
||||
canEditSkinLayoutComponent,
|
||||
getSkinLayoutComponentId,
|
||||
getSkinLayoutComponent,
|
||||
getSkinLayoutComponents,
|
||||
type SkinLayoutDocument,
|
||||
type SkinLayoutPlacement,
|
||||
} from "../../../src/shared/skin-layout.js";
|
||||
import { analyzeSkinLayoutGeometry, clampSkinLayoutOffset, getSkinLayoutOffsetBounds } from "../services/skin-layout-geometry.js";
|
||||
import type { SkinLayoutOffsetBounds } from "../services/skin-layout-geometry.js";
|
||||
import { orderSequentialFocusTargets } from "../services/skin-layout-focus.js";
|
||||
import { resolveSkinLayoutLanguage, skinLayoutLabels } from "../i18n/skin-layout.js";
|
||||
import {
|
||||
clearActiveSkinLayoutOverrides,
|
||||
getActiveSkinLayoutContext,
|
||||
getActiveSkinLayoutOverride,
|
||||
getActiveSkinLayoutOverrides,
|
||||
getEffectiveSkinLayoutPlacement,
|
||||
initializeSkinLayoutRuntime,
|
||||
previewActiveSkinLayoutPlacement,
|
||||
refreshSkinLayout,
|
||||
replaceActiveSkinLayoutOverrides,
|
||||
saveActiveSkinLayoutPlacement,
|
||||
setSkinLayoutEditorState,
|
||||
type ActiveSkinLayoutContext,
|
||||
} from "../services/skin-layout-runtime.js";
|
||||
import {
|
||||
exportSkinLayout,
|
||||
exportSkinLayoutMigrationRecovery,
|
||||
getSkinLayoutMigrationRecovery,
|
||||
importSkinLayout,
|
||||
} from "../services/skin-layout-storage.js";
|
||||
|
||||
interface DragState {
|
||||
pointerId: number;
|
||||
componentId: string;
|
||||
startX: number;
|
||||
startY: number;
|
||||
originX: number;
|
||||
originY: number;
|
||||
placement: SkinLayoutPlacement;
|
||||
changed: boolean;
|
||||
}
|
||||
|
||||
interface FocusPreviewTarget {
|
||||
key: string;
|
||||
tabIndex: number;
|
||||
componentName: string;
|
||||
accessibleName: string;
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
height: number;
|
||||
meetsTouchTarget: boolean;
|
||||
order?: number;
|
||||
}
|
||||
|
||||
function componentIdForElement(element: HTMLElement): string | null {
|
||||
return getSkinLayoutComponentId(element.dataset.wsPart, element.dataset.wsControlKind);
|
||||
}
|
||||
|
||||
export function useSkinLayoutEditor() {
|
||||
const isOpen = ref(false);
|
||||
const isEditing = ref(false);
|
||||
const canUndo = ref(false);
|
||||
const canRedo = ref(false);
|
||||
const focusPreviewEnabled = ref(false);
|
||||
const filter = ref("");
|
||||
const selectedComponentId = ref("");
|
||||
const statusMessage = ref("");
|
||||
const ignoredWarningKey = ref("");
|
||||
const context = shallowRef<ActiveSkinLayoutContext | null>(null);
|
||||
const revision = ref(0);
|
||||
let contextKey = "";
|
||||
let observer: MutationObserver | null = null;
|
||||
let drag: DragState | null = null;
|
||||
let viewportRefreshFrame = 0;
|
||||
let geometryRefreshFrame = 0;
|
||||
let geometryRefreshQueued = false;
|
||||
let history: SkinLayoutDocument[] = [];
|
||||
let historyIndex = -1;
|
||||
let lastHistoryChangeAt = 0;
|
||||
|
||||
const labels = computed(() => skinLayoutLabels[context.value?.root.lang ? resolveSkinLayoutLanguage(context.value.root.lang) : "zh"]);
|
||||
const available = computed(() => Boolean(context.value));
|
||||
const components = computed(() => {
|
||||
revision.value;
|
||||
const page = context.value?.page;
|
||||
return page ? getSkinLayoutComponents(page).filter((component) => component.editable) : [];
|
||||
});
|
||||
const filteredComponents = computed(() => {
|
||||
const search = filter.value.trim().toLowerCase();
|
||||
return components.value.filter((component) => !search || component.id.toLowerCase().includes(search)
|
||||
|| component.name.toLowerCase().includes(search));
|
||||
});
|
||||
const selectedPlacement = computed(() => {
|
||||
revision.value;
|
||||
return selectedComponentId.value ? getEffectiveSkinLayoutPlacement(selectedComponentId.value) ?? {} : {};
|
||||
});
|
||||
const selectedVisible = computed(() => selectedPlacement.value.visible !== false);
|
||||
const selectedScale = computed(() => selectedPlacement.value.scale ?? 1);
|
||||
const selectedWidth = computed(() => selectedPlacement.value.width ?? 320);
|
||||
const selectedHeight = computed(() => selectedPlacement.value.height ?? 160);
|
||||
const selectedX = computed(() => selectedPlacement.value.x ?? 0);
|
||||
const selectedY = computed(() => selectedPlacement.value.y ?? 0);
|
||||
const selectedForeground = computed(() => selectedPlacement.value.foreground ?? "#ffffff");
|
||||
const selectedBackground = computed(() => selectedPlacement.value.background ?? "#ffffff");
|
||||
const selectedBorder = computed(() => selectedPlacement.value.border ?? "#ffffff");
|
||||
const selectedRadius = computed(() => selectedPlacement.value.radius ?? 0);
|
||||
const selectedComponent = computed(() => context.value && selectedComponentId.value
|
||||
? getSkinLayoutComponent(selectedComponentId.value, context.value.page) : undefined);
|
||||
const focusPreviewTargets = computed(() => {
|
||||
revision.value;
|
||||
const active = context.value;
|
||||
if (!active || !focusPreviewEnabled.value) return [];
|
||||
const candidates: FocusPreviewTarget[] = [];
|
||||
const selector = "a[href], area[href], button, input, select, textarea, iframe, summary, [tabindex], [contenteditable]:not([contenteditable='false']), audio[controls], video[controls]";
|
||||
const focusable = [...active.root.querySelectorAll<HTMLElement>(selector)];
|
||||
const isVisibleFocusTarget = (element: HTMLElement) => {
|
||||
if (element.tabIndex < 0 || element.matches(":disabled") || element.closest("[hidden], [inert]")) return false;
|
||||
if (!element.getClientRects().length) return false;
|
||||
const style = window.getComputedStyle(element);
|
||||
return style.visibility !== "hidden" && style.visibility !== "collapse";
|
||||
};
|
||||
const radioGroups = new Map<object, Map<string, HTMLInputElement[]>>();
|
||||
for (const element of active.root.querySelectorAll<HTMLInputElement>('input[type="radio"][name]')) {
|
||||
const owner = element.form ?? element.getRootNode() as object;
|
||||
let groups = radioGroups.get(owner);
|
||||
if (!groups) radioGroups.set(owner, groups = new Map());
|
||||
const group = groups.get(element.name) ?? [];
|
||||
group.push(element);
|
||||
groups.set(element.name, group);
|
||||
}
|
||||
for (const element of focusable) {
|
||||
if (!isVisibleFocusTarget(element)) continue;
|
||||
if (element instanceof HTMLInputElement && element.type === "radio" && element.name) {
|
||||
const owner = element.form ?? element.getRootNode() as object;
|
||||
const group = radioGroups.get(owner)?.get(element.name) ?? [element];
|
||||
const activeRadio = group.find((radio) => radio.checked && isVisibleFocusTarget(radio))
|
||||
?? group.find(isVisibleFocusTarget);
|
||||
if (activeRadio !== element) continue;
|
||||
}
|
||||
const owner = element.closest<HTMLElement>("[data-ws-part]");
|
||||
if (!owner || !active.root.contains(owner)) continue;
|
||||
const id = componentIdForElement(owner);
|
||||
const component = id ? getSkinLayoutComponent(id, active.page) : undefined;
|
||||
if (!id || !component || component.category === "trusted-chrome"
|
||||
|| !canEditSkinLayoutComponent(id, active.page, ancestorComponentIds(owner, active.root))) continue;
|
||||
const rect = element.getBoundingClientRect();
|
||||
const labelledBy = element.getAttribute("aria-labelledby")?.split(/\s+/)
|
||||
.map((labelId) => document.getElementById(labelId)?.textContent ?? "").filter(Boolean).join(" ");
|
||||
const nativeLabels = "labels" in element
|
||||
? [...((element as HTMLInputElement).labels ?? [])].map((label) => label.textContent ?? "").join(" ") : "";
|
||||
const accessibleName = (labelledBy || element.getAttribute("aria-label") || nativeLabels
|
||||
|| element.getAttribute("alt") || element.getAttribute("title") || element.getAttribute("placeholder")
|
||||
|| element.textContent || "").replace(/\s+/g, " ").trim().slice(0, 100);
|
||||
candidates.push({
|
||||
key: `${id}:${candidates.length}`,
|
||||
tabIndex: element.tabIndex,
|
||||
componentName: component.name,
|
||||
accessibleName,
|
||||
left: rect.left,
|
||||
top: rect.top,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
meetsTouchTarget: rect.width >= 44 && rect.height >= 44,
|
||||
});
|
||||
}
|
||||
return orderSequentialFocusTargets(candidates).map((target, index) => ({ ...target, order: index + 1 }));
|
||||
});
|
||||
const selectedSizeBounds = computed(() => selectedComponent.value ?? {
|
||||
minWidth: 44, maxWidth: 2400, minHeight: 44, maxHeight: 2400, minScale: 0.25, maxScale: 4,
|
||||
});
|
||||
const migrationRecovery = computed(() => {
|
||||
revision.value;
|
||||
return context.value ? getSkinLayoutMigrationRecovery(context.value.skinId) : null;
|
||||
});
|
||||
const migrationRecoveryCount = computed(() => migrationRecovery.value
|
||||
? migrationRecovery.value.items.length + migrationRecovery.value.omittedCount : 0);
|
||||
function ancestorComponentIds(element: HTMLElement, root: HTMLElement): string[] {
|
||||
const ids: string[] = [];
|
||||
let ancestor = element.parentElement;
|
||||
while (ancestor && ancestor !== root) {
|
||||
const id = componentIdForElement(ancestor);
|
||||
if (id) ids.push(id);
|
||||
ancestor = ancestor.parentElement;
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function componentTargets(active: ActiveSkinLayoutContext, id: string): HTMLElement[] {
|
||||
const component = getSkinLayoutComponent(id, active.page);
|
||||
if (!component) return [];
|
||||
return [...active.root.querySelectorAll<HTMLElement>(`[data-ws-part="${component.selectorPart}"]`)].filter((element) => {
|
||||
if (component.controlKind && element.dataset.wsControlKind !== component.controlKind) return false;
|
||||
if (!canEditSkinLayoutComponent(id, active.page, ancestorComponentIds(element, active.root))) return false;
|
||||
return Boolean(element.getClientRects().length) && element.dataset.wsLayoutHidden !== "true";
|
||||
});
|
||||
}
|
||||
|
||||
function offsetBounds(axis: "x" | "y"): SkinLayoutOffsetBounds | null {
|
||||
const active = context.value;
|
||||
const id = selectedComponentId.value;
|
||||
if (!active || !id) return null;
|
||||
const targets = componentTargets(active, id).map((element) => element.getBoundingClientRect());
|
||||
if (!targets.length) return null;
|
||||
const currentOffset = selectedPlacement.value[axis] ?? 0;
|
||||
return getSkinLayoutOffsetBounds(targets, active.root.getBoundingClientRect(), currentOffset, axis)
|
||||
?? { minimum: 0, maximum: 0 };
|
||||
}
|
||||
|
||||
const positionBoundsX = computed(() => {
|
||||
revision.value;
|
||||
return offsetBounds("x") ?? { minimum: -2000, maximum: 2000 };
|
||||
});
|
||||
const positionBoundsY = computed(() => {
|
||||
revision.value;
|
||||
return offsetBounds("y") ?? { minimum: -2000, maximum: 2000 };
|
||||
});
|
||||
|
||||
const detectedLayoutWarnings = computed(() => {
|
||||
revision.value;
|
||||
const active = context.value;
|
||||
const id = selectedComponentId.value;
|
||||
const placement = selectedPlacement.value;
|
||||
if (!active || !id || placement.visible === false
|
||||
|| ![placement.x, placement.y, placement.width, placement.height, placement.scale].some((value) => value !== undefined)) return [];
|
||||
const targets = componentTargets(active, id);
|
||||
if (!targets.length) return [];
|
||||
const targetSet = new Set(targets);
|
||||
const peers = [...active.root.querySelectorAll<HTMLElement>("[data-ws-part]")].filter((peer) => {
|
||||
if (targetSet.has(peer) || !peer.getClientRects().length) return false;
|
||||
const peerId = componentIdForElement(peer);
|
||||
if (!peerId) return false;
|
||||
return targets.every((target) => !peer.contains(target) && !target.contains(peer));
|
||||
}).map((peer) => peer.getBoundingClientRect());
|
||||
const issues = analyzeSkinLayoutGeometry(
|
||||
targets.map((element) => element.getBoundingClientRect()),
|
||||
active.root.getBoundingClientRect(),
|
||||
peers,
|
||||
);
|
||||
const warnings: string[] = [];
|
||||
if (issues.overflow) warnings.push(labels.value.overflowWarning);
|
||||
if (issues.overlap) warnings.push(labels.value.overlapWarning);
|
||||
return warnings;
|
||||
});
|
||||
|
||||
function currentWarningKey(): string {
|
||||
const active = context.value;
|
||||
return active ? [active.skinId, active.page, active.profile, selectedComponentId.value, JSON.stringify(selectedPlacement.value)].join(":") : "";
|
||||
}
|
||||
|
||||
const layoutWarnings = computed(() => ignoredWarningKey.value === currentWarningKey() ? [] : detectedLayoutWarnings.value);
|
||||
|
||||
function ignoreLayoutWarnings(): void {
|
||||
if (layoutWarnings.value.length) ignoredWarningKey.value = currentWarningKey();
|
||||
}
|
||||
|
||||
function reviseLayout(): void {
|
||||
revision.value += 1;
|
||||
if (typeof window === "undefined" || geometryRefreshQueued) return;
|
||||
geometryRefreshQueued = true;
|
||||
void nextTick(() => {
|
||||
if (!geometryRefreshQueued) return;
|
||||
geometryRefreshFrame = window.requestAnimationFrame(() => {
|
||||
geometryRefreshFrame = 0;
|
||||
geometryRefreshQueued = false;
|
||||
revision.value += 1;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function syncContext(): void {
|
||||
const next = getActiveSkinLayoutContext();
|
||||
const key = next ? [next.skinId, next.page, next.profile, next.root.lang].join(":") : "";
|
||||
if (key === contextKey) return;
|
||||
contextKey = key;
|
||||
context.value = next;
|
||||
history = next ? [getActiveSkinLayoutOverrides()] : [];
|
||||
historyIndex = history.length ? 0 : -1;
|
||||
lastHistoryChangeAt = 0;
|
||||
updateHistoryControls();
|
||||
const first = next ? getSkinLayoutComponents(next.page).find((component) => component.editable)?.id ?? "" : "";
|
||||
if (!next || !getSkinLayoutComponent(selectedComponentId.value, next.page)?.editable) selectedComponentId.value = first;
|
||||
reviseLayout();
|
||||
setSkinLayoutEditorState(isEditing.value, selectedComponentId.value || null);
|
||||
}
|
||||
|
||||
function scheduleViewportRefresh(): void {
|
||||
if (viewportRefreshFrame) window.cancelAnimationFrame(viewportRefreshFrame);
|
||||
viewportRefreshFrame = window.requestAnimationFrame(() => {
|
||||
viewportRefreshFrame = 0;
|
||||
const previousRevision = revision.value;
|
||||
syncContext();
|
||||
if (revision.value === previousRevision) revision.value += 1;
|
||||
});
|
||||
}
|
||||
|
||||
function selectComponent(id: string): void {
|
||||
if (!context.value || !getSkinLayoutComponent(id, context.value.page)?.editable) return;
|
||||
selectedComponentId.value = id;
|
||||
reviseLayout();
|
||||
setSkinLayoutEditorState(isEditing.value, id);
|
||||
}
|
||||
|
||||
function setEditing(value: boolean): void {
|
||||
isEditing.value = value;
|
||||
setSkinLayoutEditorState(value, value ? selectedComponentId.value || null : null);
|
||||
}
|
||||
|
||||
function setFocusPreview(value: boolean): void {
|
||||
focusPreviewEnabled.value = value;
|
||||
reviseLayout();
|
||||
}
|
||||
|
||||
function setOpen(value: boolean): void {
|
||||
isOpen.value = value;
|
||||
statusMessage.value = "";
|
||||
if (!value) setEditing(false);
|
||||
}
|
||||
|
||||
function updateSelected(field: keyof SkinLayoutPlacement, value: boolean | number | string): void {
|
||||
if (!selectedComponentId.value) return;
|
||||
ignoredWarningKey.value = "";
|
||||
const local = getActiveSkinLayoutOverride(selectedComponentId.value) ?? {};
|
||||
const next = { ...local, [field]: value } as SkinLayoutPlacement;
|
||||
try {
|
||||
saveActiveSkinLayoutPlacement(selectedComponentId.value, next);
|
||||
recordHistory();
|
||||
statusMessage.value = "";
|
||||
} catch {
|
||||
statusMessage.value = labels.value.saveFailed;
|
||||
return;
|
||||
}
|
||||
reviseLayout();
|
||||
}
|
||||
|
||||
function setVisible(value: boolean): void { updateSelected("visible", value); }
|
||||
function setX(value: number): void { updateSelected("x", clampSkinLayoutOffset(value, offsetBounds("x") ?? { minimum: -2000, maximum: 2000 })); }
|
||||
function setY(value: number): void { updateSelected("y", clampSkinLayoutOffset(value, offsetBounds("y") ?? { minimum: -2000, maximum: 2000 })); }
|
||||
function setScale(value: number): void { updateSelected("scale", Math.max(selectedSizeBounds.value.minScale, Math.min(selectedSizeBounds.value.maxScale, value))); }
|
||||
function setWidth(value: number): void { updateSelected("width", Math.max(selectedSizeBounds.value.minWidth, Math.min(selectedSizeBounds.value.maxWidth, Math.round(value)))); }
|
||||
function setHeight(value: number): void { updateSelected("height", Math.max(selectedSizeBounds.value.minHeight, Math.min(selectedSizeBounds.value.maxHeight, Math.round(value)))); }
|
||||
function setForeground(value: string): void { updateSelected("foreground", value); }
|
||||
function setBackground(value: string): void { updateSelected("background", value); }
|
||||
function setBorder(value: string): void { updateSelected("border", value); }
|
||||
function setRadius(value: number): void { updateSelected("radius", Math.max(0, Math.min(64, value))); }
|
||||
|
||||
function resetComponent(): void {
|
||||
if (!selectedComponentId.value) return;
|
||||
try {
|
||||
saveActiveSkinLayoutPlacement(selectedComponentId.value, null);
|
||||
recordHistory(true);
|
||||
statusMessage.value = "";
|
||||
} catch {
|
||||
statusMessage.value = labels.value.saveFailed;
|
||||
return;
|
||||
}
|
||||
reviseLayout();
|
||||
}
|
||||
|
||||
function resetAll(): void {
|
||||
try {
|
||||
clearActiveSkinLayoutOverrides();
|
||||
statusMessage.value = "";
|
||||
recordHistory(true);
|
||||
} catch { statusMessage.value = labels.value.saveFailed; }
|
||||
reviseLayout();
|
||||
}
|
||||
|
||||
function updateHistoryControls(): void {
|
||||
canUndo.value = historyIndex > 0;
|
||||
canRedo.value = historyIndex >= 0 && historyIndex < history.length - 1;
|
||||
}
|
||||
|
||||
function copyLayout(layout: SkinLayoutDocument): SkinLayoutDocument {
|
||||
return JSON.parse(JSON.stringify(layout)) as SkinLayoutDocument;
|
||||
}
|
||||
|
||||
function recordHistory(forceNew = false): void {
|
||||
if (!context.value) return;
|
||||
const next = copyLayout(getActiveSkinLayoutOverrides());
|
||||
const now = Date.now();
|
||||
if (historyIndex < 0) {
|
||||
history = [next];
|
||||
historyIndex = 0;
|
||||
} else {
|
||||
history = history.slice(0, historyIndex + 1);
|
||||
if (!forceNew && historyIndex > 0 && now - lastHistoryChangeAt < 500) history[historyIndex] = next;
|
||||
else {
|
||||
history.push(next);
|
||||
historyIndex += 1;
|
||||
}
|
||||
if (history.length > 50) {
|
||||
history.shift();
|
||||
historyIndex -= 1;
|
||||
}
|
||||
}
|
||||
lastHistoryChangeAt = now;
|
||||
updateHistoryControls();
|
||||
}
|
||||
|
||||
function undo(): void {
|
||||
if (historyIndex <= 0) return;
|
||||
const targetIndex = historyIndex - 1;
|
||||
try {
|
||||
replaceActiveSkinLayoutOverrides(copyLayout(history[targetIndex]));
|
||||
historyIndex = targetIndex;
|
||||
lastHistoryChangeAt = 0;
|
||||
statusMessage.value = "";
|
||||
reviseLayout();
|
||||
} catch { statusMessage.value = labels.value.saveFailed; }
|
||||
updateHistoryControls();
|
||||
}
|
||||
|
||||
function redo(): void {
|
||||
if (historyIndex < 0 || historyIndex >= history.length - 1) return;
|
||||
const targetIndex = historyIndex + 1;
|
||||
try {
|
||||
replaceActiveSkinLayoutOverrides(copyLayout(history[targetIndex]));
|
||||
historyIndex = targetIndex;
|
||||
lastHistoryChangeAt = 0;
|
||||
statusMessage.value = "";
|
||||
reviseLayout();
|
||||
} catch { statusMessage.value = labels.value.saveFailed; }
|
||||
updateHistoryControls();
|
||||
}
|
||||
|
||||
function exportCurrent(): void {
|
||||
if (!context.value) return;
|
||||
const blob = new Blob([exportSkinLayout(getActiveSkinLayoutOverrides())], { type: "application/json" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = "webspeak-layout-" + context.value.skinId.replace(/[^a-z0-9.-]/g, "-") + ".json";
|
||||
anchor.click();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 30_000);
|
||||
}
|
||||
|
||||
function exportRecovery(): void {
|
||||
const skinId = context.value?.skinId;
|
||||
if (!skinId || !migrationRecovery.value) return;
|
||||
const blob = new Blob([exportSkinLayoutMigrationRecovery(skinId)], { type: "application/json" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = "webspeak-layout-recovery-" + skinId.replace(/[^a-z0-9.-]/g, "-") + ".json";
|
||||
anchor.click();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 30_000);
|
||||
}
|
||||
|
||||
async function importFile(file: File | undefined): Promise<void> {
|
||||
if (!file) return;
|
||||
if (file.size > 128 * 1024) {
|
||||
statusMessage.value = labels.value.importFailed;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
replaceActiveSkinLayoutOverrides(importSkinLayout(await file.text()));
|
||||
recordHistory(true);
|
||||
statusMessage.value = labels.value.imported;
|
||||
reviseLayout();
|
||||
} catch {
|
||||
statusMessage.value = labels.value.importFailed;
|
||||
}
|
||||
}
|
||||
|
||||
function startDrag(event: PointerEvent): void {
|
||||
if (!isEditing.value || !context.value || !(event.target instanceof Element)) return;
|
||||
if (event.target.closest("[data-ws-layout-editor]")) return;
|
||||
const root = event.target.closest<HTMLElement>(".ws-skin-root[data-ws-page]");
|
||||
if (!root || root !== context.value.root) return;
|
||||
const element = event.target.closest<HTMLElement>("[data-ws-part]");
|
||||
if (!element || !root.contains(element)) return;
|
||||
const id = componentIdForElement(element);
|
||||
const ancestors: string[] = [];
|
||||
let ancestor = element.parentElement;
|
||||
while (ancestor && ancestor !== root) {
|
||||
const ancestorId = componentIdForElement(ancestor);
|
||||
if (ancestorId) ancestors.push(ancestorId);
|
||||
ancestor = ancestor.parentElement;
|
||||
}
|
||||
if (!id || !canEditSkinLayoutComponent(id, context.value.page, ancestors)) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
event.stopImmediatePropagation();
|
||||
selectComponent(id);
|
||||
const placement = getEffectiveSkinLayoutPlacement(id) ?? {};
|
||||
drag = {
|
||||
pointerId: event.pointerId,
|
||||
componentId: id,
|
||||
startX: event.clientX,
|
||||
startY: event.clientY,
|
||||
originX: placement.x ?? 0,
|
||||
originY: placement.y ?? 0,
|
||||
placement,
|
||||
changed: false,
|
||||
};
|
||||
}
|
||||
|
||||
function moveDrag(event: PointerEvent): void {
|
||||
if (!drag || event.pointerId !== drag.pointerId) return;
|
||||
ignoredWarningKey.value = "";
|
||||
const xBounds = offsetBounds("x");
|
||||
const yBounds = offsetBounds("y");
|
||||
const x = clampSkinLayoutOffset(drag.originX + event.clientX - drag.startX, xBounds ?? { minimum: -2000, maximum: 2000 });
|
||||
const y = clampSkinLayoutOffset(drag.originY + event.clientY - drag.startY, yBounds ?? { minimum: -2000, maximum: 2000 });
|
||||
if (x === drag.originX && y === drag.originY) return;
|
||||
drag.changed = true;
|
||||
drag.placement = { ...drag.placement, x, y };
|
||||
previewActiveSkinLayoutPlacement(drag.componentId, drag.placement);
|
||||
reviseLayout();
|
||||
}
|
||||
|
||||
function endDrag(event: PointerEvent): void {
|
||||
if (!drag || event.pointerId !== drag.pointerId) return;
|
||||
const finished = drag;
|
||||
drag = null;
|
||||
if (finished.changed) {
|
||||
const local = getActiveSkinLayoutOverride(finished.componentId) ?? {};
|
||||
try {
|
||||
saveActiveSkinLayoutPlacement(finished.componentId, {
|
||||
...local,
|
||||
x: finished.placement.x,
|
||||
y: finished.placement.y,
|
||||
});
|
||||
recordHistory(true);
|
||||
} catch {
|
||||
statusMessage.value = labels.value.saveFailed;
|
||||
previewActiveSkinLayoutPlacement(finished.componentId, null);
|
||||
}
|
||||
} else {
|
||||
previewActiveSkinLayoutPlacement(finished.componentId, null);
|
||||
}
|
||||
reviseLayout();
|
||||
}
|
||||
|
||||
function cancelDrag(): void {
|
||||
if (!drag) return;
|
||||
previewActiveSkinLayoutPlacement(drag.componentId, null);
|
||||
drag = null;
|
||||
refreshSkinLayout();
|
||||
reviseLayout();
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
if (!isOpen.value || !isEditing.value || !(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "z") return;
|
||||
if (event.target instanceof HTMLElement && /^(INPUT|TEXTAREA|SELECT)$/.test(event.target.tagName)) return;
|
||||
event.preventDefault();
|
||||
if (event.shiftKey) redo();
|
||||
else undo();
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
initializeSkinLayoutRuntime();
|
||||
syncContext();
|
||||
observer = new MutationObserver(() => {
|
||||
syncContext();
|
||||
if (focusPreviewEnabled.value) revision.value += 1;
|
||||
});
|
||||
observer.observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
characterData: true,
|
||||
attributes: true,
|
||||
attributeFilter: ["data-ws-page", "data-ws-skin", "lang", "tabindex", "disabled", "href", "aria-label", "aria-labelledby", "title", "placeholder", "hidden", "inert", "aria-hidden", "class", "style"],
|
||||
});
|
||||
document.addEventListener("pointerdown", startDrag, true);
|
||||
document.addEventListener("pointermove", moveDrag, true);
|
||||
document.addEventListener("pointerup", endDrag, true);
|
||||
document.addEventListener("pointercancel", endDrag, true);
|
||||
document.addEventListener("keydown", onKeydown);
|
||||
document.addEventListener("change", onFocusStateChange, true);
|
||||
document.addEventListener("input", onFocusStateChange, true);
|
||||
window.addEventListener("blur", cancelDrag);
|
||||
window.addEventListener("resize", scheduleViewportRefresh, { passive: true });
|
||||
window.addEventListener("scroll", scheduleViewportRefresh, { capture: true, passive: true });
|
||||
});
|
||||
|
||||
function onFocusStateChange(): void {
|
||||
if (focusPreviewEnabled.value) revision.value += 1;
|
||||
}
|
||||
|
||||
onUnmounted(() => {
|
||||
observer?.disconnect();
|
||||
document.removeEventListener("pointerdown", startDrag, true);
|
||||
document.removeEventListener("pointermove", moveDrag, true);
|
||||
document.removeEventListener("pointerup", endDrag, true);
|
||||
document.removeEventListener("pointercancel", endDrag, true);
|
||||
document.removeEventListener("keydown", onKeydown);
|
||||
document.removeEventListener("change", onFocusStateChange, true);
|
||||
document.removeEventListener("input", onFocusStateChange, true);
|
||||
window.removeEventListener("blur", cancelDrag);
|
||||
window.removeEventListener("resize", scheduleViewportRefresh);
|
||||
window.removeEventListener("scroll", scheduleViewportRefresh, true);
|
||||
if (viewportRefreshFrame) window.cancelAnimationFrame(viewportRefreshFrame);
|
||||
if (geometryRefreshFrame) window.cancelAnimationFrame(geometryRefreshFrame);
|
||||
geometryRefreshQueued = false;
|
||||
setSkinLayoutEditorState(false, null);
|
||||
});
|
||||
|
||||
return {
|
||||
isOpen,
|
||||
isEditing,
|
||||
available,
|
||||
context,
|
||||
labels,
|
||||
filter,
|
||||
filteredComponents,
|
||||
selectedComponentId,
|
||||
selectedPlacement,
|
||||
selectedVisible,
|
||||
selectedScale,
|
||||
selectedWidth,
|
||||
selectedHeight,
|
||||
canUndo,
|
||||
canRedo,
|
||||
focusPreviewEnabled,
|
||||
focusPreviewTargets,
|
||||
selectedX,
|
||||
selectedY,
|
||||
selectedForeground,
|
||||
selectedBackground,
|
||||
selectedBorder,
|
||||
selectedRadius,
|
||||
selectedSizeBounds,
|
||||
positionBoundsX,
|
||||
positionBoundsY,
|
||||
statusMessage,
|
||||
layoutWarnings,
|
||||
ignoreLayoutWarnings,
|
||||
migrationRecovery,
|
||||
migrationRecoveryCount,
|
||||
setOpen,
|
||||
setEditing,
|
||||
setFocusPreview,
|
||||
selectComponent,
|
||||
setVisible,
|
||||
setX,
|
||||
setY,
|
||||
setScale,
|
||||
setWidth,
|
||||
setHeight,
|
||||
setForeground,
|
||||
setBackground,
|
||||
setBorder,
|
||||
setRadius,
|
||||
resetComponent,
|
||||
resetAll,
|
||||
undo,
|
||||
redo,
|
||||
exportCurrent,
|
||||
exportRecovery,
|
||||
importFile,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import type { Language } from "./web-client.js";
|
||||
|
||||
type SkinLayoutLabels = {
|
||||
editButton: string;
|
||||
title: string;
|
||||
hint: string;
|
||||
component: string;
|
||||
filter: string;
|
||||
visible: string;
|
||||
positionX: string;
|
||||
positionY: string;
|
||||
size: string;
|
||||
width: string;
|
||||
height: string;
|
||||
foreground: string;
|
||||
background: string;
|
||||
border: string;
|
||||
radius: string;
|
||||
resetItem: string;
|
||||
resetAll: string;
|
||||
export: string;
|
||||
import: string;
|
||||
close: string;
|
||||
editMode: string;
|
||||
focusPreview: string;
|
||||
focusPreviewEmpty: string;
|
||||
focusPreviewUnnamed: string;
|
||||
focusPreviewTargetSize: string;
|
||||
focusPreviewTargetAdequate: string;
|
||||
focusPreviewTargetSmall: string;
|
||||
skinLoadError: (skinId: string) => string;
|
||||
skinUseBuiltIn: string;
|
||||
undo: string;
|
||||
redo: string;
|
||||
saveFailed: string;
|
||||
overlapWarning: string;
|
||||
overflowWarning: string;
|
||||
ignoreWarnings: string;
|
||||
imported: string;
|
||||
importFailed: string;
|
||||
migrationWarning: (count: number) => string;
|
||||
exportRecovery: string;
|
||||
};
|
||||
|
||||
export const skinLayoutLabels: Record<Language, SkinLayoutLabels> = {
|
||||
zh: {
|
||||
editButton: "布局",
|
||||
title: "自定义页面布局",
|
||||
hint: "打开编辑模式后,直接拖动页面组件调整位置。布局只保存在此浏览器。",
|
||||
component: "当前组件",
|
||||
filter: "搜索组件 ID",
|
||||
visible: "显示此组件",
|
||||
positionX: "水平偏移",
|
||||
positionY: "垂直偏移",
|
||||
size: "缩放",
|
||||
width: "宽度",
|
||||
height: "高度",
|
||||
foreground: "文字颜色",
|
||||
background: "背景颜色",
|
||||
border: "边框颜色",
|
||||
radius: "圆角",
|
||||
resetItem: "重置此组件",
|
||||
resetAll: "重置当前皮肤布局",
|
||||
export: "导出",
|
||||
import: "导入",
|
||||
close: "关闭",
|
||||
editMode: "拖动组件",
|
||||
focusPreview: "预览键盘顺序与触屏命中范围",
|
||||
focusPreviewEmpty: "当前页面没有可见的键盘焦点控件。",
|
||||
focusPreviewUnnamed: "未命名控件",
|
||||
focusPreviewTargetSize: "实际区域 {width} × {height} px",
|
||||
focusPreviewTargetAdequate: "触控范围符合 44 × 44 px",
|
||||
focusPreviewTargetSmall: "触控范围小于 44 × 44 px",
|
||||
skinLoadError: (skinId) => `皮肤“${skinId}”加载失败,已返回默认界面。你可以停用此选择并记住内置皮肤。`,
|
||||
skinUseBuiltIn: "停用此选择并记住内置皮肤",
|
||||
undo: "撤销",
|
||||
redo: "重做",
|
||||
saveFailed: "浏览器存储不可用,布局更改未保存",
|
||||
overlapWarning: "此位置可能与其他组件重叠。",
|
||||
overflowWarning: "此组件超出页面布局区域。",
|
||||
ignoreWarnings: "忽略当前提示",
|
||||
imported: "布局已导入",
|
||||
importFailed: "布局文件无效或与当前组件不兼容",
|
||||
migrationWarning: (count) => `已升级旧布局;${count} 项无法自动应用,旧数据已保留供恢复。`,
|
||||
exportRecovery: "导出旧布局数据",
|
||||
},
|
||||
en: {
|
||||
editButton: "Layout",
|
||||
title: "Customize page layout",
|
||||
hint: "Enable editing and drag page components to reposition them. Changes stay in this browser.",
|
||||
component: "Selected component",
|
||||
filter: "Search component ID",
|
||||
visible: "Show this component",
|
||||
positionX: "Horizontal offset",
|
||||
positionY: "Vertical offset",
|
||||
size: "Scale",
|
||||
width: "Width",
|
||||
height: "Height",
|
||||
foreground: "Text color",
|
||||
background: "Background",
|
||||
border: "Border color",
|
||||
radius: "Corner radius",
|
||||
resetItem: "Reset component",
|
||||
resetAll: "Reset this skin layout",
|
||||
export: "Export",
|
||||
import: "Import",
|
||||
close: "Close",
|
||||
editMode: "Move components",
|
||||
focusPreview: "Preview keyboard order and touch targets",
|
||||
focusPreviewEmpty: "No visible keyboard-focusable controls on this page.",
|
||||
focusPreviewUnnamed: "Unnamed control",
|
||||
focusPreviewTargetSize: "Actual area {width} × {height} px",
|
||||
focusPreviewTargetAdequate: "Touch target meets 44 × 44 px",
|
||||
focusPreviewTargetSmall: "Touch target is smaller than 44 × 44 px",
|
||||
skinLoadError: (skinId) => `Skin “${skinId}” failed to load and the built-in interface was restored. You can stop selecting it and remember a built-in skin.`,
|
||||
skinUseBuiltIn: "Stop selecting this skin and remember a built-in skin",
|
||||
undo: "Undo",
|
||||
redo: "Redo",
|
||||
saveFailed: "Browser storage is unavailable; the layout change was not saved",
|
||||
overlapWarning: "This position may overlap another component.",
|
||||
overflowWarning: "This component extends beyond the page layout area.",
|
||||
ignoreWarnings: "Ignore these hints for this layout",
|
||||
imported: "Layout imported",
|
||||
importFailed: "The layout file is invalid or incompatible with this client",
|
||||
migrationWarning: (count) => `The old layout was upgraded; ${count} item(s) could not be applied and were kept for recovery.`,
|
||||
exportRecovery: "Export old layout data",
|
||||
},
|
||||
de: {
|
||||
editButton: "Layout",
|
||||
title: "Seitenlayout anpassen",
|
||||
hint: "Aktiviere den Bearbeitungsmodus und ziehe Komponenten an ihre neue Position. Änderungen bleiben in diesem Browser.",
|
||||
component: "Ausgewählte Komponente",
|
||||
filter: "Komponenten-ID suchen",
|
||||
visible: "Komponente anzeigen",
|
||||
positionX: "Horizontaler Versatz",
|
||||
positionY: "Vertikaler Versatz",
|
||||
size: "Skalierung",
|
||||
width: "Breite",
|
||||
height: "Höhe",
|
||||
foreground: "Textfarbe",
|
||||
background: "Hintergrund",
|
||||
border: "Rahmenfarbe",
|
||||
radius: "Eckenradius",
|
||||
resetItem: "Komponente zurücksetzen",
|
||||
resetAll: "Skin-Layout zurücksetzen",
|
||||
export: "Exportieren",
|
||||
import: "Importieren",
|
||||
close: "Schließen",
|
||||
editMode: "Komponenten verschieben",
|
||||
focusPreview: "Tastaturreihenfolge und Touch-Ziele anzeigen",
|
||||
focusPreviewEmpty: "Auf dieser Seite sind keine sichtbaren Tastaturziele.",
|
||||
focusPreviewUnnamed: "Unbenanntes Steuerelement",
|
||||
focusPreviewTargetSize: "Tatsächliche Fläche {width} × {height} px",
|
||||
focusPreviewTargetAdequate: "Touch-Ziel erfüllt 44 × 44 px",
|
||||
focusPreviewTargetSmall: "Touch-Ziel kleiner als 44 × 44 px",
|
||||
skinLoadError: (skinId) => `Skin „${skinId}“ konnte nicht geladen werden; die integrierte Oberfläche wurde wiederhergestellt. Du kannst diese Auswahl beenden und einen integrierten Skin speichern.`,
|
||||
skinUseBuiltIn: "Diesen Skin nicht mehr auswählen",
|
||||
undo: "Rückgängig",
|
||||
redo: "Wiederholen",
|
||||
saveFailed: "Der Browserspeicher ist nicht verfügbar; die Änderung wurde nicht gespeichert",
|
||||
overlapWarning: "Diese Position kann eine andere Komponente überdecken.",
|
||||
overflowWarning: "Diese Komponente liegt außerhalb des Seitenlayouts.",
|
||||
ignoreWarnings: "Diese Hinweise für dieses Layout ausblenden",
|
||||
imported: "Layout importiert",
|
||||
importFailed: "Die Layoutdatei ist ungültig oder inkompatibel",
|
||||
migrationWarning: (count) => `Das alte Layout wurde aktualisiert; ${count} Einträge konnten nicht übernommen werden und bleiben zur Wiederherstellung erhalten.`,
|
||||
exportRecovery: "Alte Layoutdaten exportieren",
|
||||
},
|
||||
ru: {
|
||||
editButton: "Макет",
|
||||
title: "Настройка макета",
|
||||
hint: "Включите режим редактирования и перетаскивайте компоненты. Изменения сохраняются в этом браузере.",
|
||||
component: "Выбранный компонент",
|
||||
filter: "Поиск ID компонента",
|
||||
visible: "Показывать компонент",
|
||||
positionX: "Смещение по горизонтали",
|
||||
positionY: "Смещение по вертикали",
|
||||
size: "Масштаб",
|
||||
width: "Ширина",
|
||||
height: "Высота",
|
||||
foreground: "Цвет текста",
|
||||
background: "Фон",
|
||||
border: "Цвет границы",
|
||||
radius: "Радиус угла",
|
||||
resetItem: "Сбросить компонент",
|
||||
resetAll: "Сбросить макет скина",
|
||||
export: "Экспорт",
|
||||
import: "Импорт",
|
||||
close: "Закрыть",
|
||||
editMode: "Перемещать компоненты",
|
||||
focusPreview: "Показать порядок клавиатуры и сенсорные цели",
|
||||
focusPreviewEmpty: "На странице нет видимых элементов клавиатурной навигации.",
|
||||
focusPreviewUnnamed: "Элемент без названия",
|
||||
focusPreviewTargetSize: "Фактическая область {width} × {height} px",
|
||||
focusPreviewTargetAdequate: "Сенсорная цель соответствует 44 × 44 px",
|
||||
focusPreviewTargetSmall: "Сенсорная цель меньше 44 × 44 px",
|
||||
skinLoadError: (skinId) => `Не удалось загрузить тему «${skinId}»; восстановлен встроенный интерфейс. Можно отказаться от неё и сохранить встроенную тему.`,
|
||||
skinUseBuiltIn: "Больше не выбирать эту тему",
|
||||
undo: "Отменить",
|
||||
redo: "Повторить",
|
||||
saveFailed: "Хранилище браузера недоступно; изменение не сохранено",
|
||||
overlapWarning: "Компонент может перекрывать другой компонент.",
|
||||
overflowWarning: "Компонент выходит за пределы области страницы.",
|
||||
ignoreWarnings: "Скрыть эти подсказки для этой раскладки",
|
||||
imported: "Макет импортирован",
|
||||
importFailed: "Файл макета недействителен или несовместим",
|
||||
migrationWarning: (count) => `Старая раскладка обновлена; ${count} элементов не применено, исходные данные сохранены для восстановления.`,
|
||||
exportRecovery: "Экспортировать старые данные",
|
||||
},
|
||||
ja: {
|
||||
editButton: "レイアウト",
|
||||
title: "ページレイアウトをカスタマイズ",
|
||||
hint: "編集を有効にして、コンポーネントをドラッグして配置します。設定はこのブラウザーに保存されます。",
|
||||
component: "選択中のコンポーネント",
|
||||
filter: "コンポーネント ID を検索",
|
||||
visible: "このコンポーネントを表示",
|
||||
positionX: "横方向の移動",
|
||||
positionY: "縦方向の移動",
|
||||
size: "拡大縮小",
|
||||
width: "幅",
|
||||
height: "高さ",
|
||||
foreground: "文字色",
|
||||
background: "背景色",
|
||||
border: "枠線の色",
|
||||
radius: "角丸",
|
||||
resetItem: "コンポーネントをリセット",
|
||||
resetAll: "このスキンのレイアウトをリセット",
|
||||
export: "エクスポート",
|
||||
import: "インポート",
|
||||
close: "閉じる",
|
||||
editMode: "コンポーネントを移動",
|
||||
focusPreview: "キーボード順序とタッチ領域を表示",
|
||||
focusPreviewEmpty: "このページに表示中のキーボード操作対象はありません。",
|
||||
focusPreviewUnnamed: "名前のないコントロール",
|
||||
focusPreviewTargetSize: "実際の領域 {width} × {height} px",
|
||||
focusPreviewTargetAdequate: "タッチ領域は 44 × 44 px 以上です",
|
||||
focusPreviewTargetSmall: "タッチ領域が 44 × 44 px 未満です",
|
||||
skinLoadError: (skinId) => `スキン「${skinId}」を読み込めず、標準の画面に戻しました。このスキンを使わず、標準スキンを保存できます。`,
|
||||
skinUseBuiltIn: "このスキンを使わず標準スキンを保存",
|
||||
undo: "元に戻す",
|
||||
redo: "やり直す",
|
||||
saveFailed: "ブラウザーのストレージを利用できないため、変更を保存できませんでした",
|
||||
overlapWarning: "この位置では、ほかのコンポーネントと重なる可能性があります。",
|
||||
overflowWarning: "コンポーネントがページ領域からはみ出しています。",
|
||||
ignoreWarnings: "このレイアウトのヒントを無視",
|
||||
imported: "レイアウトをインポートしました",
|
||||
importFailed: "レイアウトファイルが無効か、このクライアントと互換性がありません",
|
||||
migrationWarning: (count) => `旧レイアウトを更新しました。${count} 件は適用できず、復元用にデータを保存しました。`,
|
||||
exportRecovery: "旧レイアウトデータをエクスポート",
|
||||
},
|
||||
};
|
||||
|
||||
export function resolveSkinLayoutLanguage(value: string | undefined): Language {
|
||||
return value === "en" || value === "de" || value === "ru" || value === "ja" ? value : "zh";
|
||||
}
|
||||
@@ -32,7 +32,7 @@ export const BUILTIN_SKIN_CATALOG: SkinCatalogEntry[] = [
|
||||
{
|
||||
id: BUILTIN_ILLUSIA_SKIN_ID,
|
||||
name: "ILLUSIA风",
|
||||
version: "1.0.28",
|
||||
version: "1.0.29",
|
||||
author: "WebSpeak Project",
|
||||
license: "All rights reserved",
|
||||
description: "A bright original-character art skin for the home, voice room, and demo pages.",
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
createSkinExtensionApproval,
|
||||
getSkinExtensionUpgradeConsentDelta,
|
||||
isSkinExtensionBootstrapHello,
|
||||
isSkinExtensionPermissionApproved,
|
||||
parseSkinExtensionApproval,
|
||||
parseSkinExtensionManifest,
|
||||
parseSkinExtensionRequestMessage,
|
||||
sanitizeSkinExtensionSessionStatus,
|
||||
SKIN_EXTENSION_MESSAGE_CHANNEL,
|
||||
type SkinExtensionManifest,
|
||||
} from "../../../src/shared/skin-extension.js";
|
||||
import {
|
||||
createSkinExtensionSandboxPrototype,
|
||||
SKIN_EXTENSION_RUNTIME_ENABLED,
|
||||
SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT,
|
||||
SKIN_EXTENSION_SANDBOX_REQUESTS_PER_SECOND,
|
||||
SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT,
|
||||
SkinExtensionSandboxError,
|
||||
} from "./skin-extension-sandbox.js";
|
||||
|
||||
function manifest(overrides: Record<string, unknown> = {}) {
|
||||
return parseSkinExtensionManifest({
|
||||
schemaVersion: 1,
|
||||
packageType: "extension",
|
||||
id: "community.status-card",
|
||||
name: "Status card",
|
||||
version: "1.0.0",
|
||||
apiVersion: 1,
|
||||
permissions: ["session.status.read"],
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
test("extension manifests use a separate strict schema and reject unknown capabilities", () => {
|
||||
const parsed = manifest();
|
||||
assert.equal(parsed.packageType, "extension");
|
||||
assert.deepEqual(parsed.permissions, ["session.status.read"]);
|
||||
assert.throws(() => manifest({ unexpected: true }), { code: "SKIN_EXTENSION_UNKNOWN_FIELD" });
|
||||
assert.throws(() => manifest({ permissions: ["filesystem.read"] }), { code: "SKIN_EXTENSION_PERMISSION_UNKNOWN" });
|
||||
assert.throws(() => manifest({ permissions: ["session.status.read", "session.status.read"] }), { code: "SKIN_EXTENSION_PERMISSION_DUPLICATE" });
|
||||
assert.throws(() => manifest({ version: "latest" }), { code: "SKIN_EXTENSION_MANIFEST_INVALID" });
|
||||
assert.throws(() => manifest({ apiVersion: 2 }), { code: "SKIN_EXTENSION_API_UNSUPPORTED" });
|
||||
});
|
||||
|
||||
test("approval is host-shaped, permission-specific, and cannot be reused for another extension", () => {
|
||||
const parsed = manifest();
|
||||
const approval = createSkinExtensionApproval(parsed);
|
||||
assert.equal(isSkinExtensionPermissionApproved(approval, parsed.id, "session.status.read"), true);
|
||||
assert.equal(isSkinExtensionPermissionApproved(approval, "other.extension", "session.status.read"), false);
|
||||
assert.deepEqual(parseSkinExtensionApproval(approval), approval);
|
||||
assert.throws(() => parseSkinExtensionApproval({ ...approval, permissions: { "filesystem.read": 1 } }), { code: "SKIN_EXTENSION_APPROVAL_INVALID" });
|
||||
assert.throws(() => getSkinExtensionUpgradeConsentDelta(approval, manifest({ id: "other.extension" })), { code: "SKIN_EXTENSION_ID_CHANGED" });
|
||||
});
|
||||
|
||||
test("an extension upgrade needs new consent when it adds or changes a capability", () => {
|
||||
const approval = createSkinExtensionApproval(manifest());
|
||||
const unchanged = getSkinExtensionUpgradeConsentDelta(approval, manifest({ version: "2.0.0" }));
|
||||
assert.equal(unchanged.requiresConsent, false, "a version change alone does not silently change permission meaning");
|
||||
|
||||
const approvalWithoutPermissions = createSkinExtensionApproval(manifest({ permissions: [] }));
|
||||
const added = getSkinExtensionUpgradeConsentDelta(approvalWithoutPermissions, manifest({ version: "2.0.0" }));
|
||||
assert.deepEqual(added.addedPermissions, ["session.status.read"]);
|
||||
assert.equal(added.requiresConsent, true);
|
||||
|
||||
const removed = getSkinExtensionUpgradeConsentDelta(approval, manifest({ version: "2.0.0", permissions: [] }));
|
||||
assert.deepEqual(removed.removedPermissions, ["session.status.read"]);
|
||||
assert.equal(removed.requiresConsent, false, "removing a capability cannot expand an existing approval");
|
||||
|
||||
const outdatedApproval = { ...approval, permissions: { "session.status.read": 2 } };
|
||||
const changedMeaning = getSkinExtensionUpgradeConsentDelta(outdatedApproval, manifest({ version: "2.0.0" }));
|
||||
assert.deepEqual(changedMeaning.changedMeaningPermissions, ["session.status.read"]);
|
||||
assert.equal(changedMeaning.requiresConsent, true);
|
||||
|
||||
const changedApi = getSkinExtensionUpgradeConsentDelta({ ...approval, apiVersion: 2 }, manifest({ version: "2.0.0" }) as SkinExtensionManifest);
|
||||
assert.equal(changedApi.apiVersionChanged, true);
|
||||
assert.equal(changedApi.requiresConsent, true);
|
||||
});
|
||||
|
||||
test("bootstrap accepts only the exact opaque iframe source, nonce, origin, and transferred port", () => {
|
||||
const expectedSource = {};
|
||||
const valid = {
|
||||
source: expectedSource,
|
||||
origin: "null",
|
||||
data: { channel: SKIN_EXTENSION_MESSAGE_CHANNEL, type: "hello", apiVersion: 1, nonce: "secret" },
|
||||
ports: [{}],
|
||||
};
|
||||
assert.equal(isSkinExtensionBootstrapHello(valid, expectedSource, "secret"), true);
|
||||
assert.equal(isSkinExtensionBootstrapHello({ ...valid, source: {} }, expectedSource, "secret"), false);
|
||||
assert.equal(isSkinExtensionBootstrapHello({ ...valid, origin: "https://example.invalid" }, expectedSource, "secret"), false);
|
||||
assert.equal(isSkinExtensionBootstrapHello({ ...valid, data: { ...valid.data, nonce: "wrong" } }, expectedSource, "secret"), false);
|
||||
assert.equal(isSkinExtensionBootstrapHello({ ...valid, ports: [] }, expectedSource, "secret"), false);
|
||||
assert.equal(isSkinExtensionBootstrapHello({ ...valid, data: { ...valid.data, extra: true } }, expectedSource, "secret"), false);
|
||||
});
|
||||
|
||||
test("capability requests have a fixed envelope and empty, bounded payload", () => {
|
||||
const message = {
|
||||
channel: SKIN_EXTENSION_MESSAGE_CHANNEL,
|
||||
apiVersion: 1,
|
||||
nonce: "secret",
|
||||
id: "r1",
|
||||
type: "request",
|
||||
permission: "session.status.read",
|
||||
payload: {},
|
||||
};
|
||||
assert.deepEqual(parseSkinExtensionRequestMessage(message, "secret"), message);
|
||||
assert.equal(parseSkinExtensionRequestMessage({ ...message, nonce: "wrong" }, "secret"), null);
|
||||
assert.equal(parseSkinExtensionRequestMessage({ ...message, payload: { includePrivateChat: true } }, "secret"), null);
|
||||
assert.equal(parseSkinExtensionRequestMessage({ ...message, extra: true }, "secret"), null);
|
||||
assert.equal(parseSkinExtensionRequestMessage({ ...message, permission: "chat.private.read" }, "secret"), null);
|
||||
assert.equal(parseSkinExtensionRequestMessage({ ...message, id: "a".repeat(65) }, "secret"), null);
|
||||
});
|
||||
|
||||
test("session status copies only low-sensitivity fields and rejects invalid values", () => {
|
||||
const safe = sanitizeSkinExtensionSessionStatus({ connected: true, channelName: "Lounge\n", memberCount: 3, token: "must not escape" });
|
||||
assert.deepEqual(safe, { connected: true, channelName: "Lounge ", memberCount: 3 });
|
||||
assert.equal("token" in safe, false);
|
||||
assert.throws(() => sanitizeSkinExtensionSessionStatus({ connected: true, channelName: null, memberCount: -1 }));
|
||||
assert.throws(() => sanitizeSkinExtensionSessionStatus({ connected: "yes", channelName: null, memberCount: 0 }));
|
||||
});
|
||||
|
||||
test("JavaScript extensions stay disabled because Workers have no hard memory quota", () => {
|
||||
assert.equal(SKIN_EXTENSION_RUNTIME_ENABLED, false);
|
||||
assert.ok(SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT <= 64 * 1024);
|
||||
assert.ok(SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT <= 8 * 1024);
|
||||
assert.ok(SKIN_EXTENSION_SANDBOX_REQUESTS_PER_SECOND <= 10);
|
||||
assert.ok(new SkinExtensionSandboxError("DISABLED", "disabled") instanceof Error);
|
||||
});
|
||||
|
||||
test("the prototype rejects source beyond its fixed startup budget before creating a frame", () => {
|
||||
const parsed = manifest();
|
||||
const approval = createSkinExtensionApproval(parsed);
|
||||
assert.throws(() => createSkinExtensionSandboxPrototype({
|
||||
container: {} as HTMLElement,
|
||||
manifest: parsed,
|
||||
approval,
|
||||
source: "x".repeat(SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT + 1),
|
||||
readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }),
|
||||
prototypeOnly: true,
|
||||
}), { code: "SKIN_EXTENSION_SOURCE_TOO_LARGE" });
|
||||
});
|
||||
@@ -0,0 +1,501 @@
|
||||
import {
|
||||
isSkinExtensionBootstrapHello,
|
||||
isSkinExtensionPermissionApproved,
|
||||
parseSkinExtensionApproval,
|
||||
parseSkinExtensionManifest,
|
||||
parseSkinExtensionRequestMessage,
|
||||
sanitizeSkinExtensionSessionStatus,
|
||||
SKIN_EXTENSION_API_VERSION,
|
||||
SKIN_EXTENSION_MESSAGE_CHANNEL,
|
||||
type SkinExtensionApproval,
|
||||
type SkinExtensionManifest,
|
||||
type SkinExtensionPermissionId,
|
||||
type SkinExtensionSessionStatus,
|
||||
} from "../../../src/shared/skin-extension.js";
|
||||
|
||||
export const SKIN_EXTENSION_RUNTIME_ENABLED = false as const;
|
||||
export const SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT = 64 * 1024;
|
||||
export const SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT = 8 * 1024;
|
||||
export const SKIN_EXTENSION_SANDBOX_REQUESTS_PER_SECOND = 10;
|
||||
export const SKIN_EXTENSION_SANDBOX_MAX_REQUESTS = 10_000;
|
||||
|
||||
const HANDSHAKE_TIMEOUT_MS = 3_000;
|
||||
const SHUTDOWN_TIMEOUT_MS = 100;
|
||||
const MESSAGE_CHANNEL = SKIN_EXTENSION_MESSAGE_CHANNEL;
|
||||
|
||||
export class SkinExtensionSandboxError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
super(message);
|
||||
this.name = "SkinExtensionSandboxError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface SkinExtensionSandboxOptions {
|
||||
container: HTMLElement;
|
||||
manifest: unknown;
|
||||
approval: unknown;
|
||||
source: string;
|
||||
readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>;
|
||||
/** The only entry point is explicitly marked as a development prototype and is not wired into the application. */
|
||||
prototypeOnly: true;
|
||||
}
|
||||
|
||||
export interface SkinExtensionSandboxHandle {
|
||||
readonly frame: HTMLIFrameElement;
|
||||
readonly manifest: SkinExtensionManifest;
|
||||
readonly approval: SkinExtensionApproval;
|
||||
readonly ready: Promise<void>;
|
||||
readonly stopped: Promise<void>;
|
||||
readonly closed: boolean;
|
||||
readonly closeReason: string | null;
|
||||
readonly acceptedRequests: number;
|
||||
readonly rejectedRequests: number;
|
||||
revokePermission(permission: SkinExtensionPermissionId): void;
|
||||
close(reason?: string): void;
|
||||
}
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
const prototype = Object.getPrototypeOf(value);
|
||||
return prototype === Object.prototype || prototype === null;
|
||||
}
|
||||
|
||||
function randomNonce(view: Window): string {
|
||||
const bytes = new Uint8Array(32);
|
||||
view.crypto.getRandomValues(bytes);
|
||||
return Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
function toBase64(source: string): string {
|
||||
const bytes = new TextEncoder().encode(source);
|
||||
let binary = "";
|
||||
for (let offset = 0; offset < bytes.length; offset += 0x8000) {
|
||||
binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
function createWorkerDataUrl(source: string): string {
|
||||
const pluginModuleUrl = `data:text/javascript;base64,${toBase64(source)}`;
|
||||
const workerBootstrap = `
|
||||
const __wsPluginModuleUrl = ${JSON.stringify(pluginModuleUrl)};
|
||||
const __wsApiVersion = ${SKIN_EXTENSION_API_VERSION};
|
||||
const __wsDeniedGlobals = ["Worker", "SharedWorker", "fetch", "XMLHttpRequest", "WebSocket", "EventSource", "WebTransport", "importScripts", "indexedDB", "caches", "WebAssembly"];
|
||||
for (const __wsName of __wsDeniedGlobals) {
|
||||
try { Object.defineProperty(globalThis, __wsName, { value: undefined, writable: false, configurable: false }); } catch {}
|
||||
if (globalThis[__wsName] !== undefined) throw new Error("The worker cannot disable a restricted global.");
|
||||
}
|
||||
let __wsPort = null;
|
||||
let __wsSequence = 0;
|
||||
const __wsPending = new Map();
|
||||
self.addEventListener("message", async function __wsInitialize(event) {
|
||||
if (__wsPort || event.data?.type !== "initialize" || event.ports.length !== 1 || Object.keys(event.data).length !== 1) return;
|
||||
__wsPort = event.ports[0];
|
||||
__wsPort.onmessage = (portEvent) => {
|
||||
const response = portEvent.data;
|
||||
if (!response || typeof response !== "object" || response.type !== "response" || typeof response.id !== "string") return;
|
||||
const pending = __wsPending.get(response.id);
|
||||
if (!pending) return;
|
||||
__wsPending.delete(response.id);
|
||||
if (response.ok === true) pending.resolve(response.data);
|
||||
else pending.reject(new Error(typeof response.error?.message === "string" ? response.error.message : "Extension request denied."));
|
||||
};
|
||||
__wsPort.start();
|
||||
const api = Object.freeze({
|
||||
apiVersion: __wsApiVersion,
|
||||
request(permission, payload = {}) {
|
||||
if (!__wsPort) return Promise.reject(new Error("Extension runtime is closed."));
|
||||
if (typeof permission !== "string" || !payload || typeof payload !== "object" || Array.isArray(payload) || Object.keys(payload).length !== 0) return Promise.reject(new Error("Invalid extension request."));
|
||||
if (__wsPending.size >= 16) return Promise.reject(new Error("Too many pending extension requests."));
|
||||
const id = "r" + (++__wsSequence).toString(36);
|
||||
return new Promise((resolve, reject) => {
|
||||
__wsPending.set(id, { resolve, reject });
|
||||
__wsPort.postMessage({ type: "request", id, permission, payload: {} });
|
||||
});
|
||||
},
|
||||
});
|
||||
Object.defineProperty(globalThis, "WebSpeakExtension", { value: api, writable: false, configurable: false });
|
||||
__wsPort.postMessage({ type: "worker-ready" });
|
||||
try { await import(__wsPluginModuleUrl); }
|
||||
catch { __wsPort.postMessage({ type: "plugin-error" }); }
|
||||
});`;
|
||||
return `data:text/javascript;base64,${toBase64(workerBootstrap)}`;
|
||||
}
|
||||
|
||||
function createSandboxDocument(workerUrl: string, nonce: string): string {
|
||||
const policy = [
|
||||
"default-src 'none'",
|
||||
`script-src 'nonce-${nonce}' data:`,
|
||||
"style-src 'unsafe-inline'",
|
||||
"connect-src 'none'",
|
||||
"img-src 'none'",
|
||||
"media-src 'none'",
|
||||
"font-src 'none'",
|
||||
"object-src 'none'",
|
||||
"frame-src 'none'",
|
||||
"child-src 'none'",
|
||||
"worker-src data:",
|
||||
"manifest-src 'none'",
|
||||
"form-action 'none'",
|
||||
"base-uri 'none'",
|
||||
"navigate-to 'none'",
|
||||
].join("; ");
|
||||
|
||||
return `<!doctype html>
|
||||
<html><head><meta charset="utf-8"><meta name="referrer" content="no-referrer">
|
||||
<meta http-equiv="Content-Security-Policy" content="${policy}">
|
||||
<title>Isolated WebSpeak extension</title></head>
|
||||
<body><main id="extension-root" aria-label="Extension component"></main>
|
||||
<script nonce="${nonce}">
|
||||
(() => {
|
||||
"use strict";
|
||||
const channelName = ${JSON.stringify(MESSAGE_CHANNEL)};
|
||||
const apiVersion = ${SKIN_EXTENSION_API_VERSION};
|
||||
const nonce = ${JSON.stringify(nonce)};
|
||||
const workerUrl = ${JSON.stringify(workerUrl)};
|
||||
const parentChannel = new MessageChannel();
|
||||
const parentPort = parentChannel.port1;
|
||||
const workerChannel = new MessageChannel();
|
||||
let worker = null;
|
||||
let workerPort = workerChannel.port1;
|
||||
let started = false;
|
||||
let stopped = false;
|
||||
|
||||
function stopWorker() {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
if (worker) worker.terminate();
|
||||
if (workerPort) { workerPort.onmessage = null; workerPort.close(); }
|
||||
parentPort.postMessage({ channel: channelName, apiVersion, nonce, type: "shutdown-complete" });
|
||||
}
|
||||
|
||||
function validHostEnvelope(data) {
|
||||
return !!data && typeof data === "object" && !Array.isArray(data)
|
||||
&& data.channel === channelName && data.apiVersion === apiVersion && data.nonce === nonce;
|
||||
}
|
||||
|
||||
parentPort.onmessage = (event) => {
|
||||
const data = event.data;
|
||||
if (!validHostEnvelope(data)) return;
|
||||
if (data.type === "shutdown" && Object.keys(data).length === 4) { stopWorker(); return; }
|
||||
if (data.type === "host-ready" && Object.keys(data).length === 4 && !started) {
|
||||
started = true;
|
||||
try {
|
||||
worker = new Worker(workerUrl, { type: "module", name: "webspeak-skin-extension" });
|
||||
worker.onerror = () => parentPort.postMessage({ channel: channelName, apiVersion, nonce, type: "runtime-error" });
|
||||
workerPort.onmessage = (workerEvent) => {
|
||||
const message = workerEvent.data;
|
||||
if (!message || typeof message !== "object" || Array.isArray(message)) return;
|
||||
if (message.type === "worker-ready" && Object.keys(message).length === 1) {
|
||||
parentPort.postMessage({ channel: channelName, apiVersion, nonce, type: "client-ready" });
|
||||
return;
|
||||
}
|
||||
if (message.type === "plugin-error" && Object.keys(message).length === 1) {
|
||||
parentPort.postMessage({ channel: channelName, apiVersion, nonce, type: "runtime-error" });
|
||||
return;
|
||||
}
|
||||
const keys = Object.keys(message).sort().join(",");
|
||||
if (message.type !== "request" || keys !== "id,payload,permission,type" || !/^r[A-Za-z0-9_-]{0,63}$/.test(message.id)
|
||||
|| typeof message.permission !== "string" || !message.payload || typeof message.payload !== "object"
|
||||
|| Array.isArray(message.payload) || Object.keys(message.payload).length !== 0) return;
|
||||
parentPort.postMessage({ channel: channelName, apiVersion, nonce, id: message.id, type: "request", permission: message.permission, payload: {} });
|
||||
};
|
||||
workerPort.start();
|
||||
worker.postMessage({ type: "initialize" }, [workerChannel.port2]);
|
||||
} catch {
|
||||
parentPort.postMessage({ channel: channelName, apiVersion, nonce, type: "runtime-error" });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (data.type === "response" && typeof data.id === "string") {
|
||||
try { workerPort.postMessage(data); } catch { stopWorker(); }
|
||||
}
|
||||
};
|
||||
parentPort.onmessageerror = stopWorker;
|
||||
parentPort.start();
|
||||
parent.postMessage({ channel: channelName, apiVersion, nonce, type: "hello" }, "*", [parentChannel.port2]);
|
||||
})();
|
||||
</script></body></html>`;
|
||||
}
|
||||
|
||||
function serializedMessageBytes(value: unknown): number {
|
||||
try {
|
||||
const serialized = JSON.stringify(value);
|
||||
return serialized === undefined ? Number.POSITIVE_INFINITY : new TextEncoder().encode(serialized).byteLength;
|
||||
} catch {
|
||||
return Number.POSITIVE_INFINITY;
|
||||
}
|
||||
}
|
||||
|
||||
function isReadyMessage(value: unknown, nonce: string): boolean {
|
||||
return isPlainRecord(value)
|
||||
&& Object.keys(value).length === 4
|
||||
&& value.channel === MESSAGE_CHANNEL
|
||||
&& value.apiVersion === SKIN_EXTENSION_API_VERSION
|
||||
&& value.nonce === nonce
|
||||
&& value.type === "client-ready";
|
||||
}
|
||||
|
||||
export function createSkinExtensionSandboxPrototype(options: SkinExtensionSandboxOptions): SkinExtensionSandboxHandle {
|
||||
if (options.prototypeOnly !== true) {
|
||||
throw new SkinExtensionSandboxError("SKIN_EXTENSION_RUNTIME_DISABLED", "Executable extensions are disabled.");
|
||||
}
|
||||
if (!options.container || typeof options.source !== "string") {
|
||||
throw new SkinExtensionSandboxError("SKIN_EXTENSION_INPUT_INVALID", "The extension runtime input is invalid.");
|
||||
}
|
||||
|
||||
const manifest = parseSkinExtensionManifest(options.manifest);
|
||||
const approval = parseSkinExtensionApproval(options.approval);
|
||||
if (approval.pluginId !== manifest.id || approval.apiVersion !== manifest.apiVersion) {
|
||||
throw new SkinExtensionSandboxError("SKIN_EXTENSION_RECONSENT_REQUIRED", "The extension must be reviewed and approved again.");
|
||||
}
|
||||
for (const permission of manifest.permissions) {
|
||||
if (!isSkinExtensionPermissionApproved(approval, manifest.id, permission)) {
|
||||
throw new SkinExtensionSandboxError("SKIN_EXTENSION_RECONSENT_REQUIRED", "A requested extension permission has not been approved.");
|
||||
}
|
||||
}
|
||||
if (new TextEncoder().encode(options.source).byteLength > SKIN_EXTENSION_SANDBOX_SOURCE_LIMIT) {
|
||||
throw new SkinExtensionSandboxError("SKIN_EXTENSION_SOURCE_TOO_LARGE", "The extension source exceeds the prototype size limit.");
|
||||
}
|
||||
|
||||
const document = options.container.ownerDocument;
|
||||
const view = document.defaultView;
|
||||
if (!view || !view.crypto?.getRandomValues || typeof MessageChannel === "undefined") {
|
||||
throw new SkinExtensionSandboxError("SKIN_EXTENSION_BROWSER_UNSUPPORTED", "This browser cannot create the isolated extension prototype.");
|
||||
}
|
||||
const hostWindow = view;
|
||||
const nonce = randomNonce(hostWindow);
|
||||
const workerUrl = createWorkerDataUrl(options.source);
|
||||
const frame = document.createElement("iframe");
|
||||
frame.setAttribute("sandbox", "allow-scripts");
|
||||
frame.setAttribute("allow", "camera 'none'; microphone 'none'; display-capture 'none'; geolocation 'none'");
|
||||
frame.setAttribute("referrerpolicy", "no-referrer");
|
||||
frame.setAttribute("title", `${manifest.name} isolated component`);
|
||||
frame.tabIndex = 0;
|
||||
frame.style.display = "block";
|
||||
frame.style.width = "100%";
|
||||
frame.style.height = "100%";
|
||||
frame.style.border = "0";
|
||||
frame.style.background = "transparent";
|
||||
frame.srcdoc = createSandboxDocument(workerUrl, nonce);
|
||||
|
||||
let active = true;
|
||||
let closeReason: string | null = null;
|
||||
let port: MessagePort | null = null;
|
||||
let readySettled = false;
|
||||
let stopTimer: number | undefined;
|
||||
let stoppedSettled = false;
|
||||
let loadCount = 0;
|
||||
let invalidMessages = 0;
|
||||
let totalRequests = 0;
|
||||
let acceptedRequests = 0;
|
||||
let rejectedRequests = 0;
|
||||
const requestTimes: number[] = [];
|
||||
const recentRequestIds = new Set<string>();
|
||||
const recentRequestIdOrder: string[] = [];
|
||||
const pendingHostRequests = new Map<string, AbortController>();
|
||||
let resolveReady!: () => void;
|
||||
let rejectReady!: (reason: Error) => void;
|
||||
const ready = new Promise<void>((resolve, reject) => {
|
||||
resolveReady = resolve;
|
||||
rejectReady = reject;
|
||||
});
|
||||
let resolveStopped!: () => void;
|
||||
const stopped = new Promise<void>((resolve) => { resolveStopped = resolve; });
|
||||
const timer = hostWindow.setTimeout(() => close("handshake-timeout", new SkinExtensionSandboxError("SKIN_EXTENSION_HANDSHAKE_TIMEOUT", "The extension did not complete its isolated handshake.")), HANDSHAKE_TIMEOUT_MS);
|
||||
|
||||
function finalizeStop(): void {
|
||||
if (stoppedSettled) return;
|
||||
stoppedSettled = true;
|
||||
if (stopTimer !== undefined) hostWindow.clearTimeout(stopTimer);
|
||||
if (port) {
|
||||
port.onmessage = null;
|
||||
port.onmessageerror = null;
|
||||
port.close();
|
||||
port = null;
|
||||
}
|
||||
frame.remove();
|
||||
resolveStopped();
|
||||
}
|
||||
|
||||
function close(reason = "closed", error?: Error): void {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
closeReason = reason;
|
||||
hostWindow.clearTimeout(timer);
|
||||
hostWindow.removeEventListener("message", onWindowMessage);
|
||||
frame.removeEventListener("load", onFrameLoad);
|
||||
frame.removeEventListener("error", onFrameError);
|
||||
for (const controller of pendingHostRequests.values()) controller.abort();
|
||||
pendingHostRequests.clear();
|
||||
requestTimes.length = 0;
|
||||
recentRequestIds.clear();
|
||||
recentRequestIdOrder.length = 0;
|
||||
if (!readySettled) {
|
||||
readySettled = true;
|
||||
rejectReady(error ?? new SkinExtensionSandboxError("SKIN_EXTENSION_RUNTIME_CLOSED", "The extension runtime closed before it was ready."));
|
||||
}
|
||||
if (port) {
|
||||
try {
|
||||
port.postMessage({ channel: MESSAGE_CHANNEL, apiVersion: SKIN_EXTENSION_API_VERSION, nonce, type: "shutdown" });
|
||||
stopTimer = hostWindow.setTimeout(finalizeStop, SHUTDOWN_TIMEOUT_MS);
|
||||
} catch {
|
||||
finalizeStop();
|
||||
}
|
||||
} else finalizeStop();
|
||||
}
|
||||
|
||||
function failInvalidMessage(): void {
|
||||
invalidMessages += 1;
|
||||
if (invalidMessages >= 3) close("invalid-protocol");
|
||||
}
|
||||
|
||||
function sendResponse(id: string, ok: true, data: SkinExtensionSessionStatus): void;
|
||||
function sendResponse(id: string, ok: false, code: string, message: string): void;
|
||||
function sendResponse(id: string, ok: boolean, dataOrCode: SkinExtensionSessionStatus | string, message?: string): void {
|
||||
if (!active || !port) return;
|
||||
const response = ok
|
||||
? { channel: MESSAGE_CHANNEL, apiVersion: SKIN_EXTENSION_API_VERSION, nonce, id, type: "response", ok: true, data: dataOrCode }
|
||||
: { channel: MESSAGE_CHANNEL, apiVersion: SKIN_EXTENSION_API_VERSION, nonce, id, type: "response", ok: false, error: { code: dataOrCode, message } };
|
||||
try { port.postMessage(response); }
|
||||
catch { close("response-failed"); }
|
||||
}
|
||||
|
||||
function consumeRequestRate(now: number): boolean {
|
||||
while (requestTimes.length > 0 && now - requestTimes[0] >= 1000) requestTimes.shift();
|
||||
if (requestTimes.length >= SKIN_EXTENSION_SANDBOX_REQUESTS_PER_SECOND) return false;
|
||||
requestTimes.push(now);
|
||||
return true;
|
||||
}
|
||||
|
||||
async function handleRequest(value: unknown): Promise<void> {
|
||||
if (!active || !port) return;
|
||||
if (serializedMessageBytes(value) > SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT) {
|
||||
close("message-too-large");
|
||||
return;
|
||||
}
|
||||
if (!consumeRequestRate(hostWindow.performance.now())) {
|
||||
close("message-rate-exceeded");
|
||||
return;
|
||||
}
|
||||
const request = parseSkinExtensionRequestMessage(value, nonce);
|
||||
if (!request) {
|
||||
failInvalidMessage();
|
||||
return;
|
||||
}
|
||||
if (recentRequestIds.has(request.id) || pendingHostRequests.has(request.id)) {
|
||||
close("duplicate-request-id");
|
||||
return;
|
||||
}
|
||||
recentRequestIds.add(request.id);
|
||||
recentRequestIdOrder.push(request.id);
|
||||
if (recentRequestIdOrder.length > 256) recentRequestIds.delete(recentRequestIdOrder.shift()!);
|
||||
totalRequests += 1;
|
||||
if (totalRequests > SKIN_EXTENSION_SANDBOX_MAX_REQUESTS) {
|
||||
close("request-budget-exceeded");
|
||||
return;
|
||||
}
|
||||
if (!manifest.permissions.includes(request.permission)
|
||||
|| !isSkinExtensionPermissionApproved(approval, manifest.id, request.permission)) {
|
||||
rejectedRequests += 1;
|
||||
sendResponse(request.id, false, "CAPABILITY_NOT_APPROVED", "The extension capability is not approved.");
|
||||
return;
|
||||
}
|
||||
if (request.permission !== "session.status.read") {
|
||||
rejectedRequests += 1;
|
||||
sendResponse(request.id, false, "CAPABILITY_UNAVAILABLE", "The extension capability is unavailable in this prototype.");
|
||||
return;
|
||||
}
|
||||
|
||||
acceptedRequests += 1;
|
||||
const controller = new AbortController();
|
||||
pendingHostRequests.set(request.id, controller);
|
||||
try {
|
||||
const status = sanitizeSkinExtensionSessionStatus(await options.readSessionStatus(controller.signal));
|
||||
if (active && pendingHostRequests.get(request.id) === controller) {
|
||||
pendingHostRequests.delete(request.id);
|
||||
sendResponse(request.id, true, status);
|
||||
}
|
||||
} catch {
|
||||
if (pendingHostRequests.get(request.id) === controller) pendingHostRequests.delete(request.id);
|
||||
if (active) sendResponse(request.id, false, "HOST_DATA_UNAVAILABLE", "The requested session status is unavailable.");
|
||||
}
|
||||
}
|
||||
|
||||
function onPortMessage(event: MessageEvent): void {
|
||||
if (!active) {
|
||||
const value = event.data;
|
||||
if (isPlainRecord(value) && Object.keys(value).length === 4
|
||||
&& value.channel === MESSAGE_CHANNEL && value.apiVersion === SKIN_EXTENSION_API_VERSION
|
||||
&& value.nonce === nonce && value.type === "shutdown-complete") finalizeStop();
|
||||
return;
|
||||
}
|
||||
if (serializedMessageBytes(event.data) > SKIN_EXTENSION_SANDBOX_MESSAGE_LIMIT) {
|
||||
close("message-too-large");
|
||||
return;
|
||||
}
|
||||
if (isPlainRecord(event.data) && Object.keys(event.data).length === 4
|
||||
&& event.data.channel === MESSAGE_CHANNEL && event.data.apiVersion === SKIN_EXTENSION_API_VERSION
|
||||
&& event.data.nonce === nonce && event.data.type === "runtime-error") {
|
||||
close("worker-error", new SkinExtensionSandboxError("SKIN_EXTENSION_WORKER_FAILED", "The isolated extension worker failed."));
|
||||
return;
|
||||
}
|
||||
if (!readySettled) {
|
||||
if (!isReadyMessage(event.data, nonce)) {
|
||||
close("invalid-handshake", new SkinExtensionSandboxError("SKIN_EXTENSION_HANDSHAKE_INVALID", "The isolated extension handshake was invalid."));
|
||||
return;
|
||||
}
|
||||
readySettled = true;
|
||||
hostWindow.clearTimeout(timer);
|
||||
resolveReady();
|
||||
return;
|
||||
}
|
||||
void handleRequest(event.data);
|
||||
}
|
||||
|
||||
function onWindowMessage(event: MessageEvent): void {
|
||||
if (!active || port) {
|
||||
for (const transferredPort of event.ports) transferredPort.close();
|
||||
return;
|
||||
}
|
||||
const validHello = isSkinExtensionBootstrapHello({ source: event.source, origin: event.origin, data: event.data, ports: event.ports }, frame.contentWindow, nonce);
|
||||
if (!validHello) {
|
||||
for (const transferredPort of event.ports) transferredPort.close();
|
||||
return;
|
||||
}
|
||||
port = event.ports[0];
|
||||
port.onmessage = onPortMessage;
|
||||
port.onmessageerror = () => close("message-deserialization-failed");
|
||||
port.start();
|
||||
hostWindow.removeEventListener("message", onWindowMessage);
|
||||
port.postMessage({ channel: MESSAGE_CHANNEL, apiVersion: SKIN_EXTENSION_API_VERSION, nonce, type: "host-ready" });
|
||||
}
|
||||
|
||||
function onFrameLoad(): void {
|
||||
loadCount += 1;
|
||||
if (loadCount > 1) close("frame-navigation");
|
||||
}
|
||||
|
||||
function onFrameError(): void { close("frame-error"); }
|
||||
|
||||
hostWindow.addEventListener("message", onWindowMessage);
|
||||
frame.addEventListener("load", onFrameLoad);
|
||||
frame.addEventListener("error", onFrameError);
|
||||
options.container.append(frame);
|
||||
|
||||
return {
|
||||
frame,
|
||||
manifest,
|
||||
approval,
|
||||
ready,
|
||||
stopped,
|
||||
get closed() { return !active; },
|
||||
get closeReason() { return closeReason; },
|
||||
get acceptedRequests() { return acceptedRequests; },
|
||||
get rejectedRequests() { return rejectedRequests; },
|
||||
revokePermission(permission) {
|
||||
if (manifest.permissions.includes(permission)) close(`permission-revoked:${permission}`);
|
||||
},
|
||||
close,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
|
||||
SKIN_EXTENSION_WASM_SOURCE_LIMIT,
|
||||
SkinExtensionWasmPolicyError,
|
||||
validateSkinExtensionWasmBytes,
|
||||
validateSkinExtensionWasmImportsAndExports,
|
||||
} from "./skin-extension-wasm-policy.js";
|
||||
import {
|
||||
createSkinExtensionWasmCappedRunProbe,
|
||||
createSkinExtensionWasmGcAllocationProbe,
|
||||
createSkinExtensionWasmInfiniteStartProbe,
|
||||
createSkinExtensionWasmInternalMemoryProbe,
|
||||
createSkinExtensionWasmInternalTableProbe,
|
||||
createSkinExtensionWasmOversizedElementVectorProbe,
|
||||
createSkinExtensionWasmOversizedFunctionBodyProbe,
|
||||
createSkinExtensionWasmOversizedLocalProbe,
|
||||
createSkinExtensionWasmOversizedSignatureProbe,
|
||||
createSkinExtensionWasmPrefixByteImmediateProbe,
|
||||
createSkinExtensionWasmStatusProbe,
|
||||
createSkinExtensionWasmTooManyFunctionsProbe,
|
||||
} from "../../test/skin-extension-wasm-fixture.js";
|
||||
|
||||
test("Wasm metadata policy accepts only a single run export and one bounded host memory", () => {
|
||||
const metadata = validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmPrefixByteImmediateProbe());
|
||||
assert.deepEqual(metadata, { usesSessionStatus: false, memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES });
|
||||
});
|
||||
|
||||
test("Wasm policy rejects module-defined memory or tables that bypass host limits", () => {
|
||||
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmInternalMemoryProbe()), {
|
||||
code: "SKIN_EXTENSION_WASM_RESOURCE_DECLARATION",
|
||||
});
|
||||
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmInternalTableProbe()), {
|
||||
code: "SKIN_EXTENSION_WASM_RESOURCE_DECLARATION",
|
||||
});
|
||||
});
|
||||
|
||||
test("Wasm metadata parser rejects missing import memory, malformed sections, and oversized modules", () => {
|
||||
assert.throws(() => validateSkinExtensionWasmImportsAndExports(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0])), {
|
||||
code: "SKIN_EXTENSION_WASM_IMPORT_INVALID",
|
||||
});
|
||||
assert.throws(() => validateSkinExtensionWasmBytes(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 127])), {
|
||||
code: "SKIN_EXTENSION_WASM_INVALID",
|
||||
});
|
||||
assert.throws(() => validateSkinExtensionWasmBytes(new Uint8Array(SKIN_EXTENSION_WASM_SOURCE_LIMIT + 1)), {
|
||||
code: "SKIN_EXTENSION_WASM_SIZE",
|
||||
});
|
||||
assert.ok(new SkinExtensionWasmPolicyError("test", "test") instanceof Error);
|
||||
});
|
||||
|
||||
test("Wasm preflight caps function count and body size before the interpreter sees a module", () => {
|
||||
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmTooManyFunctionsProbe()), {
|
||||
code: "SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT",
|
||||
});
|
||||
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmOversizedFunctionBodyProbe()), {
|
||||
code: "SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT",
|
||||
});
|
||||
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmInfiniteStartProbe()), {
|
||||
code: "SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE",
|
||||
});
|
||||
});
|
||||
|
||||
test("Wasm preflight rejects GC allocation and bounds nested vectors before interpretation", () => {
|
||||
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmGcAllocationProbe()), {
|
||||
code: "SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE",
|
||||
});
|
||||
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmOversizedSignatureProbe()), {
|
||||
code: "SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT",
|
||||
});
|
||||
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmOversizedLocalProbe()), {
|
||||
code: "SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT",
|
||||
});
|
||||
assert.throws(() => validateSkinExtensionWasmBytes(createSkinExtensionWasmOversizedElementVectorProbe()), {
|
||||
code: "SKIN_EXTENSION_WASM_RESOURCE_DECLARATION",
|
||||
});
|
||||
});
|
||||
|
||||
test("Wasm import parsing reads the bounded permission contract without native compilation", () => {
|
||||
const status = createSkinExtensionWasmStatusProbe();
|
||||
assert.throws(() => validateSkinExtensionWasmImportsAndExports(status), {
|
||||
code: "SKIN_EXTENSION_WASM_PERMISSION_INVALID",
|
||||
});
|
||||
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(status, ["session.status.read"]), {
|
||||
usesSessionStatus: true,
|
||||
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
|
||||
});
|
||||
assert.equal(validateSkinExtensionWasmImportsAndExports(createSkinExtensionWasmCappedRunProbe()).usesSessionStatus, false);
|
||||
});
|
||||
|
||||
test("Wasm instruction scanning distinguishes extension prefixes from signed integer bytes", () => {
|
||||
const bytes = createSkinExtensionWasmPrefixByteImmediateProbe();
|
||||
assert.doesNotThrow(() => validateSkinExtensionWasmBytes(bytes));
|
||||
assert.deepEqual(validateSkinExtensionWasmImportsAndExports(bytes), {
|
||||
usesSessionStatus: false,
|
||||
memoryMaximumPages: SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,437 @@
|
||||
export const SKIN_EXTENSION_WASM_SOURCE_LIMIT = 256 * 1024;
|
||||
export const SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES = 64;
|
||||
export const SKIN_EXTENSION_WASM_PAGE_BYTES = 64 * 1024;
|
||||
export const SKIN_EXTENSION_WASM_STARTUP_TIMEOUT_MS = 3_000;
|
||||
export const SKIN_EXTENSION_WASM_EXECUTION_LIMIT_MS = 100;
|
||||
export const SKIN_EXTENSION_WASM_MESSAGE_LIMIT = 8 * 1024;
|
||||
export const SKIN_EXTENSION_WASM_STATUS_READ_LIMIT = 10;
|
||||
export const SKIN_EXTENSION_WASM_STATUS_BYTES_LIMIT = 512;
|
||||
export const SKIN_EXTENSION_WASM_FUEL_LIMIT = 10_000_000n;
|
||||
export const SKIN_EXTENSION_WASM_INTERPRETER_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;
|
||||
export const SKIN_EXTENSION_WASM_FUNCTION_LIMIT = 128;
|
||||
export const SKIN_EXTENSION_WASM_FUNCTION_BODY_LIMIT = 32 * 1024;
|
||||
export const SKIN_EXTENSION_WASM_CODE_BYTES_LIMIT = 192 * 1024;
|
||||
const SKIN_EXTENSION_WASM_SIGNATURE_VALUE_LIMIT = 64;
|
||||
const SKIN_EXTENSION_WASM_LOCAL_GROUP_LIMIT = 256;
|
||||
const SKIN_EXTENSION_WASM_LOCAL_LIMIT = 4_096;
|
||||
|
||||
const WASM_HEADER = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00] as const;
|
||||
const SCALAR_VALUE_TYPES = new Set([0x7f, 0x7e, 0x7d, 0x7c]);
|
||||
const BOUNDED_VECTOR_COUNTS = new Map<number, number>([
|
||||
[1, 128], // types
|
||||
[2, 2], // memory and one optional capability import
|
||||
[3, SKIN_EXTENSION_WASM_FUNCTION_LIMIT],
|
||||
[6, 128], // globals
|
||||
[7, 64], // exports; the runner later requires exactly run
|
||||
[9, 64], // element segments
|
||||
[11, 64], // data segments
|
||||
[12, 64], // data segments referenced by bulk-memory operations
|
||||
]);
|
||||
|
||||
export class SkinExtensionWasmPolicyError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
super(message);
|
||||
this.name = "SkinExtensionWasmPolicyError";
|
||||
}
|
||||
}
|
||||
|
||||
function readU32(bytes: Uint8Array, offset: number, end: number): { value: number; next: number } {
|
||||
let value = 0;
|
||||
let shift = 0;
|
||||
for (let index = 0; index < 5; index += 1) {
|
||||
if (offset >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has a truncated section length.");
|
||||
const byte = bytes[offset++];
|
||||
if (index === 4 && (byte & 0xf0) !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has an overflowing section length.");
|
||||
value |= (byte & 0x7f) << shift;
|
||||
if ((byte & 0x80) === 0) return { value: value >>> 0, next: offset };
|
||||
shift += 7;
|
||||
}
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has an invalid section length.");
|
||||
}
|
||||
|
||||
function skipSignedLeb128(bytes: Uint8Array, offset: number, end: number, maxBytes: number): number {
|
||||
for (let index = 0; index < maxBytes; index += 1) {
|
||||
if (offset >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function contains a truncated integer immediate.");
|
||||
if ((bytes[offset++] & 0x80) === 0) return offset;
|
||||
}
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function contains an oversized integer immediate.");
|
||||
}
|
||||
|
||||
function requireScalarValueType(bytes: Uint8Array, offset: number, end: number): number {
|
||||
if (offset >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module contains a truncated value type.");
|
||||
if (!SCALAR_VALUE_TYPES.has(bytes[offset])) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "The Wasm prototype accepts numeric scalar types only; reference, vector, and GC types are disabled.");
|
||||
}
|
||||
return offset + 1;
|
||||
}
|
||||
|
||||
function validateTypeSection(bytes: Uint8Array, start: number, end: number): void {
|
||||
let cursor = readU32(bytes, start, end);
|
||||
if (cursor.value > 128) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module contains too many function types.");
|
||||
for (let typeIndex = 0; typeIndex < cursor.value; typeIndex += 1) {
|
||||
if (cursor.next >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension type section is truncated.");
|
||||
if (bytes[cursor.next++] !== 0x60) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "The Wasm prototype accepts function types only; GC and recursive types are disabled.");
|
||||
}
|
||||
const parameters = readU32(bytes, cursor.next, end);
|
||||
cursor.next = parameters.next;
|
||||
if (parameters.value > SKIN_EXTENSION_WASM_SIGNATURE_VALUE_LIMIT) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension function signature contains too many parameters.");
|
||||
}
|
||||
for (let index = 0; index < parameters.value; index += 1) cursor.next = requireScalarValueType(bytes, cursor.next, end);
|
||||
|
||||
const results = readU32(bytes, cursor.next, end);
|
||||
cursor.next = results.next;
|
||||
if (results.value > SKIN_EXTENSION_WASM_SIGNATURE_VALUE_LIMIT) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension function signature contains too many results.");
|
||||
}
|
||||
for (let index = 0; index < results.value; index += 1) cursor.next = requireScalarValueType(bytes, cursor.next, end);
|
||||
}
|
||||
if (cursor.next !== end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension type section contains trailing bytes.");
|
||||
}
|
||||
|
||||
function readBlockType(bytes: Uint8Array, offset: number, end: number): number {
|
||||
if (offset >= end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function contains a truncated block type.");
|
||||
const valueType = bytes[offset];
|
||||
if (valueType === 0x40 || SCALAR_VALUE_TYPES.has(valueType)) return offset + 1;
|
||||
if (valueType === 0x6f || valueType === 0x70 || valueType === 0x7b || valueType === 0x63 || valueType === 0x64) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "Reference and vector block types are disabled in the Wasm prototype.");
|
||||
}
|
||||
return skipSignedLeb128(bytes, offset, end, 5);
|
||||
}
|
||||
|
||||
function scanFunctionBody(bytes: Uint8Array, start: number, end: number): number {
|
||||
let cursor = readU32(bytes, start, end);
|
||||
if (cursor.value > SKIN_EXTENSION_WASM_LOCAL_GROUP_LIMIT) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension function contains too many local groups.");
|
||||
}
|
||||
const localGroupCount = cursor.value;
|
||||
let localCount = 0;
|
||||
for (let index = 0; index < localGroupCount; index += 1) {
|
||||
const group = readU32(bytes, cursor.next, end);
|
||||
cursor.next = group.next;
|
||||
localCount += group.value;
|
||||
if (localCount > SKIN_EXTENSION_WASM_LOCAL_LIMIT) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension module declares too many local values.");
|
||||
}
|
||||
cursor.next = requireScalarValueType(bytes, cursor.next, end);
|
||||
}
|
||||
|
||||
while (cursor.next < end) {
|
||||
const opcode = bytes[cursor.next++];
|
||||
if ((opcode >= 0x45 && opcode <= 0xc4)
|
||||
|| opcode === 0x00 || opcode === 0x01 || opcode === 0x05 || opcode === 0x0b
|
||||
|| opcode === 0x0f || opcode === 0x1a || opcode === 0x1b) continue;
|
||||
|
||||
if (opcode === 0x02 || opcode === 0x03 || opcode === 0x04) {
|
||||
cursor.next = readBlockType(bytes, cursor.next, end);
|
||||
continue;
|
||||
}
|
||||
if (opcode === 0x0c || opcode === 0x0d || opcode === 0x10
|
||||
|| (opcode >= 0x20 && opcode <= 0x24)) {
|
||||
cursor = readU32(bytes, cursor.next, end);
|
||||
continue;
|
||||
}
|
||||
if (opcode === 0x0e) {
|
||||
const labels = readU32(bytes, cursor.next, end);
|
||||
cursor.next = labels.next;
|
||||
if (labels.value > end - cursor.next) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension branch table is truncated.");
|
||||
for (let index = 0; index <= labels.value; index += 1) cursor = readU32(bytes, cursor.next, end);
|
||||
continue;
|
||||
}
|
||||
if (opcode === 0x11) {
|
||||
cursor = readU32(bytes, cursor.next, end);
|
||||
const table = readU32(bytes, cursor.next, end);
|
||||
if (table.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported table.");
|
||||
cursor.next = table.next;
|
||||
continue;
|
||||
}
|
||||
if (opcode === 0x1c) {
|
||||
const selected = readU32(bytes, cursor.next, end);
|
||||
cursor.next = selected.next;
|
||||
if (selected.value > SKIN_EXTENSION_WASM_SIGNATURE_VALUE_LIMIT) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "A typed selection contains too many values.");
|
||||
}
|
||||
for (let index = 0; index < selected.value; index += 1) cursor.next = requireScalarValueType(bytes, cursor.next, end);
|
||||
continue;
|
||||
}
|
||||
if (opcode >= 0x28 && opcode <= 0x3e) {
|
||||
const alignment = readU32(bytes, cursor.next, end);
|
||||
cursor.next = alignment.next;
|
||||
if (alignment.value > 3) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "Multi-memory and over-aligned memory operations are disabled.");
|
||||
cursor = readU32(bytes, cursor.next, end);
|
||||
continue;
|
||||
}
|
||||
if (opcode === 0x3f || opcode === 0x40) {
|
||||
const memory = readU32(bytes, cursor.next, end);
|
||||
if (memory.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported memory.");
|
||||
cursor.next = memory.next;
|
||||
continue;
|
||||
}
|
||||
if (opcode === 0x41 || opcode === 0x42) {
|
||||
cursor.next = skipSignedLeb128(bytes, cursor.next, end, opcode === 0x41 ? 5 : 10);
|
||||
continue;
|
||||
}
|
||||
if (opcode === 0x43 || opcode === 0x44) {
|
||||
const immediateBytes = opcode === 0x43 ? 4 : 8;
|
||||
if (cursor.next + immediateBytes > end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function contains a truncated floating-point immediate.");
|
||||
cursor.next += immediateBytes;
|
||||
continue;
|
||||
}
|
||||
if (opcode === 0xfc) {
|
||||
const operation = readU32(bytes, cursor.next, end);
|
||||
cursor.next = operation.next;
|
||||
if (operation.value <= 7) continue; // Saturating numeric conversions.
|
||||
if (operation.value === 8) {
|
||||
cursor = readU32(bytes, cursor.next, end); // data index
|
||||
const memory = readU32(bytes, cursor.next, end);
|
||||
if (memory.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported memory.");
|
||||
cursor.next = memory.next;
|
||||
continue;
|
||||
}
|
||||
if (operation.value === 9) { cursor = readU32(bytes, cursor.next, end); continue; } // data.drop
|
||||
if (operation.value === 10) {
|
||||
const firstMemory = readU32(bytes, cursor.next, end);
|
||||
const secondMemory = readU32(bytes, firstMemory.next, end);
|
||||
if (firstMemory.value !== 0 || secondMemory.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported memory.");
|
||||
cursor.next = secondMemory.next;
|
||||
continue;
|
||||
}
|
||||
if (operation.value === 11) {
|
||||
const memory = readU32(bytes, cursor.next, end);
|
||||
if (memory.value !== 0) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The extension function references an unsupported memory.");
|
||||
cursor.next = memory.next;
|
||||
continue;
|
||||
}
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "Table, GC, SIMD, thread, and unknown Wasm extension instructions are disabled.");
|
||||
}
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "The Wasm prototype accepts scalar core instructions only; reference, GC, SIMD, thread, and unknown extension instructions are disabled.");
|
||||
}
|
||||
return localCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resource-policy preflight before the fixed Wasmi interpreter parses an extension.
|
||||
* It bounds the binary work up front; Wasmi still performs full module validation.
|
||||
*/
|
||||
export function validateSkinExtensionWasmBytes(source: Uint8Array): void {
|
||||
if (!(source instanceof Uint8Array) || source.byteLength < WASM_HEADER.length || source.byteLength > SKIN_EXTENSION_WASM_SOURCE_LIMIT) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_SIZE", "The extension module is empty, invalid, or exceeds its size limit.");
|
||||
}
|
||||
if (WASM_HEADER.some((byte, index) => source[index] !== byte)) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module header or version is unsupported.");
|
||||
}
|
||||
|
||||
let offset: number = WASM_HEADER.length;
|
||||
let previousSectionRank = 0;
|
||||
let customSectionCount = 0;
|
||||
const seenSections = new Set<number>();
|
||||
let definedFunctionCount: number | undefined;
|
||||
let codeFunctionCount: number | undefined;
|
||||
let codeBytes = 0;
|
||||
let totalLocalCount = 0;
|
||||
while (offset < source.byteLength) {
|
||||
const sectionId = source[offset++];
|
||||
if (sectionId > 12) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module contains an unknown section.");
|
||||
if (sectionId === 0) {
|
||||
customSectionCount += 1;
|
||||
if (customSectionCount > 8) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module contains too many custom sections.");
|
||||
} else {
|
||||
if (seenSections.has(sectionId)) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module contains a duplicate section.");
|
||||
seenSections.add(sectionId);
|
||||
// The data-count section (12) is ordered immediately before code (10) by the Wasm binary format.
|
||||
const rank = sectionId === 12 ? 9.5 : sectionId;
|
||||
if (rank <= previousSectionRank) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module sections are out of order.");
|
||||
previousSectionRank = rank;
|
||||
}
|
||||
if (sectionId === 8) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_UNSUPPORTED_FEATURE", "Module start functions are disabled; extensions may enter only through the exported run function.");
|
||||
}
|
||||
const sectionLength = readU32(source, offset, source.byteLength);
|
||||
offset = sectionLength.next;
|
||||
const sectionEnd = offset + sectionLength.value;
|
||||
if (sectionEnd > source.byteLength) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has a truncated section.");
|
||||
|
||||
if (sectionId === 1) validateTypeSection(source, offset, sectionEnd);
|
||||
|
||||
const vectorLimit = BOUNDED_VECTOR_COUNTS.get(sectionId);
|
||||
if (vectorLimit !== undefined) {
|
||||
const count = readU32(source, offset, sectionEnd);
|
||||
if (count.value > vectorLimit) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module exceeds a structural item limit.");
|
||||
if (sectionId === 3) definedFunctionCount = count.value;
|
||||
}
|
||||
|
||||
// This model permits exactly one host-provided bounded linear memory and no tables.
|
||||
// Module-defined memories, tables, and element segments would bypass that resource model.
|
||||
if (sectionId === 4 || sectionId === 5) {
|
||||
const count = readU32(source, offset, sectionEnd).value;
|
||||
if (count !== 0) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "Extension modules must import bounded memory and cannot define memory or tables.");
|
||||
}
|
||||
}
|
||||
if (sectionId === 9 && readU32(source, offset, sectionEnd).value !== 0) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "Extension modules cannot declare element segments or tables.");
|
||||
}
|
||||
|
||||
if (sectionId === 10) {
|
||||
let cursor = offset;
|
||||
const count = readU32(source, cursor, sectionEnd);
|
||||
cursor = count.next;
|
||||
if (count.value > SKIN_EXTENSION_WASM_FUNCTION_LIMIT) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module contains too many function bodies.");
|
||||
}
|
||||
codeFunctionCount = count.value;
|
||||
for (let index = 0; index < count.value; index += 1) {
|
||||
const body = readU32(source, cursor, sectionEnd);
|
||||
cursor = body.next;
|
||||
if (!body.value || body.value > SKIN_EXTENSION_WASM_FUNCTION_BODY_LIMIT) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "An extension function body exceeds its size limit.");
|
||||
}
|
||||
codeBytes += body.value;
|
||||
if (codeBytes > SKIN_EXTENSION_WASM_CODE_BYTES_LIMIT) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension code section exceeds its total size limit.");
|
||||
}
|
||||
const bodyEnd = cursor + body.value;
|
||||
if (bodyEnd > sectionEnd) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "An extension function body is truncated.");
|
||||
totalLocalCount += scanFunctionBody(source, cursor, bodyEnd);
|
||||
if (totalLocalCount > SKIN_EXTENSION_WASM_LOCAL_LIMIT) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_COMPLEXITY_LIMIT", "The extension module declares too many local values.");
|
||||
}
|
||||
cursor = bodyEnd;
|
||||
}
|
||||
if (cursor !== sectionEnd) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension code section contains trailing bytes.");
|
||||
}
|
||||
offset = sectionEnd;
|
||||
}
|
||||
if (definedFunctionCount !== undefined && codeFunctionCount !== undefined && definedFunctionCount !== codeFunctionCount) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension function and code counts do not match.");
|
||||
}
|
||||
}
|
||||
|
||||
export interface SkinExtensionWasmModuleMetadata {
|
||||
usesSessionStatus: boolean;
|
||||
memoryMaximumPages: number;
|
||||
}
|
||||
|
||||
function readWasmName(bytes: Uint8Array, offset: number, end: number): { value: string; next: number } {
|
||||
const length = readU32(bytes, offset, end);
|
||||
if (length.value > 80 || length.next + length.value > end) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module contains an invalid import or export name.");
|
||||
}
|
||||
try {
|
||||
return {
|
||||
value: new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(length.next, length.next + length.value)),
|
||||
next: length.next + length.value,
|
||||
};
|
||||
} catch {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module contains an invalid UTF-8 import or export name.");
|
||||
}
|
||||
}
|
||||
|
||||
function readImportedMemoryMaximum(bytes: Uint8Array, offset: number, end: number): { maximumPages: number; next: number } {
|
||||
const flags = readU32(bytes, offset, end);
|
||||
if (flags.value !== 0 && flags.value !== 1) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "Shared and memory64 imports are not supported.");
|
||||
}
|
||||
const minimum = readU32(bytes, flags.next, end);
|
||||
let next = minimum.next;
|
||||
let maximumPages = SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES;
|
||||
if (flags.value === 1) {
|
||||
const maximum = readU32(bytes, next, end);
|
||||
next = maximum.next;
|
||||
maximumPages = maximum.value;
|
||||
if (maximumPages < 1 || maximumPages > SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES || maximumPages < minimum.value) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The imported memory limit is outside the host's allowed range.");
|
||||
}
|
||||
}
|
||||
if (minimum.value > 1 || minimum.value > maximumPages) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_RESOURCE_DECLARATION", "The module requests more initial memory than the host provides.");
|
||||
}
|
||||
return { maximumPages, next };
|
||||
}
|
||||
|
||||
/** Parses only bounded imports/exports; author bytes never reach the browser's native Wasm compiler. */
|
||||
export function validateSkinExtensionWasmImportsAndExports(
|
||||
bytes: Uint8Array,
|
||||
grantedPermissions: readonly string[] = [],
|
||||
): SkinExtensionWasmModuleMetadata {
|
||||
validateSkinExtensionWasmBytes(bytes);
|
||||
let offset: number = WASM_HEADER.length;
|
||||
let memoryMaximumPages = SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES;
|
||||
let hasMemory = false;
|
||||
let usesSessionStatus = false;
|
||||
let hasExports = false;
|
||||
|
||||
while (offset < bytes.byteLength) {
|
||||
const sectionId = bytes[offset++];
|
||||
const sectionLength = readU32(bytes, offset, bytes.byteLength);
|
||||
offset = sectionLength.next;
|
||||
const end = offset + sectionLength.value;
|
||||
if (end > bytes.byteLength) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_INVALID", "The extension module has a truncated section.");
|
||||
|
||||
if (sectionId === 2) {
|
||||
const count = readU32(bytes, offset, end);
|
||||
if (count.value < 1 || count.value > 2) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import one host memory and at most one approved capability.");
|
||||
}
|
||||
let cursor = count.next;
|
||||
for (let index = 0; index < count.value; index += 1) {
|
||||
const moduleName = readWasmName(bytes, cursor, end);
|
||||
const fieldName = readWasmName(bytes, moduleName.next, end);
|
||||
cursor = fieldName.next;
|
||||
if (cursor >= end || moduleName.value !== "env") {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module may import only the host's env memory and approved capability.");
|
||||
}
|
||||
const kind = bytes[cursor++];
|
||||
if (kind === 0) {
|
||||
const typeIndex = readU32(bytes, cursor, end);
|
||||
cursor = typeIndex.next;
|
||||
if (fieldName.value !== "session_status_read" || usesSessionStatus) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module requested an unsupported or duplicate function import.");
|
||||
}
|
||||
usesSessionStatus = true;
|
||||
} else if (kind === 2) {
|
||||
if (fieldName.value !== "memory" || hasMemory) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import exactly one env.memory value.");
|
||||
}
|
||||
const memory = readImportedMemoryMaximum(bytes, cursor, end);
|
||||
cursor = memory.next;
|
||||
memoryMaximumPages = memory.maximumPages;
|
||||
hasMemory = true;
|
||||
} else {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "Tables, globals, tags, and unknown imports are not supported.");
|
||||
}
|
||||
}
|
||||
if (cursor !== end || !hasMemory) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import exactly one env.memory value.");
|
||||
}
|
||||
}
|
||||
|
||||
if (sectionId === 7) {
|
||||
const count = readU32(bytes, offset, end);
|
||||
if (count.value !== 1) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_EXPORT_INVALID", "The module must export only one run function.");
|
||||
}
|
||||
let cursor = count.next;
|
||||
const name = readWasmName(bytes, cursor, end);
|
||||
cursor = name.next;
|
||||
if (cursor >= end || name.value !== "run" || bytes[cursor++] !== 0) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_EXPORT_INVALID", "The module must export one function named run.");
|
||||
}
|
||||
const functionIndex = readU32(bytes, cursor, end);
|
||||
cursor = functionIndex.next;
|
||||
if (cursor !== end) throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_EXPORT_INVALID", "The module has trailing export data.");
|
||||
hasExports = true;
|
||||
}
|
||||
|
||||
offset = end;
|
||||
}
|
||||
|
||||
if (!hasMemory || !hasExports) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_IMPORT_INVALID", "The module must import bounded env.memory and export a run function.");
|
||||
}
|
||||
if (usesSessionStatus && !grantedPermissions.includes("session.status.read")) {
|
||||
throw new SkinExtensionWasmPolicyError("SKIN_EXTENSION_WASM_PERMISSION_INVALID", "The module imports session status without an approved session.status.read capability.");
|
||||
}
|
||||
return { usesSessionStatus, memoryMaximumPages };
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createSkinExtensionApproval, parseSkinExtensionManifest } from "../../../src/shared/skin-extension.js";
|
||||
import {
|
||||
createSkinExtensionWasmSandboxPrototype,
|
||||
SKIN_EXTENSION_WASM_RUNTIME_ENABLED,
|
||||
} from "./skin-extension-wasm-sandbox.js";
|
||||
import { SKIN_EXTENSION_WASM_SOURCE_LIMIT } from "./skin-extension-wasm-policy.js";
|
||||
|
||||
const manifest = parseSkinExtensionManifest({
|
||||
schemaVersion: 1,
|
||||
packageType: "extension",
|
||||
id: "test.wasm-extension",
|
||||
name: "Wasm extension",
|
||||
version: "1.0.0",
|
||||
apiVersion: 1,
|
||||
permissions: [],
|
||||
});
|
||||
|
||||
test("production Wasm execution remains disabled while the bounded runner is prototype-only", () => {
|
||||
assert.equal(SKIN_EXTENSION_WASM_RUNTIME_ENABLED, false);
|
||||
assert.throws(() => createSkinExtensionWasmSandboxPrototype({
|
||||
manifest,
|
||||
approval: createSkinExtensionApproval(manifest),
|
||||
wasmBytes: new Uint8Array(SKIN_EXTENSION_WASM_SOURCE_LIMIT + 1),
|
||||
readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }),
|
||||
prototypeOnly: true,
|
||||
}), { code: "SKIN_EXTENSION_WASM_SIZE" });
|
||||
});
|
||||
@@ -0,0 +1,217 @@
|
||||
import {
|
||||
isSkinExtensionPermissionApproved,
|
||||
parseSkinExtensionApproval,
|
||||
parseSkinExtensionManifest,
|
||||
sanitizeSkinExtensionSessionStatus,
|
||||
type SkinExtensionPermissionId,
|
||||
type SkinExtensionSessionStatus,
|
||||
} from "../../../src/shared/skin-extension.js";
|
||||
import {
|
||||
SKIN_EXTENSION_WASM_EXECUTION_LIMIT_MS,
|
||||
SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
|
||||
SKIN_EXTENSION_WASM_MESSAGE_LIMIT,
|
||||
SKIN_EXTENSION_WASM_SOURCE_LIMIT,
|
||||
SKIN_EXTENSION_WASM_STARTUP_TIMEOUT_MS,
|
||||
SKIN_EXTENSION_WASM_STATUS_READ_LIMIT,
|
||||
validateSkinExtensionWasmBytes,
|
||||
} from "./skin-extension-wasm-policy.js";
|
||||
|
||||
export const SKIN_EXTENSION_WASM_RUNTIME_ENABLED = false as const;
|
||||
|
||||
export class SkinExtensionWasmSandboxError extends Error {
|
||||
constructor(readonly code: string, message: string) {
|
||||
super(message);
|
||||
this.name = "SkinExtensionWasmSandboxError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface SkinExtensionWasmSandboxResult {
|
||||
result: number | string;
|
||||
linearMemoryBytes: number;
|
||||
statusReadCount: number;
|
||||
sessionSnapshot?: SkinExtensionSessionStatus;
|
||||
}
|
||||
|
||||
export interface SkinExtensionWasmSandboxOptions {
|
||||
manifest: unknown;
|
||||
approval: unknown;
|
||||
wasmBytes: Uint8Array;
|
||||
readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>;
|
||||
/** This prototype is available only to the development security harness. */
|
||||
prototypeOnly: true;
|
||||
}
|
||||
|
||||
export interface SkinExtensionWasmSandboxHandle {
|
||||
readonly ready: Promise<void>;
|
||||
readonly result: Promise<SkinExtensionWasmSandboxResult>;
|
||||
readonly stopped: Promise<void>;
|
||||
readonly closed: boolean;
|
||||
readonly closeReason: string | null;
|
||||
readonly capabilityRequests: number;
|
||||
revokePermission(permission: SkinExtensionPermissionId): void;
|
||||
close(reason?: string): void;
|
||||
}
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
const prototype = Object.getPrototypeOf(value);
|
||||
return prototype === Object.prototype || prototype === null;
|
||||
}
|
||||
|
||||
function messageSize(value: unknown): number {
|
||||
try { return new TextEncoder().encode(JSON.stringify(value)).byteLength; }
|
||||
catch { return SKIN_EXTENSION_WASM_MESSAGE_LIMIT + 1; }
|
||||
}
|
||||
|
||||
/** Development-only Wasm runner: no author JavaScript is evaluated and every job owns one terminable Worker. */
|
||||
export function createSkinExtensionWasmSandboxPrototype(options: SkinExtensionWasmSandboxOptions): SkinExtensionWasmSandboxHandle {
|
||||
if (options.prototypeOnly !== true) throw new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_PROTOTYPE_ONLY", "The Wasm runner is a development-only security prototype.");
|
||||
if (!(options.wasmBytes instanceof Uint8Array) || !options.wasmBytes.byteLength || options.wasmBytes.byteLength > SKIN_EXTENSION_WASM_SOURCE_LIMIT) {
|
||||
throw new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_SIZE", "The extension module is empty or exceeds its source limit.");
|
||||
}
|
||||
|
||||
const manifest = parseSkinExtensionManifest(options.manifest);
|
||||
const approval = parseSkinExtensionApproval(options.approval);
|
||||
validateSkinExtensionWasmBytes(options.wasmBytes);
|
||||
const grantedPermissions = manifest.permissions.filter((permission) =>
|
||||
isSkinExtensionPermissionApproved(approval, manifest.id, permission));
|
||||
const wasmBytes = options.wasmBytes.slice();
|
||||
const worker = new Worker(new URL("./skin-extension-wasm-worker.ts", import.meta.url), {
|
||||
type: "module",
|
||||
name: "webspeak-skin-extension-wasm-prototype",
|
||||
});
|
||||
|
||||
let active = true;
|
||||
let closeReason: string | null = null;
|
||||
const hostAbortController = new AbortController();
|
||||
let readySettled = false;
|
||||
let resultSettled = false;
|
||||
let capabilityRequests = 0;
|
||||
let approvedSessionStatus: SkinExtensionSessionStatus | undefined;
|
||||
let startupTimer: number | undefined;
|
||||
let executionTimer: number | undefined;
|
||||
let resolveReady!: () => void;
|
||||
let rejectReady!: (error: Error) => void;
|
||||
let resolveResult!: (value: SkinExtensionWasmSandboxResult) => void;
|
||||
let rejectResult!: (error: Error) => void;
|
||||
let resolveStopped!: () => void;
|
||||
const ready = new Promise<void>((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
|
||||
const result = new Promise<SkinExtensionWasmSandboxResult>((resolve, reject) => { resolveResult = resolve; rejectResult = reject; });
|
||||
const stopped = new Promise<void>((resolve) => { resolveStopped = resolve; });
|
||||
void ready.catch(() => undefined);
|
||||
void result.catch(() => undefined);
|
||||
|
||||
function finish(reason: string, error?: Error): void {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
closeReason = reason;
|
||||
approvedSessionStatus = undefined;
|
||||
hostAbortController.abort();
|
||||
if (startupTimer !== undefined) clearTimeout(startupTimer);
|
||||
if (executionTimer !== undefined) clearTimeout(executionTimer);
|
||||
worker.onmessage = null;
|
||||
worker.onmessageerror = null;
|
||||
worker.onerror = null;
|
||||
worker.terminate();
|
||||
if (!readySettled) {
|
||||
readySettled = true;
|
||||
rejectReady(error ?? new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_CLOSED", "The Wasm extension stopped before execution began."));
|
||||
}
|
||||
if (!resultSettled) {
|
||||
resultSettled = true;
|
||||
rejectResult(error ?? new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_CLOSED", "The Wasm extension stopped before returning a result."));
|
||||
}
|
||||
resolveStopped();
|
||||
}
|
||||
|
||||
function complete(value: SkinExtensionWasmSandboxResult): void {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
closeReason = "completed";
|
||||
if (startupTimer !== undefined) clearTimeout(startupTimer);
|
||||
if (executionTimer !== undefined) clearTimeout(executionTimer);
|
||||
worker.onmessage = null;
|
||||
worker.onmessageerror = null;
|
||||
worker.onerror = null;
|
||||
worker.terminate();
|
||||
if (!readySettled) { readySettled = true; resolveReady(); }
|
||||
if (!resultSettled) { resultSettled = true; resolveResult(value); }
|
||||
resolveStopped();
|
||||
}
|
||||
|
||||
worker.onmessage = (event: MessageEvent<unknown>) => {
|
||||
if (!active || messageSize(event.data) > SKIN_EXTENSION_WASM_MESSAGE_LIMIT || !isPlainRecord(event.data)) {
|
||||
finish("invalid-message", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_MESSAGE_INVALID", "The Wasm worker returned an invalid or oversized message."));
|
||||
return;
|
||||
}
|
||||
const message = event.data;
|
||||
if (message.type === "capability-request") {
|
||||
if (Object.keys(message).length !== 3 || message.requestId !== "session-status-1" || message.permission !== "session.status.read"
|
||||
|| capabilityRequests !== 0 || !grantedPermissions.includes("session.status.read")) {
|
||||
finish("capability-denied", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_PERMISSION_INVALID", "The Wasm worker requested an unapproved capability."));
|
||||
return;
|
||||
}
|
||||
capabilityRequests += 1;
|
||||
Promise.resolve().then(() => options.readSessionStatus(hostAbortController.signal)).then(sanitizeSkinExtensionSessionStatus).then((status) => {
|
||||
if (!active) return;
|
||||
approvedSessionStatus = status;
|
||||
worker.postMessage({ type: "capability-response", requestId: message.requestId, approved: true, status });
|
||||
}).catch(() => {
|
||||
if (active) worker.postMessage({ type: "capability-response", requestId: message.requestId, approved: false });
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (message.type === "running" && Object.keys(message).length === 1) {
|
||||
if (readySettled) {
|
||||
finish("invalid-message", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_MESSAGE_INVALID", "The Wasm worker sent an unexpected execution-start message."));
|
||||
return;
|
||||
}
|
||||
readySettled = true;
|
||||
if (startupTimer !== undefined) clearTimeout(startupTimer);
|
||||
resolveReady();
|
||||
executionTimer = window.setTimeout(() => finish("execution-timeout", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_EXECUTION_TIMEOUT", "The Wasm extension exceeded its execution time limit.")), SKIN_EXTENSION_WASM_EXECUTION_LIMIT_MS);
|
||||
return;
|
||||
}
|
||||
if (message.type === "complete") {
|
||||
const expectedKeys = ["type", "result", "linearMemoryBytes", "statusReadCount"];
|
||||
if (Object.keys(message).length !== expectedKeys.length
|
||||
|| Object.keys(message).some((key) => !expectedKeys.includes(key))
|
||||
|| (typeof message.result !== "number" && typeof message.result !== "string")
|
||||
|| !Number.isSafeInteger(message.linearMemoryBytes) || (message.linearMemoryBytes as number) < 0
|
||||
|| (message.linearMemoryBytes as number) > SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES * 64 * 1024
|
||||
|| !Number.isSafeInteger(message.statusReadCount) || (message.statusReadCount as number) < 0
|
||||
|| (message.statusReadCount as number) > SKIN_EXTENSION_WASM_STATUS_READ_LIMIT) {
|
||||
finish("invalid-result", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_RESULT_INVALID", "The Wasm worker returned a result outside its allowed shape."));
|
||||
return;
|
||||
}
|
||||
complete({ result: message.result as number | string, linearMemoryBytes: message.linearMemoryBytes as number,
|
||||
statusReadCount: message.statusReadCount as number, ...(approvedSessionStatus ? { sessionSnapshot: approvedSessionStatus } : {}) });
|
||||
return;
|
||||
}
|
||||
if (message.type === "error" && Object.keys(message).length === 3
|
||||
&& typeof message.code === "string" && typeof message.message === "string") {
|
||||
finish("worker-error", new SkinExtensionWasmSandboxError(message.code, message.message));
|
||||
return;
|
||||
}
|
||||
finish("invalid-message", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_MESSAGE_INVALID", "The Wasm worker returned an unsupported message."));
|
||||
};
|
||||
worker.onmessageerror = () => finish("message-deserialization-failed", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_MESSAGE_INVALID", "The Wasm worker message could not be decoded."));
|
||||
worker.onerror = () => finish("worker-error", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_WORKER_FAILED", "The isolated Wasm worker failed."));
|
||||
startupTimer = window.setTimeout(() => finish("startup-timeout", new SkinExtensionWasmSandboxError("SKIN_EXTENSION_WASM_STARTUP_TIMEOUT", "The Wasm worker did not finish initialization in time.")), SKIN_EXTENSION_WASM_STARTUP_TIMEOUT_MS);
|
||||
|
||||
const bytes = wasmBytes.buffer.slice(wasmBytes.byteOffset, wasmBytes.byteOffset + wasmBytes.byteLength) as ArrayBuffer;
|
||||
worker.postMessage({ type: "run", bytes, approvedPermissions: grantedPermissions }, [bytes]);
|
||||
|
||||
return {
|
||||
ready,
|
||||
result,
|
||||
stopped,
|
||||
get closed() { return !active; },
|
||||
get closeReason() { return closeReason; },
|
||||
get capabilityRequests() { return capabilityRequests; },
|
||||
revokePermission(permission) {
|
||||
if (manifest.permissions.includes(permission)) finish(`permission-revoked:${permission}`);
|
||||
},
|
||||
close(reason = "closed") { finish(reason); },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import {
|
||||
sanitizeSkinExtensionSessionStatus,
|
||||
type SkinExtensionSessionStatus,
|
||||
} from "../../../src/shared/skin-extension.js";
|
||||
import {
|
||||
SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES,
|
||||
SKIN_EXTENSION_WASM_FUEL_LIMIT,
|
||||
SKIN_EXTENSION_WASM_MESSAGE_LIMIT,
|
||||
SKIN_EXTENSION_WASM_STATUS_BYTES_LIMIT,
|
||||
SKIN_EXTENSION_WASM_STATUS_READ_LIMIT,
|
||||
validateSkinExtensionWasmImportsAndExports,
|
||||
} from "./skin-extension-wasm-policy.js";
|
||||
|
||||
interface RunMessage {
|
||||
type: "run";
|
||||
bytes: ArrayBuffer;
|
||||
approvedPermissions: string[];
|
||||
}
|
||||
|
||||
interface CapabilityResponse {
|
||||
type: "capability-response";
|
||||
requestId: string;
|
||||
approved: boolean;
|
||||
status?: unknown;
|
||||
}
|
||||
|
||||
interface WasmiInterpreterExports extends WebAssembly.Exports {
|
||||
memory: WebAssembly.Memory;
|
||||
alloc: (size: number) => number;
|
||||
run: (modulePointer: number, moduleLength: number, statusPointer: number, statusLength: number,
|
||||
statusPermissionGranted: number, memoryMaximumPages: number, fuel: bigint) => bigint;
|
||||
last_error_code: () => number;
|
||||
last_status_read_count: () => number;
|
||||
last_guest_memory_bytes: () => number;
|
||||
}
|
||||
|
||||
const scope = self as unknown as {
|
||||
addEventListener(type: string, listener: (event: MessageEvent<unknown>) => void): void;
|
||||
postMessage(message: unknown): void;
|
||||
};
|
||||
let started = false;
|
||||
let pendingCapability: { requestId: string; resolve: (message: CapabilityResponse) => void } | null = null;
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
const prototype = Object.getPrototypeOf(value);
|
||||
return prototype === Object.prototype || prototype === null;
|
||||
}
|
||||
|
||||
function sendError(code: string, message: string): void {
|
||||
scope.postMessage({ type: "error", code, message });
|
||||
}
|
||||
|
||||
scope.addEventListener("message", (event: MessageEvent<unknown>) => {
|
||||
const value = event.data;
|
||||
if (isPlainRecord(value) && value.type === "capability-response" && pendingCapability
|
||||
&& value.requestId === pendingCapability.requestId && typeof value.approved === "boolean") {
|
||||
const resolve = pendingCapability.resolve;
|
||||
pendingCapability = null;
|
||||
resolve(value as unknown as CapabilityResponse);
|
||||
return;
|
||||
}
|
||||
if (started || !isPlainRecord(value) || value.type !== "run" || !(value.bytes instanceof ArrayBuffer)
|
||||
|| !Array.isArray(value.approvedPermissions) || value.approvedPermissions.some((permission) => typeof permission !== "string")
|
||||
|| Object.keys(value).some((key) => !["type", "bytes", "approvedPermissions"].includes(key))) {
|
||||
sendError("SKIN_EXTENSION_WASM_JOB_INVALID", "The isolated Wasm job message is invalid.");
|
||||
return;
|
||||
}
|
||||
started = true;
|
||||
void run(value as unknown as RunMessage);
|
||||
});
|
||||
|
||||
async function requestSessionStatus(): Promise<SkinExtensionSessionStatus> {
|
||||
const requestId = "session-status-1";
|
||||
const response = await new Promise<CapabilityResponse>((resolve) => {
|
||||
pendingCapability = { requestId, resolve };
|
||||
scope.postMessage({ type: "capability-request", requestId, permission: "session.status.read" });
|
||||
});
|
||||
if (!response.approved) throw new Error("The host denied session.status.read.");
|
||||
return sanitizeSkinExtensionSessionStatus(response.status);
|
||||
}
|
||||
|
||||
async function run(job: RunMessage): Promise<void> {
|
||||
try {
|
||||
const bytes = new Uint8Array(job.bytes);
|
||||
const metadata = validateSkinExtensionWasmImportsAndExports(bytes, job.approvedPermissions);
|
||||
const interpreter = await loadWasmiInterpreter();
|
||||
const status = metadata.usesSessionStatus ? await requestSessionStatus() : null;
|
||||
const statusBytes = status ? new TextEncoder().encode(JSON.stringify(status)) : null;
|
||||
if (statusBytes && statusBytes.byteLength > SKIN_EXTENSION_WASM_STATUS_BYTES_LIMIT) {
|
||||
sendError("SKIN_EXTENSION_WASM_STATUS_SIZE", "The approved session snapshot exceeds its size limit.");
|
||||
return;
|
||||
}
|
||||
|
||||
const payloadLength = bytes.byteLength + (statusBytes?.byteLength ?? 0);
|
||||
const pointer = interpreter.alloc(payloadLength);
|
||||
if (!pointer) {
|
||||
sendError("SKIN_EXTENSION_WASM_INTERPRETER_MEMORY_LIMIT", "The extension input exceeds the interpreter's bounded memory.");
|
||||
return;
|
||||
}
|
||||
new Uint8Array(interpreter.memory.buffer, pointer, bytes.byteLength).set(bytes);
|
||||
const statusPointer = statusBytes ? pointer + bytes.byteLength : 0;
|
||||
if (statusBytes) new Uint8Array(interpreter.memory.buffer, statusPointer, statusBytes.byteLength).set(statusBytes);
|
||||
|
||||
scope.postMessage({ type: "running" });
|
||||
const rawResult = interpreter.run(pointer, bytes.byteLength, statusPointer, statusBytes?.byteLength ?? 0,
|
||||
metadata.usesSessionStatus ? 1 : 0, metadata.memoryMaximumPages, SKIN_EXTENSION_WASM_FUEL_LIMIT);
|
||||
const errorCode = interpreter.last_error_code();
|
||||
if (errorCode !== 0) {
|
||||
const code = errorCode === 5 ? "SKIN_EXTENSION_WASM_EXECUTION_LIMIT"
|
||||
: errorCode === 6 ? "SKIN_EXTENSION_WASM_MEMORY_LIMIT"
|
||||
: errorCode === 10 ? "SKIN_EXTENSION_WASM_IMPORT_INVALID"
|
||||
: errorCode === 11 ? "SKIN_EXTENSION_WASM_PERMISSION_INVALID"
|
||||
: "SKIN_EXTENSION_WASM_INTERPRETER_FAILED";
|
||||
sendError(code, "The extension was rejected or stopped inside the bounded Wasmi interpreter.");
|
||||
return;
|
||||
}
|
||||
|
||||
const result = Number(rawResult);
|
||||
const statusReadCount = interpreter.last_status_read_count();
|
||||
const linearMemoryBytes = interpreter.last_guest_memory_bytes();
|
||||
if (!Number.isSafeInteger(result) || !Number.isSafeInteger(statusReadCount) || statusReadCount < 0
|
||||
|| statusReadCount > SKIN_EXTENSION_WASM_STATUS_READ_LIMIT || !Number.isSafeInteger(linearMemoryBytes)
|
||||
|| linearMemoryBytes < 0 || linearMemoryBytes > metadata.memoryMaximumPages * 64 * 1024
|
||||
|| linearMemoryBytes > SKIN_EXTENSION_WASM_MEMORY_LIMIT_PAGES * 64 * 1024) {
|
||||
sendError("SKIN_EXTENSION_WASM_RESULT_INVALID", "The interpreter returned a value outside the allowed resource policy.");
|
||||
return;
|
||||
}
|
||||
const message = {
|
||||
type: "complete",
|
||||
result,
|
||||
linearMemoryBytes,
|
||||
statusReadCount,
|
||||
};
|
||||
if (new TextEncoder().encode(JSON.stringify(message)).byteLength > SKIN_EXTENSION_WASM_MESSAGE_LIMIT) {
|
||||
sendError("SKIN_EXTENSION_WASM_MESSAGE_SIZE", "The module result exceeds its message limit.");
|
||||
return;
|
||||
}
|
||||
scope.postMessage(message);
|
||||
} catch (error) {
|
||||
const candidate = error as { code?: unknown; message?: unknown };
|
||||
const code = typeof candidate?.code === "string" ? candidate.code : "SKIN_EXTENSION_WASM_FAILED";
|
||||
const detail = typeof candidate?.message === "string" ? ` ${candidate.message.slice(0, 240)}` : "";
|
||||
sendError(code, `The bounded Wasm extension failed validation or execution.${detail}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadWasmiInterpreter(): Promise<WasmiInterpreterExports> {
|
||||
const response = await fetch(new URL("/skin-wasm-interpreter.wasm", self.location.origin), { cache: "force-cache" });
|
||||
if (!response.ok) throw new Error("The bounded Wasmi interpreter asset could not be loaded.");
|
||||
const contentLength = Number(response.headers.get("content-length"));
|
||||
if (Number.isFinite(contentLength) && (contentLength < 8 || contentLength > 8 * 1024 * 1024)) {
|
||||
throw new Error("The bounded Wasmi interpreter asset has an invalid size.");
|
||||
}
|
||||
const artifact = await response.arrayBuffer();
|
||||
if (artifact.byteLength < 8 || artifact.byteLength > 8 * 1024 * 1024) {
|
||||
throw new Error("The bounded Wasmi interpreter asset has an invalid size.");
|
||||
}
|
||||
const { instance } = await WebAssembly.instantiate(artifact);
|
||||
const exports = instance.exports as unknown as WasmiInterpreterExports;
|
||||
if (!(exports.memory instanceof WebAssembly.Memory) || typeof exports.alloc !== "function"
|
||||
|| typeof exports.run !== "function" || typeof exports.last_error_code !== "function"
|
||||
|| typeof exports.last_status_read_count !== "function" || typeof exports.last_guest_memory_bytes !== "function") {
|
||||
throw new Error("The bounded Wasmi interpreter exposes an incompatible runtime interface.");
|
||||
}
|
||||
return exports;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { orderSequentialFocusTargets } from "./skin-layout-focus.js";
|
||||
|
||||
test("focus preview follows browser order: positive tabindex first, then DOM order, excluding negative targets", () => {
|
||||
const targets = [
|
||||
{ id: "first-dom", tabIndex: 0 },
|
||||
{ id: "second-positive", tabIndex: 2 },
|
||||
{ id: "first-positive", tabIndex: 1 },
|
||||
{ id: "programmatic-only", tabIndex: -1 },
|
||||
{ id: "second-dom", tabIndex: 0 },
|
||||
{ id: "same-positive", tabIndex: 1 },
|
||||
];
|
||||
|
||||
assert.deepEqual(orderSequentialFocusTargets(targets).map((target) => target.id), [
|
||||
"first-positive", "same-positive", "second-positive", "first-dom", "second-dom",
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
export interface SequentialFocusTarget {
|
||||
tabIndex: number;
|
||||
}
|
||||
|
||||
/** Mirrors browser sequential focus order for a DOM-ordered list of focusable controls. */
|
||||
export function orderSequentialFocusTargets<T extends SequentialFocusTarget>(targets: readonly T[]): T[] {
|
||||
return targets
|
||||
.map((target, domOrder) => ({ target, domOrder }))
|
||||
.filter(({ target }) => Number.isInteger(target.tabIndex) && target.tabIndex >= 0)
|
||||
.sort((left, right) => {
|
||||
const leftBucket = left.target.tabIndex > 0 ? 0 : 1;
|
||||
const rightBucket = right.target.tabIndex > 0 ? 0 : 1;
|
||||
return leftBucket - rightBucket
|
||||
|| (leftBucket === 0 ? left.target.tabIndex - right.target.tabIndex : 0)
|
||||
|| left.domOrder - right.domOrder;
|
||||
})
|
||||
.map(({ target }) => target);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
analyzeSkinLayoutGeometry,
|
||||
clampSkinLayoutOffset,
|
||||
getSkinLayoutOffsetBounds,
|
||||
} from "./skin-layout-geometry.js";
|
||||
|
||||
const page = { left: 0, top: 0, right: 800, bottom: 600 };
|
||||
|
||||
test("layout diagnostics detect collision and overflow only when bounds actually intersect", () => {
|
||||
const target = { left: 700, top: 520, right: 840, bottom: 660 };
|
||||
const issues = analyzeSkinLayoutGeometry([target], page, [{ left: 720, top: 540, right: 780, bottom: 580 }]);
|
||||
assert.deepEqual(issues, { overflow: true, overlap: true });
|
||||
assert.deepEqual(analyzeSkinLayoutGeometry(
|
||||
[{ left: 0, top: 0, right: 40, bottom: 40 }], page,
|
||||
[{ left: 48, top: 0, right: 90, bottom: 40 }],
|
||||
), { overflow: false, overlap: false });
|
||||
assert.deepEqual(analyzeSkinLayoutGeometry([
|
||||
{ left: 0, top: 0, right: 140, bottom: 80 },
|
||||
{ left: 100, top: 0, right: 240, bottom: 80 },
|
||||
], page, []), { overflow: false, overlap: true });
|
||||
});
|
||||
|
||||
test("position controls clamp every matching instance inside the available layout container", () => {
|
||||
const bounds = getSkinLayoutOffsetBounds([
|
||||
{ left: 100, top: 80, right: 220, bottom: 160 },
|
||||
{ left: 300, top: 300, right: 420, bottom: 380 },
|
||||
], page, 0, "x");
|
||||
assert.deepEqual(bounds, { minimum: -100, maximum: 380 });
|
||||
assert.equal(clampSkinLayoutOffset(-500, bounds), -100);
|
||||
assert.equal(clampSkinLayoutOffset(500, bounds), 380);
|
||||
assert.equal(getSkinLayoutOffsetBounds([{ left: -40, top: 20, right: 860, bottom: 50 }], page, 0, "x"), null);
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
export interface SkinLayoutRect {
|
||||
left: number;
|
||||
top: number;
|
||||
right: number;
|
||||
bottom: number;
|
||||
}
|
||||
|
||||
export interface SkinLayoutOffsetBounds {
|
||||
minimum: number;
|
||||
maximum: number;
|
||||
}
|
||||
|
||||
export interface SkinLayoutGeometryIssues {
|
||||
overflow: boolean;
|
||||
overlap: boolean;
|
||||
}
|
||||
|
||||
export function analyzeSkinLayoutGeometry(
|
||||
targets: readonly SkinLayoutRect[],
|
||||
container: SkinLayoutRect,
|
||||
peers: readonly SkinLayoutRect[],
|
||||
overlapThreshold = 8,
|
||||
): SkinLayoutGeometryIssues {
|
||||
const intersects = (first: SkinLayoutRect, second: SkinLayoutRect) => {
|
||||
const width = Math.min(first.right, second.right) - Math.max(first.left, second.left);
|
||||
const height = Math.min(first.bottom, second.bottom) - Math.max(first.top, second.top);
|
||||
return width > overlapThreshold && height > overlapThreshold;
|
||||
};
|
||||
const overflow = targets.some((target) => target.left < container.left - 1 || target.top < container.top - 1
|
||||
|| target.right > container.right + 1 || target.bottom > container.bottom + 1);
|
||||
const overlap = targets.some((target, index) => peers.some((peer) => intersects(target, peer))
|
||||
|| targets.slice(index + 1).some((peer) => intersects(target, peer)));
|
||||
return { overflow, overlap };
|
||||
}
|
||||
|
||||
export function getSkinLayoutOffsetBounds(
|
||||
targets: readonly SkinLayoutRect[],
|
||||
container: SkinLayoutRect,
|
||||
currentOffset: number,
|
||||
axis: "x" | "y",
|
||||
absoluteLimit = 2000,
|
||||
): SkinLayoutOffsetBounds | null {
|
||||
if (!targets.length || !Number.isFinite(currentOffset)) return null;
|
||||
const containerStart = axis === "x" ? container.left : container.top;
|
||||
const containerEnd = axis === "x" ? container.right : container.bottom;
|
||||
let minimum = -absoluteLimit;
|
||||
let maximum = absoluteLimit;
|
||||
for (const target of targets) {
|
||||
const start = axis === "x" ? target.left : target.top;
|
||||
const end = axis === "x" ? target.right : target.bottom;
|
||||
const baseStart = start - currentOffset;
|
||||
const baseEnd = end - currentOffset;
|
||||
minimum = Math.max(minimum, containerStart - baseStart);
|
||||
maximum = Math.min(maximum, containerEnd - baseEnd);
|
||||
}
|
||||
return minimum <= maximum ? { minimum: Math.ceil(minimum), maximum: Math.floor(maximum) } : null;
|
||||
}
|
||||
|
||||
export function clampSkinLayoutOffset(value: number, bounds: SkinLayoutOffsetBounds | null): number {
|
||||
if (!bounds || !Number.isFinite(value)) return 0;
|
||||
return Math.max(bounds.minimum, Math.min(bounds.maximum, Math.round(value)));
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
import layoutRuntimeCss from "../skins/layout-runtime.css?inline";
|
||||
import {
|
||||
canEditSkinLayoutComponent,
|
||||
getSkinLayoutComponentId,
|
||||
getSkinLayoutComponent,
|
||||
type SkinLayoutDocument,
|
||||
type SkinLayoutPage,
|
||||
type SkinLayoutPlacement,
|
||||
type SkinLayoutProfile,
|
||||
} from "../../../src/shared/skin-layout.js";
|
||||
import {
|
||||
clearSkinLayoutOverrides,
|
||||
loadSkinLayoutOverrides,
|
||||
saveSkinLayoutOverrides,
|
||||
updateSkinLayoutOverride,
|
||||
} from "./skin-layout-storage.js";
|
||||
|
||||
const STYLE_ID = "webspeak-layout-runtime";
|
||||
const MOBILE_QUERY = "(max-width: 740px)";
|
||||
const TABLET_QUERY = "(min-width: 741px) and (max-width: 1100px)";
|
||||
|
||||
export interface ActiveSkinLayoutContext {
|
||||
root: HTMLElement;
|
||||
skinId: string;
|
||||
page: SkinLayoutPage;
|
||||
profile: SkinLayoutProfile;
|
||||
}
|
||||
|
||||
let activePackageSkinId: string | null = null;
|
||||
let activePackageLayout: SkinLayoutDocument | null = null;
|
||||
let observer: MutationObserver | null = null;
|
||||
let refreshFrame = 0;
|
||||
let editorEnabled = false;
|
||||
let selectedComponentId: string | null = null;
|
||||
let previewComponentId: string | null = null;
|
||||
let previewPlacement: SkinLayoutPlacement | null = null;
|
||||
let previewScope = "";
|
||||
|
||||
function isLayoutPage(value: string | undefined): value is SkinLayoutPage {
|
||||
return value === "home" || value === "voice" || value === "demo";
|
||||
}
|
||||
|
||||
function currentProfile(): SkinLayoutProfile {
|
||||
if (typeof window === "undefined") return "desktop";
|
||||
if (window.matchMedia(MOBILE_QUERY).matches) return "mobile";
|
||||
return window.matchMedia(TABLET_QUERY).matches ? "tablet" : "desktop";
|
||||
}
|
||||
|
||||
function activeRoots(): HTMLElement[] {
|
||||
if (typeof document === "undefined") return [];
|
||||
return [...document.querySelectorAll<HTMLElement>(".ws-skin-root[data-ws-page]")];
|
||||
}
|
||||
|
||||
export function getActiveSkinLayoutContext(): ActiveSkinLayoutContext | null {
|
||||
const root = activeRoots()[0];
|
||||
if (!root || !isLayoutPage(root.dataset.wsPage)) return null;
|
||||
return {
|
||||
root,
|
||||
skinId: root.dataset.wsSkin || activePackageSkinId || "builtin.light",
|
||||
page: root.dataset.wsPage,
|
||||
profile: currentProfile(),
|
||||
};
|
||||
}
|
||||
|
||||
function effectivePlacements(context: ActiveSkinLayoutContext): Record<string, SkinLayoutPlacement> {
|
||||
const packageEntries = activePackageSkinId === context.skinId
|
||||
? activePackageLayout?.pages[context.page]?.[context.profile] ?? {}
|
||||
: {};
|
||||
const userEntries = loadSkinLayoutOverrides(context.skinId).pages[context.page]?.[context.profile] ?? {};
|
||||
const result: Record<string, SkinLayoutPlacement> = {};
|
||||
for (const [id, placement] of Object.entries(packageEntries)) result[id] = { ...placement };
|
||||
for (const [id, placement] of Object.entries(userEntries)) result[id] = { ...result[id], ...placement };
|
||||
const scope = context.skinId + ":" + context.page + ":" + context.profile;
|
||||
if (previewComponentId && previewPlacement && previewScope === scope) {
|
||||
result[previewComponentId] = { ...result[previewComponentId], ...previewPlacement };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function setVariable(element: HTMLElement, dataFlag: string, variable: string, value: string | undefined): void {
|
||||
if (value === undefined) {
|
||||
delete element.dataset[dataFlag];
|
||||
element.style.removeProperty(variable);
|
||||
} else {
|
||||
element.dataset[dataFlag] = "true";
|
||||
element.style.setProperty(variable, value);
|
||||
}
|
||||
}
|
||||
|
||||
function clearLayoutAttributes(element: HTMLElement): void {
|
||||
for (const key of ["wsLayoutActive", "wsLayoutHidden", "wsLayoutSelected", "wsLayoutForeground", "wsLayoutBackground", "wsLayoutBorder", "wsLayoutRadius", "wsLayoutWidth", "wsLayoutHeight", "wsLayoutTouchTarget"]) {
|
||||
delete element.dataset[key];
|
||||
}
|
||||
for (const key of ["--ws-layout-x", "--ws-layout-y", "--ws-layout-scale", "--ws-layout-width", "--ws-layout-height", "--ws-layout-foreground", "--ws-layout-background", "--ws-layout-border", "--ws-layout-radius"]) {
|
||||
element.style.removeProperty(key);
|
||||
}
|
||||
}
|
||||
|
||||
function componentId(element: HTMLElement): string | null {
|
||||
return getSkinLayoutComponentId(element.dataset.wsPart, element.dataset.wsControlKind);
|
||||
}
|
||||
|
||||
function trustedAncestorIds(element: HTMLElement, root: HTMLElement): string[] {
|
||||
const ids: string[] = [];
|
||||
let ancestor = element.parentElement;
|
||||
while (ancestor && ancestor !== root) {
|
||||
const id = componentId(ancestor);
|
||||
if (id) ids.push(id);
|
||||
ancestor = ancestor.parentElement;
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function applyRoot(root: HTMLElement): void {
|
||||
const pageValue = root.dataset.wsPage;
|
||||
if (!isLayoutPage(pageValue)) return;
|
||||
const skinId = root.dataset.wsSkin || activePackageSkinId || "builtin.light";
|
||||
const context: ActiveSkinLayoutContext = { root, skinId, page: pageValue, profile: currentProfile() };
|
||||
const placements = effectivePlacements(context);
|
||||
const nodes = [
|
||||
...(root.matches("[data-ws-part]") ? [root] : []),
|
||||
...root.querySelectorAll<HTMLElement>("[data-ws-part]"),
|
||||
];
|
||||
for (const element of nodes) {
|
||||
const id = componentId(element);
|
||||
const component = id ? getSkinLayoutComponent(id, context.page) : undefined;
|
||||
if (!component || !canEditSkinLayoutComponent(id!, context.page, trustedAncestorIds(element, root))) {
|
||||
clearLayoutAttributes(element);
|
||||
continue;
|
||||
}
|
||||
const placement = placements[id!];
|
||||
if (!placement || !Object.keys(placement).length) {
|
||||
clearLayoutAttributes(element);
|
||||
// Registered touch controls keep their minimum hit area even before a
|
||||
// user applies a layout override; editing must never be required for safety.
|
||||
if (component.minTouchTarget) element.dataset.wsLayoutTouchTarget = String(component.minTouchTarget);
|
||||
continue;
|
||||
}
|
||||
element.dataset.wsLayoutActive = "true";
|
||||
if (component.minTouchTarget) element.dataset.wsLayoutTouchTarget = String(component.minTouchTarget);
|
||||
else delete element.dataset.wsLayoutTouchTarget;
|
||||
if (placement.visible === false) element.dataset.wsLayoutHidden = "true";
|
||||
else delete element.dataset.wsLayoutHidden;
|
||||
if (placement.x !== undefined) element.style.setProperty("--ws-layout-x", placement.x + "px");
|
||||
else element.style.removeProperty("--ws-layout-x");
|
||||
if (placement.y !== undefined) element.style.setProperty("--ws-layout-y", placement.y + "px");
|
||||
else element.style.removeProperty("--ws-layout-y");
|
||||
if (placement.scale !== undefined) element.style.setProperty("--ws-layout-scale", String(placement.scale));
|
||||
else element.style.removeProperty("--ws-layout-scale");
|
||||
setVariable(element, "wsLayoutWidth", "--ws-layout-width", placement.width === undefined ? undefined : placement.width + "px");
|
||||
setVariable(element, "wsLayoutHeight", "--ws-layout-height", placement.height === undefined ? undefined : placement.height + "px");
|
||||
setVariable(element, "wsLayoutForeground", "--ws-layout-foreground", placement.foreground);
|
||||
setVariable(element, "wsLayoutBackground", "--ws-layout-background", placement.background);
|
||||
setVariable(element, "wsLayoutBorder", "--ws-layout-border", placement.border);
|
||||
setVariable(element, "wsLayoutRadius", "--ws-layout-radius", placement.radius === undefined ? undefined : placement.radius + "px");
|
||||
if (editorEnabled && selectedComponentId === id) element.dataset.wsLayoutSelected = "true";
|
||||
else delete element.dataset.wsLayoutSelected;
|
||||
}
|
||||
root.dataset.wsLayoutEditing = editorEnabled ? "true" : "false";
|
||||
}
|
||||
|
||||
export function refreshSkinLayout(): void {
|
||||
if (typeof document === "undefined") return;
|
||||
for (const root of activeRoots()) applyRoot(root);
|
||||
}
|
||||
|
||||
function scheduleRefresh(): void {
|
||||
if (typeof window === "undefined" || refreshFrame) return;
|
||||
refreshFrame = window.requestAnimationFrame(() => {
|
||||
refreshFrame = 0;
|
||||
refreshSkinLayout();
|
||||
});
|
||||
}
|
||||
|
||||
export function initializeSkinLayoutRuntime(): void {
|
||||
if (typeof document === "undefined") return;
|
||||
if (!document.getElementById(STYLE_ID)) {
|
||||
const style = document.createElement("style");
|
||||
style.id = STYLE_ID;
|
||||
style.textContent = layoutRuntimeCss;
|
||||
document.head.append(style);
|
||||
}
|
||||
if (!observer) {
|
||||
observer = new MutationObserver(scheduleRefresh);
|
||||
observer.observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
attributeFilter: ["data-ws-page", "data-ws-skin", "data-ws-part", "data-ws-control-kind"],
|
||||
});
|
||||
window.addEventListener("resize", scheduleRefresh, { passive: true });
|
||||
}
|
||||
scheduleRefresh();
|
||||
}
|
||||
|
||||
export function setSkinLayoutPackage(skinId: string, layout: SkinLayoutDocument | null): void {
|
||||
activePackageSkinId = skinId;
|
||||
activePackageLayout = layout;
|
||||
previewComponentId = null;
|
||||
previewPlacement = null;
|
||||
previewScope = "";
|
||||
scheduleRefresh();
|
||||
}
|
||||
|
||||
export function setSkinLayoutEditorState(enabled: boolean, selectedId: string | null = selectedComponentId): void {
|
||||
editorEnabled = enabled;
|
||||
selectedComponentId = enabled ? selectedId : null;
|
||||
scheduleRefresh();
|
||||
}
|
||||
|
||||
export function getEffectiveSkinLayoutPlacement(componentIdValue: string): SkinLayoutPlacement | undefined {
|
||||
const context = getActiveSkinLayoutContext();
|
||||
if (!context || !getSkinLayoutComponent(componentIdValue, context.page)?.editable) return undefined;
|
||||
return effectivePlacements(context)[componentIdValue];
|
||||
}
|
||||
|
||||
export function getActiveSkinLayoutOverride(componentIdValue: string): SkinLayoutPlacement | undefined {
|
||||
const context = getActiveSkinLayoutContext();
|
||||
if (!context || !getSkinLayoutComponent(componentIdValue, context.page)?.editable) return undefined;
|
||||
return loadSkinLayoutOverrides(context.skinId).pages[context.page]?.[context.profile]?.[componentIdValue];
|
||||
}
|
||||
|
||||
export function previewActiveSkinLayoutPlacement(componentIdValue: string, placement: SkinLayoutPlacement | null): void {
|
||||
const context = getActiveSkinLayoutContext();
|
||||
previewComponentId = context && placement ? componentIdValue : null;
|
||||
previewPlacement = context ? placement : null;
|
||||
previewScope = context ? context.skinId + ":" + context.page + ":" + context.profile : "";
|
||||
scheduleRefresh();
|
||||
}
|
||||
|
||||
export function saveActiveSkinLayoutPlacement(componentIdValue: string, placement: SkinLayoutPlacement | null): void {
|
||||
const context = getActiveSkinLayoutContext();
|
||||
if (!context) throw new Error("There is no active public skin layout.");
|
||||
previewComponentId = null;
|
||||
previewPlacement = null;
|
||||
previewScope = "";
|
||||
updateSkinLayoutOverride(context.skinId, context.page, context.profile, componentIdValue, placement);
|
||||
scheduleRefresh();
|
||||
}
|
||||
|
||||
export function getActiveSkinLayoutOverrides(): SkinLayoutDocument {
|
||||
const context = getActiveSkinLayoutContext();
|
||||
return context ? loadSkinLayoutOverrides(context.skinId) : { schemaVersion: 1, pages: {} };
|
||||
}
|
||||
|
||||
export function replaceActiveSkinLayoutOverrides(layout: SkinLayoutDocument): void {
|
||||
const context = getActiveSkinLayoutContext();
|
||||
if (!context) throw new Error("There is no active public skin layout.");
|
||||
saveSkinLayoutOverrides(context.skinId, layout);
|
||||
scheduleRefresh();
|
||||
}
|
||||
|
||||
export function clearActiveSkinLayoutOverrides(): void {
|
||||
const context = getActiveSkinLayoutContext();
|
||||
if (!context) return;
|
||||
previewComponentId = null;
|
||||
previewPlacement = null;
|
||||
previewScope = "";
|
||||
clearSkinLayoutOverrides(context.skinId);
|
||||
scheduleRefresh();
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
clearSkinLayoutOverrides,
|
||||
exportSkinLayoutMigrationRecovery,
|
||||
getSkinLayoutMigrationRecovery,
|
||||
LEGACY_SKIN_LAYOUT_STORAGE_KEY,
|
||||
loadSkinLayoutOverrides,
|
||||
saveSkinLayoutOverrides,
|
||||
SKIN_LAYOUT_STORAGE_KEY,
|
||||
} from "./skin-layout-storage.js";
|
||||
|
||||
class MemoryStorage {
|
||||
private readonly values = new Map<string, string>();
|
||||
getItem(key: string): string | null { return this.values.get(key) ?? null; }
|
||||
setItem(key: string, value: string): void { this.values.set(key, value); }
|
||||
}
|
||||
|
||||
function withLocalStorage<T>(run: (storage: MemoryStorage) => T): T {
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
|
||||
const storage = new MemoryStorage();
|
||||
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: storage });
|
||||
try { return run(storage); }
|
||||
finally {
|
||||
if (previous) Object.defineProperty(globalThis, "localStorage", previous);
|
||||
else Reflect.deleteProperty(globalThis, "localStorage");
|
||||
}
|
||||
}
|
||||
|
||||
test("legacy local layouts migrate matching entries and keep incompatible entries recoverable", () => {
|
||||
withLocalStorage((storage) => {
|
||||
const legacy = JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
skins: {
|
||||
"community.illusia-voice": {
|
||||
schemaVersion: 1,
|
||||
pages: { home: { desktop: {
|
||||
"home.header": { x: 32 },
|
||||
"home.retired-component": { x: 80 },
|
||||
"home.security-note": { visible: false },
|
||||
"home.connect": { scale: 0.5 },
|
||||
} } },
|
||||
},
|
||||
},
|
||||
});
|
||||
storage.setItem(LEGACY_SKIN_LAYOUT_STORAGE_KEY, legacy);
|
||||
|
||||
const migrated = loadSkinLayoutOverrides("community.illusia-voice");
|
||||
assert.deepEqual(migrated.pages.home?.desktop, { "home.header": { x: 32 } });
|
||||
assert.deepEqual(JSON.parse(storage.getItem(SKIN_LAYOUT_STORAGE_KEY) ?? "null").schemaVersion, 2);
|
||||
assert.equal(storage.getItem(LEGACY_SKIN_LAYOUT_STORAGE_KEY), legacy, "the source config remains intact as a backup");
|
||||
|
||||
const recovery = getSkinLayoutMigrationRecovery("community.illusia-voice");
|
||||
assert.equal(recovery?.sourceVersion, 1);
|
||||
assert.equal(recovery?.items.length, 3);
|
||||
assert.equal(recovery?.omittedCount, 0);
|
||||
const exported = JSON.parse(exportSkinLayoutMigrationRecovery("community.illusia-voice"));
|
||||
assert.equal(exported.skinId, "community.illusia-voice");
|
||||
assert.equal(exported.items.length, 3);
|
||||
});
|
||||
});
|
||||
|
||||
test("version 2 layout overrides can be saved, loaded, and cleared per skin", () => {
|
||||
withLocalStorage((storage) => {
|
||||
saveSkinLayoutOverrides("community.illusia-voice", {
|
||||
schemaVersion: 1,
|
||||
pages: { home: { mobile: { "home.header": { x: 8, visible: true } } } },
|
||||
});
|
||||
assert.equal(loadSkinLayoutOverrides("community.illusia-voice").pages.home?.mobile?.["home.header"]?.x, 8);
|
||||
clearSkinLayoutOverrides("community.illusia-voice");
|
||||
assert.deepEqual(loadSkinLayoutOverrides("community.illusia-voice"), { schemaVersion: 1, pages: {} });
|
||||
assert.equal(JSON.parse(storage.getItem(SKIN_LAYOUT_STORAGE_KEY) ?? "null").schemaVersion, 2);
|
||||
});
|
||||
});
|
||||
|
||||
test("an unknown newer local storage version is preserved instead of overwritten", () => {
|
||||
withLocalStorage((storage) => {
|
||||
const future = JSON.stringify({ schemaVersion: 99, skins: { "community.illusia-voice": { retained: true } } });
|
||||
storage.setItem(SKIN_LAYOUT_STORAGE_KEY, future);
|
||||
assert.throws(() => saveSkinLayoutOverrides("community.illusia-voice", { schemaVersion: 1, pages: {} }));
|
||||
assert.equal(storage.getItem(SKIN_LAYOUT_STORAGE_KEY), future);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,266 @@
|
||||
import {
|
||||
getSkinLayoutComponent,
|
||||
parseSkinLayoutJson,
|
||||
validateSkinLayout,
|
||||
type SkinLayoutDocument,
|
||||
type SkinLayoutPage,
|
||||
type SkinLayoutPlacement,
|
||||
type SkinLayoutProfile,
|
||||
} from "../../../src/shared/skin-layout.js";
|
||||
|
||||
export const SKIN_LAYOUT_STORAGE_KEY = "webspeak:skin-layouts:v2";
|
||||
export const LEGACY_SKIN_LAYOUT_STORAGE_KEY = "webspeak:skin-layouts:v1";
|
||||
const MAX_STORAGE_BYTES = 1024 * 1024;
|
||||
const MAX_RECOVERY_BYTES = 128 * 1024;
|
||||
|
||||
interface SkinLayoutCollection {
|
||||
schemaVersion: 2;
|
||||
skins: Record<string, SkinLayoutDocument>;
|
||||
recoveries: Record<string, SkinLayoutMigrationRecovery>;
|
||||
}
|
||||
|
||||
export interface SkinLayoutMigrationRecovery {
|
||||
sourceVersion: number;
|
||||
items: Array<{ page: string; profile: string; componentId: string; placement: unknown }>;
|
||||
omittedCount: number;
|
||||
backupKey: string;
|
||||
}
|
||||
|
||||
interface StorageLike {
|
||||
getItem(key: string): string | null;
|
||||
setItem(key: string, value: string): void;
|
||||
}
|
||||
|
||||
function emptyDocument(): SkinLayoutDocument {
|
||||
return { schemaVersion: 1, pages: {} };
|
||||
}
|
||||
|
||||
function emptyCollection(): SkinLayoutCollection {
|
||||
return { schemaVersion: 2, skins: {}, recoveries: {} };
|
||||
}
|
||||
|
||||
function isSkinId(value: string): boolean {
|
||||
return value.length <= 80 && /^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(value);
|
||||
}
|
||||
|
||||
function getBrowserStorage(): StorageLike | null {
|
||||
try {
|
||||
return typeof localStorage === "undefined" ? null : localStorage;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function serializedBytes(value: unknown): number {
|
||||
return new TextEncoder().encode(JSON.stringify(value)).byteLength;
|
||||
}
|
||||
|
||||
function parseCollection(source: string | null): SkinLayoutCollection {
|
||||
if (!source) return emptyCollection();
|
||||
if (new TextEncoder().encode(source).byteLength > MAX_STORAGE_BYTES) throw new Error("Saved skin layouts exceed the local storage limit.");
|
||||
let raw: unknown;
|
||||
try { raw = JSON.parse(source); }
|
||||
catch { throw new Error("Saved skin layouts are not valid JSON."); }
|
||||
if (!isRecord(raw) || raw.schemaVersion !== 2 || !isRecord(raw.skins) || !isRecord(raw.recoveries)) {
|
||||
throw new Error("Saved skin layouts use an unsupported storage version.");
|
||||
}
|
||||
const skins: Record<string, SkinLayoutDocument> = {};
|
||||
for (const [id, layout] of Object.entries(raw.skins)) {
|
||||
if (!isSkinId(id)) throw new Error("Saved skin layouts contain an invalid skin ID.");
|
||||
skins[id] = validateSkinLayout(layout);
|
||||
}
|
||||
const recoveries: Record<string, SkinLayoutMigrationRecovery> = {};
|
||||
for (const [id, recovery] of Object.entries(raw.recoveries)) {
|
||||
if (!isSkinId(id) || !isRecord(recovery) || !Array.isArray(recovery.items)
|
||||
|| typeof recovery.sourceVersion !== "number" || !Number.isInteger(recovery.sourceVersion)
|
||||
|| typeof recovery.omittedCount !== "number" || !Number.isInteger(recovery.omittedCount)
|
||||
|| recovery.items.length > 1024) throw new Error("Saved skin layout recovery data is invalid.");
|
||||
recoveries[id] = {
|
||||
sourceVersion: recovery.sourceVersion,
|
||||
items: recovery.items.filter(isRecord).map((item) => ({
|
||||
page: typeof item.page === "string" ? item.page.slice(0, 80) : "",
|
||||
profile: typeof item.profile === "string" ? item.profile.slice(0, 20) : "",
|
||||
componentId: typeof item.componentId === "string" ? item.componentId.slice(0, 120) : "",
|
||||
placement: item.placement,
|
||||
})),
|
||||
omittedCount: Math.max(0, recovery.omittedCount),
|
||||
backupKey: LEGACY_SKIN_LAYOUT_STORAGE_KEY,
|
||||
};
|
||||
}
|
||||
return { schemaVersion: 2, skins, recoveries };
|
||||
}
|
||||
|
||||
function recoverLegacyLayout(layout: unknown): { layout: SkinLayoutDocument; items: SkinLayoutMigrationRecovery["items"] } {
|
||||
const items: SkinLayoutMigrationRecovery["items"] = [];
|
||||
const pages: SkinLayoutDocument["pages"] = {};
|
||||
const remember = (page: string, profile: string, componentId: string, placement: unknown) => {
|
||||
if (items.length < 1024) items.push({ page: page.slice(0, 80), profile: profile.slice(0, 20), componentId: componentId.slice(0, 120), placement });
|
||||
};
|
||||
if (!isRecord(layout) || layout.schemaVersion !== 1 || !isRecord(layout.pages)) {
|
||||
remember("", "", "__document__", layout);
|
||||
return { layout: emptyDocument(), items };
|
||||
}
|
||||
for (const [pageKey, rawPage] of Object.entries(layout.pages)) {
|
||||
if (!(pageKey === "home" || pageKey === "voice" || pageKey === "demo") || !isRecord(rawPage)) {
|
||||
remember(pageKey, "", "__page__", rawPage);
|
||||
continue;
|
||||
}
|
||||
const profiles: NonNullable<SkinLayoutDocument["pages"][SkinLayoutPage]> = {};
|
||||
for (const [profileKey, rawProfile] of Object.entries(rawPage)) {
|
||||
if (!(profileKey === "desktop" || profileKey === "tablet" || profileKey === "mobile") || !isRecord(rawProfile)) {
|
||||
remember(pageKey, profileKey, "__profile__", rawProfile);
|
||||
continue;
|
||||
}
|
||||
const placements: Record<string, SkinLayoutPlacement> = {};
|
||||
for (const [id, placement] of Object.entries(rawProfile)) {
|
||||
const component = getSkinLayoutComponent(id, pageKey);
|
||||
try {
|
||||
if (!component?.editable) throw new Error("Component no longer exists or is not editable.");
|
||||
const verified = validateSkinLayout({ schemaVersion: 1, pages: { [pageKey]: { [profileKey]: { [id]: placement } } } });
|
||||
const normalized = verified.pages[pageKey]?.[profileKey]?.[id];
|
||||
if (!normalized) throw new Error("Placement could not be migrated.");
|
||||
placements[id] = normalized;
|
||||
} catch {
|
||||
remember(pageKey, profileKey, id, placement);
|
||||
}
|
||||
}
|
||||
if (Object.keys(placements).length) profiles[profileKey] = placements;
|
||||
}
|
||||
if (Object.keys(profiles).length) pages[pageKey] = profiles;
|
||||
}
|
||||
return { layout: validateSkinLayout({ schemaVersion: 1, pages }), items };
|
||||
}
|
||||
|
||||
function migrateLegacyCollection(source: string): SkinLayoutCollection {
|
||||
if (new TextEncoder().encode(source).byteLength > MAX_STORAGE_BYTES) throw new Error("Legacy skin layouts exceed the local storage limit.");
|
||||
let raw: unknown;
|
||||
try { raw = JSON.parse(source); }
|
||||
catch { throw new Error("Legacy skin layouts are not valid JSON."); }
|
||||
if (!isRecord(raw) || raw.schemaVersion !== 1 || !isRecord(raw.skins)) {
|
||||
throw new Error("Legacy skin layouts use an unsupported storage version.");
|
||||
}
|
||||
const collection = emptyCollection();
|
||||
for (const [id, storedLayout] of Object.entries(raw.skins)) {
|
||||
if (!isSkinId(id)) continue;
|
||||
const recovered = recoverLegacyLayout(storedLayout);
|
||||
collection.skins[id] = recovered.layout;
|
||||
if (recovered.items.length) {
|
||||
const recovery: SkinLayoutMigrationRecovery = {
|
||||
sourceVersion: 1,
|
||||
items: [],
|
||||
omittedCount: recovered.items.length,
|
||||
backupKey: LEGACY_SKIN_LAYOUT_STORAGE_KEY,
|
||||
};
|
||||
for (const item of recovered.items) {
|
||||
recovery.items.push(item);
|
||||
recovery.omittedCount -= 1;
|
||||
if (serializedBytes(recovery) > MAX_RECOVERY_BYTES) {
|
||||
recovery.items.pop();
|
||||
recovery.omittedCount += 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
collection.recoveries[id] = recovery;
|
||||
}
|
||||
}
|
||||
return collection;
|
||||
}
|
||||
|
||||
function readCollection(storage: StorageLike): SkinLayoutCollection {
|
||||
const current = storage.getItem(SKIN_LAYOUT_STORAGE_KEY);
|
||||
if (current !== null) return parseCollection(current);
|
||||
const legacy = storage.getItem(LEGACY_SKIN_LAYOUT_STORAGE_KEY);
|
||||
if (legacy === null) return emptyCollection();
|
||||
const migrated = migrateLegacyCollection(legacy);
|
||||
try { storage.setItem(SKIN_LAYOUT_STORAGE_KEY, JSON.stringify(migrated)); }
|
||||
catch { /* Keep the legacy key untouched and allow this page to use the migrated copy in memory. */ }
|
||||
return migrated;
|
||||
}
|
||||
|
||||
export function loadSkinLayoutOverrides(skinId: string): SkinLayoutDocument {
|
||||
if (!isSkinId(skinId)) return emptyDocument();
|
||||
const storage = getBrowserStorage();
|
||||
if (!storage) return emptyDocument();
|
||||
try { return readCollection(storage).skins[skinId] ?? emptyDocument(); }
|
||||
catch { return emptyDocument(); }
|
||||
}
|
||||
|
||||
export function getSkinLayoutMigrationRecovery(skinId: string): SkinLayoutMigrationRecovery | null {
|
||||
if (!isSkinId(skinId)) return null;
|
||||
const storage = getBrowserStorage();
|
||||
if (!storage) return null;
|
||||
try { return readCollection(storage).recoveries[skinId] ?? null; }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
export function exportSkinLayoutMigrationRecovery(skinId: string): string {
|
||||
const recovery = getSkinLayoutMigrationRecovery(skinId);
|
||||
if (!recovery) throw new Error("There is no recovered legacy layout data.");
|
||||
return JSON.stringify({ schemaVersion: 1, skinId, ...recovery }, null, 2);
|
||||
}
|
||||
|
||||
export function saveSkinLayoutOverrides(skinId: string, layout: SkinLayoutDocument): void {
|
||||
if (!isSkinId(skinId)) throw new Error("Skin ID is invalid.");
|
||||
const validated = validateSkinLayout(layout);
|
||||
const storage = getBrowserStorage();
|
||||
if (!storage) throw new Error("Local browser storage is unavailable.");
|
||||
let collection: SkinLayoutCollection;
|
||||
try { collection = readCollection(storage); }
|
||||
catch { throw new Error("Local browser storage could not be read."); }
|
||||
collection.skins[skinId] = validated;
|
||||
const serialized = JSON.stringify(collection);
|
||||
if (new TextEncoder().encode(serialized).byteLength > MAX_STORAGE_BYTES) throw new Error("Saved skin layouts exceed the local storage limit.");
|
||||
try { storage.setItem(SKIN_LAYOUT_STORAGE_KEY, serialized); }
|
||||
catch { throw new Error("Local browser storage could not be written."); }
|
||||
}
|
||||
|
||||
export function updateSkinLayoutOverride(
|
||||
skinId: string,
|
||||
page: SkinLayoutPage,
|
||||
profile: SkinLayoutProfile,
|
||||
componentId: string,
|
||||
placement: SkinLayoutPlacement | null,
|
||||
): SkinLayoutDocument {
|
||||
const component = getSkinLayoutComponent(componentId, page);
|
||||
if (!component?.editable) throw new Error("This skin component cannot be customized.");
|
||||
const layout = loadSkinLayoutOverrides(skinId);
|
||||
const pages = { ...layout.pages };
|
||||
const pageLayout = { ...(pages[page] ?? {}) };
|
||||
const profileLayout = { ...(pageLayout[profile] ?? {}) };
|
||||
if (placement === null || Object.keys(placement).length === 0) delete profileLayout[componentId];
|
||||
else profileLayout[componentId] = placement;
|
||||
if (Object.keys(profileLayout).length) pageLayout[profile] = profileLayout;
|
||||
else delete pageLayout[profile];
|
||||
if (Object.keys(pageLayout).length) pages[page] = pageLayout;
|
||||
else delete pages[page];
|
||||
const validated = validateSkinLayout({ schemaVersion: 1, pages });
|
||||
saveSkinLayoutOverrides(skinId, validated);
|
||||
return validated;
|
||||
}
|
||||
|
||||
export function clearSkinLayoutOverrides(skinId: string): void {
|
||||
if (!isSkinId(skinId)) return;
|
||||
const storage = getBrowserStorage();
|
||||
if (!storage) throw new Error("Local browser storage is unavailable.");
|
||||
let collection: SkinLayoutCollection;
|
||||
try { collection = readCollection(storage); }
|
||||
catch { throw new Error("Local browser storage could not be read."); }
|
||||
delete collection.skins[skinId];
|
||||
delete collection.recoveries[skinId];
|
||||
const serialized = JSON.stringify(collection);
|
||||
if (new TextEncoder().encode(serialized).byteLength > MAX_STORAGE_BYTES) throw new Error("Saved skin layouts exceed the local storage limit.");
|
||||
try { storage.setItem(SKIN_LAYOUT_STORAGE_KEY, serialized); }
|
||||
catch { throw new Error("Local browser storage could not be written."); }
|
||||
}
|
||||
|
||||
export function exportSkinLayout(layout: SkinLayoutDocument): string {
|
||||
return JSON.stringify(validateSkinLayout(layout), null, 2);
|
||||
}
|
||||
|
||||
export function importSkinLayout(source: string): SkinLayoutDocument {
|
||||
return parseSkinLayoutJson(source);
|
||||
}
|
||||
@@ -127,12 +127,18 @@ test("skin content supports localized interface message overrides and includes t
|
||||
assert.ok(skin.assets["assets/preview.png"]);
|
||||
});
|
||||
|
||||
test("the ILLUSIA visual-only example imports without replacing WebSpeak's base translations", async () => {
|
||||
const bytes = await readFile(new URL("../../../docs/examples/illusia-voice.wskin", import.meta.url));
|
||||
const skin = await importSkinPack(new File([bytes], "illusia-voice.wskin", { type: "application/octet-stream" }));
|
||||
test("the ILLUSIA v2 example and bundled package import without replacing WebSpeak's base translations", async () => {
|
||||
const exampleBytes = await readFile(new URL("../../../docs/examples/illusia-voice.wskin", import.meta.url));
|
||||
const bundledBytes = await readFile(new URL("../../public/skins/illusia-voice.wskin", import.meta.url));
|
||||
assert.deepEqual(bundledBytes, exampleBytes);
|
||||
const skin = await importSkinPack(new File([exampleBytes], "illusia-voice.wskin", { type: "application/octet-stream" }));
|
||||
assert.equal(skin.id, "community.illusia-voice");
|
||||
assert.equal(skin.name, "ILLUSIA风");
|
||||
assert.equal(skin.version, "1.0.28");
|
||||
assert.equal(skin.version, "1.0.29");
|
||||
assert.equal(skin.schemaVersion, 2);
|
||||
assert.equal(skin.packageType, "layout-skin");
|
||||
assert.deepEqual(skin.permissions, []);
|
||||
assert.deepEqual(skin.layoutData, { schemaVersion: 1, pages: {} });
|
||||
assert.equal(skin.minAppVersion, "0.2.7-preview");
|
||||
assert.equal(skin.contentData, undefined);
|
||||
assert.equal(skin.previewBlob?.type, "image/webp");
|
||||
@@ -250,3 +256,52 @@ function makeSkin(css: string, content?: unknown): File {
|
||||
const bytes = zipSync(packageFiles);
|
||||
return new File([bytes.slice().buffer as ArrayBuffer], "skin.wskin", { type: "application/octet-stream" });
|
||||
}
|
||||
|
||||
test("schema version 2 skin packages load only validated declarative layouts with no permissions", async () => {
|
||||
const layout = {
|
||||
schemaVersion: 1,
|
||||
pages: {
|
||||
home: { desktop: { "home.header": { x: 48, y: -12, scale: 1.1, background: "#123456" } } },
|
||||
},
|
||||
};
|
||||
const skin = await importSkinPack(makeSkinV2(layout));
|
||||
assert.equal(skin.schemaVersion, 2);
|
||||
assert.equal(skin.packageType, "layout-skin");
|
||||
assert.deepEqual(skin.permissions, []);
|
||||
assert.equal(skin.layoutData?.pages.home?.desktop?.["home.header"]?.x, 48);
|
||||
assert.equal(skin.layoutData?.pages.home?.desktop?.["home.header"]?.background, "#123456");
|
||||
|
||||
await assert.rejects(
|
||||
importSkinPack(makeSkinV2(layout, { permissions: ["network.fetch"] })),
|
||||
(error: unknown) => error instanceof SkinPackError && error.code === "SKIN_PERMISSION_INVALID",
|
||||
);
|
||||
await assert.rejects(
|
||||
importSkinPack(makeSkinV2(layout, { capabilities: ["network.fetch"] })),
|
||||
(error: unknown) => error instanceof SkinPackError && error.code === "SKIN_MANIFEST_INVALID",
|
||||
);
|
||||
await assert.rejects(
|
||||
importSkinPack(makeSkinV2({ schemaVersion: 1, pages: { home: { desktop: { "home.unknown": { x: 4 } } } } })),
|
||||
(error: unknown) => error instanceof SkinPackError && error.code === "SKIN_LAYOUT_INVALID",
|
||||
);
|
||||
await assert.rejects(
|
||||
importSkinPack(makeSkinV2({ schemaVersion: 1, pages: { home: { desktop: { "home.security-note": { visible: false } } } } })),
|
||||
(error: unknown) => error instanceof SkinPackError && error.code === "SKIN_LAYOUT_INVALID",
|
||||
);
|
||||
});
|
||||
|
||||
function makeSkinV2(layout: unknown, manifestChanges: Record<string, unknown> = {}): File {
|
||||
const packageFiles: Record<string, Uint8Array> = {
|
||||
"manifest.json": strToU8(JSON.stringify({
|
||||
...manifest,
|
||||
schemaVersion: 2,
|
||||
packageType: "layout-skin",
|
||||
layout: "layout.json",
|
||||
permissions: [],
|
||||
...manifestChanges,
|
||||
})),
|
||||
"skin.css": strToU8('[data-ws-part="home.header"] { color: #123456; }'),
|
||||
"layout.json": strToU8(JSON.stringify(layout)),
|
||||
};
|
||||
const bytes = zipSync(packageFiles);
|
||||
return new File([bytes.slice().buffer as ArrayBuffer], "skin-v2.wskin", { type: "application/octet-stream" });
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import postcss, { type AtRule, type Declaration, type Node, type Rule } from "po
|
||||
import selectorParser from "postcss-selector-parser";
|
||||
import valueParser from "postcss-value-parser";
|
||||
import { unzipSync } from "fflate";
|
||||
import { parseSkinLayoutJson, type SkinLayoutDocument } from "../../../src/shared/skin-layout.js";
|
||||
|
||||
const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024;
|
||||
const MAX_EXPANDED_BYTES = 50 * 1024 * 1024;
|
||||
@@ -51,7 +52,8 @@ const ZIP_EOCD = 0x06054b50;
|
||||
const ZIP_CENTRAL_FILE = 0x02014b50;
|
||||
|
||||
export interface SkinManifest {
|
||||
schemaVersion: 1;
|
||||
schemaVersion: 1 | 2;
|
||||
packageType?: "layout-skin";
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
@@ -59,6 +61,8 @@ export interface SkinManifest {
|
||||
license: string;
|
||||
description?: string;
|
||||
entry: string;
|
||||
layout?: string;
|
||||
permissions?: [];
|
||||
content?: string;
|
||||
minAppVersion: string;
|
||||
preview?: string;
|
||||
@@ -89,6 +93,7 @@ export interface InstalledSkin extends SkinManifest {
|
||||
css: string;
|
||||
assets: Record<string, Blob>;
|
||||
contentData?: SkinContent;
|
||||
layoutData?: SkinLayoutDocument;
|
||||
previewBlob?: Blob;
|
||||
warnings: string[];
|
||||
installedAt: number;
|
||||
@@ -148,7 +153,7 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
|
||||
|
||||
const assets: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
|
||||
for (const [path, bytes] of files) {
|
||||
if (["manifest.json", manifest.entry, manifest.content].includes(path)) continue;
|
||||
if (["manifest.json", manifest.entry, manifest.layout, manifest.content].includes(path)) continue;
|
||||
const mimeType = assetMimeType(path);
|
||||
if (!mimeType) throw new SkinPackError(`Unsupported package file: ${path}`, "SKIN_FILE_UNSUPPORTED");
|
||||
if (mimeType.startsWith("font/") && bytes.byteLength > MAX_FONT_BYTES) throw new SkinPackError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
|
||||
@@ -163,6 +168,14 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
|
||||
contentData = parseContent(contentBytes);
|
||||
}
|
||||
|
||||
let layoutData: SkinLayoutDocument | undefined;
|
||||
if (manifest.layout) {
|
||||
const layoutBytes = files.get(manifest.layout);
|
||||
if (!layoutBytes) throw new SkinPackError("layout.json is missing from the package.", "SKIN_LAYOUT_MISSING");
|
||||
try { layoutData = parseSkinLayoutJson(decoder.decode(layoutBytes)); }
|
||||
catch (error) { throw new SkinPackError("layout.json is invalid: " + (error instanceof Error ? error.message : "unknown layout error"), "SKIN_LAYOUT_INVALID"); }
|
||||
}
|
||||
|
||||
let previewBlob: Blob | undefined;
|
||||
if (manifest.preview) {
|
||||
const previewBytes = files.get(manifest.preview);
|
||||
@@ -174,7 +187,7 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
|
||||
}
|
||||
|
||||
const compiled = compileSkinCss(decoder.decode(cssBytes), manifest.id, assets);
|
||||
return { ...manifest, css: compiled.css, assets, contentData, previewBlob, warnings: compiled.warnings, installedAt: Date.now() };
|
||||
return { ...manifest, css: compiled.css, assets, contentData, layoutData, previewBlob, warnings: compiled.warnings, installedAt: Date.now() };
|
||||
}
|
||||
|
||||
export function resolveSkinCssAssets(css: string, assets: Record<string, Blob>): { css: string; objectUrls: string[] } {
|
||||
@@ -319,30 +332,44 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
|
||||
catch { throw new SkinPackError("manifest.json must contain valid UTF-8 JSON.", "SKIN_MANIFEST_INVALID"); }
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new SkinPackError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID");
|
||||
const raw = value as Record<string, unknown>;
|
||||
const schemaVersion = raw.schemaVersion;
|
||||
if (schemaVersion !== 1 && schemaVersion !== 2) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION");
|
||||
if (schemaVersion === 2) {
|
||||
const fields = new Set(["schemaVersion", "packageType", "id", "name", "version", "author", "license", "description", "entry", "layout", "permissions", "content", "minAppVersion", "preview"]);
|
||||
const unknown = Object.keys(raw).find((key) => !fields.has(key));
|
||||
if (unknown) throw new SkinPackError(`Version 2 skin manifest contains an unsupported field: ${unknown}.`, "SKIN_MANIFEST_INVALID");
|
||||
}
|
||||
const stringField = (key: string, max: number, required = true): string | undefined => {
|
||||
const field = raw[key];
|
||||
if (field == null && !required) return undefined;
|
||||
if (typeof field !== "string" || !field.trim() || field.length > max) throw new SkinPackError(`manifest.json has an invalid ${key} field.`, "SKIN_MANIFEST_INVALID");
|
||||
return field.trim();
|
||||
};
|
||||
if (raw.schemaVersion !== 1) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION");
|
||||
if (schemaVersion === 2 && (raw.packageType !== "layout-skin" || !Array.isArray(raw.permissions) || raw.permissions.length !== 0)) {
|
||||
throw new SkinPackError("Layout skin packages must declare the layout-skin type and no executable permissions.", "SKIN_PERMISSION_INVALID");
|
||||
}
|
||||
if (schemaVersion === 1 && (raw.layout !== undefined || raw.packageType !== undefined || raw.permissions !== undefined)) {
|
||||
throw new SkinPackError("Version 1 skin packages cannot declare layout or plugin fields.", "SKIN_SCHEMA_VERSION");
|
||||
}
|
||||
const id = stringField("id", 80)!;
|
||||
if (!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(id) || id.startsWith("builtin.")) throw new SkinPackError("Skin IDs must be unique lowercase IDs and cannot use the reserved builtin. prefix.", "SKIN_ID_INVALID");
|
||||
const entry = stringField("entry", 120)!;
|
||||
const layout = schemaVersion === 2 ? stringField("layout", 120)! : undefined;
|
||||
const content = stringField("content", 120, false);
|
||||
const preview = stringField("preview", 120, false);
|
||||
for (const path of [entry, content, preview].filter((item): item is string => Boolean(item))) {
|
||||
for (const path of [entry, layout, content, preview].filter((item): item is string => Boolean(item))) {
|
||||
if (path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) throw new SkinPackError(`manifest.json has an unsafe path: ${path}`, "SKIN_PATH_INVALID");
|
||||
}
|
||||
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
const version = stringField("version", 32)!;
|
||||
const minAppVersion = stringField("minAppVersion", 32)!;
|
||||
if (!semver.test(version) || !semver.test(minAppVersion)) throw new SkinPackError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID");
|
||||
if (!entry.toLowerCase().endsWith(".css") || (content && !content.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The entry must be CSS, content must be JSON, and preview must be a supported image.", "SKIN_MANIFEST_INVALID");
|
||||
const declaredFiles = ["manifest.json", entry, ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
|
||||
if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The CSS entry, layout, content, or preview path is invalid.", "SKIN_MANIFEST_INVALID");
|
||||
const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
|
||||
if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinPackError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
schemaVersion,
|
||||
...(schemaVersion === 2 ? { packageType: "layout-skin" as const, permissions: [] as [] } : {}),
|
||||
id,
|
||||
name: stringField("name", 80)!,
|
||||
version,
|
||||
@@ -350,6 +377,7 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
|
||||
license: stringField("license", 80)!,
|
||||
description: stringField("description", 400, false),
|
||||
entry,
|
||||
layout,
|
||||
content,
|
||||
minAppVersion,
|
||||
preview,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { applyTheme, getBuiltinSkinCss, getStoredTheme, isDarkTheme } from "./th
|
||||
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";
|
||||
|
||||
export const ACTIVE_SKIN_KEY = "webspeak:active-skin";
|
||||
export const BUILTIN_LIGHT_SKIN = "builtin.light";
|
||||
@@ -52,6 +53,7 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine
|
||||
operation.check();
|
||||
if (id === BUILTIN_LIGHT_SKIN || id === BUILTIN_DARK_SKIN) {
|
||||
removeCustomSkinStyle();
|
||||
setSkinLayoutPackage(id, null);
|
||||
applyTheme(id === BUILTIN_DARK_SKIN ? "dark" : "light");
|
||||
markCoreControls();
|
||||
storeSkinId(id);
|
||||
@@ -120,6 +122,7 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine
|
||||
activeAssetUrls = compiled.objectUrls;
|
||||
candidateUrls = [];
|
||||
previousAssetUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
setSkinLayoutPackage(skin.id, skin.layoutData ?? null);
|
||||
storeSkinId(id);
|
||||
return skin;
|
||||
} catch {
|
||||
@@ -132,6 +135,7 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine
|
||||
function fallBackToBuiltin(): null {
|
||||
const fallback = isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN;
|
||||
removeCustomSkinStyle();
|
||||
setSkinLayoutPackage(fallback, null);
|
||||
applyTheme(fallback === BUILTIN_DARK_SKIN ? "dark" : "light");
|
||||
storeSkinId(fallback);
|
||||
return null;
|
||||
@@ -141,6 +145,7 @@ export function clearCustomSkinStyle(): void {
|
||||
pendingActivation?.cancel();
|
||||
pendingActivation = null;
|
||||
removeCustomSkinStyle();
|
||||
setSkinLayoutPackage(getStoredSkinId() ?? BUILTIN_LIGHT_SKIN, null);
|
||||
}
|
||||
|
||||
function removeCustomSkinStyle(): void {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import test from "node:test";
|
||||
import {
|
||||
createSkinExtensionWasmCappedRunProbe,
|
||||
createSkinExtensionWasmInfiniteRunProbe,
|
||||
createSkinExtensionWasmPrefixByteImmediateProbe,
|
||||
} from "../../test/skin-extension-wasm-fixture.js";
|
||||
|
||||
interface WasmiInterpreterExports extends WebAssembly.Exports {
|
||||
memory: WebAssembly.Memory;
|
||||
alloc: (size: number) => number;
|
||||
run: (modulePointer: number, moduleLength: number, statusPointer: number, statusLength: number,
|
||||
statusPermissionGranted: number, memoryMaximumPages: number, fuel: bigint) => bigint;
|
||||
last_error_code: () => number;
|
||||
last_guest_memory_bytes: () => number;
|
||||
}
|
||||
|
||||
test("the fixed Wasmi artifact caps its own memory and stops guest execution at fuel", async () => {
|
||||
const artifact = await readFile(new URL("../../public/skin-wasm-interpreter.wasm", import.meta.url));
|
||||
const { instance } = await WebAssembly.instantiate(artifact);
|
||||
const runtime = instance.exports as unknown as WasmiInterpreterExports;
|
||||
|
||||
function run(module: Uint8Array): { result: number; error: number; guestMemoryBytes: number } {
|
||||
const pointer = runtime.alloc(module.byteLength);
|
||||
assert.notEqual(pointer, 0, "the bounded interpreter should accept the small fixture");
|
||||
new Uint8Array(runtime.memory.buffer, pointer, module.byteLength).set(module);
|
||||
const result = runtime.run(pointer, module.byteLength, 0, 0, 0, 64, 10_000_000n);
|
||||
return {
|
||||
result: Number(result),
|
||||
error: runtime.last_error_code(),
|
||||
guestMemoryBytes: runtime.last_guest_memory_bytes(),
|
||||
};
|
||||
}
|
||||
|
||||
assert.deepEqual(run(createSkinExtensionWasmPrefixByteImmediateProbe()), {
|
||||
result: 123,
|
||||
error: 0,
|
||||
guestMemoryBytes: 64 * 1024,
|
||||
});
|
||||
assert.equal(run(createSkinExtensionWasmInfiniteRunProbe()).error, 5, "the fuel budget must trap a non-returning module");
|
||||
assert.deepEqual(run(createSkinExtensionWasmCappedRunProbe()), {
|
||||
result: -1,
|
||||
error: 0,
|
||||
guestMemoryBytes: 4 * 1024 * 1024,
|
||||
});
|
||||
|
||||
const memory = runtime.memory;
|
||||
const currentPages = memory.buffer.byteLength / (64 * 1024);
|
||||
memory.grow(1024 - currentPages);
|
||||
assert.equal(memory.buffer.byteLength, 64 * 1024 * 1024, "the interpreter container should reach its 64 MiB cap");
|
||||
assert.throws(() => memory.grow(1), RangeError, "the interpreter container must not grow beyond its cap");
|
||||
});
|
||||
@@ -65,9 +65,9 @@ export function applyTheme(theme: ThemeMode, options: { preserveCustomSkins?: bo
|
||||
style.textContent = activeSkin.css;
|
||||
}
|
||||
|
||||
export function saveTheme(theme: ThemeMode): void {
|
||||
export function saveTheme(theme: ThemeMode, options: { preserveCustomSkins?: boolean } = {}): void {
|
||||
if (typeof localStorage !== "undefined") localStorage.setItem(THEME_KEY, theme);
|
||||
applyTheme(theme);
|
||||
applyTheme(theme, options);
|
||||
}
|
||||
|
||||
export function isDarkTheme(theme: ThemeMode): boolean {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
.ws-skin-root[data-ws-layout-hidden="true"],
|
||||
.ws-skin-root [data-ws-layout-hidden="true"] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.ws-skin-root [data-ws-layout-active="true"] {
|
||||
translate: var(--ws-layout-x, 0px) var(--ws-layout-y, 0px) !important;
|
||||
scale: var(--ws-layout-scale, 1) !important;
|
||||
}
|
||||
|
||||
.ws-skin-root [data-ws-layout-width="true"] {
|
||||
width: var(--ws-layout-width) !important;
|
||||
}
|
||||
|
||||
.ws-skin-root [data-ws-layout-height="true"] {
|
||||
height: var(--ws-layout-height) !important;
|
||||
}
|
||||
|
||||
.ws-skin-root [data-ws-layout-touch-target="44"] {
|
||||
min-width: 44px !important;
|
||||
min-height: 44px !important;
|
||||
}
|
||||
|
||||
.ws-skin-root [data-ws-layout-foreground="true"] {
|
||||
color: var(--ws-layout-foreground) !important;
|
||||
}
|
||||
|
||||
.ws-skin-root [data-ws-layout-background="true"] {
|
||||
background-color: var(--ws-layout-background) !important;
|
||||
}
|
||||
|
||||
.ws-skin-root [data-ws-layout-border="true"] {
|
||||
border-color: var(--ws-layout-border) !important;
|
||||
}
|
||||
|
||||
.ws-skin-root [data-ws-layout-radius="true"] {
|
||||
border-radius: var(--ws-layout-radius) !important;
|
||||
}
|
||||
|
||||
.ws-skin-root[data-ws-layout-editing="true"] [data-ws-layout-selected="true"] {
|
||||
outline: 2px solid #4f46e5 !important;
|
||||
outline-offset: 2px !important;
|
||||
cursor: move !important;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div :class="['demo-page', 'ws-skin-root', { 'skin-initializing': !skinReady }]" data-ws-part="app" data-ws-page="demo">
|
||||
<div :class="['demo-page', 'ws-skin-root', { 'skin-initializing': !skinReady }]" :lang="language" data-ws-part="app" data-ws-page="demo">
|
||||
<header class="demo-header" data-ws-part="demo.header">
|
||||
<div class="demo-brand" data-ws-part="demo.brand"><span><Icon name="waveform" :size="21" /></span><div><strong>WebSpeak</strong><small>{{ copy.browserClient }}</small></div></div>
|
||||
<div class="demo-tools" data-ws-part="demo.header-tools"><span class="demo-badge" data-ws-part="demo.badge">{{ copy.demoBadge }}</span><SkinSwitcher v-model="activeSkinId" data-ws-part="demo.skin-switcher" :menu-label="copy.skinSelector" :options="skinOptions" @change="onSkinChange" /><LanguageSwitcher v-model="language" data-ws-part="demo.language-switcher" :menu-label="copy.languageMenu" @change="persistLanguage" /><a href="/" data-ws-part="demo.home-link">{{ copy.back }}</a></div>
|
||||
@@ -18,7 +18,25 @@
|
||||
<section class="demo-main" data-ws-part="demo.main">
|
||||
<div class="demo-hero" data-ws-part="demo.hero"><div><span class="demo-live" data-ws-part="demo.live"><i></i>{{ copy.simulated }}</span><h1 data-ws-part="demo.hero.title"><Icon name="volume" :size="24" /> {{ selectedChannel.name }}</h1><p data-ws-part="demo.hero.description">{{ copy.heroLead }}</p><small data-ws-part="demo.hero.online"><Icon name="users" :size="14" /> {{ selectedChannel.members.length }} {{ copy.online }}</small></div><div class="demo-wave" data-ws-part="demo.wave" aria-hidden="true"><i v-for="bar in bars" :key="bar" :style="{ height: `${bar}px` }"></i></div></div>
|
||||
<div class="demo-section-heading" data-ws-part="demo.voice-heading"><span>{{ copy.voiceActivity }}</span><strong>{{ copy.speakingNow }}</strong></div>
|
||||
<div class="demo-voice-grid" data-ws-part="demo.voice-grid"><article v-for="member in selectedChannel.members" :key="member.id" :class="['demo-voice-card', { speaking: speakingId === member.id }]" data-ws-part="demo.voice-card" :data-ws-state="speakingId === member.id ? 'speaking' : 'connected'" @click="speakingId = member.id"><i data-ws-part="demo.avatar" :style="avatarStyle(member.name)">{{ member.name[0] }}</i><strong data-ws-part="demo.member-name">{{ member.name }}</strong><span data-ws-part="demo.member-status">{{ speakingId === member.id ? copy.speaking : copy.connected }}</span></article></div>
|
||||
<div class="demo-voice-grid" data-ws-part="demo.voice-grid">
|
||||
<article
|
||||
v-for="member in selectedChannel.members"
|
||||
:key="member.id"
|
||||
:class="['demo-voice-card', { speaking: speakingId === member.id }]"
|
||||
data-ws-part="demo.voice-card"
|
||||
:data-ws-state="speakingId === member.id ? 'speaking' : 'connected'"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
:aria-pressed="speakingId === member.id"
|
||||
@click="speakingId = member.id"
|
||||
@keydown.enter.prevent="speakingId = member.id"
|
||||
@keydown.space.prevent="speakingId = member.id"
|
||||
>
|
||||
<i data-ws-part="demo.avatar" :style="avatarStyle(member.name)">{{ member.name[0] }}</i>
|
||||
<strong data-ws-part="demo.member-name">{{ member.name }}</strong>
|
||||
<span data-ws-part="demo.member-status">{{ speakingId === member.id ? copy.speaking : copy.connected }}</span>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div class="demo-chat-head" data-ws-part="demo.chat.heading"><div><span>{{ copy.textChannel }}</span><strong># {{ selectedChannel.name }} {{ copy.chat }}</strong></div><div class="demo-tabs" data-ws-part="demo.chat.tabs"><button v-for="tab in tabs" :key="tab.id" type="button" :class="{ active: activeTab === tab.id }" data-ws-part="demo.chat.tab" :data-ws-state="activeTab === tab.id ? 'active' : 'idle'" @click="activeTab = tab.id">{{ tab.label }}</button></div></div>
|
||||
<div class="demo-messages" data-ws-part="demo.chat.messages"><div v-for="message in visibleMessages" :key="message.id" :class="['demo-message', { mine: message.mine }]" data-ws-part="demo.chat.message" :data-ws-state="message.mine ? 'mine' : 'other'" @dblclick="message.mine = !message.mine"><i :style="avatarStyle(message.author)">{{ message.author[0] }}</i><div><small>{{ message.author }} · {{ message.time }}</small><p>{{ messageText(message) }}</p></div></div><div v-if="!visibleMessages.length" class="demo-empty" data-ws-part="demo.chat.empty"><Icon name="message" :size="22" /><strong>{{ copy.emptyChat }}</strong></div></div>
|
||||
@@ -29,12 +47,14 @@
|
||||
</main>
|
||||
<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" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
|
||||
import SkinLoadRecoveryNotice from "../components/SkinLoadRecoveryNotice.vue";
|
||||
import SkinSwitcher, { type SkinOption } from "../components/SkinSwitcher.vue";
|
||||
import { saveLocalPreferences } from "../services/local-persistence.js";
|
||||
import { BUILTIN_ILLUSIA_SKIN_ID, isPublicSkinEnabled } from "../services/skin-catalog.js";
|
||||
@@ -49,7 +69,8 @@ const storedLanguage = localStorage.getItem("webspeak:language");
|
||||
const language = ref<Language>(storedLanguage === "en" || storedLanguage === "de" || storedLanguage === "ru" || storedLanguage === "ja" ? storedLanguage : "zh");
|
||||
const baseCopy = computed(() => language.value === "zh" ? zh : language.value === "de" ? de : language.value === "ru" ? ru : language.value === "ja" ? ja : en);
|
||||
const { activeSkin, activeSkinId, skinReady, installedSkins, catalogSkins,
|
||||
select: onSkinChange, initialize: initializeSkin } = usePublicSkin();
|
||||
skinLoadError, select: onSkinChange, initialize: initializeSkin,
|
||||
switchToBuiltInAfterLoadError } = usePublicSkin();
|
||||
const skinOptions = computed<SkinOption[]>(() => [
|
||||
...catalogSkins.value.map((skin) => ({
|
||||
value: skin.id,
|
||||
@@ -130,5 +151,5 @@ function avatarStyle(name: string) { let hash = 0; for (const char of name) hash
|
||||
.demo-page[data-ws-skin="builtin.dark"] .demo-hero { background: linear-gradient(112deg, #173e3a, #172321); }
|
||||
.demo-page[data-ws-skin="builtin.dark"] .demo-message p, .demo-page[data-ws-skin="builtin.dark"] .demo-composer, .demo-page[data-ws-skin="builtin.dark"] .demo-actions-panel > button { background: #202f2c; color: #d7e7e3; }
|
||||
.demo-page[data-ws-skin="builtin.dark"] .demo-chat-head, .demo-page[data-ws-skin="builtin.dark"] .demo-user { border-color: #30413d; }
|
||||
.demo-page :where(button, a, input, select):focus-visible { outline: 3px solid #69d2c7; outline-offset: 2px; }
|
||||
.demo-page :where(button, a, input, select, [role="button"]):focus-visible { outline: 3px solid #69d2c7; outline-offset: 2px; }
|
||||
</style>
|
||||
@@ -7,6 +7,7 @@
|
||||
{ 'skin-initializing': !skinReady, 'keyboard-open': mobileViewport.keyboardOpen },
|
||||
]"
|
||||
:style="{ '--ws-viewport-height': `${mobileViewport.height}px`, '--ws-viewport-top': `${mobileViewport.top}px` }"
|
||||
:lang="language"
|
||||
data-ws-part="app"
|
||||
:data-ws-page="showVoiceShell ? 'voice' : 'home'"
|
||||
>
|
||||
@@ -908,12 +909,14 @@
|
||||
{{ toast }}</div
|
||||
>
|
||||
</div>
|
||||
<SkinLoadRecoveryNotice :error="skinLoadError" :language="language" @use-built-in="switchToBuiltInAfterLoadError" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { observeMobileViewport } from "../services/mobile-viewport.js";
|
||||
import { computed, onMounted, onUnmounted, reactive, ref, shallowRef, watch } from "vue";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import SkinLoadRecoveryNotice from "../components/SkinLoadRecoveryNotice.vue";
|
||||
import VoiceMemberCards from "../components/web-client/VoiceMemberCards.vue";
|
||||
import VoicePerformancePanel from "../components/web-client/VoicePerformancePanel.vue";
|
||||
import ScreenShareSettingsDialog from "../components/web-client/ScreenShareSettingsDialog.vue";
|
||||
@@ -1121,7 +1124,8 @@ const {
|
||||
const themeMode = ref<ThemeMode>(getStoredTheme());
|
||||
applyTheme(themeMode.value);
|
||||
const publicSkin = usePublicSkin({ activeSkin, themeMode, appVersion: () => appVersion.value });
|
||||
const { activeSkinId, skinReady, installedSkins, catalogSkins, select: onSkinChange, initialize: initializeSkin } = publicSkin;
|
||||
const { activeSkinId, skinReady, skinLoadError, installedSkins, catalogSkins,
|
||||
select: onSkinChange, initialize: initializeSkin, switchToBuiltInAfterLoadError } = publicSkin;
|
||||
const skinOptions = computed<SkinOption[]>(() => [
|
||||
...catalogSkins.value.map((skin) => ({
|
||||
value: skin.id,
|
||||
|
||||
Reference in new issue
Block a user