diff --git a/components/PluginHostInteractionHost.test.tsx b/components/PluginHostInteractionHost.test.tsx index 679ec43ca..82d139ec0 100644 --- a/components/PluginHostInteractionHost.test.tsx +++ b/components/PluginHostInteractionHost.test.tsx @@ -58,6 +58,8 @@ test('host dialog drives choice/input/copy and the two-phase clipboard share usi await click(document.querySelector('input[type="radio"]')!); await click(button('Continue')); assert.deepEqual(await choice.promise, { cancelled: false, value: 'compose' }); + await assert.rejects(begin({ kind: 'input', title: 'Invalid hidden newline', initialValue: 'first\nsecond' }), /invalid/); + assert.equal(document.querySelector('[role="dialog"]'), null, 'invalid initial text never creates a misleading single-line dialog'); const input = await begin({ kind: 'input', title: 'Synthetic input', initialValue: 'synthetic output' }); assert.equal(document.querySelector('input')?.value, 'synthetic output'); await click(button('Continue')); @@ -83,7 +85,7 @@ test('host dialog drives choice/input/copy and the two-phase clipboard share usi assert.deepEqual(writes, ['synthetic output']); assert.equal(service.pending.size, 0); } finally { - await act(async () => { root.unmount(); }); service.shutdown(); dom.window.close(); + await act(async () => { root.unmount(); await settle(); }); service.shutdown(); dom.window.close(); for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); } } }); diff --git a/docs/plugin-platform/host-interactions.md b/docs/plugin-platform/host-interactions.md index 7e1ed44b0..3c0b91220 100644 --- a/docs/plugin-platform/host-interactions.md +++ b/docs/plugin-platform/host-interactions.md @@ -10,10 +10,15 @@ separate parent-owned gate. | SDK call | Permission | Result | | --- | --- | --- | | `ui.quickPick(title, items)` | `ui.interact` | Approved item ID or `undefined` on cancel | -| `ui.input(title, initialValue?)` | `ui.interact` | Approved text or `undefined` on cancel | +| `ui.input(title, initialValue?)` | `ui.interact` | Approved single-line text or `undefined` on cancel | | `clipboard.readText(title)` | `clipboard.read` | Explicitly shared snapshot or `undefined` on cancel | | `clipboard.writeText(text, title)` | `clipboard.write` | `true` after copy, `false` on cancel | +`ui.input` rejects CR and LF in initial values before any dialog is displayed, +and rejects line breaks on submission. It does not silently remove hidden +newlines. The displayed single-line value is the value submitted to the plugin. +Clipboard text continues to support multiple lines. + All calls use the canonical `ui.interact` RPC. No host DOM, native object, router, general command ID, or arbitrary IPC channel enters the SDK. Existing API versions remain offered. A plugin requiring the new workflow declares @@ -67,6 +72,13 @@ Admission runs before the permission prompt. The generic capability quotas and byte windows still apply. Text exceeding its cap is rejected without silent truncation. RPC uses the same generated deadline. +After a native permission decision, an originally foreground request can wait +at most one second for the same owner to regain focus. The host never focuses +the window itself, presents content in the background, or postpones admission +for an originally background request. Hide, lock, revoke, runtime stop, owner +replacement and reload invalidate this admission, even during the permission +dialog. Runtime activity and foreground state are checked again after waiting. + Input cancellation, timeout, disable/update/crash/revoke, owner blur/hide/close, main-document reload, renderer exit, and app lock invalidate pending tokens. Same-document or subframe navigation does not permanently unregister a live diff --git a/electron/plugins/generated/plugin-contract.schema.json b/electron/plugins/generated/plugin-contract.schema.json index 918c951a0..c2b15b0b1 100644 --- a/electron/plugins/generated/plugin-contract.schema.json +++ b/electron/plugins/generated/plugin-contract.schema.json @@ -297,6 +297,12 @@ }, "additionalProperties": false }, + "HostSingleLineInputText": { + "description": "Single-line host input. CR and LF are rejected before display and on submission; clipboard text remains multiline.", + "type": "string", + "maxLength": 4096, + "pattern": "^[^\\u0000\\r\\n]*$" + }, "HostInputRequest": { "type": "object", "required": [ @@ -314,9 +320,7 @@ "pattern": "^[^\\u0000-\\u001f\\u007f]*$" }, "initialValue": { - "type": "string", - "maxLength": 4096, - "pattern": "^[^\\u0000]*$" + "$ref": "#/$defs/HostSingleLineInputText" } }, "additionalProperties": false diff --git a/electron/plugins/hostInteractionService.cjs b/electron/plugins/hostInteractionService.cjs index e67b553b6..0467c6560 100644 --- a/electron/plugins/hostInteractionService.cjs +++ b/electron/plugins/hostInteractionService.cjs @@ -9,6 +9,7 @@ const HOST_INTERACTION_FEATURE = schema.$defs.HostInteractionFeature.const; const validateRequest = createDefinitionValidator("HostInteractionRequest"); const validateResponse = createDefinitionValidator("HostInteractionResponse"); const validateResult = createDefinitionValidator("HostInteractionResult"); +const validateSingleLineInput = createDefinitionValidator("HostSingleLineInputText"); const PROMPT_CHANNEL = "netcatty:plugins:host-interaction"; function fail(code, message) { return new PluginRpcError(RPC_ERRORS[code], message); } @@ -56,6 +57,8 @@ class PluginHostInteractionService { this.pending = new Map(); this.rates = new Map(); this.admissions = new WeakMap(); + this.admissionRevision = 0; + this.focusRestoreMs = Math.min(options.focusRestoreMs ?? 1_000, 1_000); this.owner = null; this.ownerCleanup = null; this.closed = false; @@ -68,8 +71,8 @@ class PluginHostInteractionService { metadata: { capability: "ui", mutating: true }, validateParams: assertInteractionRequest, authorization: (params, context) => { - this.#admit(params, context); - this.admissions.set(params, context.runtimeId); + const sender = this.#admit(params, context); + this.admissions.set(params, { sender, runtimeId: context.runtimeId, revision: this.admissionRevision }); return interactionAuthorization(params); }, }); @@ -87,7 +90,11 @@ class PluginHostInteractionService { if (this.owner) this.releaseWindow(this.owner); this.owner = sender; const close = () => this.releaseWindow(sender); - const blur = () => this.cancelAll(); + // A native permission dialog can temporarily blur its parent. Already + // displayed interactions still cancel immediately; pre-prompt admission + // can only resume once this same owner actually regains focus. + const blur = () => this.cancelAll(false); + const hide = () => this.cancelAll(); const navigate = (details, _url, isInPlace, isMainFrame) => { const main = details?.isMainFrame ?? isMainFrame; const sameDocument = details?.isSameDocument ?? isInPlace; @@ -97,13 +104,13 @@ class PluginHostInteractionService { sender.on?.("did-start-navigation", navigate); sender.on?.("render-process-gone", close); window.on?.("blur", blur); - window.on?.("hide", blur); + window.on?.("hide", hide); this.ownerCleanup = () => { sender.removeListener?.("destroyed", close); sender.removeListener?.("did-start-navigation", navigate); sender.removeListener?.("render-process-gone", close); window.removeListener?.("blur", blur); - window.removeListener?.("hide", blur); + window.removeListener?.("hide", hide); }; return true; } @@ -182,9 +189,33 @@ class PluginHostInteractionService { async request(params, context) { await context.assertActive(); - const preauthorized = this.admissions.get(params) === context.runtimeId; + const admission = this.admissions.get(params); this.admissions.delete(params); - const sender = preauthorized ? this.#assertWindow() : this.#admit(params, context); + let sender; + if (admission?.runtimeId === context.runtimeId) { + // Electron may resolve showMessageBox before restoring parent focus. + // Never focus it ourselves or defer an originally background request. + // Owner replacement, lock, hide, revoke and runtime stop invalidate this + // host-owned admission, including changes during the permission prompt. + const deadline = Date.now() + this.focusRestoreMs; + for (;;) { + context.signal?.throwIfAborted(); + if (admission.revision !== this.admissionRevision || admission.sender !== this.owner) { + throw fail("cancelled", "Host interaction admission was revoked"); + } + const window = this.getWindow(); + if (this.closed || this.isLocked() || window?.webContents !== admission.sender + || window.isDestroyed?.() || admission.sender.isDestroyed?.() || window.isVisible?.() === false) { + throw fail("unavailable", "Host interaction owner is unavailable"); + } + if (window.isFocused?.() === true) break; + if (Date.now() >= deadline) throw fail("unavailable", "Host interactions require the focused unlocked main window"); + await new Promise((resolve) => setTimeout(resolve, Math.min(20, Math.max(1, deadline - Date.now())))); + } + await context.assertActive(); + if (admission.revision !== this.admissionRevision) throw fail("cancelled", "Host interaction admission was revoked"); + sender = this.#assertWindow(admission.sender); + } else sender = this.#admit(params, context); if (this.pending.size >= LIMITS.pendingTotal || [...this.pending.values()].some((entry) => entry.context.runtimeId === context.runtimeId || entry.sender === sender)) { throw fail("resourceExhausted", "Host interaction limit reached"); } @@ -240,7 +271,10 @@ class PluginHostInteractionService { } if (response.action !== "submit") throw fail("invalidArgument", "Host interaction action is invalid"); let value; - if (entry.params.kind === "input") value = assertTextBytes(response.value); + if (entry.params.kind === "input") { + if (!validateSingleLineInput(response.value)) throw fail("invalidArgument", "Host input must be a single line"); + value = assertTextBytes(response.value); + } else if (entry.params.kind === "quickPick") { if (!entry.params.items.some((item) => item.id === response.value)) throw fail("invalidArgument", "Host interaction choice is invalid"); value = response.value; @@ -260,6 +294,7 @@ class PluginHostInteractionService { releaseWindow(sender) { if (this.owner !== sender) return; + this.admissionRevision++; this.owner = null; this.ownerCleanup?.(); this.ownerCleanup = null; for (const entry of [...this.pending.values()]) { @@ -267,17 +302,20 @@ class PluginHostInteractionService { } } releasePlugin(pluginId) { + this.admissionRevision++; for (const entry of [...this.pending.values()]) { if (entry.context.pluginId === pluginId) this.#finish(entry, null, fail("cancelled", "Plugin access was revoked")); } } releaseRuntime(runtimeId) { + this.admissionRevision++; for (const entry of [...this.pending.values()]) { if (entry.context.runtimeId === runtimeId) this.#finish(entry, null, fail("cancelled", "Plugin runtime stopped")); } this.rates.delete(runtimeId); } - cancelAll() { + cancelAll(invalidateAdmission = true) { + if (invalidateAdmission) this.admissionRevision++; for (const entry of [...this.pending.values()]) this.#finish(entry, null, fail("cancelled", "Host interaction was cancelled")); } shutdown() { diff --git a/electron/plugins/hostInteractionService.test.cjs b/electron/plugins/hostInteractionService.test.cjs index 25f4f4129..d16872dc5 100644 --- a/electron/plugins/hostInteractionService.test.cjs +++ b/electron/plugins/hostInteractionService.test.cjs @@ -34,7 +34,7 @@ function fixture(t, options = {}) { const respond = (prompt, action, value) => service.respond(sender, { requestId: prompt.requestId, actionToken: prompt.actionToken, action, ...(value === undefined ? {} : { value }) }); return { service, sender, window, context, messages, audit, writes, charges, begin, respond, signal, get reads() { return reads; }, revoke() { onRevoke({ pluginId: context.pluginId }); }, - lock() { locked = true; }, blur() { focused = false; window.emit("blur"); }, stale() { active = false; }, + lock() { locked = true; }, blur() { focused = false; window.emit("blur"); }, focus() { focused = true; window.emit("focus"); }, stale() { active = false; }, }; } @@ -50,6 +50,67 @@ test("normal input and quick pick return only an approved bounded value", async assert.equal(f.reads, 0); assert.deepEqual(f.writes, []); }); +test("Once permission dialog may restore the same owner's focus after its decision resolves", async (t) => { + const { PluginHostRpcRegistry } = require("./hostRpcRegistry.cjs"); + const { PluginPermissionEngine } = require("./permissionEngine.cjs"); + const f = fixture(t); + let decisions = 0; + const engine = new PluginPermissionEngine({ + database: { listPermissionGrants: () => [], recordSecurityAudit() {} }, + requestDecision: async (request) => { + decisions++; + f.blur(); + setTimeout(() => f.focus(), 30); + return { requestId: request.requestId, decision: "allow", scope: "once" }; + }, + }); + t.after(() => engine.shutdown()); + const registry = new PluginHostRpcRegistry(); + registry.use(engine.createMiddleware()); + f.service.registerRpcCapabilities(registry); + const route = registry.createRoutes({ ...f.context, runtimeKind: "browser", assertCurrent() {}, + manifest: { id: f.context.pluginId, publisher: "example", permissions: { optional: ["ui.interact"] } }, + }).requestHandlers["ui.interact"]; + const result = route({ kind: "input", title: "Synthetic input", initialValue: "visible" }, { signal: f.context.signal }); + await new Promise((resolve) => setTimeout(resolve, 10)); + assert.equal(f.messages.length, 0, "no dialog is delivered while the owner is backgrounded"); + await new Promise((resolve) => setTimeout(resolve, 45)); + const prompt = f.messages.find((message) => !message.closed); + assert.ok(prompt); + await f.respond(prompt, "submit", "visible"); + assert.deepEqual(await result, { cancelled: false, value: "visible" }); + assert.equal(decisions, 1); + assert.equal(f.reads, 0); assert.deepEqual(f.writes, []); +}); + +test("focus restoration is bounded and admission cannot survive owner or access lifecycle changes", async (t) => { + for (const action of ["timeout", "hide", "revoke", "runtime", "window", "lock", "signal", "stale"]) { + const f = fixture(t, { focusRestoreMs: 35 }); + let authorize; + f.service.registerRpcCapabilities({ registerRequest(_name, _handler, options) { authorize = options.authorization; } }); + const params = assertInteractionRequest({ kind: "clipboard.write", title: "Never copied", text: "synthetic" }); + authorize(params, f.context); // admission is host-owned and originally foregrounded + f.blur(); + const result = f.service.request(params, f.context); + void result.catch(() => {}); + await new Promise((resolve) => setTimeout(resolve, 5)); + if (action === "hide") f.window.emit("hide"); + if (action === "revoke") f.revoke(); + if (action === "runtime") f.service.releaseRuntime(f.context.runtimeId); + if (action === "window") { f.sender.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false }); f.service.setReady(f.sender, true); } + if (action === "lock") f.lock(); + if (action === "signal") f.signal.abort(); + if (action === "stale") f.stale(); + if (action !== "timeout") f.focus(); + await assert.rejects(result, /focused unlocked|revoked|unavailable|abort|stale/i, action); + assert.equal(f.messages.length, 0, action); + assert.deepEqual(f.writes, []); assert.equal(f.reads, 0); + } + const background = fixture(t); + background.blur(); + await assert.rejects(background.service.request(assertInteractionRequest({ kind: "input", title: "Background" }), background.context), /focused unlocked/); +}); + test("clipboard read waits for preview action and a separate single-use sharing confirmation", async (t) => { const f = fixture(t); const request = await f.begin({ kind: "clipboard.read", title: "Share text" }); @@ -193,3 +254,17 @@ test("host lock subscription cancels previewed text before it can be shared", as assert.equal(await f.respond(preview, "submit"), false); assert.equal(f.reads, 1); assert.equal(f.service.pending.size, 0); }); + +test("single-line inputs reject CR/LF before display and submission while clipboard text stays multiline", async (t) => { + const f = fixture(t); + for (const text of ["first\nsecond", "first\rsecond", "first\r\nsecond"]) { + assert.throws(() => assertInteractionRequest({ kind: "input", title: "Single line", initialValue: text }), /invalid/); + const request = await f.begin({ kind: "input", title: "Single line", initialValue: "first second" }); + await assert.rejects(f.respond(request.prompt, "submit", text), /single line/); + await assert.rejects(request.promise, /single line/); + } + const copy = await f.begin({ kind: "clipboard.write", title: "Multiline clipboard", text: "first\nsecond" }); + await f.respond(copy.prompt, "submit"); + assert.deepEqual(await copy.promise, { cancelled: false, value: true }); + assert.deepEqual(f.writes, ["first\nsecond"]); +}); diff --git a/packages/plugin-contract/schema/plugin-contract.schema.json b/packages/plugin-contract/schema/plugin-contract.schema.json index d264452b6..9eb6f8737 100644 --- a/packages/plugin-contract/schema/plugin-contract.schema.json +++ b/packages/plugin-contract/schema/plugin-contract.schema.json @@ -244,6 +244,12 @@ }, "additionalProperties": false }, + "HostSingleLineInputText": { + "description": "Single-line host input. CR and LF are rejected before display and on submission; clipboard text remains multiline.", + "type": "string", + "maxLength": 4096, + "pattern": "^[^\\u0000\\r\\n]*$" + }, "HostInputRequest": { "type": "object", "required": [ @@ -260,11 +266,7 @@ "maxLength": 128, "pattern": "^[^\\u0000-\\u001f\\u007f]*$" }, - "initialValue": { - "type": "string", - "maxLength": 4096, - "pattern": "^[^\\u0000]*$" - } + "initialValue": { "$ref": "#/$defs/HostSingleLineInputText" } }, "additionalProperties": false }, diff --git a/packages/plugin-contract/src/generated/plugin-contract.ts b/packages/plugin-contract/src/generated/plugin-contract.ts index a357d446f..cf04406be 100644 --- a/packages/plugin-contract/src/generated/plugin-contract.ts +++ b/packages/plugin-contract/src/generated/plugin-contract.ts @@ -181,7 +181,7 @@ export type HostClipboardWriteRequest = { export type HostInputRequest = { kind: "input"; title: string; - initialValue?: string; + initialValue?: HostSingleLineInputText; }; export type HostInteractionClosed = { @@ -234,6 +234,8 @@ export type HostQuickPickRequest = { items: Array; }; +export type HostSingleLineInputText = string; + export type IconReference = (ThemeIcon) | (PackageIcon); export type ImporterDetectPayload = { diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts index 0233c0433..4967e7349 100644 --- a/packages/plugin-sdk/src/index.ts +++ b/packages/plugin-sdk/src/index.ts @@ -111,6 +111,7 @@ export interface PluginCommands { export interface PluginHostUI { quickPick(title: string, items: readonly import("@netcatty/plugin-contract").HostQuickPickItem[]): Promise; + /** Single-line text. The host rejects CR/LF in initial values and submitted responses. */ input(title: string, initialValue?: string): Promise; }