Compare commits

...
17 changed files with 460 additions and 34 deletions

No files matched your search

@@ -337,3 +337,43 @@ test('explicit CSS matching the last committed value supersedes pending CSS', ()
console.warn = originalWarn;
}
});
test('omitted css preserves previous stylesheet and apply failures emit diagnostics', () => {
const originalWarn = console.warn;
console.warn = () => {};
try {
const f = fixture();
const diagnostics: Array<{ source?: string; message: string; extra?: Record<string, unknown> }> = [];
const bridgeWithDiag = {
...f.bridge,
logDiagnostic: async (payload: { source?: string; message: string; extra?: Record<string, unknown> }) => {
diagnostics.push(payload);
return { success: true };
},
};
const store = new PluginViewSessions();
const view = store.acquire('diag-test', bridgeWithDiag, request);
const id = f.opened[0].instanceId;
const node = { id: 'n1', type: 1 as const, element: 'div', attributes: {}, children: [] };
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 1, css: '.n{display:flex}', mutations: [[0, '~', node, 0]] });
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 2, mutations: [[3, 'n1', 'class', 'n']] });
assert.equal(view.getSnapshot().css.includes('display:flex'), true);
assert.equal(view.getSnapshot().error, false);
// Duplicate-node recoverable errors should emit at most one diagnostic per session.
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 3, mutations: [[0, 'n1', { id: 'n1', type: 1, element: 'span', attributes: {}, children: [] }, 0]] } as Update);
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 4, mutations: [[0, 'n1', { id: 'n1', type: 1, element: 'span', attributes: {}, children: [] }, 0]] } as Update);
assert.equal(diagnostics.length, 1);
assert.equal(diagnostics[0].extra?.kind, 'duplicate-node-update');
// Trigger an out-of-order sequence failure and verify diagnostic is logged.
f.update({ kind: 'host-ui.update', viewId: request.viewId, instanceId: id, sequence: 99, mutations: [] });
assert.equal(view.getSnapshot().error, true);
assert.equal(diagnostics.length, 2);
assert.equal(diagnostics[1].source, 'plugin-view');
assert.match(diagnostics[1].message, /Invalid plugin update order/);
store.dispose();
} finally {
console.warn = originalWarn;
}
});
+27 -3
View File
@@ -3,7 +3,9 @@ import { registerLoadedPluginViewSessions } from './pluginViewSessionRegistry';
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
type Bridge = Pick<NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>;
type NetcattyBridgeApi = NonNullable<ReturnType<typeof import('../../infrastructure/services/netcattyBridge').netcattyBridge.get>>;
type Bridge = Pick<NetcattyBridgeApi, 'openHostDrawnPluginView' | 'closeHostDrawnPluginView' | 'onHostDrawnPluginViewUpdate' | 'onPluginViewClosed' | 'sendHostDrawnPluginViewEvent' | 'getPluginViewResource'>
& Partial<Pick<NetcattyBridgeApi, 'logDiagnostic'>>;
export type PluginViewSnapshot = { tree: ReturnType<ReturnType<typeof createPluginRemoteTree>['snapshot']>; css: string; loading: boolean; error: boolean; settled: boolean };
const empty = (): PluginViewSnapshot => ({ tree: { children: [] }, css: '', loading: true, error: false, settled: true });
const EMPTY_FIRST_FRAME_GRACE_MS = 60;
@@ -26,6 +28,7 @@ export class PluginViewSessions {
const id = crypto.randomUUID();
const tree = createPluginRemoteTree();
let state = empty(); let sequence = 1; let eventId = 0; let disposed = false; let users = 0;
let loggedDuplicateNode = false;
let lastRawCss: string | null = null;
let pendingCss: string | null = null;
let pendingRawCss: string | null = null;
@@ -48,7 +51,7 @@ export class PluginViewSessions {
let stagedRawCss: string | null = null;
try {
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
if (update.cssUnchanged) {
if (update.cssUnchanged || update.css === undefined) {
// keep pending CSS, if any, for the nextCss fallback below
} else if (lastRawCss !== null && update.css === lastRawCss) {
// Explicit CSS equal to the last committed raw CSS supersedes any pending stylesheet.
@@ -85,9 +88,23 @@ export class PluginViewSessions {
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.warn(`[PluginViewSession] Failed to apply update for ${request.viewId}: ${message}`, error);
const duplicateNode = isDuplicatePluginViewNodeError(error);
if (!duplicateNode || !loggedDuplicateNode) {
if (duplicateNode) loggedDuplicateNode = true;
void bridge.logDiagnostic?.({
source: 'plugin-view',
message: `Failed to apply update for ${request.viewId}: ${message}`,
extra: {
kind: duplicateNode ? 'duplicate-node-update' : 'apply-update-failed',
viewId: request.viewId,
sequence: update.sequence,
mutationCount: Array.isArray(update.mutations) ? update.mutations.length : null,
},
}).catch(() => {});
}
// Recoverable duplicate-only batches are normalized as moves in
// createPluginRemoteTree(); only unrecoverable duplicates reach here.
if (isDuplicatePluginViewNodeError(error)) {
if (duplicateNode) {
if (stagedCss !== null && stagedRawCss !== null) {
pendingCss = stagedCss;
pendingRawCss = stagedRawCss;
@@ -130,6 +147,13 @@ export class PluginViewSessions {
void bridge.sendHostDrawnPluginViewEvent?.(id, { ...event, eventId: ++eventId }).catch((error) => {
const message = error instanceof Error ? error.message : String(error);
console.warn(`[PluginViewSession] Failed to send event for ${request.viewId}: ${message}`);
if (!disposed) {
void bridge.logDiagnostic?.({
source: 'plugin-view',
message: `Failed to send event for ${request.viewId}: ${message}`,
extra: { kind: 'send-event-failed', viewId: request.viewId, eventType: event.type },
}).catch(() => {});
}
dispose(true);
});
},
+17
View File
@@ -343,6 +343,23 @@ function createBridgeRegistrar(context) {
isAppLocked: () => getAppLockController?.()?.getRuntimeState?.()?.locked !== false,
subscribeAppLock: (listener) => getAppLockController?.()?.subscribe?.(listener),
getLocale: () => getWindowManager().getCurrentLanguage?.() ?? "en",
onRuntimeFailure: ({ kind, pluginId, pluginVersion, runtimeId, runtimeKind, crashCount, quarantined, error }) => {
crashLogBridge.captureError("plugin-runtime", error ?? new Error(`Plugin runtime failure (${kind})`), {
kind,
pluginId,
pluginVersion,
runtimeId,
runtimeKind,
crashCount,
quarantined,
});
},
onViewDiagnostic: (kind, message, extra) => {
crashLogBridge.captureDiagnostic("plugin-view", message, {
kind,
...(extra && typeof extra === "object" ? extra : {}),
});
},
requestTerminalInterceptorSelection: async ({ direction, providers }) => {
const messages = terminalInterceptorMessages(getWindowManager().getCurrentLanguage?.() ?? "en");
const buttons = [
+17 -3
View File
@@ -10,6 +10,11 @@ const { invalidArgument, freezeJson } = require("./validationUtils.cjs");
const { InteractiveCommandFeature, InteractiveCommandLimits } = require("./generated/plugin-contract.schema.json").$defs;
const MAX_SETTING_BYTES = 128 * 1024;
// Host-drawn view updates may carry up to MAX_BATCH_BYTES (1 MiB) of remote DOM
// mutations plus MAX_CSS_LENGTH (128 KiB) of stylesheet text and JSON escaping
// overhead; keep a dedicated view-message cap aligned with those downstream
// policies instead of reusing the 128 KiB setting cap.
const MAX_VIEW_MESSAGE_BYTES = 2 * 1024 * 1024;
const MAX_PATTERN_LENGTH = 512;
const MAX_PATTERN_VALUE_LENGTH = 4_096;
const MAX_SCOPE_ID_LENGTH = 256;
@@ -19,8 +24,8 @@ function notFound(message) {
return new PluginRpcError(RPC_ERRORS.notFound, message);
}
function assertJsonValue(value, label = "value") {
try { assertPluginJsonValue(value, { maxBytes: MAX_SETTING_BYTES }); }
function assertJsonValue(value, label = "value", maxBytes = MAX_SETTING_BYTES) {
try { assertPluginJsonValue(value, { maxBytes }); }
catch (error) {
throw invalidArgument(`Plugin ${label} must be a bounded JSON value: ${error?.message ?? error}`);
}
@@ -201,7 +206,15 @@ class PluginContributionService {
});
registry.registerNotification("views.postMessage", (params, context) => {
const view = this.#assertOwnedContribution(context.manifest, "views", params?.viewId, context.pluginId);
assertJsonValue(params?.message, "view message");
const isHostUiUpdate = params?.message
&& typeof params.message === "object"
&& !Array.isArray(params.message)
&& params.message.kind === "host-ui.update";
assertJsonValue(
params?.message,
"view message",
isHostUiUpdate ? MAX_VIEW_MESSAGE_BYTES : MAX_SETTING_BYTES,
);
const event = freezeJson({ pluginId: context.pluginId, viewId: view.id, message: params.message });
for (const listener of [...this.viewMessageListeners]) {
try { listener(event); } catch {}
@@ -611,6 +624,7 @@ class PluginContributionService {
module.exports = {
MAX_SETTING_BYTES,
MAX_VIEW_MESSAGE_BYTES,
MAX_PATTERN_VALUE_LENGTH,
PluginContributionService,
assertJsonValue,
+58 -1
View File
@@ -6,7 +6,7 @@ const os = require("node:os");
const path = require("node:path");
const test = require("node:test");
const { assertJsonValue, MAX_SETTING_BYTES, PluginContributionService } = require("./contributionService.cjs");
const { assertJsonValue, MAX_SETTING_BYTES, MAX_VIEW_MESSAGE_BYTES, PluginContributionService } = require("./contributionService.cjs");
const { PluginDatabase } = require("./database.cjs");
const { PluginHostRpcRegistry } = require("./hostRpcRegistry.cjs");
const { PluginPermissionEngine } = require("./permissionEngine.cjs");
@@ -740,3 +740,60 @@ test("host settings groups are localized and preferences persist without activat
await service.resetSetting(pluginManifest.id, settingId);
assert.equal(snapshot().value, "hello");
});
test("views.postMessage allows view payloads above MAX_SETTING_BYTES up to MAX_VIEW_MESSAGE_BYTES", async (t) => {
const pluginManifest = manifest();
pluginManifest.permissions = { required: ["views"] };
const { service, database } = setup(t, pluginManifest);
const registry = new PluginHostRpcRegistry();
const permissionEngine = new PluginPermissionEngine({ database });
permissionEngine.setMode(database.getActivePlugin(pluginManifest.id), "views", "allow");
registry.use(permissionEngine.createMiddleware());
service.registerRpcCapabilities(registry);
const delivered = [];
service.onDidPostViewMessage((event) => delivered.push(event));
const routes = registry.createRoutes({
pluginId: pluginManifest.id,
pluginVersion: pluginManifest.version,
runtimeId: "runtime-views-budget",
runtimeKind: "browser",
manifest: pluginManifest,
assertCurrent() {},
});
const transport = { signal: new AbortController().signal };
// A 256 KiB host-ui.update payload exceeds MAX_SETTING_BYTES (128 KiB) but
// must succeed within MAX_VIEW_MESSAGE_BYTES (2 MiB).
const largeMessage = {
kind: "host-ui.update",
instanceId: "inst-large",
sequence: 1,
css: ".x{display:grid}",
mutations: [[0, "~", { id: "1", type: 3, data: "a".repeat(MAX_SETTING_BYTES + 64 * 1024) }, 0]],
};
await routes.notificationHandlers["views.postMessage"](
{ viewId: `${pluginManifest.id}.view`, message: largeMessage },
transport,
);
assert.equal(delivered.length, 1);
assert.equal(delivered[0].message.instanceId, "inst-large");
// Non-host-ui.update view messages keep the tighter MAX_SETTING_BYTES cap.
await assert.rejects(
() => Promise.resolve(routes.notificationHandlers["views.postMessage"](
{ viewId: `${pluginManifest.id}.view`, message: { kind: "custom.event", payload: "x".repeat(MAX_SETTING_BYTES) } },
transport,
)),
/Plugin view message must be a bounded JSON value/,
);
// host-ui.update payloads exceeding MAX_VIEW_MESSAGE_BYTES must still be rejected.
await assert.rejects(
() => Promise.resolve(routes.notificationHandlers["views.postMessage"](
{ viewId: `${pluginManifest.id}.view`, message: { kind: "host-ui.update", payload: "x".repeat(MAX_VIEW_MESSAGE_BYTES) } },
transport,
)),
/Plugin view message must be a bounded JSON value/,
);
});
@@ -4215,6 +4215,9 @@
"stateScope": {
"type": "string",
"maxLength": 128
},
"supportsOptionalCss": {
"type": "boolean"
}
},
"additionalProperties": false
@@ -4243,8 +4246,7 @@
"kind",
"instanceId",
"sequence",
"mutations",
"css"
"mutations"
],
"properties": {
"kind": {
+86 -12
View File
@@ -2,21 +2,36 @@
const { createHash } = require("node:crypto");
const { createDefinitionValidator } = require("./contractValidator.cjs");
const { redactLogValue } = require("./pluginLogger.cjs");
const { describePluginRuntime } = require("../../domain/pluginRuntimePolicy.cjs");
const { validatePluginMutationBatch } = require("../../domain/pluginRemoteTreePolicy.cjs");
const { validatePluginStylesheet } = require("../../domain/pluginViewStylePolicy.cjs");
const validateMessage = createDefinitionValidator("HostDrawnViewMessage");
const validateOpen = createDefinitionValidator("HostDrawnViewOpenRequest");
const validateEvent = createDefinitionValidator("HostDrawnViewEvent");
const DIAGNOSTIC_WINDOW_MS = 60_000;
const DIAGNOSTIC_MAX_PER_WINDOW = 5;
const DIAGNOSTIC_MAX_KEYS = 256;
function sanitizeViewErrorReason(error) {
if (error?.remote === true) {
const code = Number.isInteger(error.code) ? error.code : "unknown";
return `Remote plugin RPC error (code ${code})`;
}
const raw = error instanceof Error ? error.message : String(error ?? "unknown");
return String(redactLogValue(raw)).slice(0, 512);
}
/** Owns logical views only: never creates a native view or exposes plugin code to the host. */
class HostDrawnViewHost {
constructor({ electron, contributionService, resources, packageStore, permissionEngine, runtimePool, isLocked = () => false, subscribeLock, logger = console }) {
constructor({ electron, contributionService, resources, packageStore, permissionEngine, runtimePool, isLocked = () => false, subscribeLock, logger = console, onDiagnostic = null }) {
this.resources = resources;
this.packageStore = packageStore ?? null;
this.permissionEngine = permissionEngine ?? null;
this.runtimePool = runtimePool ?? null;
this.logger = logger ?? null;
this.onDiagnostic = typeof onDiagnostic === "function" ? onDiagnostic : null;
this.diagnosticWindows = new Map();
this.electron = electron; this.contributions = contributionService; this.isLocked = isLocked;
this.instances = new Map(); this.opening = new Map(); this.activationWaiters = new Set(); this.closed = false;
this.messageSubscription = contributionService.onDidPostViewMessage((event) => this.receive(event));
@@ -37,6 +52,32 @@ class HostDrawnViewHost {
for (const id of [...this.instances.keys()]) void this.close(id, undefined, "app-locked");
});
}
#emitDiagnostic(kind, pluginId, summary, extra = {}) {
if (!this.onDiagnostic || this.isLocked()) return;
const key = `${pluginId ?? "unknown"}:${kind}`;
const now = Date.now();
let entry = this.diagnosticWindows.get(key);
if (!entry || now - entry.start >= DIAGNOSTIC_WINDOW_MS) {
if (!entry && this.diagnosticWindows.size >= DIAGNOSTIC_MAX_KEYS) {
const oldestKey = this.diagnosticWindows.keys().next().value;
if (oldestKey !== undefined) this.diagnosticWindows.delete(oldestKey);
}
entry = { start: now, count: 0 };
this.diagnosticWindows.set(key, entry);
}
if (entry.count >= DIAGNOSTIC_MAX_PER_WINDOW) return;
entry.count += 1;
const safeSummary = String(redactLogValue(summary)).slice(0, 512);
const safeExtra = {};
for (const [field, value] of Object.entries(extra)) {
safeExtra[field] = typeof value === "string"
? String(redactLogValue(value)).slice(0, 512)
: value;
}
try {
this.onDiagnostic(kind, safeSummary, safeExtra);
} catch {}
}
owned(id, sender) {
const instance = this.instances.get(id);
if (!instance) throw new Error("Plugin view was not found");
@@ -77,7 +118,7 @@ class HostDrawnViewHost {
};
this.instances.set(id, instance);
owner.once("closed", instance.ownerClosed); sender.on("render-process-gone", instance.rendererGone); sender.on("did-start-navigation", instance.navigating);
instance.startPromise = this.contributions.runtimeSupervisor.notify(plugin.id, "plugin.view.message", { viewId: view.id, message: { kind: "host-ui.open", instanceId: id, stateScope: createHash("sha256").update(payload.scopeId).digest("hex") } }, { expectedIdentity: identity });
instance.startPromise = this.contributions.runtimeSupervisor.notify(plugin.id, "plugin.view.message", { viewId: view.id, message: { kind: "host-ui.open", instanceId: id, stateScope: createHash("sha256").update(payload.scopeId).digest("hex"), supportsOptionalCss: true } }, { expectedIdentity: identity });
await instance.startPromise;
ensure();
this.contributions.assertViewActivationCurrent(activation, { context: payload.context });
@@ -86,6 +127,19 @@ class HostDrawnViewHost {
this.#notifyInstanceReady(instance);
return { instanceId: id };
} catch (error) {
if (!opening.cancelled && !this.closed && !this.isLocked()) {
const reason = sanitizeViewErrorReason(error);
this.#emitDiagnostic(
"open-failed",
null,
`Failed to open plugin view ${payload.viewId}: ${reason}`,
{
viewId: payload.viewId,
instanceId: id,
reason,
},
);
}
await this.close(id, undefined, "open-failed");
throw error;
} finally {
@@ -97,9 +151,19 @@ class HostDrawnViewHost {
const message = event.message;
if (!validateMessage(message) || message.kind !== "host-ui.update") {
if (message && typeof message === "object" && message.kind === "host-ui.update") {
this.logger?.warn?.(
`[HostDrawnViewHost] Dropped schema-invalid update for ${event.viewId ?? "unknown"} (${event.pluginId ?? "unknown"})`,
);
const summary = `Dropped schema-invalid update for ${event.viewId ?? "unknown"} (${event.pluginId ?? "unknown"})`;
this.logger?.warn?.(`[HostDrawnViewHost] ${summary}`);
const knownInstanceId = typeof message.instanceId === "string"
&& message.instanceId.length <= 128
&& this.instances.has(message.instanceId)
? message.instanceId
: null;
this.#emitDiagnostic("schema-invalid-update", event.pluginId ?? null, summary, {
pluginId: event.pluginId ?? null,
viewId: event.viewId ?? null,
instanceId: knownInstanceId,
sequence: typeof message.sequence === "number" && Number.isSafeInteger(message.sequence) ? message.sequence : null,
});
}
return;
}
@@ -112,11 +176,13 @@ class HostDrawnViewHost {
if (now - instance.rateStart >= 1000) { instance.rateStart = now; instance.rateCount = 0; }
if (++instance.rateCount > 120) throw new Error("Plugin view update rate exceeded");
validatePluginMutationBatch(message.mutations);
const cssUnchanged = instance.lastRawCss !== null && message.css === instance.lastRawCss;
const cssOmitted = message.css === undefined;
const cssUnchanged = instance.lastRawCss !== null && (cssOmitted || message.css === instance.lastRawCss);
let canonicalCss = instance.lastCanonicalCss;
if (!cssUnchanged) {
canonicalCss = validatePluginStylesheet(message.css);
instance.lastRawCss = message.css;
const rawCss = cssOmitted ? "" : message.css;
canonicalCss = validatePluginStylesheet(rawCss);
instance.lastRawCss = rawCss;
instance.lastCanonicalCss = canonicalCss;
}
instance.sequence = message.sequence;
@@ -127,10 +193,18 @@ class HostDrawnViewHost {
instance.sender.send("netcatty:plugins:host-ui-update", outgoing);
}
} catch (error) {
const reason = error instanceof Error ? error.message : String(error);
this.logger?.warn?.(
`[HostDrawnViewHost] Closing view ${instance.viewId} (${instance.pluginId}) after invalid update #${message.sequence}: ${reason}`,
);
const reason = sanitizeViewErrorReason(error);
const summary = `Closing view ${instance.viewId} (${instance.pluginId}) after invalid update #${message.sequence}: ${reason}`;
this.logger?.warn?.(`[HostDrawnViewHost] ${summary}`);
this.#emitDiagnostic("invalid-update", instance.pluginId, summary, {
pluginId: instance.pluginId,
viewId: instance.viewId,
instanceId: instance.id,
sequence: message.sequence,
mutationCount: Array.isArray(message.mutations) ? message.mutations.length : null,
cssLength: typeof message.css === "string" ? message.css.length : null,
reason,
});
void this.close(instance.id, undefined, "invalid-update");
}
}
+46 -4
View File
@@ -15,8 +15,16 @@ function fixture(resources) {
runtimeSupervisor: { async notify(...args) { notifications.push(args); } },
};
const warnings = [];
const host = new HostDrawnViewHost({ electron: { BrowserWindow: { fromWebContents: (s) => s === sender ? owner : null } }, contributionService: contributions, resources, isLocked: () => locked, logger: { warn: (msg) => warnings.push(msg) } });
return { host, sender, other, owner, notifications, warnings, message: (message, overrides = {}) => onMessage({ pluginId: identity.pluginId, viewId: "com.test.plugin.view", message, ...overrides }), change: (event) => onChange(event), lock() { locked = true; }, stale() { valid = false; } };
const diagnostics = [];
const host = new HostDrawnViewHost({
electron: { BrowserWindow: { fromWebContents: (s) => s === sender ? owner : null } },
contributionService: contributions,
resources,
isLocked: () => locked,
logger: { warn: (msg) => warnings.push(msg) },
onDiagnostic: (kind, message, extra) => diagnostics.push({ kind, message, extra }),
});
return { host, sender, other, owner, notifications, warnings, diagnostics, message: (message, overrides = {}) => onMessage({ pluginId: identity.pluginId, viewId: "com.test.plugin.view", message, ...overrides }), change: (event) => onChange(event), lock() { locked = true; }, stale() { valid = false; } };
}
const open = (f) => f.host.open({ viewId: "com.test.plugin.view", instanceId: "instance-1", scopeId: "scope", context: {} }, f.sender);
const update = (sequence = 1) => ({ kind: "host-ui.update", instanceId: "instance-1", sequence, css: '.x{display:grid}', mutations: [[0, "~", { id: "1", type: 1, element: "div", attributes: {}, children: [] }, 0]] });
@@ -87,15 +95,49 @@ test("updates are rate limited and resource caches are bounded", async () => {
assert.equal(f.host.instances.size, 0); await f.host.shutdown();
});
test("unchanged CSS is deduplicated over internal host-to-renderer IPC", async () => {
test("unchanged CSS is deduplicated over internal host-to-renderer IPC and omitted CSS is accepted", async () => {
const f = fixture(); await open(f);
assert.equal(f.notifications[0][2].message.supportsOptionalCss, true);
f.message(update(1));
f.message(update(2));
assert.equal(f.sender.sent.length, 2);
const omittedCssUpdate = { kind: "host-ui.update", instanceId: "instance-1", sequence: 3, mutations: [] };
f.message(omittedCssUpdate);
assert.equal(f.sender.sent.length, 3);
assert.equal(f.sender.sent[0][1].css, ".x{display:grid}");
assert.equal(f.sender.sent[0][1].cssUnchanged, undefined);
assert.equal(f.sender.sent[1][1].css, "");
assert.equal(f.sender.sent[1][1].cssUnchanged, true);
assert.equal(f.sender.sent[2][1].css, "");
assert.equal(f.sender.sent[2][1].cssUnchanged, true);
await f.host.shutdown();
});
test("diagnostics hook receives schema-invalid and invalid-update events with rate limiting and safe fields", async () => {
const f = fixture(); await open(f);
// Untrusted oversized instanceId must never be logged verbatim, and spam is rate-limited.
for (let i = 0; i < 10; i++) {
f.message({ kind: "host-ui.update", instanceId: "secret-".repeat(100), sequence: 0, mutations: [] });
}
assert.equal(f.diagnostics.length, 5);
assert.equal(f.diagnostics[0].kind, "schema-invalid-update");
assert.equal(f.diagnostics[0].extra.instanceId, null);
f.message(update(2));
assert.equal(f.diagnostics.length, 6);
assert.equal(f.diagnostics[5].kind, "invalid-update");
assert.equal(f.diagnostics[5].extra.pluginId, "com.test.plugin");
assert.match(f.diagnostics[5].extra.reason, /Invalid view update sequence/);
await f.host.shutdown();
});
test("sequence 1 with omitted css defaults cleanly to empty stylesheet", async () => {
const f = fixture(); await open(f);
f.message({ kind: "host-ui.update", instanceId: "instance-1", sequence: 1, mutations: [] });
assert.equal(f.sender.sent.length, 1);
assert.equal(f.sender.sent[0][1].css, "");
assert.equal(f.sender.sent[0][1].cssUnchanged, undefined);
f.message({ kind: "host-ui.update", instanceId: "instance-1", sequence: 2, mutations: [] });
assert.equal(f.sender.sent[1][1].cssUnchanged, true);
await f.host.shutdown();
});
+2
View File
@@ -388,6 +388,7 @@ function createPluginHostService(options) {
resolveRuntimeKind,
resolveSecurityPrincipal: options.resolveSecurityPrincipal,
runtimeMessageGuard,
onRuntimeFailure: options.onRuntimeFailure,
getInitialEnvironment: () => contributionService.getEnvironment(),
runtimeResourceMonitor: quotaManager,
runtimeCleanup: async (identity) => {
@@ -604,6 +605,7 @@ function createPluginHostService(options) {
}),
isLocked: options.isAppLocked,
subscribeLock: options.subscribeAppLock,
onDiagnostic: options.onViewDiagnostic,
})
: null;
viewOpenService = new PluginViewOpenService({
+3 -1
View File
@@ -220,7 +220,9 @@ class PluginRpcRouter {
}
this.#forgetPending(message.id, pending);
if (Object.hasOwn(message, "error")) {
pending.reject(new PluginRpcError(message.error.code, message.error.message, message.error.data));
const remoteError = new PluginRpcError(message.error.code, message.error.message, message.error.data);
remoteError.remote = true;
pending.reject(remoteError);
return;
}
try {
+37 -1
View File
@@ -12,7 +12,7 @@ const {
PLUGIN_CRASH_QUARANTINE_THRESHOLD,
PLUGIN_CRASH_WINDOW_MS,
} = require("./constants.cjs");
const { PluginLogger } = require("./pluginLogger.cjs");
const { PluginLogger, redactLogValue } = require("./pluginLogger.cjs");
const { PluginRpcError, RPC_ERRORS, raceWithAbort } = require("./rpcRouter.cjs");
const {
assertHostMethod,
@@ -48,6 +48,15 @@ function resolveDefaultRuntimeKind({ plugin }) {
return describePluginRuntime(plugin.manifest).defaultRuntimeKind;
}
function sanitizeHostErrorMessage(error) {
if (error?.remote === true) {
const code = Number.isInteger(error.code) ? error.code : "unknown";
return `Remote plugin RPC error (code ${code})`;
}
const raw = error instanceof Error ? error.message : String(error ?? "unknown");
return String(redactLogValue(raw)).slice(0, 512);
}
class RuntimeSupervisor {
constructor(options) {
this.electron = options.electron;
@@ -69,6 +78,7 @@ class RuntimeSupervisor {
if (this.runtimeMessageGuard != null && typeof this.runtimeMessageGuard !== "function") {
throw new TypeError("Plugin runtime message guard must be a function");
}
this.onRuntimeFailure = typeof options.onRuntimeFailure === "function" ? options.onRuntimeFailure : null;
this.getInitialEnvironment = options.getInitialEnvironment ?? (() => null);
if (typeof this.getInitialEnvironment !== "function") {
throw new TypeError("Plugin initial-environment provider must be a function");
@@ -429,6 +439,25 @@ class RuntimeSupervisor {
return error;
}
#reportRuntimeFailure(kind, identity, error, extra = {}) {
if (!this.onRuntimeFailure) return;
const safeError = new Error(sanitizeHostErrorMessage(error));
if (error instanceof Error && error.remote !== true && typeof error.code !== "undefined") {
safeError.code = error.code;
}
try {
this.onRuntimeFailure({
kind,
pluginId: identity.pluginId,
pluginVersion: identity.pluginVersion,
runtimeId: identity.runtimeId,
runtimeKind: identity.runtimeKind,
...extra,
error: safeError,
});
} catch {}
}
#recordContainmentFailure(identity, error) {
this.uncontainedPlugins.add(identity.pluginId);
const active = this.database.getActivePlugin(identity.pluginId);
@@ -439,6 +468,7 @@ class RuntimeSupervisor {
error: error?.message ?? String(error),
quarantinedAt: Date.now(),
});
this.#reportRuntimeFailure("containment-failure", identity, error, { quarantined: true });
}
async #handleExit(pluginId, runtime, identity, details) {
@@ -469,6 +499,7 @@ class RuntimeSupervisor {
this.#emitRuntimeState(identity, "error", {
error: error?.message ?? String(error),
});
this.#reportRuntimeFailure("runtime-error", identity, error, { quarantined: false });
return;
}
const crash = this.database.recordCrash(
@@ -481,6 +512,10 @@ class RuntimeSupervisor {
error: error?.message ?? String(error),
quarantinedAt: crash.quarantinedAt,
});
this.#reportRuntimeFailure("runtime-crash", identity, error, {
crashCount: crash.count,
quarantined: crash.quarantined,
});
}
stop(pluginId) {
@@ -581,6 +616,7 @@ class RuntimeSupervisor {
if (plugin?.enabled) this.database.setEnabled(identity.pluginId, false);
await this.stop(identity.pluginId);
this.#setRuntimeState(identity, "error", { error: error?.message ?? String(error) });
this.#reportRuntimeFailure("policy-violation", identity, error, { quarantined: false });
}
getRuntimeIdentity(pluginId) {
@@ -215,6 +215,7 @@ test("repeated activation failures quarantine after the third crash window event
test("unexpected process exit is contained and recorded without touching other runtimes", async (context) => {
let exit;
const failures = [];
const fixture = createFixture(context, (options) => {
exit = options.onExit;
return {
@@ -228,6 +229,8 @@ test("unexpected process exit is contained and recorded without touching other r
},
async stop() {},
};
}, {
onRuntimeFailure: (event) => failures.push(event),
});
await fixture.supervisor.start(fixture.manifest.id);
exit({ expected: false, error: new Error("process crashed") });
@@ -235,6 +238,29 @@ test("unexpected process exit is contained and recorded without touching other r
const plugin = fixture.database.getActivePlugin(fixture.manifest.id);
assert.equal(plugin.runtime.status, "error");
assert.match(plugin.runtime.lastError, /process crashed/);
assert.equal(failures.length, 1);
assert.equal(failures[0].kind, "runtime-crash");
assert.equal(failures[0].pluginId, fixture.manifest.id);
assert.equal(failures[0].crashCount, 1);
assert.match(failures[0].error.message, /process crashed/);
// Remote plugin-authored RPC errors must be redacted before reaching onRuntimeFailure.
const remoteErr = new Error("SELECT * FROM users WHERE password='super-secret-value'");
remoteErr.code = -32603;
remoteErr.remote = true;
await fixture.supervisor.start(fixture.manifest.id);
exit({ expected: false, error: remoteErr });
await new Promise((resolve) => setImmediate(resolve));
assert.equal(failures.length, 2);
assert.equal(failures[1].error.message, "Remote plugin RPC error (code -32603)");
assert.doesNotMatch(failures[1].error.message, /super-secret-value/);
// Policy violation stops the runtime and reports policy-violation failure.
const identity = await fixture.supervisor.start(fixture.manifest.id);
await fixture.supervisor.enforcePolicyViolation(identity, new Error("Plugin memory limit exceeded"));
assert.equal(failures.length, 3);
assert.equal(failures[2].kind, "policy-violation");
assert.match(failures[2].error.message, /Plugin memory limit exceeded/);
});
test("a startup exit and its rejected start count as one crash", async (context) => {
@@ -3612,6 +3612,9 @@
"stateScope": {
"type": "string",
"maxLength": 128
},
"supportsOptionalCss": {
"type": "boolean"
}
},
"additionalProperties": false
@@ -3640,8 +3643,7 @@
"kind",
"instanceId",
"sequence",
"mutations",
"css"
"mutations"
],
"properties": {
"kind": {
@@ -1564,6 +1564,9 @@ test("ViewOpenParams, ViewOpenResult, and HostDrawnViewMessage host-ui.activate
for (const valid of [
{ kind: "host-ui.open", instanceId: "inst-1" },
{ kind: "host-ui.open", instanceId: "inst-1", stateScope: "scope-hash" },
{ kind: "host-ui.open", instanceId: "inst-1", stateScope: "scope-hash", supportsOptionalCss: true },
{ kind: "host-ui.update", instanceId: "inst-1", sequence: 1, css: ".a{color:red}", mutations: [] },
{ kind: "host-ui.update", instanceId: "inst-1", sequence: 2, mutations: [] },
{ kind: "host-ui.activate", instanceId: "inst-1" },
{ kind: "host-ui.activate", instanceId: "inst-1", params: { connectionId: "conn-1" } },
{ kind: "host-ui.activate", instanceId: "inst-1", params: null },
@@ -306,6 +306,7 @@ export type HostDrawnViewMessage = ({
kind: "host-ui.open";
instanceId: string;
stateScope?: string;
supportsOptionalCss?: boolean;
}) | ({
kind: "host-ui.close";
instanceId: string;
@@ -315,7 +316,7 @@ export type HostDrawnViewMessage = ({
sequence: number;
acknowledgedEvent?: number;
mutations: Array<JsonValue>;
css: string;
css?: string;
}) | ({
kind: "host-ui.event";
instanceId: string;
+11 -4
View File
@@ -286,6 +286,7 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
syncElementIndex: () => void;
scheduleFlush: () => void;
flushScheduled: boolean;
supportsOptionalCss: boolean;
sequence: number;
acknowledgedEvent: number;
sentAck: number;
@@ -651,16 +652,19 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
}
for (const nodeId of view.controls.keys()) if (!live.has(nodeId)) view.controls.delete(nodeId);
if (!mutations.length && view.sentAck === view.acknowledgedEvent) return;
view.sentAck = view.acknowledgedEvent;
const safeMutations = JSON.parse(JSON.stringify(mutations)) as JsonValue;
const nextSequence = view.sequence + 1;
const includeCss = !view.supportsOptionalCss || view.sequence === 0;
views.postMessage(viewId, {
kind: 'host-ui.update',
instanceId: id,
sequence: ++view.sequence,
sequence: nextSequence,
acknowledgedEvent: view.acknowledgedEvent,
css,
...(includeCss ? { css } : {}),
mutations: safeMutations,
} as JsonValue);
view.sequence = nextSequence;
view.sentAck = view.acknowledgedEvent;
};
const domObserver = new MutationObserver((records) => {
send(records);
@@ -710,6 +714,7 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
syncElementIndex,
scheduleFlush,
flushScheduled: false,
supportsOptionalCss: message.supportsOptionalCss === true,
sequence: 0,
acknowledgedEvent: 0,
sentAck: 0,
@@ -736,7 +741,9 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
// next microtask if mount produced no DOM mutations.
void Promise.resolve().then(() => {
if (instances.get(id) === view && view.sequence === 0) {
views.postMessage(viewId, { kind: 'host-ui.update', instanceId: id, sequence: ++view.sequence, css, mutations: [] });
const nextSequence = view.sequence + 1;
views.postMessage(viewId, { kind: 'host-ui.update', instanceId: id, sequence: nextSequence, css, mutations: [] });
view.sequence = nextSequence;
}
});
} else if (message.kind === 'host-ui.close') close(id);
@@ -1267,3 +1267,80 @@ test('hostDom preserves leading header and nav siblings across React Suspense la
dom.window.close();
}
});
test('hostDom omits unchanged css after sequence 1 when host advertises supportsOptionalCss', async () => {
const dom = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'MouseEvent']) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
const { act, useState } = await import('react');
const { registerHostReactView } = await import('./hostReact.js');
let receive: (value: JsonValue) => void = () => {};
const messages: Array<Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>> = [];
const views = {
onDidReceiveMessage(_id: string, listener: (value: JsonValue) => void) { receive = listener; return { dispose() {} }; },
postMessage(_id: string, value: JsonValue) { messages.push(value as unknown as Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>); },
getState: async () => undefined,
setState: async () => {},
};
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount((v) => v + 1)}>Count {count}</button>;
}
const stylesheet = '.btn{display:flex}';
const registration = registerHostReactView(views, 'com.example.optional-css', () => <Counter />, stylesheet);
try {
// 1. Host advertises supportsOptionalCss: css sent once on sequence 1, omitted afterwards.
await act(async () => { receive({ kind: 'host-ui.open', instanceId: 'opt-1', supportsOptionalCss: true }); await new Promise((r) => setTimeout(r, 20)); });
assert.equal(messages.length, 1);
assert.equal(messages[0].css, stylesheet);
const mountRoot = (messages[0].mutations[0] as unknown[])[2] as { children: Array<{ id: string }> };
const buttonId = mountRoot.children[0].id;
await act(async () => { receive({ kind: 'host-ui.event', instanceId: 'opt-1', event: { eventId: 1, type: 'click', nodeId: buttonId } }); await new Promise((r) => setTimeout(r, 20)); });
assert.ok(messages.length >= 2);
for (const subsequent of messages.slice(1)) {
assert.equal(Object.hasOwn(subsequent, 'css'), false, 'subsequent updates must omit unchanged css when supportsOptionalCss is true');
}
await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'opt-1' }); });
// 2. Legacy host without supportsOptionalCss (or supportsOptionalCss: false): css continues to be included on every update.
messages.length = 0;
await act(async () => { receive({ kind: 'host-ui.open', instanceId: 'legacy-1', supportsOptionalCss: false }); await new Promise((r) => setTimeout(r, 20)); });
assert.equal(messages[0].css, stylesheet);
const legacyRoot = (messages[0].mutations[0] as unknown[])[2] as { children: Array<{ id: string }> };
await act(async () => { receive({ kind: 'host-ui.event', instanceId: 'legacy-1', event: { eventId: 1, type: 'click', nodeId: legacyRoot.children[0].id } }); await new Promise((r) => setTimeout(r, 20)); });
assert.ok(messages.length >= 2);
assert.equal(messages.at(-1)!.css, stylesheet, 'legacy hosts without supportsOptionalCss must still receive css');
await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'legacy-1' }); });
// 3. Empty initial render (null component) sends css on sequence 1 and omits it on subsequent render.
messages.length = 0;
let triggerShow: (() => void) | null = null;
function Delayed() {
const [shown, setShown] = useState(false);
triggerShow = () => setShown(true);
return shown ? <div>ready</div> : null;
}
const delayedReg = registerHostReactView(views, 'com.example.optional-css-empty', () => <Delayed />, stylesheet);
try {
await act(async () => { receive({ kind: 'host-ui.open', instanceId: 'empty-1', supportsOptionalCss: true }); await new Promise((r) => setTimeout(r, 20)); });
assert.ok(messages.length >= 1);
assert.equal(messages[0].css, stylesheet);
const countBefore = messages.length;
await act(async () => { triggerShow?.(); await new Promise((r) => setTimeout(r, 20)); });
assert.ok(messages.length > countBefore);
assert.equal(Object.hasOwn(messages.at(-1)!, 'css'), false);
await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'empty-1' }); });
} finally {
delayedReg.dispose();
}
} finally {
registration.dispose();
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
dom.window.close();
}
});