Files
Netcatty/electron/plugins/hostByteStreamAuthorization.test.cjs
T
陈大猫 f4a087e890 feat(plugins): add host-rendered IDE primitives, STARTTLS/SSH bindings, file/secret APIs, and pooled image rasterizer (#4437)
- Add host-rendered native IDE primitives (PluginCodeEditor/Monaco, PluginDataGrid/@tanstack/react-virtual, PluginSplitPane, PluginErCanvas) with Shadow DOM slot projection (zero iframes, zero plugin JS in renderer)
- Expand Remote DOM budgets, expose full 22 Netcatty semantic CSS tokens, add dblclick/contextmenu/scroll/selection events, cursor-anchored PluginPopover, database theme icon, and full-bleed chrome flag
- Add dynamic user-approved TCP/TLS byte streams (incl. localhost opt-in blocking internal control ports), in-band STARTTLS upgrade with cert fingerprint confirmation, durable revocable Vault SSH host bindings, plugin-owned encrypted secrets, native ui.openFile/saveFile streaming handles, 4 MiB clipboard, and prefix-filtered storage.keys
- Optimize plugin view image pipeline with pooled sandboxed rasterizer window (auto-destroyed on idle/error/dispose), LRU version+hash cache in PluginViewResources, transient failure eviction in HostDrawnViewHost, renderer-side session deduplication, and RemoteImageElement cache + retry
- Temporarily enable plugin host by default in hostBootstrap.cjs (marked TODO(revert), opt-out via NETCATTY_PLUGIN_DEV=0)
2026-11-26 17:52:27 +08:00

155 lines
8.3 KiB
JavaScript

"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const { EventEmitter } = require("node:events");
const { PluginHostInteractionService } = require("./hostInteractionService.cjs");
const { PluginHostVaultService } = require("./hostVaultService.cjs");
const { PluginHostRpcRegistry } = require("./hostRpcRegistry.cjs");
async function fixture(t) {
const prompts = [], opens = [];
let mode = "allow", now = Date.now(), release;
const sender = Object.assign(new EventEmitter(), { id: 3, isDestroyed: () => false, send(_channel, prompt) { if (!prompt.closed) prompts.push(prompt); } });
const owner = Object.assign(new EventEmitter(), { webContents: sender, isFocused: () => true, isVisible: () => true, isDestroyed: () => false });
const interaction = new PluginHostInteractionService({ getWindow: () => owner, isLocked: () => false,
database: { recordSecurityAudit() {} }, quotaManager: { chargeBytes() {} },
permissionEngine: { getMode: () => mode, onDidRevoke: () => ({ dispose() {} }) },
});
interaction.setReady(sender, true);
const binding = { runtimeId: "runtime", pluginId: "plugin" };
const vault = new PluginHostVaultService({ interactionService: interaction, clock: () => now,
sourceBinding: { resolve: async () => binding, releaseRuntime() {}, shutdown() {} },
openStream: async (endpoint, context, actualSender, options) => {
const open = { endpoint, context, actualSender, options, closed: false }; opens.push(open);
if (release) await new Promise((resolve) => { release.resolve = resolve; });
await context.assertActive();
context.signal.addEventListener("abort", () => { open.closed = true; });
return { descriptor: { handleId: "11111111-1111-4111-8111-111111111111", endpoint, inputStreamId: "input-one", outputStreamId: "output-one", windowBytes: 65536 }, close: () => { open.closed = true; } };
},
});
t.after(() => interaction.shutdown());
const registry = new PluginHostRpcRegistry(); vault.registerRpcCapabilities(registry);
const identity = { ...binding, runtimeKind: "browser", pluginVersion: "1.0.0", manifest: { features: { required: ["network.byte-streams", "network.host-byte-streams"] } } };
const routes = registry.createRoutes(identity);
const call = (name, params) => routes.requestHandlers[name](params, { signal: new AbortController().signal });
const tick = () => new Promise((resolve) => setImmediate(resolve));
const respond = (action, extra = {}, options) => {
const prompt = prompts.at(-1);
return interaction.respond(sender, { requestId: prompt.requestId, actionToken: prompt.actionToken, action, ...extra }, options);
};
const selection = call("vault.selectHosts", { title: "Choose" }); await tick();
await respond("submit", { resources: [{ resourceId: "host-one", revision: "r1", label: "Test", hostname: "test.invalid", username: "fixture", group: "", tags: [], protocol: "ssh" }] });
const selected = (await selection).hosts[0].target;
const params = { target: selected, expectedRevision: selected.revision, endpoint: "tcp://127.0.0.1:3306" };
return { interaction, vault, identity, prompts, opens, params, call, respond, tick,
setMode(value) { mode = value; }, expire() { now += 300_001; }, stall() { release = {}; return release; },
};
}
test("host stream requires negotiated features, exact endpoint and unmodified selected host reference", async (t) => {
const f = await fixture(t);
for (const params of [
{ ...f.params, password: "caller-secret" },
{ ...f.params, endpoint: "tcp://user:secret@localhost:3306" },
{ ...f.params, target: { ...f.params.target, handle: "forged" } },
{ ...f.params, expectedRevision: "changed" },
]) await assert.rejects(f.call("network.stream.connectViaHost", params));
f.identity.manifest.features.required = ["network.byte-streams"];
await assert.rejects(f.call("network.stream.connectViaHost", f.params), /negotiated/);
assert.equal(f.opens.length, 0);
});
test("Allow still reviews destination, consumes the native commit once, and lock closes the stream", async (t) => {
const f = await fixture(t);
const pending = f.call("network.stream.connectViaHost", f.params); await f.tick();
assert.equal(f.opens.length, 0);
assert.equal(f.prompts.at(-1).request.endpoint, f.params.endpoint);
await f.respond("submit");
const prompt = f.prompts.at(-1);
const response = { requestId: prompt.requestId, actionToken: prompt.actionToken, action: "commit" };
assert.equal(await f.interaction.respond(f.interaction.owner, response, { hostId: "host-one" }), true);
const descriptor = await pending;
assert.equal(descriptor.endpoint, f.params.endpoint);
assert.equal(await f.interaction.respond(f.interaction.owner, response, { hostId: "host-one" }), false);
assert.equal(f.opens.length, 1);
f.expire(); await f.opens[0].context.assertActive();
f.interaction.cancelAll();
assert.equal(f.opens[0].closed, true);
});
test("Deny, cancellation and a mismatched native host never dial", async (t) => {
const f = await fixture(t);
f.setMode("deny"); await assert.rejects(f.call("network.stream.connectViaHost", f.params));
f.setMode("allow");
let pending = f.call("network.stream.connectViaHost", f.params); await f.tick();
await f.respond("cancel"); assert.deepEqual(await pending, { cancelled: true });
pending = f.call("network.stream.connectViaHost", f.params); void pending.catch(() => {}); await f.tick();
await f.respond("submit");
await assert.rejects(f.respond("commit", {}, { hostId: "other-host" }));
await assert.rejects(pending);
assert.equal(f.opens.length, 0);
});
test("window closure during opening aborts the operation and rejects a late connection", async (t) => {
const f = await fixture(t); const gate = f.stall();
const pending = f.call("network.stream.connectViaHost", f.params); void pending.catch(() => {}); await f.tick();
await f.respond("submit");
const committing = f.respond("commit", {}, { hostId: "host-one" }); void committing.catch(() => {}); await f.tick();
f.interaction.releaseWindow(f.interaction.owner);
gate.resolve();
await assert.rejects(committing); await assert.rejects(pending);
assert.equal(f.opens[0].context.signal.aborted, true);
assert.equal(f.vault.streams.size, 0);
});
test("durable SSH tunnel binding survives selection expiry and blur, enforces exact endpoint, and can be revoked", async (t) => {
const f = await fixture(t);
const pending = f.call("network.stream.connectViaHost", { ...f.params, durable: true });
await f.tick();
await f.respond("submit", { remember: true });
await f.respond("commit", {}, { hostId: "host-one" });
const first = await pending;
assert.equal(typeof first.hostBindingToken, "string");
assert.ok(first.hostBindingToken.startsWith("hb_"));
// Expire ephemeral selection and clear selections (simulating blur/restart).
f.expire();
f.vault.clearSelections();
// Mismatched endpoint with the same durable token must be rejected.
await assert.rejects(
f.call("network.stream.connectViaHost", { hostBindingToken: first.hostBindingToken, endpoint: "tcp://127.0.0.1:5432" }),
/binding/u,
);
// Forged token must be rejected.
await assert.rejects(
f.call("network.stream.connectViaHost", { hostBindingToken: "hb_forged_token_000000000000000000", endpoint: f.params.endpoint }),
/binding/u,
);
// Reconnect with durable token skips request phase and emits autoCommit prompt bound to host-one.
const reconnect = f.call("network.stream.connectViaHost", {
hostBindingToken: first.hostBindingToken,
endpoint: f.params.endpoint,
});
await f.tick();
const prompt = f.prompts.at(-1);
assert.equal(prompt.phase, "commit");
assert.equal(prompt.autoCommit, true);
assert.equal(prompt.durableHostId, "host-one");
await f.respond("commit", {}, { hostId: "host-one" });
const second = await reconnect;
assert.equal(second.endpoint, f.params.endpoint);
assert.equal(second.hostBindingToken, first.hostBindingToken);
assert.equal(f.opens.length, 2);
// Revoke durable binding -> subsequent reconnect fails closed.
const revoked = await f.call("vault.revokeHostBinding", { hostBindingToken: first.hostBindingToken });
assert.deepEqual(revoked, { revoked: true });
await assert.rejects(
f.call("network.stream.connectViaHost", { hostBindingToken: first.hostBindingToken, endpoint: f.params.endpoint }),
/binding/u,
);
});