Compare commits

...
Author SHA1 Message Date
陈大猫 82e64a60d8 docs: note that the plugin system and official plugins are still unstable
Tell users the plugin system and current official plugins are still
in an unstable stage, and that issues are welcome and will be fixed
promptly. Linked from all four README locales to the announcement
in Discussions #4554.
2026-11-29 17:29:51 +08:00
陈大猫 3c4f561beb fix(rdp): send local clipboard images to the remote desktop (#4552)
* fix(rdp): send local clipboard images to the remote desktop

Fixes #4551

* fix(rdp): invalidate clipboard echo guards on format replacement

Fixes the Codex P2 on PR #4552: a later text-only or image-only clipboard must replace the remote clipboard even when one format matches a stale guard from the previous snapshot.

* fix(rdp): write mixed remote clipboard text and PNG locally

Addresses the Codex P2 on PR #4552: write mixed remote snapshots locally as both text/plain and image/png so the echo guard does not wipe remote text on refocus. Fall back to PNG, then text, if the mixed write fails.
2026-11-29 17:25:37 +08:00
陈大猫 d04bf9ce72 fix(terminal): clear full snippet label on autocomplete accept when the name has spaces (#4550)
Fixes #4549
2026-11-29 16:49:21 +08:00
陈大猫 bfe63719d8 feat(terminal): unify 1px focus and magnification borders with deterministic state (#4543) (#4545)
* feat(terminal): unify 1px focus and magnification borders with deterministic state

* fix(terminal): preserve zoom entry animation on unchanged initial ResizeObserver callback

* test(terminal): update browserPanelLifecycle vm stub for setMagnifiedPanesByTab
2026-11-29 14:45:56 +08:00
陈大猫 08f22349c1 fix(plugins): clear stale PluginDataGrid editingCell and blur timer on row removal (#4547) 2026-11-29 14:41:35 +08:00
陈大猫 c846cd6fd8 feat(vault): allow Direct (no proxy) on groups (#4442) (#4546) 2026-11-29 14:34:10 +08:00
Netcatty-Bot 2506b5d1bc Update Nix release metadata for v1.1.95 (#4536) 2026-11-29 12:50:41 +08:00
陈大猫 a24be98a6b fix(rdp): reuse MCS server public key when license request has no cert (#4542)
Related #4540
2026-11-29 12:23:04 +08:00
陈大猫 b08a1398e3 test(plugins): sync Database 0.3.2 brand fixture and list avatar assertions (#4537) 2026-11-29 09:18:47 +08:00
61 changed files with 2391 additions and 252 deletions

No files matched your search

+4
View File
@@ -46,6 +46,8 @@
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **お知らせ:** プラグインシステムおよび現在の公式プラグイン(Netcatty Database、Netcatty Monitor)は、まだ不安定な段階にあります。ご利用の際はご注意ください。問題があればいつでも [Issue を作成](https://github.com/binaricat/Netcatty/issues)してください。できるだけ早く対応します。詳しくは[お知らせ](https://github.com/binaricat/Netcatty/discussions/4554)をご覧ください。
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -84,6 +86,8 @@ Catty Agent にサーバーの健全性チェックを依頼すると、適切
<a name="plugin-system"></a>
# 🧩 プラグインシステム — Netcatty を安全に拡張
> **お知らせ:** プラグインシステムおよび現在の公式プラグイン(Netcatty Database、Netcatty Monitor)は、まだ不安定な段階にあります。ご利用の際はご注意ください。問題があればいつでも [Issue を作成](https://github.com/binaricat/Netcatty/issues)してください。できるだけ早く対応します。詳しくは[お知らせ](https://github.com/binaricat/Netcatty/discussions/4554)をご覧ください。
> **SSH 鍵やホストレンダラーを公開することなく機能を追加できます。** Netcatty のセキュリティ優先プラグイン基盤は、通常プラグインをオフラインのサンドボックス内で実行し、**ホストレンダリング UI**(Closed Shadow DOM + ネイティブ Monaco、DataGrid、BI/メトリクスチャート、Vault SSH トンネルプロキシ)のみで画面を描画します。
### ✨ 主な特徴
+4
View File
@@ -46,6 +46,8 @@
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **Notice:** The plugin system and the current official plugins (Netcatty Database and Netcatty Monitor) are still in an unstable stage. Please keep that in mind while using them. If you run into a problem, feel free to [open an Issue](https://github.com/binaricat/Netcatty/issues) — I'll fix it as soon as I can. See the [announcement](https://github.com/binaricat/Netcatty/discussions/4554).
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -86,6 +88,8 @@ Watch Catty Agent orchestrate a Docker Swarm cluster across two servers in one c
<a name="plugin-system"></a>
# 🧩 Plugin System — Extend Netcatty Safely
> **Notice:** The plugin system and the current official plugins (Netcatty Database and Netcatty Monitor) are still in an unstable stage. Please keep that in mind while using them. If you run into a problem, feel free to [open an Issue](https://github.com/binaricat/Netcatty/issues) — I'll fix it as soon as I can. See the [announcement](https://github.com/binaricat/Netcatty/discussions/4554).
> **Build and install rich extensions without exposing your SSH keys or host renderer.** Netcatty's security-first plugin platform runs ordinary extensions inside an offline, sandboxed runtime and renders custom views exclusively through **Host-Rendered UI** (closed Shadow DOM + native Monaco, DataGrid, BI/Metric charts, and Vault SSH tunnel brokers).
### ✨ Highlights
+4
View File
@@ -46,6 +46,8 @@
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **说明:** 插件系统和现有的官方插件(Netcatty 数据库、Netcatty 监控)目前仍处于不稳定阶段,使用时请多加留意。如果你遇到问题,欢迎随时[提交 Issue](https://github.com/binaricat/Netcatty/issues),我会尽快修复。详见[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -84,6 +86,8 @@
<a name="plugin-system"></a>
# 🧩 插件系统 — 安全扩展你的工作台
> **说明:** 插件系统和现有的官方插件(Netcatty 数据库、Netcatty 监控)目前仍处于不稳定阶段,使用时请多加留意。如果你遇到问题,欢迎随时[提交 Issue](https://github.com/binaricat/Netcatty/issues),我会尽快修复。详见[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
> **在不暴露 SSH 密钥与主进程渲染器的前提下自由扩展 Netcatty。** Netcatty 的安全优先插件平台将普通插件隔离在离线沙箱中运行,并通过**宿主渲染 UI**(Closed Shadow DOM + 原生 Monaco 编辑器、虚拟化数据网格、实时监控/BI 图表与 Vault SSH 隧道代理)呈现原生手感界面。
### ✨ 核心亮点
+4
View File
@@ -46,6 +46,8 @@
<a href="./README.md">English</a> · <a href="./README.zh-CN.md">简体中文</a> · <a href="./README.zh-TW.md">繁體中文</a> · <a href="./README.ja-JP.md">日本語</a>
</p>
> **說明:** 外掛系統與現有的官方外掛(Netcatty 資料庫、Netcatty 監控)目前仍處於不穩定階段,使用時請多加留意。若遇到問題,歡迎隨時[提交 Issue](https://github.com/binaricat/Netcatty/issues),我會盡快修復。詳見[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
---
<img width="3358" height="1984" alt="image" src="docs/assets/readme/overview.webp" />
@@ -84,6 +86,8 @@
<a name="plugin-system"></a>
# 🧩 外掛系統 —— 安全擴充你的工作台
> **說明:** 外掛系統與現有的官方外掛(Netcatty 資料庫、Netcatty 監控)目前仍處於不穩定階段,使用時請多加留意。若遇到問題,歡迎隨時[提交 Issue](https://github.com/binaricat/Netcatty/issues),我會盡快修復。詳見[公告](https://github.com/binaricat/Netcatty/discussions/4554)。
> **在不暴露 SSH 金鑰與宿主渲染器的前提下自由擴充 Netcatty。** Netcatty 的安全優先外掛平台將一般外掛隔離於離線沙箱中執行,並透過**宿主渲染 UI**(Closed Shadow DOM + 原生 Monaco 編輯器、虛擬化資料格、即時監控/BI 圖表與 Vault SSH 通道代理)呈現原生體驗。
### ✨ 核心亮點
+31 -1
View File
@@ -604,7 +604,37 @@ export function AppSideEffects() {
});
// Window controls - must be before update toast effect which uses openSettingsWindow
const { openSettingsWindow } = useWindowControls();
const { openSettingsWindow, isFullscreen, onFullscreenChanged } = useWindowControls();
// Sync host platform and fullscreen state to DOM so platform-aware chrome
// (such as macOS rounded window corners on outer split-pane focus borders)
// stays accurate across fullscreen transitions without per-pane polling.
useEffect(() => {
const isMac = typeof navigator !== 'undefined' && /Mac/i.test(navigator.platform);
if (isMac) {
document.documentElement.setAttribute('data-platform', 'darwin');
} else {
document.documentElement.removeAttribute('data-platform');
document.documentElement.removeAttribute('data-window-fullscreen');
return undefined;
}
let cancelled = false;
const syncFullscreen = (value: boolean) => {
if (value) {
document.documentElement.setAttribute('data-window-fullscreen', 'true');
} else {
document.documentElement.removeAttribute('data-window-fullscreen');
}
};
void isFullscreen().then((value) => {
if (!cancelled) syncFullscreen(!!value);
});
const unsubscribe = onFullscreenChanged((value) => syncFullscreen(!!value));
return () => {
cancelled = true;
unsubscribe();
};
}, [isFullscreen, onFullscreenChanged]);
const _handleTrayJumpToSession = useEffectEvent((sessionId: string) => {
return handleTrayJumpToSessionImpl(() => ({
sessionId,
+15 -1
View File
@@ -16,5 +16,19 @@ export const useClipboardBackend = () => {
return await bridge.writeClipboardText(text) === true;
}, []);
return { readClipboardText, writeClipboardText };
const readClipboardImagePng = useCallback(async (): Promise<Uint8Array | null> => {
const bridge = netcattyBridge.get();
if (bridge?.readClipboardImagePng) return await bridge.readClipboardImagePng();
// Browser fallback when the native clipboard bridge is unavailable.
const items = await navigator.clipboard?.read();
for (const item of items ?? []) {
if (!item.types.includes("image/png")) continue;
const blob = await item.getType("image/png");
return new Uint8Array(await blob.arrayBuffer());
}
return null;
}, []);
return { readClipboardText, writeClipboardText, readClipboardImagePng };
};
@@ -58,6 +58,7 @@ export const isAutoStartProxyReady = (
host.proxyProfileId && !validProxyProfileIds.has(host.proxyProfileId),
);
const missingGroupProxyProfile = Boolean(
!host.directProxy &&
!host.proxyConfig &&
!host.proxyProfileId &&
rawGroupDefaults.proxyProfileId &&
@@ -0,0 +1,167 @@
import assert from "node:assert/strict";
import test from "node:test";
import React from "react";
import { act, create, type ReactTestRenderer } from "react-test-renderer";
import { I18nProvider } from "../application/i18n/I18nProvider.tsx";
import type { GroupConfig } from "../types.ts";
import GroupDetailsPanel from "./GroupDetailsPanel.tsx";
import { ProxyPanel } from "./host-details/ProxyPanel.tsx";
import { AsidePanel } from "./ui/aside-panel.tsx";
import { Badge } from "./ui/badge.tsx";
import { TooltipProvider } from "./ui/tooltip.tsx";
import { installDomEnvironment } from "./test-support/renderReactDom.tsx";
async function mountGroupDetails(config: GroupConfig | undefined) {
const environment = globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean };
const previous = environment.IS_REACT_ACT_ENVIRONMENT;
const dom = installDomEnvironment();
const previousRaf = globalThis.requestAnimationFrame;
const previousCancelRaf = globalThis.cancelAnimationFrame;
globalThis.requestAnimationFrame = (callback) => setTimeout(() => callback(0), 0) as unknown as number;
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
environment.IS_REACT_ACT_ENVIRONMENT = true;
let renderer: ReactTestRenderer | undefined;
let saved: GroupConfig | undefined;
await act(async () => {
renderer = create(
<I18nProvider locale="en">
<TooltipProvider>
<GroupDetailsPanel
groupPath={config?.path ?? "corp/local"}
config={config}
availableKeys={[]}
identities={[]}
proxyProfiles={[]}
allHosts={[]}
groups={["corp", "corp/local"]}
groupConfigs={[
{ path: "corp", proxyConfig: { type: "http", host: "corp-proxy.example.com", port: 8080 } },
...(config ? [config] : []),
]}
terminalThemeId="default"
terminalFontSize={14}
onSave={(value) => { saved = value; }}
onCancel={() => {}}
/>
</TooltipProvider>
</I18nProvider>,
);
});
const cleanup = async () => {
if (renderer) await act(async () => { renderer!.unmount(); });
globalThis.requestAnimationFrame = previousRaf;
globalThis.cancelAnimationFrame = previousCancelRaf;
dom.cleanup();
environment.IS_REACT_ACT_ENVIRONMENT = previous;
};
return {
get root() {
return renderer!.root;
},
getSaved: () => saved,
cleanup,
};
}
const findProxySummaryButton = (root: ReactTestRenderer["root"]) =>
root.findAllByType("button").find((button) => {
const badges = button.findAllByType(Badge);
return badges.some((badge) =>
badge.props.children === "HTTP" || badge.props.children === "Direct (no proxy)",
);
});
test("GroupDetailsPanel lets a child group choose Direct (no proxy) and persists directProxy", async () => {
const harness = await mountGroupDetails({
path: "corp/local",
protocol: "ssh",
proxyConfig: { type: "http", host: "old-proxy.example.com", port: 8080 },
});
try {
const proxyButton = findProxySummaryButton(harness.root);
assert.ok(proxyButton, "Proxy summary button should be rendered");
await act(async () => {
proxyButton.props.onClick();
});
const proxyPanel = harness.root.findByType(ProxyPanel);
assert.equal(typeof proxyPanel.props.onSelectDirectProxy, "function");
assert.equal(proxyPanel.props.directProxy, undefined);
await act(async () => {
proxyPanel.props.onSelectDirectProxy!();
});
const updatedPanel = harness.root.findByType(ProxyPanel);
assert.equal(updatedPanel.props.directProxy, true);
assert.equal(updatedPanel.props.proxyConfig, undefined);
assert.equal(updatedPanel.props.selectedProxyProfileId, undefined);
await act(async () => {
updatedPanel.props.onBack();
});
const proxyButtonAfter = findProxySummaryButton(harness.root);
assert.ok(proxyButtonAfter);
const badge = proxyButtonAfter.findByType(Badge);
assert.equal(badge.props.children, "Direct (no proxy)");
await act(async () => {
harness.root.findByType(AsidePanel).props.actions.props.onClick();
});
const saved = harness.getSaved();
assert.ok(saved, "onSave should be called");
assert.equal(saved.directProxy, true);
assert.equal(saved.proxyConfig, undefined);
assert.equal(saved.proxyProfileId, undefined);
} finally {
await harness.cleanup();
}
});
test("GroupDetailsPanel clears directProxy when removed in ProxyPanel so parent proxy applies again", async () => {
const harness = await mountGroupDetails({
path: "corp/local",
directProxy: true,
});
try {
const proxyButton = findProxySummaryButton(harness.root);
assert.ok(proxyButton, "SSH section and Proxy summary should open automatically for directProxy groups");
assert.equal(proxyButton.findByType(Badge).props.children, "Direct (no proxy)");
await act(async () => {
proxyButton.props.onClick();
});
const proxyPanel = harness.root.findByType(ProxyPanel);
assert.equal(proxyPanel.props.directProxy, true);
await act(async () => {
proxyPanel.props.onClearProxy();
});
assert.equal(harness.root.findByType(ProxyPanel).props.directProxy, undefined);
await act(async () => {
harness.root.findByType(ProxyPanel).props.onBack();
});
await act(async () => {
harness.root.findByType(AsidePanel).props.actions.props.onClick();
});
const saved = harness.getSaved();
assert.ok(saved, "onSave should be called");
assert.equal(saved.directProxy, undefined);
assert.equal(saved.proxyConfig, undefined);
assert.equal(saved.proxyProfileId, undefined);
} finally {
await harness.cleanup();
}
});
+5
View File
@@ -33,6 +33,11 @@ test("GroupDetailsPanel keeps the SSH section when X11 forwarding is set", () =>
assert.equal(hasGroupSshFields({ x11Forwarding: false }), true);
});
test("GroupDetailsPanel keeps the SSH section when directProxy is set", () => {
assert.equal(hasGroupSshFields({ directProxy: true }), true);
assert.equal(hasGroupSshFields({ directProxy: false }), false);
});
test("GroupDetailsPanel treats cleared telnet credentials as explicit settings", () => {
assert.equal(hasGroupTelnetFields({ telnetUsername: "" }), true);
assert.equal(hasGroupTelnetFields({ telnetPassword: "" }), true);
+47 -24
View File
@@ -121,6 +121,7 @@ export const hasGroupSshFields = (c: Partial<GroupConfig>): boolean => {
return Boolean(
c.proxyProfileId ||
c.proxyConfig ||
c.directProxy === true ||
c.hostChain ||
c.startupCommand ||
c.startupCommandRunMode !== undefined,
@@ -350,23 +351,29 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
() => proxyProfiles.find((profile) => profile.id === form.proxyProfileId),
[form.proxyProfileId, proxyProfiles],
);
const hasMissingProxyProfile = Boolean(form.proxyProfileId && !selectedProxyProfile);
const hasMissingProxyProfile = Boolean(!form.directProxy && form.proxyProfileId && !selectedProxyProfile);
const hasProxyConfig = Boolean(
form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId,
form.directProxy || form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId,
);
const proxySummaryType = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
: formatProxyConfigType(selectedProxyProfile?.config || form.proxyConfig) || "HTTP";
const proxySummaryLabel = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? selectedProxyProfile.label
: formatProxyConfigEndpoint(form.proxyConfig);
const proxySummaryTooltip = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? `${selectedProxyProfile.label} - ${formatProxyConfigEndpoint(selectedProxyProfile.config)}`
: `${formatProxyConfigType(form.proxyConfig)} ${formatProxyConfigEndpoint(form.proxyConfig)}`;
const proxySummaryType = form.directProxy
? t("hostDetails.proxy.direct")
: hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
: formatProxyConfigType(selectedProxyProfile?.config || form.proxyConfig) || "HTTP";
const proxySummaryLabel = form.directProxy
? t("hostDetails.proxy.directHint")
: hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? selectedProxyProfile.label
: formatProxyConfigEndpoint(form.proxyConfig);
const proxySummaryTooltip = form.directProxy
? `${t("hostDetails.proxy.direct")} - ${t("hostDetails.proxy.directHint")}`
: hasMissingProxyProfile
? t("hostDetails.proxyPanel.missingSaved")
: selectedProxyProfile
? `${selectedProxyProfile.label} - ${formatProxyConfigEndpoint(selectedProxyProfile.config)}`
: `${formatProxyConfigType(form.proxyConfig)} ${formatProxyConfigEndpoint(form.proxyConfig)}`;
const update = <K extends keyof GroupConfig>(key: K, value: GroupConfig[K] | undefined) => {
setForm((prev) => ({ ...prev, [key]: value }));
@@ -463,6 +470,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -479,6 +487,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -494,6 +503,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -513,6 +523,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
if (!hasAnyProtocol) {
delete next.proxyProfileId;
delete next.proxyConfig;
delete next.directProxy;
}
return next;
});
@@ -525,7 +536,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
const updateProxyConfig = useCallback(
(field: keyof ProxyConfig, value: ProxyConfig[keyof ProxyConfig]) => {
setForm((prev) => {
const { proxyProfileId: _proxyProfileId, ...rest } = prev;
const { proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
return {
...rest,
proxyConfig: updateProxyConfigField(prev.proxyConfig, field, value),
@@ -537,19 +548,26 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
const clearProxyConfig = useCallback(() => {
setForm((prev) => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev;
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
return rest;
});
}, []);
const selectProxyProfile = useCallback((profileId: string | undefined) => {
setForm((prev) => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev;
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, directProxy: _directProxy, ...rest } = prev;
if (!profileId) return rest;
return { ...rest, proxyProfileId: profileId };
});
}, []);
const selectDirectProxy = useCallback(() => {
setForm((prev) => {
const { proxyConfig: _proxyConfig, proxyProfileId: _proxyProfileId, ...rest } = prev;
return { ...rest, directProxy: true };
});
}, []);
// Chain helpers
const chainedHosts = useMemo(() => {
const ids = form.hostChain?.hostIds || [];
@@ -751,7 +769,6 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
setNameError(t("vault.groups.errors.invalidChars"));
return;
}
const newPath = parentGroup ? `${parentGroup}/${trimmedName}` : trimmedName;
if (newPath !== groupPath && groups.includes(newPath)) {
setNameError(t("vault.groups.errors.duplicatePath"));
@@ -772,7 +789,7 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
const anyProtocolEnabled = sshEnabled || rdpEnabled || vncEnabled || telnetEnabled;
const anyRoutingProtocolEnabled = sshEnabled || rdpEnabled || vncEnabled;
const proxySave = anyProtocolEnabled
const proxySave = anyProtocolEnabled && !form.directProxy
? prepareProxyConfigForSave({
proxyConfig: form.proxyConfig,
proxyProfileId: form.proxyProfileId,
@@ -917,10 +934,14 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
}),
...(finalRdpConfig && { rdpConfig: finalRdpConfig }),
...(finalVncConfig && { vncConfig: finalVncConfig }),
...(anyProtocolEnabled && {
...(form.proxyProfileId !== undefined && { proxyProfileId: form.proxyProfileId }),
...(normalizedProxyConfig !== undefined && { proxyConfig: normalizedProxyConfig }),
}),
...(anyProtocolEnabled && (
form.directProxy === true
? { directProxy: true }
: {
...(form.proxyProfileId !== undefined && { proxyProfileId: form.proxyProfileId }),
...(normalizedProxyConfig !== undefined && { proxyConfig: normalizedProxyConfig }),
}
)),
...(anyRoutingProtocolEnabled && {
...(form.hostChain !== undefined && { hostChain: form.hostChain }),
}),
@@ -954,8 +975,10 @@ const GroupDetailsPanel: React.FC<GroupDetailsPanelPropsWithResize> = ({
proxyProfiles={proxyProfiles}
identities={identities}
selectedProxyProfileId={form.proxyProfileId}
directProxy={form.directProxy}
onUpdateProxy={updateProxyConfig}
onSelectProxyProfile={selectProxyProfile}
onSelectDirectProxy={selectDirectProxy}
onClearProxy={clearProxyConfig}
onBack={() => setActiveSubPanel("none")}
onCancel={onCancel}
+5 -1
View File
@@ -63,6 +63,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
proxySummaryType,
proxySummaryLabel,
proxySummaryTooltip,
displayDirectProxy = Boolean(form.directProxy),
proxyInherited = false,
clearProxyConfig,
}) => {
@@ -784,7 +785,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
title={t("hostDetails.proxy")}
className="overflow-hidden"
>
{form.directProxy ? (
{displayDirectProxy ? (
<div className="w-full min-w-0 grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
<button
type="button"
@@ -796,8 +797,10 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
</Badge>
<span className="block min-w-0 overflow-hidden text-ellipsis whitespace-nowrap text-sm">
{t("hostDetails.proxy.directHint")}
{proxyInherited ? ` · ${t("vault.groups.details.inherited")}` : ""}
</span>
</button>
{!proxyInherited && (
<Button
type="button"
variant="ghost"
@@ -808,6 +811,7 @@ export const HostDetailsAdvancedSections: React.FC<HostDetailsAdvancedSectionsPr
>
<X size={14} />
</Button>
)}
</div>
) : form.proxyConfig?.host || form.proxyConfig?.command || form.proxyProfileId || proxyInherited ? (
<div className="w-full min-w-0 grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
@@ -691,6 +691,34 @@ test("HostDetailsPanel direct proxy hides inherited group proxy", () => {
assert.match(markup, /Direct \(no proxy\)/);
assert.doesNotMatch(markup, /group-proxy\.example\.com/);
assert.doesNotMatch(markup, /Inherited from group/);
});
test("HostDetailsPanel displays inherited group directProxy and hides global default proxy", () => {
const previous = getActiveGlobalDefaultProxyProfileId();
try {
publishActiveGlobalDefaultProxyProfileId("global-proxy");
const markup = renderHostDetailsWithGroup(networkSshHost, {
directProxy: true,
});
assert.match(markup, /Direct \(no proxy\)/);
assert.match(markup, /Inherited from group/);
assert.doesNotMatch(markup, /Configure proxy/);
const overridden = renderHostDetailsWithGroup({
...networkSshHost,
proxyConfig: { type: "http", host: "host-proxy.example.com", port: 9090 },
}, {
directProxy: true,
});
assert.match(overridden, /host-proxy\.example\.com/);
assert.doesNotMatch(overridden, /Direct \(no proxy\)/);
assert.doesNotMatch(overridden, /Inherited from group/);
} finally {
publishActiveGlobalDefaultProxyProfileId(previous);
}
});
test("HostDetailsPanel displays inherited group jump hosts", () => {
+6 -3
View File
@@ -517,8 +517,10 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
const hasHostProxyOverride = form.directProxy === true
|| form.proxyProfileId !== undefined
|| form.proxyConfig !== undefined;
const displayDirectProxy = form.directProxy === true
|| (!hasHostProxyOverride && effectiveAuthHost.directProxy === true);
const displayProxyProfileId = resolveDisplayProxyProfileId(form, effectiveAuthHost.proxyProfileId);
const displayProxyConfig = form.directProxy
const displayProxyConfig = displayDirectProxy
? undefined
: (form.proxyConfig ?? effectiveAuthHost.proxyConfig);
const selectedProxyProfile = useMemo(
@@ -527,7 +529,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
);
const hasMissingProxyProfile = Boolean(displayProxyProfileId && !selectedProxyProfile);
const proxyInherited = !hasHostProxyOverride && Boolean(
displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command,
displayDirectProxy || displayProxyProfileId || displayProxyConfig?.host || displayProxyConfig?.command,
);
const proxySummaryType = hasMissingProxyProfile
? t("hostDetails.proxyPanel.missing")
@@ -1518,7 +1520,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
proxyProfiles={proxyProfiles}
identities={identities}
selectedProxyProfileId={displayProxyProfileId}
directProxy={form.directProxy}
directProxy={displayDirectProxy}
allowClear={hasHostProxyOverride}
onUpdateProxy={updateProxyConfig}
onSelectProxyProfile={selectProxyProfile}
@@ -1902,6 +1904,7 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
proxySummaryType={proxySummaryType}
proxySummaryLabel={proxySummaryLabel}
proxySummaryTooltip={proxySummaryTooltip}
displayDirectProxy={displayDirectProxy}
proxyInherited={proxyInherited}
clearProxyConfig={clearProxyConfig}
/>
+12
View File
@@ -226,3 +226,15 @@ test("ProxyPanel offers keychain identities for HTTP and SOCKS5 proxy credential
assert.match(markup, /Proxy login/);
assert.match(markup, /proxy-user/);
});
test("ProxyPanel shows saved proxy selector and enables saving without profiles when directProxy is selected", () => {
const markup = renderPanel({
directProxy: true,
onSelectDirectProxy: () => {},
});
assert.match(markup, /Saved proxy/);
assert.match(markup, /Remove Proxy/);
assert.doesNotMatch(markup, /Proxy host/);
assert.doesNotMatch(markup, /disabled=""/);
});
+85 -57
View File
@@ -137,8 +137,10 @@ import {
} from '../domain/sidePanelLayout';
import { useWorkspaceLayoutPresetState } from '../application/state/useWorkspaceLayoutPresetState';
import {
isPaneMagnificationSelectionValid,
canMagnifyPaneSurface,
pruneMagnifiedPanesByTab,
resolvePaneMagnificationCandidate,
setTabMagnifiedPane,
type PaneMagnificationController,
type PaneMagnificationTarget,
} from '../domain/paneMagnification';
@@ -318,12 +320,11 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
onRemoveSessionFromWorkspace,
}) => {
const { t } = useI18n();
const [magnifiedPane, setMagnifiedPane] = useState<{
tabId: string;
target: PaneMagnificationTarget;
} | null>(null);
const magnifiedPaneRef = useRef(magnifiedPane);
magnifiedPaneRef.current = magnifiedPane;
const [magnifiedPanesByTab, setMagnifiedPanesByTab] = useState<
ReadonlyMap<string, PaneMagnificationTarget>
>(() => new Map());
const magnifiedPanesByTabRef = useRef(magnifiedPanesByTab);
magnifiedPanesByTabRef.current = magnifiedPanesByTab;
const lastInteractedPaneRef = useRef<Map<string, PaneMagnificationTarget>>(new Map());
// Side panel state must be initialized before any callbacks reference its
// setters or refs in their dependency arrays.
@@ -345,8 +346,8 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
}, [sessions]);
useEffect(() => {
setMagnifiedPane((current) => {
if (!current) return current;
setMagnifiedPanesByTab((current) => {
if (current.size === 0) return current;
const terminalPanes = sessions.map((session) => ({
tabId: session.workspaceId ?? session.id,
sessionId: session.id,
@@ -354,9 +355,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const sidePanelPanes = Array.from(sidePanelLayouts.entries()).flatMap(([tabId, layout]) => (
collectSidePanelPanes(layout.root).map((pane) => ({ tabId, paneId: pane.id }))
));
return isPaneMagnificationSelectionValid(current, terminalPanes, sidePanelPanes)
? current
: null;
return pruneMagnifiedPanesByTab(current, terminalPanes, sidePanelPanes);
});
}, [sessions, sidePanelLayouts]);
const terminalRendererCwdBySessionRef = useRef<Map<string, string>>(new Map());
@@ -475,11 +474,18 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
// Stable callback references for Terminal components
const handleCloseSession = useCallback((sessionId: string) => {
setMagnifiedPane((current) => (
current?.target.kind === 'terminal' && current.target.sessionId === sessionId
? null
: current
));
setMagnifiedPanesByTab((current) => {
if (current.size === 0) return current;
let changed = false;
const next = new Map(current);
for (const [tabId, target] of next) {
if (target.kind === 'terminal' && target.sessionId === sessionId) {
next.delete(tabId);
changed = true;
}
}
return changed ? next : current;
});
for (const [tabId, target] of lastInteractedPaneRef.current) {
if (target.kind === 'terminal' && target.sessionId === sessionId) {
lastInteractedPaneRef.current.delete(tabId);
@@ -1773,9 +1779,9 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const handleCloseSidePanel = useCallback(() => {
const activeTabId = activeTabIdRef.current;
if (!activeTabId) return;
setMagnifiedPane((current) => (
current?.tabId === activeTabId && current.target.kind === 'side-panel'
? null
setMagnifiedPanesByTab((current) => (
current.get(activeTabId)?.kind === 'side-panel'
? setTabMagnifiedPane(current, activeTabId, null)
: current
));
const sessionIdToRefocus = getActiveTerminalSessionId();
@@ -1906,14 +1912,27 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const handleMagnifyTerminalPane = useCallback((tabId: string, sessionId: string) => {
const target: PaneMagnificationTarget = { kind: 'terminal', sessionId };
lastInteractedPaneRef.current.set(tabId, target);
setMagnifiedPane((current) => (
current?.tabId === tabId
&& current.target.kind === 'terminal'
&& current.target.sessionId === sessionId
? null
: { tabId, target }
));
}, []);
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
if (existing?.kind === 'terminal' && existing.sessionId === sessionId) {
return setTabMagnifiedPane(current, tabId, null);
}
const workspace = workspacesRef.current.find((candidate) => candidate.id === tabId);
const workspaceSessionIds = workspace ? collectSessionIds(workspace.root) : [];
const standaloneSession = sessionsRef.current.find((candidate) => (
candidate.id === tabId && !candidate.workspaceId
));
const terminalCount = workspaceSessionIds.length > 0
? workspaceSessionIds.length
: standaloneSession ? 1 : 0;
const layout = sidePanelLayoutsRef.current.get(tabId);
const sidePanelCount = layout ? collectSidePanelPanes(layout.root).length : 0;
if (!canMagnifyPaneSurface(terminalCount, sidePanelCount)) {
return current;
}
return setTabMagnifiedPane(current, tabId, target);
});
}, [sidePanelLayoutsRef]);
const handleMagnifySidePanelPane = useCallback((paneId: string) => {
const tabId = activeTabIdRef.current;
@@ -1929,18 +1948,19 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
tool: pane.tool,
};
lastInteractedPaneRef.current.set(tabId, target);
setMagnifiedPane((current) => (
current?.tabId === tabId
&& current.target.kind === 'side-panel'
&& current.target.paneId === paneId
? null
: { tabId, target }
));
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
if (existing?.kind === 'side-panel' && existing.paneId === paneId) {
return setTabMagnifiedPane(current, tabId, null);
}
return setTabMagnifiedPane(current, tabId, target);
});
}, [sidePanelLayoutsRef]);
const handleRestoreMagnifiedPane = useCallback(() => {
const tabId = activeTabIdRef.current;
setMagnifiedPane((current) => current?.tabId === tabId ? null : current);
if (!tabId) return;
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, tabId, null));
}, []);
useEffect(() => {
@@ -1949,7 +1969,8 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const tabId = activeTabStore.getActiveTabId();
if (!tabId) return null;
const workspace = workspacesRef.current.find((candidate) => candidate.id === tabId);
const hasCurrentMagnification = magnifiedPaneRef.current?.tabId === tabId;
const currentTarget = magnifiedPanesByTabRef.current.get(tabId);
const hasCurrentMagnification = !!currentTarget;
if (workspace?.viewMode === 'focus' && !hasCurrentMagnification) return null;
const workspaceSessionIds = workspace ? collectSessionIds(workspace.root) : [];
const standaloneSession = sessionsRef.current.find((candidate) => (
@@ -1971,7 +1992,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
? [focusedSidePanelPane, ...sidePanelPanes.filter((pane) => pane !== focusedSidePanelPane)]
: sidePanelPanes,
lastTarget: lastInteractedPaneRef.current.get(tabId),
current: magnifiedPaneRef.current,
current: currentTarget ? { tabId, target: currentTarget } : null,
});
return candidate ? { tabId, ...candidate } : null;
};
@@ -1983,19 +2004,23 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
focus: () => {
const target = getTarget();
if (!target || target.focused) return false;
setMagnifiedPane({ tabId: target.tabId, target: target.target });
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, target.tabId, target.target));
return true;
},
restore: () => {
const target = getTarget();
if (!target?.focused) return false;
setMagnifiedPane(null);
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(current, target.tabId, null));
return true;
},
toggle: () => {
const target = getTarget();
if (!target) return false;
setMagnifiedPane(target.focused ? null : { tabId: target.tabId, target: target.target });
setMagnifiedPanesByTab((current) => setTabMagnifiedPane(
current,
target.tabId,
target.focused ? null : target.target,
));
return true;
},
};
@@ -2029,13 +2054,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const closingPane = layout
? collectSidePanelPanes(layout.root).find((pane) => pane.id === paneId)
: undefined;
setMagnifiedPane((current) => (
current?.tabId === tabId
&& current.target.kind === 'side-panel'
&& current.target.paneId === paneId
? null
: current
));
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
return existing?.kind === 'side-panel' && existing.paneId === paneId
? setTabMagnifiedPane(current, tabId, null)
: current;
});
const closesWholePanel = closeSidePanelPaneForTab(tabId, paneId);
if (closesWholePanel) {
handleCloseSidePanel();
@@ -2063,8 +2087,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
const layout = sidePanelLayoutsRef.current.get(tabId);
const pane = layout && collectSidePanelPanes(layout.root).find((item) => item.id === paneId);
if (pane?.tool !== expectedTool) return;
setMagnifiedPane((current) => current?.tabId === tabId && current.target.kind === 'side-panel'
&& current.target.paneId === paneId ? null : current);
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
return existing?.kind === 'side-panel' && existing.paneId === paneId
? setTabMagnifiedPane(current, tabId, null)
: current;
});
closeSidePanelPaneForTab(tabId, paneId);
}, [closeSidePanelPaneForTab, sidePanelLayoutsRef]);
@@ -2151,12 +2179,12 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
if (!terminal || terminal.hiddenFromTabs || terminal.workspaceId) return false;
tabId = terminal.id;
}
setMagnifiedPane((current) => (
current?.tabId === tabId
&& !(current.target.kind === 'side-panel' && current.target.tool === 'ai')
? null
: current
));
setMagnifiedPanesByTab((current) => {
const existing = current.get(tabId);
return existing && !(existing.kind === 'side-panel' && existing.tool === 'ai')
? setTabMagnifiedPane(current, tabId, null)
: current;
});
activeTabStore.setActiveTabId(tabId);
if (prepareSidePanelTool(tabId, 'ai')) {
startTransition(() => {
@@ -2886,7 +2914,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
lastSidePanelTabRef,
mountedAiTabIds: aiMountedTabIds,
mountedSftpTabIds,
magnifiedPane,
magnifiedPanesByTab,
notesMountedTabIds,
browserMountedTabIds,
notesOpenNoteByTab,
+7 -7
View File
@@ -77,7 +77,7 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
const hasManualProxyCommand = Boolean(proxyConfig?.command?.trim());
const hasManualProxyValue = isCommandProxy ? hasManualProxyCommand : hasManualProxyHost;
const hasInvalidManualProxyPort = !isCommandProxy && hasManualProxyHost && !isValidProxyPort(proxyConfig?.port);
const effectiveProxyConfig = selectedProfile?.config ?? proxyConfig;
const effectiveProxyConfig = directProxy ? undefined : (selectedProfile?.config ?? proxyConfig);
const hasMissingIdentity = hasMissingProxyIdentity(effectiveProxyConfig, identities);
const hasIncompleteIdentity = hasIncompleteProxyIdentity(effectiveProxyConfig, identities);
const hasUnreadableIdentity = hasUnreadableProxyCredential(effectiveProxyConfig, identities);
@@ -92,9 +92,9 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
);
const selectedIdentityValue = selectedIdentity?.id || (hasMissingIdentity ? missingIdentityValue : manualCredentialsValue);
const handleBack = useCallback(() => {
if (hasInvalidManualProxyPort || hasInvalidIdentity) return;
if (!directProxy && (hasInvalidManualProxyPort || hasInvalidIdentity)) return;
onBack();
}, [hasInvalidManualProxyPort, hasInvalidIdentity, onBack]);
}, [directProxy, hasInvalidManualProxyPort, hasInvalidIdentity, onBack]);
return (
<AsidePanel
@@ -153,7 +153,7 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
{t('hostDetails.proxyPanel.missingSaved')}
</div>
)}
{selectedProfile && (
{isUsingProfile && selectedProfile && (
<div className="min-w-0 rounded-md bg-secondary/50 p-2 text-sm">
<div className="flex min-w-0 items-center gap-2">
<Badge variant="secondary" className="text-xs shrink-0">
@@ -165,17 +165,17 @@ export const ProxyPanel: React.FC<ProxyPanelPropsWithResize> = ({
</div>
</div>
)}
{selectedProfile && hasMissingIdentity && (
{isUsingProfile && selectedProfile && hasMissingIdentity && (
<div className="min-w-0 rounded-md border border-destructive/30 bg-destructive/10 p-2 text-sm text-destructive">
{t('hostDetails.proxyPanel.missingIdentity')}
</div>
)}
{selectedProfile && hasIncompleteIdentity && (
{isUsingProfile && selectedProfile && hasIncompleteIdentity && (
<div className="min-w-0 rounded-md border border-destructive/30 bg-destructive/10 p-2 text-sm text-destructive">
{t('hostDetails.proxyPanel.incompleteIdentity')}
</div>
)}
{selectedProfile && hasUnreadableIdentity && (
{isUsingProfile && selectedProfile && hasUnreadableIdentity && (
<div className="min-w-0 rounded-md border border-destructive/30 bg-destructive/10 p-2 text-sm text-destructive">
{t('hostDetails.proxyPanel.unreadableIdentity')}
</div>
@@ -704,3 +704,107 @@ test('RemoteImageElement renders a transparent placeholder while loading and nev
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('PluginDataGrid clears stale editingCell and pending blur timer when insertedRows shrink or row is deleted', async () => {
const dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'http://localhost', pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'FocusEvent', 'ShadowRoot']) {
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 });
Object.assign(dom.window, {
ResizeObserver: class {
private cb: (entries: unknown[]) => void;
constructor(cb: (entries: unknown[]) => void) { this.cb = cb; }
observe(target: Element) {
this.cb([{ target, borderBoxSize: [{ inlineSize: 800, blockSize: 600 }], contentRect: { width: 800, height: 600 } }]);
}
unobserve() {}
disconnect() {}
},
});
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
x: 0, y: 0, width: 800, height: 600, top: 0, left: 0, right: 800, bottom: 600, toJSON() {},
});
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const events: Array<Record<string, unknown>> = [];
const makeTree = (insertedRows: Array<Record<string, unknown>>, deletedRowIndices: number[] = []) => ({
children: [
{
id: 'grid',
type: 1,
element: 'div',
attributes: {
'data-plugin-widget': 'data-grid',
'data-plugin-widget-props': JSON.stringify({
columns: [
{ name: 'id', type: 'INTEGER', primaryKey: true },
{ name: 'name', type: 'TEXT' },
],
rows: [[1, 'Alice']],
insertedRows,
deletedRowIndices,
editable: true,
}),
},
children: [],
},
],
});
const root = createRoot(document.getElementById('root')!);
try {
await act(async () => {
root.render(<PluginRemoteSurface tree={makeTree([{ id: null, name: null }])} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
const gridHost = document.querySelector('[data-plugin-widget-node="grid"]') as HTMLElement;
const insertedNameCell = gridHost.querySelector('[role="gridcell"][data-row-index="1"][data-col-name="name"]') as HTMLElement;
assert.ok(insertedNameCell, 'inserted row cell rendered');
await act(async () => {
insertedNameCell.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
});
const input = gridHost.querySelector('[role="gridcell"][data-row-index="1"][data-col-name="name"] input') as HTMLInputElement;
assert.ok(input, 'cell input opened on inserted row');
await act(async () => {
input.dispatchEvent(new dom.window.FocusEvent('blur', { bubbles: false }));
});
// Discard insertedRows immediately after blur and before blurTimeout(0) fires
await act(async () => {
root.render(<PluginRemoteSurface tree={makeTree([])} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
await act(async () => {
await new Promise((r) => setTimeout(r, 25));
});
assert.equal(
events.some((e) => e.widgetEvent === 'cellEdit' && (e.detail as { rowIndex?: number })?.rowIndex === 1),
false,
'discarding inserted row must cancel pending blur cellEdit for removed row',
);
// Re-adding an inserted row must NOT reopen the stale editing input
await act(async () => {
root.render(<PluginRemoteSurface tree={makeTree([{ id: null, name: null }])} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
});
assert.equal(
gridHost.querySelector('[role="gridcell"][data-row-index="1"][data-col-name="name"] input'),
null,
're-adding inserted row starts clean without stale editingCell input',
);
} finally {
await act(async () => root.unmount());
dom.window.close();
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');
}
});
+2 -2
View File
@@ -1,9 +1,9 @@
[
{
"id": "com.binaricat.netcatty-database",
"version": "0.3.1",
"version": "0.3.2",
"repository": "binaricat/netcatty-database-plugin",
"commit": "84928ba5ca9638e509a11b7a578c400c0a320d06",
"commit": "81c3dd7ad9193b0d3a44df1531daeb6c758b4ee8",
"icon": {
"kind": "package",
"light": "assets/plugin-icon-light.png",
@@ -89,6 +89,22 @@ export function PluginDataGrid({
);
const totalRows = rows.length + insertedRows.length;
useEffect(() => {
if (!editingCell) return;
const colAtIdx = visibleCols[editingCell.colIndex];
const invalidRow =
editingCell.rowIndex < 0 || editingCell.rowIndex >= totalRows || deletedSet.has(editingCell.rowIndex);
const invalidCol = !colAtIdx || colAtIdx.col.name !== editingCell.colName;
if (invalidRow || invalidCol) {
if (blurTimerRef.current !== null) {
clearTimeout(blurTimerRef.current);
blurTimerRef.current = null;
}
editingCellRef.current = null;
setEditingCell(null);
}
}, [editingCell, totalRows, deletedSet, visibleCols]);
const getColWidth = useCallback((col: PluginDataGridColumn): number => {
const custom = colWidths[col.name];
if (custom !== undefined) return custom;
+37 -20
View File
@@ -9,6 +9,8 @@ import React, {
} from 'react';
import { AlertCircle, UploadCloud } from 'lucide-react';
import { useI18n } from '../../application/i18n/I18nProvider';
import { useClipboardBackend } from '../../application/state/useClipboardBackend';
import { buildRdpClipboardItemData, nextRdpClipboardGuardState, selectRdpClipboardData } from '../../domain/rdpClipboard';
import {
computeMonitorVirtualBounds,
mapViewportToVirtualDesktopCoords,
@@ -186,6 +188,7 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
ref,
) {
const { t } = useI18n();
const { readClipboardImagePng } = useClipboardBackend();
const containerRef = useRef<HTMLDivElement | null>(null);
const viewportRef = useRef<HTMLDivElement | null>(null);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
@@ -199,7 +202,9 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
const modRef = useRef<IronRdpModule | null>(null);
const audioPlayerRef = useRef<RdpAudioPlayer | null>(null);
const lastAltRightUpRef = useRef(0);
const lastRemoteClipboardTextRef = useRef('');
const lastClipboardGuardStateRef = useRef<ReturnType<typeof nextRdpClipboardGuardState>>({
lastText: '', lastPngFingerprint: null,
});
const uploadedFilesRef = useRef<File[]>([]);
const uploadTransferIdRef = useRef<string>('');
const uploadedHighWaterByIndexRef = useRef<Map<number, number>>(new Map());
@@ -601,21 +606,31 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
const mod = modRef.current;
if (!session || !mod) return;
try {
const text = await navigator.clipboard?.readText();
if (text && (force || text !== lastRemoteClipboardTextRef.current)) {
lastRemoteClipboardTextRef.current = text;
const data = new mod.ClipboardData();
try {
data.addText('text/plain', text);
await session.onClipboardPaste(data);
} finally {
try { data.free(); } catch { /* ignore */ }
}
// A denied or unsupported read of one format must not block the other.
const [textResult, pngResult] = await Promise.allSettled([
Promise.resolve().then(() => navigator.clipboard?.readText()),
readClipboardImagePng(),
]);
const { text, pngBytes } = selectRdpClipboardData({
text: textResult.status === 'fulfilled' ? textResult.value : null,
pngBytes: pngResult.status === 'fulfilled' ? pngResult.value : null,
...lastClipboardGuardStateRef.current,
force,
});
if (!text && !pngBytes) return;
const data = new mod.ClipboardData();
try {
if (text) data.addText('text/plain', text);
if (pngBytes) data.addBinary('image/png', pngBytes);
await session.onClipboardPaste(data);
lastClipboardGuardStateRef.current = nextRdpClipboardGuardState({ text, pngBytes });
} finally {
try { data.free(); } catch { /* ignore */ }
}
} catch {
// Clipboard permission or empty
}
}, []);
}, [readClipboardImagePng]);
const syncClipboardNow = useCallback(() => syncLocalClipboardToRdp(true), [syncLocalClipboardToRdp]);
@@ -1168,18 +1183,20 @@ export const RdpCanvasView = React.memo(forwardRef<RemoteDesktopCanvasHandle, Rd
pngBytes = val;
}
}
lastClipboardGuardStateRef.current = nextRdpClipboardGuardState({ text: plainText, pngBytes });
if (pngBytes && typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {
const pngCopy = new Uint8Array(pngBytes.byteLength);
pngCopy.set(pngBytes);
const blob = new Blob([pngCopy], { type: 'image/png' });
void navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]).catch(() => {
if (plainText) {
lastRemoteClipboardTextRef.current = plainText;
void navigator.clipboard?.writeText(plainText).catch(() => {});
const data = buildRdpClipboardItemData({ text: plainText, pngBytes });
void navigator.clipboard.write([new ClipboardItem(data)]).catch(async () => {
if (plainText !== null) {
// Some clipboards reject mixed formats; keep the PNG if possible.
try {
await navigator.clipboard.write([new ClipboardItem({ 'image/png': data['image/png'] })]);
} catch {
await navigator.clipboard?.writeText(plainText).catch(() => {});
}
}
});
} else if (plainText !== null) {
lastRemoteClipboardTextRef.current = plainText;
void navigator.clipboard?.writeText(plainText).catch(() => {});
}
} catch {
@@ -7,19 +7,27 @@ import { PluginPackageManager } from './PluginPackageManager';
import type { usePluginManager } from '../../../application/state/usePluginManager';
test('state pill exposes actual state, opposite action, focus styling and pending disable without granting permissions', async () => {
const globals = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
const globals = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean; requestAnimationFrame?: typeof requestAnimationFrame };
const previous = globals.IS_REACT_ACT_ENVIRONMENT; globals.IS_REACT_ACT_ENVIRONMENT = true;
const previousRaf = globals.requestAnimationFrame;
globals.requestAnimationFrame ??= (fn) => { fn(0); return 0; };
const calls: unknown[] = [];
const plugin = { id: 'com.test.pill', activeVersion: '1.0.0', enabled: true, manifest: { name: 'Pill' }, runtime: {} } as NetcattyInstalledPlugin;
const plugin = { id: 'com.test.pill', activeVersion: '1.0.0', enabled: true, manifest: { name: 'Pill', engines: { netcatty: '*', api: '*' } }, runtime: {} } as NetcattyInstalledPlugin;
const manager = { available: true, plugins: [plugin], busy: false, setEnabled: async (...args: unknown[]) => { calls.push(args); } } as unknown as ReturnType<typeof usePluginManager>;
let renderer: ReactTestRenderer;
const render = (enabled: boolean, busy = false) => <I18nProvider locale="en"><PluginPackageManager manager={{ ...manager, busy, plugins: [{ ...plugin, enabled }] }} /></I18nProvider>;
try {
await act(async () => { renderer = create(render(true)); });
const pill = () => renderer.root.findAllByType('button').find((node) => node.props['aria-pressed'] !== undefined)!;
const listAvatar = () => renderer.root.findAllByType('button').find((node) => node.props['aria-label'] === 'View details Pill' && typeof node.props.className === 'string' && node.props.className.includes('h-8 w-8'));
const detailLogoSlot = () => renderer.root.findAllByType('div').find((node) => node.props.className === 'flex h-12 w-12 shrink-0 items-center justify-center');
assert.ok(listAvatar(), 'list card renders 32px avatar details button');
assert.doesNotMatch(listAvatar()!.props.className, /\bbg-/, 'list avatar has no extra decorative background');
assert.equal(detailLogoSlot(), undefined, 'list render does not include the 48px detail logo slot');
await act(async () => listAvatar()!.props.onClick());
assert.ok(detailLogoSlot(), 'logo keeps its 48px layout slot without an extra decorative background');
assert.doesNotMatch(detailLogoSlot()!.props.className, /\bbg-/);
assert.equal(pill().props['aria-pressed'], true);
const logoSlot = renderer.root.findAllByType('div').find((node) => node.props.className === 'flex h-12 w-12 shrink-0 items-center justify-center');
assert.ok(logoSlot, 'logo keeps its 48px layout slot without an extra decorative background');
assert.equal(pill().props['aria-label'], 'Disable Pill');
assert.ok(pill().children.includes('Enabled'));
assert.match(pill().props.className, /rounded-full/);
@@ -39,5 +47,9 @@ test('state pill exposes actual state, opposite action, focus styling and pendin
assert.match(pill().props.className, /bg-muted/);
assert.equal(pill().props.style, undefined);
await act(async () => renderer.unmount());
} finally { globals.IS_REACT_ACT_ENVIRONMENT = previous; }
} finally {
globals.IS_REACT_ACT_ENVIRONMENT = previous;
if (previousRaf === undefined) Reflect.deleteProperty(globals, 'requestAnimationFrame');
else globals.requestAnimationFrame = previousRaf;
}
});
@@ -301,7 +301,8 @@ export function getCommandToRecordOnEnter(
/**
* Keystrokes that remove the text a snippet acceptance replaces.
* Line-start keeps the shell kill-line (Ctrl+U, or backspaces on Windows).
* Mid-line and program read-prompts delete only the word being typed.
* Matching label prefixes replace the longest suffix starting at a word boundary.
* Otherwise, mid-line and program read-prompts delete only the word being typed.
* POSIX word delete sends DEL, the tty erase character. Ctrl-H is literal
* input to canonical `read` when erase is ^?, while readline still deletes
* on DEL. Windows line editing keeps backspace.
@@ -313,18 +314,35 @@ export function computeSnippetAcceptClearSequence(options: {
os: string;
promptText: string;
snippetKind?: "snippet" | "script";
snippetLabel?: string;
}): string {
const line = options.line ?? "";
if (line.length === 0) return "";
let matchedLabelSuffix: string | undefined;
if (options.snippetKind !== "script" && options.snippetLabel) {
const label = options.snippetLabel.toLowerCase();
// Scan from the start so the first boundary match is the longest suffix.
for (let start = 0; start < line.length; start += 1) {
if (start > 0 && !/\s/.test(line[start - 1])) continue;
const suffix = line.slice(start);
if (label.startsWith(suffix.toLowerCase())) {
matchedLabelSuffix = suffix;
break;
}
}
}
const { currentWord, wordIndex } = parseCommandLine(line);
const replaceWord = options.snippetKind !== "script"
&& currentWord.length > 0
&& line.endsWith(currentWord)
&& (wordIndex > 0 || isProgramInputPromptText(options.promptText));
const replaceWord = matchedLabelSuffix !== undefined
? matchedLabelSuffix !== line
: options.snippetKind !== "script"
&& currentWord.length > 0
&& line.endsWith(currentWord)
&& (wordIndex > 0 || isProgramInputPromptText(options.promptText));
if (replaceWord) {
const eraseChar = isWindowsShellLineInput(options.os, options.promptText) ? "\b" : "\x7f";
return eraseChar.repeat(Array.from(currentWord).length);
return eraseChar.repeat(Array.from(matchedLabelSuffix ?? currentWord).length);
}
return isWindowsShellLineInput(options.os, options.promptText)
@@ -1340,7 +1340,7 @@ export function useTerminalAutocomplete(
[handleCommandHistoryCleared],
);
/** Accept a snippet: clear the matched word (or the whole line for a script
/** Accept a snippet: clear the matched label or word (or the whole line for a script
* or a shell prompt), then run it via onAcceptSnippet. */
const acceptSnippet = useCallback((snippet: Snippet): boolean => {
const term = termRef.current;
@@ -1358,6 +1358,7 @@ export function useTerminalAutocomplete(
os: hostOsRef.current,
promptText: prompt.promptText,
snippetKind: snippet.kind,
snippetLabel: snippet.label,
});
if (clearSequence) writeToTerminal(clearSequence);
}
@@ -387,6 +387,102 @@ test("snippet accept deletes only the mid-line word (#3622)", () => {
);
});
test("snippet accept clears a whole-line label prefix (#4549)", () => {
for (const snippetKind of [undefined, "snippet"] as const) {
for (const line of ["Check size", "Check si", "check size"]) {
for (const os of ["linux", "windows"]) {
assert.equal(
computeSnippetAcceptClearSequence({
line,
os,
promptText: os === "windows" ? "C:\\Users\\me>" : "user@host:~$ ",
snippetKind,
snippetLabel: "Check size",
}),
os === "windows" ? "\b".repeat(line.length) : "\x15",
);
}
}
}
});
test("snippet accept deletes the longest matching label suffix at a word boundary (#4549)", () => {
for (const os of ["linux", "windows"]) {
for (const suffix of ["Check size", "Check si", "check size", "Check \u{1F680}"]) {
assert.equal(
computeSnippetAcceptClearSequence({
line: `git pull ${suffix}`,
os,
promptText: os === "windows" ? "C:\\Users\\me>" : "user@host:~$ ",
snippetKind: "snippet",
snippetLabel: suffix === "Check \u{1F680}" ? suffix : "Check size",
}),
(os === "windows" ? "\b" : "\x7f").repeat(Array.from(suffix).length),
);
}
}
assert.equal(
computeSnippetAcceptClearSequence({
line: "git pull\tCheck\tsize",
os: "linux",
promptText: "user@host:~$ ",
snippetLabel: "Check\tsize",
}),
"\x7f".repeat("Check\tsize".length),
);
assert.equal(
computeSnippetAcceptClearSequence({
line: "git pull use use",
os: "linux",
promptText: "user@host:~$ ",
snippetLabel: "use use more",
}),
"\x7f".repeat("use use".length),
);
});
test("snippet accept preserves word deletion with a single-word or unmatched label (#3622, #4549)", () => {
for (const snippetLabel of [undefined, "use", "user name", "Check size"]) {
assert.equal(
computeSnippetAcceptClearSequence({
line: "git pull use",
os: "linux",
promptText: "user@host:~$ ",
snippetLabel,
}),
"\x7f".repeat(3),
);
}
for (const line of ["size", "git pull size", "git pull xCheck size"]) {
assert.equal(
computeSnippetAcceptClearSequence({
line,
os: "linux",
promptText: "user@host:~$ ",
snippetLabel: "Check size",
}),
line === "size" ? "\x15" : "\x7f".repeat(4),
);
}
});
test("script snippet accept ignores matching labels and clears the whole line (#4549)", () => {
for (const os of ["linux", "windows"]) {
for (const promptText of ["user@host:~$ ", "Email: "]) {
assert.equal(
computeSnippetAcceptClearSequence({
line: "git pull Check size",
os,
promptText,
snippetKind: "script",
snippetLabel: "Check size",
}),
os === "windows" ? "\b".repeat("git pull Check size".length) : "\x15",
);
}
}
});
test("script snippet accept still clears the whole line (#3622)", () => {
assert.equal(
computeSnippetAcceptClearSequence({
@@ -453,4 +549,4 @@ test("computeAutocompleteAcceptWrite clears with backspaces on a mislabeled Wind
}),
"\b\b\buv run tkauto video sync-fs",
);
});
});
@@ -38,19 +38,21 @@ test('per-pane close button keeps shrink-0 so a narrow pane cannot squeeze it aw
);
});
test('magnified side panels use an inner rounded 1px border in the side panel accent', () => {
test('magnified side panels use an inner rounded 1px theme-accent border and skip zoom animation on tab switch', () => {
const source = readFileSync(new URL('./TerminalLayerSidePanelSection.tsx', import.meta.url), 'utf8');
const chromeStart = source.indexOf('className="absolute inset-3');
const chromeStart = source.indexOf('"absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl [clip-path:inset(0_round_0.375rem)]"');
assert.ok(chromeStart > 0, 'magnified side panel chrome must exist');
const chromeSource = source.slice(chromeStart, source.indexOf('\n >', chromeStart));
const strokeStart = source.indexOf('data-section="pane-magnification-stroke"', chromeStart);
const strokeSource = source.slice(strokeStart, source.indexOf('/>', strokeStart));
assert.match(chromeSource, /overflow-hidden rounded-md bg-background shadow-2xl/);
assert.match(chromeSource, /\[clip-path:inset\(0_round_0\.375rem\)\]/);
assert.match(chromeSource, /animateMagnifiedSidePane && "animate-in fade-in zoom-in-95 duration-150"/);
assert.doesNotMatch(chromeSource, /\b(?:outline|outlineOffset|border|borderColor|borderWidth|borderStyle)\b/);
assert.match(strokeSource, /className="pointer-events-none absolute inset-0 z-50"/);
assert.match(strokeSource, /boxSizing: 'border-box'/);
assert.match(strokeSource, /border: `1px solid \$\{sidePanelTheme\.accent\}`/);
assert.match(strokeSource, /border: '1px solid hsl\(var\(--primary\)\)'/);
assert.match(strokeSource, /borderRadius: 'inherit'/);
});
@@ -1148,10 +1148,32 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
const magnifiedSidePane = activeMagnifiedPane?.target.kind === 'side-panel'
? activeSidePanelPanes.find((pane) => pane.id === activeMagnifiedPane.target.paneId) ?? null
: null;
const sidePaneMagAnimRef = useRef<{
tabId: string | null;
paneId: string | null;
animate: boolean;
}>({
tabId: activeTabId ?? null,
paneId: magnifiedSidePane?.id ?? null,
animate: false,
});
if (
sidePaneMagAnimRef.current.tabId !== (activeTabId ?? null)
|| sidePaneMagAnimRef.current.paneId !== (magnifiedSidePane?.id ?? null)
) {
const sameTab = sidePaneMagAnimRef.current.tabId === (activeTabId ?? null);
const entering = !!magnifiedSidePane && sidePaneMagAnimRef.current.paneId !== magnifiedSidePane.id;
sidePaneMagAnimRef.current = {
tabId: activeTabId ?? null,
paneId: magnifiedSidePane?.id ?? null,
animate: sameTab && entering,
};
}
const animateMagnifiedSidePane = sidePaneMagAnimRef.current.animate;
const paneMagnificationShortcutLabel = getPaneMagnificationShortcutLabel(keyBindings, hotkeyScheme);
const [showMagnificationHint, setShowMagnificationHint] = useState(false);
useEffect(() => {
if (!magnifiedSidePane) {
if (!magnifiedSidePane || !sidePaneMagAnimRef.current.animate) {
setShowMagnificationHint(false);
return undefined;
}
@@ -1583,7 +1605,10 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
data-section="pane-magnification-backdrop"
/>
<div
className="absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl [clip-path:inset(0_round_0.375rem)] animate-in fade-in zoom-in-95 duration-150"
className={cn(
"absolute inset-3 flex flex-col overflow-hidden rounded-md bg-background shadow-2xl [clip-path:inset(0_round_0.375rem)]",
animateMagnifiedSidePane && "animate-in fade-in zoom-in-95 duration-150",
)}
style={{
backgroundColor: sidePanelTheme.termBg,
color: sidePanelTheme.termFg,
@@ -1616,7 +1641,7 @@ function TerminalLayerSidePanelInner({ ctx, pluginSidebar }: { ctx: SidePanelCon
className="pointer-events-none absolute inset-0 z-50"
style={{
boxSizing: 'border-box',
border: `1px solid ${sidePanelTheme.accent}`,
border: '1px solid hsl(var(--primary))',
borderRadius: 'inherit',
}}
/>
@@ -65,9 +65,13 @@ import type { ResolvedAppearance, TerminalAppearanceHostScope } from '../../doma
import type { TerminalSidePanelAutoOpenTab } from '../../domain/terminalSidePanelAutoOpen';
import type { SidePanelTool } from '../../domain/sidePanelLayout';
import {
getWorkspacePaneOuterEdges,
PANE_MAGNIFICATION_DURATION_MS,
resolveNextMagnifiedSurfaceBounds,
resolvePaneMagnificationLayoutGeometry,
resolvePaneMagnificationStyle,
shouldAnimatePaneMagnificationTransition,
type MagnifiedSurfaceBounds,
type PaneMagnificationController,
type PaneMagnificationTarget,
} from '../../domain/paneMagnification';
@@ -1560,6 +1564,14 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
}, [deferPaneLayoutUpdate, isFocusedPane, isFocusMode, isSplitViewVisible, isVisible, livePaneLayoutKey]);
const paneLayoutKey = paneLayoutKeyRef.current;
const workspacePaneCount = layoutWorkspace ? collectSessionIds(layoutWorkspace.root).length : 0;
const hasMultipleWorkspacePanes = inActiveWorkspace && !isFocusMode && workspacePaneCount > 1;
const paneOuterEdges = useMemo(
() => (hasMultipleWorkspacePanes
? getWorkspacePaneOuterEdges(layoutWorkspace?.root, session.id)
: { left: false, right: false, top: false, bottom: false }),
[hasMultipleWorkspacePanes, layoutWorkspace?.root, session.id],
);
const isMagnified = isVisible
&& magnifiedPane?.target.kind === 'terminal'
&& magnifiedPane.target.sessionId === session.id
@@ -1567,16 +1579,22 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
const isCoveredByMagnification = isVisible
&& magnifiedPane?.tabId === (activeWorkspaceId ?? session.id)
&& !isMagnified;
const [magnifiedSurfaceBounds, setMagnifiedSurfaceBounds] = useState<{
left: number;
top: number;
width: number;
height: number;
layoutOrigin: { left: number; top: number; width: number; height: number };
} | null>(null);
const [magnifiedSurfaceBounds, setMagnifiedSurfaceBounds] = useState<MagnifiedSurfaceBounds | null>(null);
const prevMagnificationTransitionRef = useRef({
isVisible,
isMagnified,
});
useLayoutEffect(() => {
const prev = prevMagnificationTransitionRef.current;
prevMagnificationTransitionRef.current = { isVisible, isMagnified };
const shouldAnimate = shouldAnimatePaneMagnificationTransition({
wasVisible: prev.isVisible,
isVisible,
wasMagnified: prev.isMagnified,
isMagnified,
});
if (!isMagnified) {
if (!isVisible) {
if (!isVisible || !shouldAnimate) {
setMagnifiedSurfaceBounds(null);
return undefined;
}
@@ -1593,10 +1611,10 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
// the pane is fixed (offsetParent would be null during a quick re-zoom).
const layoutParent = pane?.parentElement;
if (!surface || !layoutParent) return undefined;
const update = () => {
const update = (animate: boolean) => {
const bounds = surface.getBoundingClientRect();
const origin = layoutParent.getBoundingClientRect();
if (pane && pane.style.position !== 'fixed') {
if (animate && pane && pane.style.position !== 'fixed') {
const geometry = {
left: pane.style.left,
top: pane.style.top,
@@ -1611,27 +1629,30 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
pane.getBoundingClientRect();
}
}
setMagnifiedSurfaceBounds({
setMagnifiedSurfaceBounds((current) => resolveNextMagnifiedSurfaceBounds(current, {
left: bounds.left,
top: bounds.top,
width: bounds.width,
height: bounds.height,
layoutOrigin: { left: origin.left, top: origin.top, width: origin.width, height: origin.height },
});
animate,
}));
};
update();
update(shouldAnimate);
if (typeof ResizeObserver === 'undefined') return undefined;
const observer = new ResizeObserver(update);
const observer = new ResizeObserver(() => update(false));
observer.observe(surface);
return () => observer.disconnect();
}, [isMagnified, isVisible]);
const magnifiedDevicePixelRatio = typeof window === 'undefined' ? 1 : (window.devicePixelRatio || 1);
const animateMagnification = !isMagnified || (magnifiedSurfaceBounds?.animate ?? true);
const style: React.CSSProperties = resolvePaneMagnificationStyle(
layoutStyle,
isMagnified && !!magnifiedSurfaceBounds,
magnifiedSurfaceBounds,
magnifiedDevicePixelRatio,
magnifiedSurfaceBounds?.layoutOrigin,
animateMagnification,
);
useLayoutEffect(() => {
@@ -1821,6 +1842,10 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
data-session-id={session.id}
data-section="terminal-split-pane"
data-focused={isFocusedPane ? 'true' : undefined}
data-multi-pane={hasMultipleWorkspacePanes ? 'true' : undefined}
data-magnified={magnifiedSurfaceBounds ? 'true' : undefined}
data-workspace-corner-bl={paneOuterEdges.left && paneOuterEdges.bottom ? 'true' : undefined}
data-workspace-corner-br={paneOuterEdges.right && paneOuterEdges.bottom ? 'true' : undefined}
inert={isVisible && !isCoveredByMagnification ? undefined : true}
className={cn(
"absolute bg-background",
@@ -1999,7 +2024,7 @@ const TerminalPane: React.FC<TerminalPaneProps> = memo(({
className="pointer-events-none absolute inset-0 z-50"
style={{
boxSizing: 'border-box',
border: `1px solid ${sessionAppearanceTheme.colors.cursor}`,
border: '1px solid hsl(var(--primary))',
borderRadius: 'inherit',
}}
/>
@@ -28,6 +28,7 @@ import {
collectSidePanelPanes,
type SidePanelLayout,
} from '../../domain/sidePanelLayout';
import type { PaneMagnificationTarget } from '../../domain/paneMagnification';
type StableRef = React.MutableRefObject<Record<string, any>>;
@@ -54,8 +55,15 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef })
const sftpAuthHostBySessionId = s.sftpAuthHostBySessionId as Map<string, Host>;
const sidePanelOpenTabs = s.sidePanelOpenTabs as Map<string, SidePanelTab>;
const sidePanelLayouts = s.sidePanelLayouts as Map<string, SidePanelLayout>;
const magnifiedPanesByTab = s.magnifiedPanesByTab as ReadonlyMap<string, PaneMagnificationTarget>;
const showHostTreeSidebar = s.showHostTreeSidebar as boolean | undefined;
const activeMagnifiedPane = useMemo(() => {
if (!activeTabId) return null;
const target = magnifiedPanesByTab.get(activeTabId);
return target ? { tabId: activeTabId, target } : null;
}, [activeTabId, magnifiedPanesByTab]);
const activeWorkspace = useMemo(
() => (activeTabId ? workspaceById.get(activeTabId) : undefined),
[activeTabId, workspaceById],
@@ -116,7 +124,7 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef })
activeSession,
activeWorkspace,
isFocusMode,
hasMagnifiedPane: !!activeWorkspace && activeWorkspace.id === s.magnifiedPane?.tabId,
hasMagnifiedPane: !!activeWorkspace && activeWorkspace.id === activeMagnifiedPane?.tabId,
shouldKeepHiddenWorkspaceLaidOut,
onAddSessionToWorkspace: s.onAddSessionToWorkspace,
onCreateWorkspaceFromSessions: s.onCreateWorkspaceFromSessions,
@@ -574,7 +582,7 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef })
keys: s.keys,
knownHosts: s.knownHosts,
MessageSquare: s.MessageSquare,
magnifiedPane: s.magnifiedPane,
magnifiedPane: activeMagnifiedPane,
mountedAiTabIds: s.mountedAiTabIds,
mountedSftpTabIds: s.mountedSftpTabIds,
notesMountedTabIds: s.notesMountedTabIds,
@@ -724,7 +732,7 @@ export function TerminalLayerTabBridge({ stableRef }: { stableRef: StableRef })
isFocusMode,
isSidePanelOpenForCurrentTab,
isTerminalLayerVisible,
s.magnifiedPane,
activeMagnifiedPane,
resizing,
resolveAIExecutorContext,
sessionHostsMap,
+19 -6
View File
@@ -44,6 +44,11 @@ function TerminalLayerViewInner({ ctx }: { ctx: TerminalLayerViewContext }) {
const hostTreeLayoutAnimated = useTerminalHostTreeLayoutTransitionAnimated();
const isBottomDock = ctx.sidePanelPosition === 'bottom';
const workspaceTouchesBottom = !ctx.isComposeBarOpen && !(ctx.isSidePanelOpenForCurrentTab && isBottomDock);
const workspaceTouchesLeft = hostTreeLayoutWidth <= 0
&& !ctx.isFocusMode
&& !(ctx.isSidePanelOpenForCurrentTab && ctx.sidePanelPosition === 'left');
const workspaceTouchesRight = !(ctx.isSidePanelOpenForCurrentTab && ctx.sidePanelPosition === 'right');
return (
<div
@@ -51,12 +56,20 @@ function TerminalLayerViewInner({ ctx }: { ctx: TerminalLayerViewContext }) {
className={`absolute inset-0 bg-background flex min-h-0${isBottomDock ? ' flex-col' : ''}`}
data-section="terminal-workspace"
inert={ctx.isTerminalLayerVisible ? undefined : true}
style={getTerminalLayerViewStyle({
isTerminalLayerVisible: ctx.isTerminalLayerVisible,
hibernateHiddenTabs: ctx.hibernateHiddenTabs,
hostTreeLayoutWidth,
hostTreeLayoutAnimated,
})}
style={{
...getTerminalLayerViewStyle({
isTerminalLayerVisible: ctx.isTerminalLayerVisible,
hibernateHiddenTabs: ctx.hibernateHiddenTabs,
hostTreeLayoutWidth,
hostTreeLayoutAnimated,
}),
'--workspace-corner-bl-radius': workspaceTouchesBottom && workspaceTouchesLeft
? 'var(--window-corner-radius)'
: '0px',
'--workspace-corner-br-radius': workspaceTouchesBottom && workspaceTouchesRight
? 'var(--window-corner-radius)'
: '0px',
} as React.CSSProperties}
>
{/* Keep TerminalLayerSidePanelSection at a stable tree position (first
child) so cycling between side and bottom docks reorders it via flex
@@ -9,20 +9,24 @@ import { renderToStaticMarkup } from "react-dom/server";
import { TerminalLayerWorkspaceSection } from "./TerminalLayerWorkspaceSection.tsx";
test("terminal pane chrome uses an inner rounded 1px border while retaining overflow clipping", () => {
test("terminal pane chrome uses an inner rounded 1px theme-accent border while retaining overflow clipping", () => {
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
const paneSource = source.slice(source.indexOf('data-section="terminal-split-pane"'), source.indexOf('TerminalPane.displayName'));
const hostSource = paneSource.slice(0, paneSource.indexOf("<LazyLoadBoundary"));
const strokeSource = paneSource.slice(paneSource.indexOf("{magnifiedSurfaceBounds && ("));
assert.match(hostSource, /^\s*magnifiedSurfaceBounds && "overflow-hidden rounded-md shadow-2xl \[clip-path:inset\(0_round_0\.375rem\)\]",$/m);
assert.match(hostSource, /data-multi-pane=\{hasMultipleWorkspacePanes \? 'true' : undefined\}/);
assert.match(hostSource, /data-magnified=\{magnifiedSurfaceBounds \? 'true' : undefined\}/);
assert.match(hostSource, /data-workspace-corner-bl=\{paneOuterEdges\.left && paneOuterEdges\.bottom \? 'true' : undefined\}/);
assert.match(hostSource, /data-workspace-corner-br=\{paneOuterEdges\.right && paneOuterEdges\.bottom \? 'true' : undefined\}/);
assert.match(hostSource, /style=\{style\}/);
assert.doesNotMatch(hostSource, /\b(?:outline|outlineOffset|border|borderColor|borderWidth|borderStyle)\b/);
assert.match(strokeSource, /aria-hidden="true"/);
assert.match(strokeSource, /data-section="pane-magnification-stroke"/);
assert.match(strokeSource, /className="pointer-events-none absolute inset-0 z-50"/);
assert.match(strokeSource, /boxSizing: 'border-box'/);
assert.match(strokeSource, /border: `1px solid \$\{sessionAppearanceTheme\.colors\.cursor\}`/);
assert.match(strokeSource, /border: '1px solid hsl\(var\(--primary\)\)'/);
assert.match(strokeSource, /borderRadius: 'inherit'/);
});
@@ -34,30 +38,31 @@ test("restoring terminal chrome retains its inner 1px border until surface bound
assert.ok(condition);
assert.ok(styleSource);
const resolveStroke = new Function(
"isMagnified", "magnifiedSurfaceBounds", "sessionAppearanceTheme", "magnifiedDevicePixelRatio",
"isMagnified", "magnifiedSurfaceBounds", "magnifiedDevicePixelRatio",
`return ${condition[1]} ? ({${styleSource[1]}}) : null;`,
);
const bounds = { left: 0, top: 80, width: 1200, height: 800 };
const theme = { colors: { cursor: "#0088ff" } };
const bounds = { left: 0, top: 80, width: 1200, height: 800, animate: true };
for (const dpr of [1, 1.25, 1.5, 2, 3]) {
const magnified = resolveStroke(true, bounds, theme, dpr);
const restoring = resolveStroke(false, bounds, theme, dpr);
const magnified = resolveStroke(true, bounds, dpr);
const restoring = resolveStroke(false, bounds, dpr);
assert.deepEqual(restoring, magnified);
assert.equal(restoring.border, `1px solid ${theme.colors.cursor}`);
assert.equal(restoring.border, '1px solid hsl(var(--primary))');
assert.equal(restoring.boxSizing, 'border-box');
assert.equal(restoring.borderRadius, 'inherit');
for (const isMagnified of [false, true]) {
assert.equal(resolveStroke(isMagnified, null, theme, dpr), null);
assert.equal(resolveStroke(isMagnified, null, dpr), null);
}
}
});
test("magnified terminal panes snap overlay bounds to the device-pixel grid", () => {
test("magnified terminal panes snap overlay bounds to the device-pixel grid and skip animation on tab restore", () => {
const source = readFileSync(new URL("./TerminalLayerSupport.tsx", import.meta.url), "utf8");
assert.match(source, /resolvePaneMagnificationStyle\(\s*layoutStyle,\s*isMagnified && !!magnifiedSurfaceBounds,\s*magnifiedSurfaceBounds,\s*magnifiedDevicePixelRatio,\s*magnifiedSurfaceBounds\?\.layoutOrigin,\s*\)/);
assert.match(source, /resolvePaneMagnificationStyle\(\s*layoutStyle,\s*isMagnified && !!magnifiedSurfaceBounds,\s*magnifiedSurfaceBounds,\s*magnifiedDevicePixelRatio,\s*magnifiedSurfaceBounds\?\.layoutOrigin,\s*animateMagnification,\s*\)/);
assert.match(source, /layoutOrigin: \{ left: origin\.left, top: origin\.top, width: origin\.width, height: origin\.height \}/);
assert.match(source, /const magnifiedDevicePixelRatio = typeof window === 'undefined' \? 1 : \(window\.devicePixelRatio \|\| 1\)/);
assert.match(source, /shouldAnimatePaneMagnificationTransition\(/);
assert.match(source, /resolveNextMagnifiedSurfaceBounds\(current,/);
});
test("percentage zoom entry flushes pixel geometry before applying fixed bounds", () => {
@@ -80,8 +85,8 @@ test("terminal keyboard focus updates the pane selected for magnification", () =
test("closing a magnified terminal clears the overlay selection", () => {
const source = readFileSync(new URL("../TerminalLayer.tsx", import.meta.url), "utf8");
assert.match(source, /isPaneMagnificationSelectionValid\(current, terminalPanes, sidePanelPanes\)/);
assert.match(source, /current\?\.target\.kind === 'terminal' && current\.target\.sessionId === sessionId/);
assert.match(source, /pruneMagnifiedPanesByTab\(current, terminalPanes, sidePanelPanes\)/);
assert.match(source, /target\.kind === 'terminal' && target\.sessionId === sessionId/);
});
test("terminal panes expose focus mode and temporary magnification as separate actions", () => {
@@ -96,8 +101,28 @@ test("terminal panes expose focus mode and temporary magnification as separate a
test("focus mode cannot start temporary magnification but can restore stale magnification", () => {
const source = readFileSync(new URL("../TerminalLayer.tsx", import.meta.url), "utf8");
assert.match(source, /const hasCurrentMagnification = magnifiedPaneRef\.current\?\.tabId === tabId;/);
assert.match(source, /const currentTarget = magnifiedPanesByTabRef\.current\.get\(tabId\);/);
assert.match(source, /const hasCurrentMagnification = !!currentTarget;/);
assert.match(source, /if \(workspace\?\.viewMode === 'focus' && !hasCurrentMagnification\) return null;/);
assert.match(source, /if \(!canMagnifyPaneSurface\(terminalCount, sidePanelCount\)\) \{/);
});
test("workspace focus border CSS uses 1px deterministic state, suppresses on magnified/single panes, and handles macOS corners", () => {
const css = readFileSync(new URL("../../index.css", import.meta.url), "utf8");
// Default dim mode preserved
assert.match(css, /\.workspace-pane:not\(:focus-within\) \.xterm-screen \{\s*opacity: 0\.82;\s*\}/);
// 1px customizable border on multi-pane workspaces only
assert.match(css, /\[data-workspace-focus="border"\] \.workspace-pane\[data-multi-pane="true"\]::after/);
assert.match(css, /border: var\(--workspace-focus-border-width, 1px\) solid transparent;/);
// Deterministic data-focused state (not :focus-within), suppressed while magnified
assert.match(css, /\[data-workspace-focus="border"\] \.workspace-pane\[data-multi-pane="true"\]\[data-focused="true"\]:not\(\[data-magnified="true"\]\)::after/);
assert.match(css, /border-color: var\(--workspace-focus-border-color, hsl\(var\(--primary\)\)\);/);
assert.doesNotMatch(css, /\[data-workspace-focus="border"\] \.workspace-pane:focus-within::after/);
// macOS non-fullscreen rounded window corners
assert.match(css, /:root\[data-platform="darwin"\]:not\(\[data-window-fullscreen="true"\]\) \{\s*--window-corner-radius: 10px;\s*\}/);
assert.match(css, /border-bottom-left-radius: var\(--workspace-corner-bl-radius, 0px\);/);
assert.match(css, /border-bottom-right-radius: var\(--workspace-corner-br-radius, 0px\);/);
});
test("closing a magnified terminal restores its pane instead of ending the session", () => {
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { memo, useEffect, useState, useSyncExternalStore } from 'react';
import React, { memo, useEffect, useRef, useState, useSyncExternalStore } from 'react';
import { createPortal } from 'react-dom';
import { LayoutGrid, Plus } from 'lucide-react';
import { Button } from '../ui/button';
@@ -147,10 +147,34 @@ function TerminalLayerWorkspaceSectionInner({ ctx }: { ctx: WorkspaceContext })
&& magnifiedPane.target.kind === 'terminal'
? magnifiedPane
: null;
const activeMagnifiedSessionId = activeMagnifiedTerminal?.target.kind === 'terminal'
? activeMagnifiedTerminal.target.sessionId
: null;
const terminalMagHintRef = useRef<{
tabId: string | null;
sessionId: string | null;
shouldShowHint: boolean;
}>({
tabId: activeTabId ?? null,
sessionId: activeMagnifiedSessionId,
shouldShowHint: false,
});
if (
terminalMagHintRef.current.tabId !== (activeTabId ?? null)
|| terminalMagHintRef.current.sessionId !== activeMagnifiedSessionId
) {
const sameTab = terminalMagHintRef.current.tabId === (activeTabId ?? null);
const entering = !!activeMagnifiedSessionId && terminalMagHintRef.current.sessionId !== activeMagnifiedSessionId;
terminalMagHintRef.current = {
tabId: activeTabId ?? null,
sessionId: activeMagnifiedSessionId,
shouldShowHint: sameTab && entering,
};
}
const paneMagnificationShortcutLabel = getPaneMagnificationShortcutLabel(keyBindings, hotkeyScheme);
const [showMagnificationHint, setShowMagnificationHint] = useState(false);
useEffect(() => {
if (!activeMagnifiedTerminal) {
if (!activeMagnifiedTerminal || !terminalMagHintRef.current.shouldShowHint) {
setShowMagnificationHint(false);
return undefined;
}
@@ -32,7 +32,8 @@ function closePane(tool: 'browser' | 'notes') {
useCallback: (callback: unknown) => callback,
activeTabIdRef: { current: 'terminal' }, sidePanelLayoutsRef: { current: layouts },
collectSidePanelPanes,
setMagnifiedPane: () => {},
setMagnifiedPanesByTab: () => {},
setTabMagnifiedPane: (current: unknown) => current,
closeSidePanelPaneForTab: (tabId: string, paneId: string) => {
const next = closeSidePanelPane(layouts.get(tabId)!, paneId);
assert.ok(next);
+103
View File
@@ -1239,3 +1239,106 @@ test("applyGroupDefaults lets standalone RDP host with inline password inherit a
assert.equal(result.rdpConfig?.username, "Administrator");
});
test("resolveGroupDefaults and applyGroupDefaults let a child group Direct override parent group and global proxies", () => {
const configs: GroupConfig[] = [
{ path: "corp", proxyProfileId: "corp-proxy" },
{ path: "corp/local", directProxy: true },
];
const childDefaults = resolveGroupDefaults("corp/local", configs);
assert.equal(childDefaults.directProxy, true);
assert.equal(childDefaults.proxyProfileId, undefined);
assert.equal(childDefaults.proxyConfig, undefined);
const grandchildDefaults = resolveGroupDefaults("corp/local/lab", configs);
assert.equal(grandchildDefaults.directProxy, true);
assert.equal(grandchildDefaults.proxyProfileId, undefined);
const effective = applyGroupDefaults(
host({ group: "corp/local/lab" }),
grandchildDefaults,
globalProxyOptions,
);
assert.equal(effective.directProxy, true);
assert.equal(effective.proxyProfileId, undefined);
assert.equal(effective.proxyConfig, undefined);
});
test("resolveGroupDefaults lets a child group proxy override a parent group Direct setting", () => {
const configs: GroupConfig[] = [
{ path: "corp", directProxy: true },
{ path: "corp/bastion", proxyProfileId: "bastion-proxy" },
{ path: "corp/custom", proxyConfig: { type: "http", host: "custom.example.com", port: 8080 } },
];
const withProfile = resolveGroupDefaults("corp/bastion", configs);
assert.equal(withProfile.directProxy, undefined);
assert.equal(withProfile.proxyProfileId, "bastion-proxy");
const withCustom = resolveGroupDefaults("corp/custom", configs);
assert.equal(withCustom.directProxy, undefined);
assert.equal(withCustom.proxyConfig?.host, "custom.example.com");
const effective = applyGroupDefaults(host({ group: "corp/bastion" }), withProfile, globalProxyOptions);
assert.equal(effective.directProxy, undefined);
assert.equal(effective.proxyProfileId, "bastion-proxy");
});
test("resolveGroupDefaults prioritizes directProxy when co-present with proxy fields on the same group", () => {
const resolved = resolveGroupDefaults("corp", [
{
path: "corp",
directProxy: true,
proxyProfileId: "stale-profile",
proxyConfig: { type: "http", host: "stale.example.com", port: 8080 },
},
]);
assert.equal(resolved.directProxy, true);
assert.equal(resolved.proxyProfileId, undefined);
assert.equal(resolved.proxyConfig, undefined);
});
test("applyGroupDefaults lets a host choose its own proxy inside a Direct group", () => {
const groupDefaults = resolveGroupDefaults("corp/local", [
{ path: "corp", proxyProfileId: "corp-proxy" },
{ path: "corp/local", directProxy: true },
]);
const hostWithProfile = applyGroupDefaults(
host({ group: "corp/local", proxyProfileId: "host-proxy" }),
groupDefaults,
globalProxyOptions,
);
assert.equal(hostWithProfile.proxyProfileId, "host-proxy");
assert.equal(hostWithProfile.directProxy, undefined);
const customProxy = { type: "socks5" as const, host: "host-proxy.example.com", port: 1080 };
const hostWithCustom = applyGroupDefaults(
host({ group: "corp/local", proxyConfig: customProxy }),
groupDefaults,
globalProxyOptions,
);
assert.deepEqual(hostWithCustom.proxyConfig, customProxy);
assert.equal(hostWithCustom.directProxy, undefined);
assert.equal(hostWithCustom.proxyProfileId, undefined);
});
test("applyGroupDefaults inherits group directProxy for vnc/rdp hosts and skips global default", () => {
const groupDefaults = resolveGroupDefaults("corp/local", [
{ path: "corp", proxyProfileId: "corp-proxy" },
{ path: "corp/local", directProxy: true },
]);
for (const protocol of ["rdp", "vnc"] as const) {
const result = applyGroupDefaults(
host({ group: "corp/local", protocol }),
groupDefaults,
globalProxyOptions,
);
assert.equal(result.directProxy, true);
assert.equal(result.proxyProfileId, undefined);
assert.equal(result.proxyConfig, undefined);
}
});
+30 -5
View File
@@ -183,7 +183,20 @@ export function resolveGroupDefaults(
}
}
const groupSetsDirectProxy = config.directProxy === true;
if (groupSetsDirectProxy) {
delete merged.proxyProfileId;
delete merged.proxyConfig;
merged.directProxy = true;
}
for (const [key, value] of Object.entries(config)) {
if (key === 'directProxy') {
continue;
}
if (groupSetsDirectProxy && (key === 'proxyProfileId' || key === 'proxyConfig')) {
continue;
}
if (
key === 'proxyProfileId' &&
typeof value === 'string' &&
@@ -217,9 +230,11 @@ export function resolveGroupDefaults(
}
if (key === 'proxyProfileId') {
delete merged.proxyConfig;
delete merged.directProxy;
}
if (key === 'proxyConfig') {
delete merged.proxyProfileId;
delete merged.directProxy;
}
merged[key] = value;
}
@@ -243,7 +258,7 @@ export function resolveGroupDefaults(
const INHERITABLE_KEYS: (keyof GroupConfig)[] = [
'username', 'password', 'savePassword', 'authMethod', 'identityId', 'identityFileId', 'identityFilePaths',
'port', 'protocol', 'deviceType', 'agentForwarding', 'x11Forwarding', 'proxyProfileId', 'proxyConfig', 'hostChain', 'startupCommand', 'startupCommandRunMode',
'port', 'protocol', 'deviceType', 'agentForwarding', 'x11Forwarding', 'proxyProfileId', 'proxyConfig', 'directProxy', 'hostChain', 'startupCommand', 'startupCommandRunMode',
'legacyAlgorithms', 'skipEcdsaHostKey', 'algorithms',
'environmentVariables', 'charset', 'moshEnabled', 'moshServerPath',
'etEnabled', 'etPort',
@@ -297,6 +312,7 @@ const REMOTE_DESKTOP_INHERITABLE_KEYS = new Set<keyof GroupConfig>([
'hostChain',
'proxyProfileId',
'proxyConfig',
'directProxy',
]);
const STANDALONE_REMOTE_DESKTOP_SKIP_KEYS = new Set<string>([
@@ -460,6 +476,13 @@ export function applyGroupDefaults(
if (host.proxyConfig !== undefined || !groupDefaults.proxyProfileId) continue;
}
if (key === 'proxyConfig' && (host.proxyProfileId !== undefined || hostHasUsableProxyProfile)) continue;
if (key === 'directProxy') {
if (
groupDefaults.directProxy !== true ||
Boolean(host.proxyProfileId) ||
host.proxyConfig !== undefined
) continue;
}
const hostValue = (effective as unknown as Record<string, unknown>)[key];
const groupValue = (groupDefaults as unknown as Record<string, unknown>)[key];
const emptyStringIsOverride = EMPTY_STRING_OVERRIDES_GROUP_DEFAULT.has(key);
@@ -471,9 +494,6 @@ export function applyGroupDefaults(
(effective as unknown as Record<string, unknown>)[key] = groupValue;
}
}
// Explicit direct beats a host proxy, the nearest group proxy, and the
// global default. Clearing the host setting leaves directProxy unset and
// still inherits.
const isPluginHost = typeof host.protocol === 'string' && host.protocol.startsWith('plugin:');
if (!isLocalShellHost && !isSerialHost && !isPluginHost) {
const isStandaloneRdp = host.protocol === 'rdp';
@@ -506,7 +526,12 @@ export function applyGroupDefaults(
}
}
}
if (host.directProxy === true) return withoutInheritedProxy(effective);
// Explicit direct (on the host or inherited from the nearest group) beats
// parent group proxies and the global default. Clearing the setting leaves
// directProxy unset and still inherits.
if (host.directProxy === true || effective.directProxy === true) {
return withoutInheritedProxy(effective);
}
if (!effective.proxyConfig && !effective.proxyProfileId) {
const globalProxyProfileId = resolveGlobalProxyProfileId(options);
if (globalProxyProfileId) effective.proxyProfileId = globalProxyProfileId;
+5
View File
@@ -529,6 +529,11 @@ export interface GroupConfig {
x11Forwarding?: boolean;
proxyProfileId?: string;
proxyConfig?: ProxyConfig;
/**
* Explicit direct connection default for hosts in this group. Overrides
* parent group proxies and the global default proxy. Absent means inherit.
*/
directProxy?: boolean;
hostChain?: HostChainConfig;
startupCommand?: string;
startupCommandRunMode?: MultiLineRunMode;
+163
View File
@@ -2,14 +2,20 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import {
canMagnifyPaneSurface,
getAvailablePaneMagnificationController,
getPaneMagnificationShortcutLabel,
getWorkspacePaneOuterEdges,
isPaneMagnificationSelectionValid,
PANE_MAGNIFICATION_DURATION_MS,
pruneMagnifiedPanesByTab,
resolveNextMagnifiedSurfaceBounds,
resolvePaneMagnificationCandidate,
resolvePaneMagnificationLayoutGeometry,
resolvePaneMagnificationStyle,
resolveTwoPaneMagnificationStyle,
setTabMagnifiedPane,
shouldAnimatePaneMagnificationTransition,
snapCssRectToDevicePixels,
type PaneMagnificationController,
} from './paneMagnification.ts';
@@ -299,3 +305,160 @@ test('keeps a valid magnified pane focused and rejects a single-pane surface', (
current: null,
}), null);
});
test('canMagnifyPaneSurface disables magnification for a lone terminal without a side panel', () => {
assert.equal(canMagnifyPaneSurface(0, 0), false);
assert.equal(canMagnifyPaneSurface(1, 0), false);
assert.equal(canMagnifyPaneSurface(0, 1), false);
assert.equal(canMagnifyPaneSurface(1, 1), true);
assert.equal(canMagnifyPaneSurface(2, 0), true);
});
test('getWorkspacePaneOuterEdges identifies bottom-left and bottom-right corner panes in nested splits', () => {
const root = {
id: 'root',
type: 'split' as const,
direction: 'vertical' as const,
children: [
{ id: 'left', type: 'pane' as const, sessionId: 's-left' },
{
id: 'right-col',
type: 'split' as const,
direction: 'horizontal' as const,
children: [
{ id: 'top-right', type: 'pane' as const, sessionId: 's-top-right' },
{ id: 'bottom-right', type: 'pane' as const, sessionId: 's-bottom-right' },
],
},
],
};
assert.deepEqual(getWorkspacePaneOuterEdges(root, 's-left'), {
left: true,
right: false,
top: true,
bottom: true,
});
assert.deepEqual(getWorkspacePaneOuterEdges(root, 's-top-right'), {
left: false,
right: true,
top: true,
bottom: false,
});
assert.deepEqual(getWorkspacePaneOuterEdges(root, 's-bottom-right'), {
left: false,
right: true,
top: false,
bottom: true,
});
assert.deepEqual(getWorkspacePaneOuterEdges(root, 'missing'), {
left: false,
right: false,
top: false,
bottom: false,
});
});
test('shouldAnimatePaneMagnificationTransition skips zoom animation on tab-switch restore', () => {
// User triggers magnify on active visible tab -> animate
assert.equal(shouldAnimatePaneMagnificationTransition({
wasVisible: true,
isVisible: true,
wasMagnified: false,
isMagnified: true,
}), true);
// User triggers restore on active visible tab -> animate
assert.equal(shouldAnimatePaneMagnificationTransition({
wasVisible: true,
isVisible: true,
wasMagnified: true,
isMagnified: false,
}), true);
// Switching back to an already-magnified tab -> no animation
assert.equal(shouldAnimatePaneMagnificationTransition({
wasVisible: false,
isVisible: true,
wasMagnified: false,
isMagnified: true,
}), false);
// Switching away from a magnified tab -> no animation
assert.equal(shouldAnimatePaneMagnificationTransition({
wasVisible: true,
isVisible: false,
wasMagnified: true,
isMagnified: false,
}), false);
});
test('resolvePaneMagnificationStyle omits transition properties when animate is false', () => {
const original = { left: '0px', top: '0px', width: '500px', height: '400px' };
const surface = { left: 0, top: 40, width: 1000, height: 800 };
const origin = { left: 0, top: 40, width: 1000, height: 800 };
const snapped = resolvePaneMagnificationStyle(original, true, surface, 1, origin, false);
assert.equal(snapped.position, 'fixed');
assert.equal(snapped.zIndex, 50);
assert.equal(snapped.transitionProperty, undefined);
assert.equal(snapped.transitionDuration, undefined);
assert.equal(snapped.transitionTimingFunction, undefined);
assert.equal(snapped.left, '12px');
assert.equal(snapped.top, '12px');
assert.equal(snapped.width, '976px');
assert.equal(snapped.height, '776px');
});
test('per-tab magnification map preserves independent tab states and prunes closed panes', () => {
let byTab = new Map();
byTab = new Map(setTabMagnifiedPane(byTab, 'tab-a', { kind: 'terminal', sessionId: 's1' }));
byTab = new Map(setTabMagnifiedPane(byTab, 'tab-b', { kind: 'side-panel', paneId: 'p1', tool: 'sftp' }));
assert.deepEqual(byTab.get('tab-a'), { kind: 'terminal', sessionId: 's1' });
assert.deepEqual(byTab.get('tab-b'), { kind: 'side-panel', paneId: 'p1', tool: 'sftp' });
const pruned = pruneMagnifiedPanesByTab(
byTab,
[{ tabId: 'tab-a', sessionId: 's1' }],
[],
);
assert.deepEqual(pruned.get('tab-a'), { kind: 'terminal', sessionId: 's1' });
assert.equal(pruned.has('tab-b'), false);
const cleared = setTabMagnifiedPane(pruned, 'tab-a', null);
assert.equal(cleared.size, 0);
});
test('resolveNextMagnifiedSurfaceBounds preserves entry animation on unchanged initial ResizeObserver callback', () => {
const initial = {
left: 0,
top: 40,
width: 1200,
height: 800,
layoutOrigin: { left: 0, top: 40, width: 1200, height: 800 },
animate: true,
};
// Unchanged resize notification with animate=false must preserve initial animate=true reference
const afterInitialObserver = resolveNextMagnifiedSurfaceBounds(initial, {
...initial,
layoutOrigin: { ...initial.layoutOrigin },
animate: false,
});
assert.equal(afterInitialObserver, initial);
assert.equal(afterInitialObserver.animate, true);
// Real surface resize updates bounds with animate=false
const resized = resolveNextMagnifiedSurfaceBounds(initial, {
...initial,
width: 1400,
layoutOrigin: { ...initial.layoutOrigin, width: 1400 },
animate: false,
});
assert.equal(resized.width, 1400);
assert.equal(resized.animate, false);
// Restoring from hidden tab (current=null) applies animate=false immediately
const restored = resolveNextMagnifiedSurfaceBounds(null, {
...initial,
animate: false,
});
assert.equal(restored.animate, false);
});
+172 -7
View File
@@ -1,4 +1,5 @@
import type React from 'react';
import type { WorkspaceNode } from './models';
export type PaneMagnificationState = 'unavailable' | 'focusable' | 'focused';
@@ -13,6 +14,161 @@ export type PaneMagnificationTarget =
| { kind: 'terminal'; sessionId: string }
| { kind: 'side-panel'; paneId: string; tool: string };
export type WorkspacePaneOuterEdges = {
left: boolean;
right: boolean;
top: boolean;
bottom: boolean;
};
/**
* Pure threshold check matching resolvePaneMagnificationCandidate:
* a surface with fewer than 2 total panes (e.g. a single terminal with no side
* panel) is already full-size and must not magnify.
*/
export function canMagnifyPaneSurface(
terminalPaneCount: number,
sidePanelPaneCount: number,
): boolean {
return terminalPaneCount + sidePanelPaneCount >= 2;
}
/**
* Determine which outer edges of the workspace split tree a terminal session
* touches, so focus borders can match the host window's rounded corners on
* macOS without clipping while keeping interior split edges crisp.
*/
export function getWorkspacePaneOuterEdges(
root: WorkspaceNode | null | undefined,
sessionId: string,
): WorkspacePaneOuterEdges {
const empty: WorkspacePaneOuterEdges = { left: false, right: false, top: false, bottom: false };
if (!root) return empty;
const walk = (node: WorkspaceNode, edges: WorkspacePaneOuterEdges): WorkspacePaneOuterEdges | null => {
if (node.type === 'pane') {
return node.sessionId === sessionId ? edges : null;
}
const count = node.children.length;
for (let index = 0; index < count; index += 1) {
const child = node.children[index];
const childEdges: WorkspacePaneOuterEdges = node.direction === 'vertical'
? {
left: edges.left && index === 0,
right: edges.right && index === count - 1,
top: edges.top,
bottom: edges.bottom,
}
: {
left: edges.left,
right: edges.right,
top: edges.top && index === 0,
bottom: edges.bottom && index === count - 1,
};
const found = walk(child, childEdges);
if (found) return found;
}
return null;
};
return walk(root, { left: true, right: true, top: true, bottom: true }) ?? empty;
}
/**
* Animate magnification/restore only when the pane stays visible across the
* state transition (user action on the active tab). Returning to an already
* magnified tab must snap directly without replaying a zoom animation.
*/
export function shouldAnimatePaneMagnificationTransition({
wasVisible,
isVisible,
wasMagnified,
isMagnified,
}: {
wasVisible: boolean;
isVisible: boolean;
wasMagnified: boolean;
isMagnified: boolean;
}): boolean {
return wasVisible && isVisible && wasMagnified !== isMagnified;
}
export type MagnifiedSurfaceBounds = {
left: number;
top: number;
width: number;
height: number;
layoutOrigin: { left: number; top: number; width: number; height: number };
animate: boolean;
};
/**
* Merge a magnified surface measurement into existing state while ignoring
* ResizeObserver notifications whose geometry has not actually changed (most
* notably the initial observation callback delivered right after observe(),
* which would otherwise overwrite `animate: true` and cancel user-triggered
* zoom animations).
*/
export function resolveNextMagnifiedSurfaceBounds(
current: MagnifiedSurfaceBounds | null,
next: MagnifiedSurfaceBounds,
): MagnifiedSurfaceBounds {
if (
!next.animate
&& current
&& current.left === next.left
&& current.top === next.top
&& current.width === next.width
&& current.height === next.height
&& current.layoutOrigin.left === next.layoutOrigin.left
&& current.layoutOrigin.top === next.layoutOrigin.top
&& current.layoutOrigin.width === next.layoutOrigin.width
&& current.layoutOrigin.height === next.layoutOrigin.height
) {
return current;
}
return next;
}
export function setTabMagnifiedPane(
current: ReadonlyMap<string, PaneMagnificationTarget>,
tabId: string,
target: PaneMagnificationTarget | null,
): ReadonlyMap<string, PaneMagnificationTarget> {
const existing = current.get(tabId);
if (!target) {
if (!existing) return current;
const next = new Map(current);
next.delete(tabId);
return next;
}
const sameTarget = existing && existing.kind === target.kind && (
existing.kind === 'terminal'
? target.kind === 'terminal' && existing.sessionId === target.sessionId
: target.kind === 'side-panel' && existing.paneId === target.paneId && existing.tool === target.tool
);
if (sameTarget) return current;
const next = new Map(current);
next.set(tabId, target);
return next;
}
export function pruneMagnifiedPanesByTab(
current: ReadonlyMap<string, PaneMagnificationTarget>,
terminalPanes: Array<{ tabId: string; sessionId: string }>,
sidePanelPanes: Array<{ tabId: string; paneId: string }>,
): ReadonlyMap<string, PaneMagnificationTarget> {
if (current.size === 0) return current;
let changed = false;
const next = new Map<string, PaneMagnificationTarget>();
for (const [tabId, target] of current) {
if (isPaneMagnificationSelectionValid({ tabId, target }, terminalPanes, sidePanelPanes)) {
next.set(tabId, target);
} else {
changed = true;
}
}
return changed ? next : current;
}
export function isPaneMagnificationSelectionValid(
selection: { tabId: string; target: PaneMagnificationTarget },
terminalPanes: Array<{ tabId: string; sessionId: string }>,
@@ -42,7 +198,7 @@ export function resolvePaneMagnificationCandidate({
lastTarget?: PaneMagnificationTarget;
current: { tabId: string; target: PaneMagnificationTarget } | null;
}): { target: PaneMagnificationTarget; focused: boolean } | null {
if (terminalSessionIds.length + sidePanelPanes.length < 2) return null;
if (!canMagnifyPaneSurface(terminalSessionIds.length, sidePanelPanes.length)) return null;
const targetIsValid = (target: PaneMagnificationTarget) => (
target.kind === 'terminal'
? terminalSessionIds.includes(target.sessionId)
@@ -140,15 +296,24 @@ export function resolvePaneMagnificationStyle(
surfaceBounds?: { left: number; top: number; width: number; height: number } | null,
devicePixelRatio = 1,
layoutOrigin?: { left: number; top: number; width?: number; height?: number },
animate = true,
): React.CSSProperties {
// Keep the fixed overlay and transition while restoring too, so the split
// container cannot clip the pane before it has finished shrinking.
const transition: React.CSSProperties = surfaceBounds ? {
transitionProperty: 'left, top, width, height',
transitionDuration: `${PANE_MAGNIFICATION_DURATION_MS}ms`,
transitionTimingFunction: 'ease-out',
zIndex: 50,
} : {};
// When restoring magnification after a tab switch (`animate = false`), skip
// transition properties so the pane snaps immediately before paint.
const transition: React.CSSProperties = surfaceBounds ? (
animate
? {
transitionProperty: 'left, top, width, height',
transitionDuration: `${PANE_MAGNIFICATION_DURATION_MS}ms`,
transitionTimingFunction: 'ease-out',
zIndex: 50,
}
: {
zIndex: 50,
}
) : {};
// Margins compensate for the containing-block switch without animating or
// transforming the terminal and its descendants. Local split offsets then
// keep the same viewport origin when fixed positioning starts or ends.
+157
View File
@@ -0,0 +1,157 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildRdpClipboardItemData, fingerprintRdpClipboardPng, nextRdpClipboardGuardState, selectRdpClipboardData } from './rdpClipboard';
const pngBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
const emptyState = { lastText: '', lastPngFingerprint: null };
test('mixed remote clipboard data preserves both local formats and does not echo on refocus', async () => {
const snapshot = { text: 'caption', pngBytes };
const data = buildRdpClipboardItemData(snapshot);
assert.deepEqual(Object.keys(data).sort(), ['image/png', 'text/plain']);
assert.equal(data['image/png'].type, 'image/png');
assert.equal(data['text/plain'].type, 'text/plain');
const localSnapshot = {
text: await data['text/plain'].text(),
pngBytes: new Uint8Array(await data['image/png'].arrayBuffer()),
};
assert.deepEqual(localSnapshot, snapshot);
assert.deepEqual(selectRdpClipboardData({
...nextRdpClipboardGuardState(snapshot),
...localSnapshot,
}), { text: null, pngBytes: null, pngFingerprint: null });
});
test('local clipboard item data preserves image-only, text-only and empty text formats', async () => {
const imageData = buildRdpClipboardItemData({ text: null, pngBytes });
assert.deepEqual(Object.keys(imageData), ['image/png']);
assert.deepEqual(new Uint8Array(await imageData['image/png'].arrayBuffer()), pngBytes);
for (const text of ['hello', '']) {
const textData = buildRdpClipboardItemData({ text, pngBytes: null });
assert.deepEqual(Object.keys(textData), ['text/plain']);
assert.equal(await textData['text/plain'].text(), text);
}
});
test('image-only RDP clipboard data is sent', () => {
assert.deepEqual(selectRdpClipboardData({ ...emptyState, text: '', pngBytes }), {
text: null,
pngBytes,
pngFingerprint: fingerprintRdpClipboardPng(pngBytes),
});
});
test('the last pushed or received PNG is skipped unless forced', () => {
const input = {
...emptyState,
text: null,
pngBytes: new Uint8Array(pngBytes),
lastPngFingerprint: fingerprintRdpClipboardPng(pngBytes),
};
assert.equal(selectRdpClipboardData(input).pngBytes, null);
assert.deepEqual(selectRdpClipboardData({ ...input, force: true }).pngBytes, pngBytes);
assert.notEqual(fingerprintRdpClipboardPng(new Uint8Array([1, 2, 3, 4])), input.lastPngFingerprint);
});
test('text-only RDP clipboard behavior is unchanged', () => {
const input = { ...emptyState, text: 'hello', pngBytes: null };
assert.equal(selectRdpClipboardData(input).text, 'hello');
assert.equal(selectRdpClipboardData({ ...input, lastText: 'hello' }).text, null);
assert.equal(selectRdpClipboardData({ ...input, lastText: 'hello', force: true }).text, 'hello');
});
test('text and PNG are selected together', () => {
const result = selectRdpClipboardData({ ...emptyState, text: 'caption', pngBytes });
assert.equal(result.text, 'caption');
assert.equal(result.pngBytes, pngBytes);
});
test('a changed clipboard snapshot sends every present format', () => {
const result = selectRdpClipboardData({
...emptyState,
text: 'new text',
pngBytes,
lastPngFingerprint: fingerprintRdpClipboardPng(pngBytes),
});
assert.equal(result.text, 'new text');
assert.equal(result.pngBytes, pngBytes);
const imageResult = selectRdpClipboardData({
...emptyState,
text: 'same text',
lastText: 'same text',
pngBytes,
});
assert.equal(imageResult.text, 'same text');
assert.equal(imageResult.pngBytes, pngBytes);
});
test('text then image then the same text replaces each clipboard snapshot', () => {
const imageResult = selectRdpClipboardData({
lastText: 'B', lastPngFingerprint: null, text: null, pngBytes,
});
const pngFingerprint = fingerprintRdpClipboardPng(pngBytes);
assert.deepEqual(imageResult, { text: null, pngBytes, pngFingerprint });
const imageState = nextRdpClipboardGuardState(imageResult);
assert.deepEqual(imageState, { lastText: '', lastPngFingerprint: pngFingerprint });
const textResult = selectRdpClipboardData({ ...imageState, text: 'B', pngBytes: null });
assert.deepEqual(textResult, { text: 'B', pngBytes: null, pngFingerprint: null });
const textState = nextRdpClipboardGuardState(textResult);
assert.deepEqual(textState, { lastText: 'B', lastPngFingerprint: null });
assert.deepEqual(selectRdpClipboardData({ ...textState, text: null, pngBytes }), imageResult);
});
test('text-only replacement sends unchanged text when the previous snapshot included a PNG', () => {
assert.deepEqual(selectRdpClipboardData({
lastText: 'B',
lastPngFingerprint: fingerprintRdpClipboardPng(pngBytes),
text: 'B',
pngBytes: null,
}), { text: 'B', pngBytes: null, pngFingerprint: null });
});
test('image-only replacement sends the same PNG when the previous snapshot included text', () => {
const pngFingerprint = fingerprintRdpClipboardPng(pngBytes);
assert.deepEqual(selectRdpClipboardData({
lastText: 'B',
lastPngFingerprint: pngFingerprint,
text: null,
pngBytes,
}), { text: null, pngBytes, pngFingerprint });
});
test('an identical text and PNG snapshot is skipped unless forced', () => {
const pngFingerprint = fingerprintRdpClipboardPng(pngBytes);
const input = {
lastText: 'B',
lastPngFingerprint: pngFingerprint,
text: 'B',
pngBytes: new Uint8Array(pngBytes),
};
assert.deepEqual(selectRdpClipboardData(input), {
text: null, pngBytes: null, pngFingerprint: null,
});
assert.deepEqual(selectRdpClipboardData({ ...input, force: true }), {
text: 'B', pngBytes, pngFingerprint,
});
assert.deepEqual(nextRdpClipboardGuardState(input), {
lastText: 'B', lastPngFingerprint: pngFingerprint,
});
});
test('an empty clipboard snapshot clears both guard fields and sends nothing', () => {
const input = { text: undefined, pngBytes: new Uint8Array() };
assert.deepEqual(nextRdpClipboardGuardState(input), emptyState);
assert.deepEqual(selectRdpClipboardData({ ...emptyState, ...input }), {
text: null, pngBytes: null, pngFingerprint: null,
});
});
test('empty clipboard formats are ignored even when forced', () => {
assert.deepEqual(selectRdpClipboardData({
...emptyState,
text: undefined,
pngBytes: new Uint8Array(),
force: true,
}), { text: null, pngBytes: null, pngFingerprint: null });
});
+58
View File
@@ -0,0 +1,58 @@
export function buildRdpClipboardItemData({ text, pngBytes }: {
text: string | null;
pngBytes: Uint8Array | null;
}): Record<string, Blob> {
const data: Record<string, Blob> = {};
if (pngBytes) {
const pngCopy = new Uint8Array(pngBytes.byteLength);
pngCopy.set(pngBytes);
data['image/png'] = new Blob([pngCopy], { type: 'image/png' });
}
if (text !== null) {
data['text/plain'] = new Blob([text], { type: 'text/plain' });
}
return data;
}
export function fingerprintRdpClipboardPng(bytes: Uint8Array): string {
// FNV-1a plus the byte length is sufficient for clipboard echo detection.
let hash = 0x811c9dc5;
for (const byte of bytes) {
hash = Math.imul(hash ^ byte, 0x01000193);
}
return `${bytes.length}:${(hash >>> 0).toString(16)}`;
}
export function nextRdpClipboardGuardState({ text, pngBytes }: {
text: string | null | undefined;
pngBytes: Uint8Array | null;
}) {
return {
lastText: text || '',
lastPngFingerprint: pngBytes?.length ? fingerprintRdpClipboardPng(pngBytes) : null,
};
}
export function selectRdpClipboardData({
text,
pngBytes,
lastText,
lastPngFingerprint,
force = false,
}: {
text: string | null | undefined;
pngBytes: Uint8Array | null;
lastText: string;
lastPngFingerprint: string | null;
force?: boolean;
}) {
const current = nextRdpClipboardGuardState({ text, pngBytes });
if (!force && current.lastText === lastText && current.lastPngFingerprint === lastPngFingerprint) {
return { text: null, pngBytes: null, pngFingerprint: null };
}
return {
text: current.lastText || null,
pngBytes: current.lastPngFingerprint !== null ? pngBytes : null,
pngFingerprint: current.lastPngFingerprint,
};
}
+52
View File
@@ -47,6 +47,58 @@ describe('vaultGroupAgentOps', () => {
assert.equal(effective.proxyConfig?.host, 'parent-gw.test');
});
it('supports setting and clearing directProxy on groups consistently with Group Details', () => {
const proxyOptions = { validProxyProfileIds: new Set(['proxy-1']), globalProxyProfileId: 'proxy-1' };
const initialState = {
groups: ['prod', 'prod/web'],
configs: [
{ path: 'prod', proxyConfig: { type: 'http' as const, host: 'parent-gw.test', port: 3128 } },
{ path: 'prod/web', proxyProfileId: 'proxy-1' },
],
hosts,
managedSources: [],
};
const setDirect = upsertGroup(initialState, 'prod/web', '{"directProxy":true}', [], proxyProfiles);
assert.equal(setDirect.ok, true);
if (!setDirect.ok) return;
assert.equal(setDirect.config?.directProxy, true);
assert.equal(setDirect.config?.proxyProfileId, undefined);
assert.equal(setDirect.config?.proxyConfig, undefined);
const directEffective = applyGroupDefaults(
hosts[0], resolveGroupDefaults('prod/web', setDirect.state.configs, proxyOptions), proxyOptions,
);
assert.equal(directEffective.directProxy, true);
assert.equal(directEffective.proxyProfileId, undefined);
assert.equal(directEffective.proxyConfig, undefined);
const replacedWithProfile = upsertGroup(setDirect.state, 'prod/web', '{"proxyProfileId":"proxy-1"}', [], proxyProfiles);
assert.equal(replacedWithProfile.ok, true);
if (!replacedWithProfile.ok) return;
assert.equal(replacedWithProfile.config?.directProxy, undefined);
assert.equal(replacedWithProfile.config?.proxyProfileId, 'proxy-1');
const clearedViaEmptyProfile = upsertGroup(setDirect.state, 'prod/web', '{"proxyProfileId":""}', [], proxyProfiles);
assert.equal(clearedViaEmptyProfile.ok, true);
if (!clearedViaEmptyProfile.ok) return;
assert.equal(clearedViaEmptyProfile.config?.directProxy, undefined);
assert.equal(clearedViaEmptyProfile.config?.proxyProfileId, undefined);
const inheritedAgain = applyGroupDefaults(
hosts[0], resolveGroupDefaults('prod/web', clearedViaEmptyProfile.state.configs, proxyOptions), proxyOptions,
);
assert.equal(inheritedAgain.proxyConfig?.host, 'parent-gw.test');
const clearedViaFalse = upsertGroup(setDirect.state, 'prod/web', '{"directProxy":false}', [], proxyProfiles);
assert.equal(clearedViaFalse.ok, true);
if (!clearedViaFalse.ok) return;
assert.equal(clearedViaFalse.config?.directProxy, undefined);
assert.equal(
upsertGroup(initialState, 'prod/web', '{"directProxy":true,"proxyProfileId":"proxy-1"}', [], proxyProfiles).ok,
false,
);
});
it('rejects missing identities, proxy profiles, and jump hosts', () => {
const state = { groups: ['prod'], configs: [], hosts, managedSources: [] };
assert.equal(upsertGroup(state, 'prod', '{"identityId":"missing"}', [], proxyProfiles).ok, false);
+21 -1
View File
@@ -144,8 +144,18 @@ export function patchGroupConfig(
next.authMethod = undefined;
}
}
if (Object.hasOwn(defaults, 'proxyProfileId')) {
const hasProxyProfileId = Object.hasOwn(defaults, 'proxyProfileId');
const hasDirectProxy = Object.hasOwn(defaults, 'directProxy');
let parsedDirectProxy: boolean | undefined;
if (hasDirectProxy) {
parsedDirectProxy = bool(defaults.directProxy);
if (parsedDirectProxy === undefined) return { ok: false, error: 'directProxy must be true or false.' };
}
if (hasProxyProfileId) {
const proxyProfileId = String(defaults.proxyProfileId ?? '');
if (proxyProfileId && parsedDirectProxy === true) {
return { ok: false, error: 'directProxy and proxyProfileId cannot both be set.' };
}
if (proxyProfileId && !proxyProfiles.some((profile) => profile.id === proxyProfileId)) {
return { ok: false, error: `Proxy profile "${proxyProfileId}" was not found.` };
}
@@ -153,6 +163,16 @@ export function patchGroupConfig(
// group proxy (or the global default) applies, instead of blocking it.
next.proxyProfileId = proxyProfileId || undefined;
next.proxyConfig = undefined;
next.directProxy = undefined;
}
if (hasDirectProxy) {
if (parsedDirectProxy) {
next.directProxy = true;
next.proxyProfileId = undefined;
next.proxyConfig = undefined;
} else {
next.directProxy = undefined;
}
}
if (Object.hasOwn(defaults, 'jumpHostIds')) {
let ids: unknown = defaults.jumpHostIds;
+28
View File
@@ -456,6 +456,34 @@ test("CSV round-trips explicit direct proxy mode and still treats an empty Proxy
assert.equal(literal.hosts[1]?.directProxy, undefined);
});
test("CSV export writes direct for hosts inheriting group directProxy and preserves host proxy overrides", () => {
const groupProxy = { type: "socks5" as const, host: "group.example.com", port: 1080 };
const hostProxy = { type: "http" as const, host: "host.example.com", port: 8080 };
const hosts: Host[] = [
{ ...hostDefaults, id: "child-direct", label: "Child Direct", hostname: "child.example.com", group: "Corp/Local" },
{
...hostDefaults,
id: "child-override",
label: "Child Override",
hostname: "override.example.com",
group: "Corp/Local",
proxyConfig: hostProxy,
},
];
const { csv } = exportHostsToCsvWithStats(hosts, {
groupConfigs: [
{ path: "Corp", proxyConfig: groupProxy },
{ path: "Corp/Local", directProxy: true },
],
});
const lines = csv.replace(/^\uFEFF/, "").trimEnd().split("\r\n");
const proxyIndex = lines[0].split(",").indexOf("Proxy");
const proxyCell = (line: string) => line.split(",")[proxyIndex];
assert.equal(proxyCell(lines[1]), "direct");
assert.equal(proxyCell(lines[2]), "http://host.example.com:8080");
assert.equal(csv.includes("group.example.com"), false);
});
test("CSV export keeps an empty Proxy cell when only the global default is set", () => {
publishActiveGlobalDefaultProxyProfileId("global-proxy");
try {
+20 -7
View File
@@ -237,16 +237,11 @@ function createClipboardImageFileName(date = new Date()) {
return `netcatty-paste-${formatClipboardImageTimestamp(date)}.png`;
}
async function readClipboardImage({
async function readClipboardImagePngBytes({
clipboard,
fsImpl = fs,
tempDirBridge,
nativeImageImpl = null,
now = () => new Date(),
} = {}) {
if (!clipboard || !tempDirBridge?.getTempFilePath) {
return null;
}
if (!clipboard) return null;
try {
let content = null;
@@ -297,7 +292,24 @@ async function readClipboardImage({
}
if (!Buffer.isBuffer(content) || content.length === 0) return null;
return content;
} catch {
return null;
}
}
async function readClipboardImage({
clipboard,
fsImpl = fs,
tempDirBridge,
nativeImageImpl = null,
now = () => new Date(),
} = {}) {
if (!clipboard || !tempDirBridge?.getTempFilePath) return null;
try {
const content = await readClipboardImagePngBytes({ clipboard, nativeImageImpl });
if (!content) return null;
const name = createClipboardImageFileName(now());
const imagePath = tempDirBridge.getTempFilePath(name);
await fsImpl.promises.writeFile(imagePath, content);
@@ -381,4 +393,5 @@ module.exports = {
parseClipboardTextFilePaths,
readClipboardFiles,
readClipboardImage,
readClipboardImagePngBytes,
};
+55
View File
@@ -11,6 +11,7 @@ const {
parseClipboardTextFilePaths,
readClipboardFiles,
readClipboardImage,
readClipboardImagePngBytes,
} = require("./clipboardFiles.cjs");
const createFs = (entries) => ({
@@ -158,6 +159,59 @@ test("creates stable clipboard image file names", () => {
);
});
test("reads native clipboard PNG bytes without a temp directory", async () => {
const content = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
const result = await readClipboardImagePngBytes({
clipboard: {
readImage: () => ({ isEmpty: () => false, toPNG: () => content }),
read: () => assert.fail("native image read should take precedence"),
},
});
assert.deepEqual(result, content);
});
test("PNG bytes helper returns null for empty native images or PNG buffers", async () => {
assert.equal(await readClipboardImagePngBytes({
clipboard: {
readImage: () => ({
isEmpty: () => true,
toPNG: () => assert.fail("empty image must not be encoded"),
}),
},
}), null);
assert.equal(await readClipboardImagePngBytes({
clipboard: { readImage: () => ({ toPNG: () => Buffer.alloc(0) }) },
}), null);
});
test("PNG bytes helper returns null for missing or failing clipboard reads", async () => {
assert.equal(await readClipboardImagePngBytes(), null);
assert.equal(await readClipboardImagePngBytes({
clipboard: { readImage: () => { throw new Error("clipboard unavailable"); } },
}), null);
});
test("PNG bytes helper converts async clipboard images through nativeImage", async () => {
const rawBytes = Buffer.from("jpeg");
const pngBytes = Buffer.from("png");
const result = await readClipboardImagePngBytes({
clipboard: {
read: async () => [{
types: ["image/jpeg"],
getType: async () => new Blob([rawBytes], { type: "image/jpeg" }),
}],
},
nativeImageImpl: {
createFromBuffer: (bytes) => {
assert.deepEqual(bytes, rawBytes);
return { isEmpty: () => false, toPNG: () => pngBytes };
},
},
});
assert.deepEqual(result, pngBytes);
});
test("writes clipboard image to Netcatty temp directory", async () => {
const writes = [];
const content = Buffer.from([1, 2, 3]);
@@ -346,6 +400,7 @@ test("readClipboardImage and hasClipboardImage support Electron 44+ async W3C cl
};
assert.equal(await hasClipboardImage({ clipboard }), true);
assert.deepEqual(await readClipboardImagePngBytes({ clipboard }), pngBytes);
const saved = await readClipboardImage({
clipboard,
fsImpl: {
+1 -1
View File
@@ -262,7 +262,7 @@ const TOOL_INPUT_FIELDS = Object.freeze({
"vault.group.list": {},
"vault.group.create": {
path: { type: "string", description: "New group path, for example prod/web." },
defaults: { type: "string", optional: true, description: "JSON object of group defaults: username, identityId, proxyProfileId, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort." },
defaults: { type: "string", optional: true, description: "JSON object of group defaults: username, identityId, proxyProfileId, directProxy, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort." },
},
"vault.group.update": {
path: { type: "string", description: "Existing group path." },
+5 -1
View File
@@ -2,7 +2,7 @@
let cloudSyncSessionPassword = null;
const perfTrace = require("../perfTrace.cjs");
const { readClipboardFiles, readClipboardImage, hasClipboardImage } = require("../bridges/clipboardFiles.cjs");
const { readClipboardFiles, readClipboardImage, readClipboardImagePngBytes, hasClipboardImage } = require("../bridges/clipboardFiles.cjs");
const { registerSystemNotificationHandlers } = require("../bridges/systemNotification.cjs");
const {
installWindowAttention,
@@ -1207,6 +1207,10 @@ function createBridgeRegistrar(context) {
return await readClipboardImage({ clipboard, fsImpl: fs, tempDirBridge });
});
ipcMain.handle("netcatty:clipboard:readImagePng", async () => {
return await readClipboardImagePngBytes({ clipboard });
});
ipcMain.handle("netcatty:clipboard:hasImage", async () => {
return await hasClipboardImage({ clipboard });
});
+3
View File
@@ -2047,6 +2047,9 @@ function createPreloadApi(ctx) {
readClipboardImage: async () => {
return ipcRenderer.invoke("netcatty:clipboard:readImage");
},
readClipboardImagePng: async () => {
return ipcRenderer.invoke("netcatty:clipboard:readImagePng");
},
hasClipboardImage: async () => {
return ipcRenderer.invoke("netcatty:clipboard:hasImage");
},
+31 -5
View File
@@ -796,6 +796,16 @@ html[data-theme-transition] *::after {
border-right: var(--terminal-workspace-sidebar-border, none);
}
/* Host window corner radius for split-pane focus borders touching the outer
window edge. Non-fullscreen macOS windows have native rounded corners;
Linux/Windows and fullscreen windows stay square. */
:root {
--window-corner-radius: 0px;
}
:root[data-platform="darwin"]:not([data-window-fullscreen="true"]) {
--window-corner-radius: 10px;
}
/* Dim terminal text in unfocused workspace panes (default) */
.workspace-pane:not(:focus-within) .xterm-screen {
opacity: 0.82;
@@ -805,21 +815,37 @@ html[data-theme-transition] *::after {
.workspace-pane[data-menu-open] .xterm-screen {
opacity: 1;
}
/* Border-style focus indicator (opt-in via data attribute) */
/* Border-style focus indicator (opt-in via data attribute).
Driven by deterministic workspace focus state (data-focused) rather than
DOM :focus-within so dialogs, settings, and app switches do not drop the
indicator. Suppressed for single-pane workspaces and magnified panes (which
render their own independent 1px magnification stroke). */
[data-workspace-focus="border"] .workspace-pane:not(:focus-within) .xterm-screen {
opacity: 1;
}
[data-workspace-focus="border"] .workspace-pane::after {
[data-workspace-focus="border"] .workspace-pane[data-multi-pane="true"]::after {
content: "";
position: absolute;
inset: 0;
border: 2px solid transparent;
box-sizing: border-box;
border: var(--workspace-focus-border-width, 1px) solid transparent;
border-radius: inherit;
pointer-events: none;
transition: border-color 120ms ease;
z-index: 40;
}
[data-workspace-focus="border"] .workspace-pane:focus-within::after {
border-color: hsl(var(--primary));
[data-workspace-focus="border"] .workspace-pane[data-multi-pane="true"][data-workspace-corner-bl="true"]:not([data-magnified="true"])::after {
border-bottom-left-radius: var(--workspace-corner-bl-radius, 0px);
}
[data-workspace-focus="border"] .workspace-pane[data-multi-pane="true"][data-workspace-corner-br="true"]:not([data-magnified="true"])::after {
border-bottom-right-radius: var(--workspace-corner-br-radius, 0px);
}
[data-workspace-focus="border"] .workspace-pane[data-multi-pane="true"][data-focused="true"]:not([data-magnified="true"])::after {
border-color: var(--workspace-focus-border-color, hsl(var(--primary)));
}
[data-workspace-focus="border"] .workspace-pane[data-magnified="true"]::after {
border-color: transparent;
transition: none;
}
/* ── Streamdown code block overrides ── */
@@ -1212,7 +1212,7 @@
"defaults": {
"type": "string",
"optional": true,
"description": "JSON object of group defaults: username, identityId, proxyProfileId, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort."
"description": "JSON object of group defaults: username, identityId, proxyProfileId, directProxy, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort."
}
},
"policy": {
@@ -1284,7 +1284,7 @@
"defaults": {
"type": "string",
"optional": true,
"description": "JSON object of group defaults: username, identityId, proxyProfileId, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort."
"description": "JSON object of group defaults: username, identityId, proxyProfileId, directProxy, jumpHostIds, startupCommand, environmentVariables, moshEnabled, moshServerPath, etEnabled, etPort."
}
},
"policy": {
@@ -307,6 +307,7 @@ const SAFE_GROUP_CONFIG_KEYS = [
'deviceType',
'agentForwarding',
'proxyProfileId',
'directProxy',
'hostChain',
'startupCommandRunMode',
'loginScriptId',
+3 -3
View File
@@ -1,14 +1,14 @@
{
version = "1.1.94";
version = "1.1.95";
sources = {
x86_64-linux = {
appImageArch = "x86_64";
hash = "sha256-aGZRSKTQQdBsdrP26HWvqEc1W9hKJHBrbEpy/H+jRP8=";
hash = "sha256-jtkRQ4I+ZF1ihy/JE8L8c4Nj7Chy65K808y/a4fXwLE=";
};
aarch64-linux = {
appImageArch = "arm64";
hash = "sha256-xOF4Rs0vfvmzVPE2vn2QYEFEzy5nPSYriru4Vmbwc2c=";
hash = "sha256-z1qYYw/E7fkHTGGvIaTc2VGzBkQgZFEvxR7H+iBUlLc=";
};
};
}
+1
View File
@@ -9,6 +9,7 @@ Self-contained WebAssembly build of [Devolutions/IronRDP](https://github.com/Dev
2. `0002-load-balance-info-and-shell.patch` — Exposes `load_balance_info`, `alternate_shell`, and `work_dir` extensions on `SessionBuilder` for JumpServer Razor and RDS Connection Broker routing.
3. `0003-rdpdr-drives-and-multimonitor.patch` — Adds `WasmDriveBackend` for MS-RDPEFS drive redirection (`rdpdr_drives`, `rdpdr_request_callback`, `rdpdr_response`, `rdpdr_add_drive`, `rdpdr_remove_drive`, composing cleanly with audio and printer redirection) and MS-RDPEDISP multi-monitor layout extensions (`set_monitor_layout`, `display_control_caps_callback`).
4. `0004-standard-rdp-security.patch` — Fixes `ConferenceCreateRequest` GCC `connectPDU` PER length encoding, raises `ServerSecurityData` certificate size limits, and adds Standard RDP Security (MS-RDPBCGR 5.3) with 40/56/128-bit RC4 (standard & salted MAC, 4096-packet key update) and FIPS (3DES-EDE3-CBC + HMAC-SHA1) across Slow-Path, Fast-Path, and Deactivation-Reactivation, plus `security_info_callback`.
5. `0005-license-request-fallback-public-key.patch` — Reuses the server public key from Standard RDP Server Security Data when the Server License Request omits its certificate, for both new and cached license responses.
## Rebuilding
+7 -7
View File
@@ -298,13 +298,13 @@ export interface InitOutput {
readonly sessionbuilder_webSocketProtocols: (a: number, b: any) => number;
readonly sessionterminationinfo_reason: (a: number) => [number, number];
readonly setup: (a: number, b: number) => void;
readonly wasm_bindgen__convert__closures_____invoke__h0870fb11242d97da: (a: number, b: number, c: any, d: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__hc8af3a46fbf9a387: (a: number, b: number, c: any) => [number, number];
readonly wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48: (a: number, b: number, c: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_69: (a: number, b: number, c: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_70: (a: number, b: number, c: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__hda0c6eb1ba57bb78: (a: number, b: number) => void;
readonly wasm_bindgen__convert__closures_____invoke__hed1c9475885aec45: (a: number, b: number) => void;
readonly wasm_bindgen__convert__closures_____invoke__h7fd80c0d0f68485d: (a: number, b: number, c: any, d: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__h9b3b88103f98b444: (a: number, b: number, c: any) => [number, number];
readonly wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74: (a: number, b: number, c: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_69: (a: number, b: number, c: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_70: (a: number, b: number, c: any) => void;
readonly wasm_bindgen__convert__closures_____invoke__h43f4169ee688cf51: (a: number, b: number) => void;
readonly wasm_bindgen__convert__closures_____invoke__h4a921f6235159135: (a: number, b: number) => void;
readonly __wbindgen_malloc: (a: number, b: number) => number;
readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
readonly __wbindgen_exn_store: (a: number) => void;
+27 -27
View File
@@ -1238,7 +1238,7 @@ function __wbg_get_imports() {
const a = state0.a;
state0.a = 0;
try {
return wasm_bindgen__convert__closures_____invoke__h0870fb11242d97da(a, state0.b, arg0, arg1);
return wasm_bindgen__convert__closures_____invoke__h7fd80c0d0f68485d(a, state0.b, arg0, arg1);
} finally {
state0.a = a;
}
@@ -1493,33 +1493,33 @@ function __wbg_get_imports() {
return ret;
},
__wbindgen_generic_0000000000000001: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 3876, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hc8af3a46fbf9a387);
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 3867, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h9b3b88103f98b444);
return ret;
},
__wbindgen_generic_0000000000000002: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("CloseEvent")], shim_idx: 1111, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48);
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("CloseEvent")], shim_idx: 1113, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74);
return ret;
},
__wbindgen_generic_0000000000000003: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 1111, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_69);
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 1113, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_69);
return ret;
},
__wbindgen_generic_0000000000000004: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("MessageEvent")], shim_idx: 1111, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_70);
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("MessageEvent")], shim_idx: 1113, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_70);
return ret;
},
__wbindgen_generic_0000000000000005: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1103, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hda0c6eb1ba57bb78);
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1105, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h43f4169ee688cf51);
return ret;
},
__wbindgen_generic_0000000000000006: function(arg0, arg1) {
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1112, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__hed1c9475885aec45);
// Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 1114, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`.
const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h4a921f6235159135);
return ret;
},
__wbindgen_generic_0000000000000007: function(arg0) {
@@ -1548,35 +1548,35 @@ function __wbg_get_imports() {
};
}
function wasm_bindgen__convert__closures_____invoke__hda0c6eb1ba57bb78(arg0, arg1) {
wasm.wasm_bindgen__convert__closures_____invoke__hda0c6eb1ba57bb78(arg0, arg1);
function wasm_bindgen__convert__closures_____invoke__h43f4169ee688cf51(arg0, arg1) {
wasm.wasm_bindgen__convert__closures_____invoke__h43f4169ee688cf51(arg0, arg1);
}
function wasm_bindgen__convert__closures_____invoke__hed1c9475885aec45(arg0, arg1) {
wasm.wasm_bindgen__convert__closures_____invoke__hed1c9475885aec45(arg0, arg1);
function wasm_bindgen__convert__closures_____invoke__h4a921f6235159135(arg0, arg1) {
wasm.wasm_bindgen__convert__closures_____invoke__h4a921f6235159135(arg0, arg1);
}
function wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48(arg0, arg1, arg2) {
wasm.wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48(arg0, arg1, arg2);
function wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74(arg0, arg1, arg2) {
wasm.wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74(arg0, arg1, arg2);
}
function wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_69(arg0, arg1, arg2) {
wasm.wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_69(arg0, arg1, arg2);
function wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_69(arg0, arg1, arg2) {
wasm.wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_69(arg0, arg1, arg2);
}
function wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_70(arg0, arg1, arg2) {
wasm.wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_70(arg0, arg1, arg2);
function wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_70(arg0, arg1, arg2) {
wasm.wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_70(arg0, arg1, arg2);
}
function wasm_bindgen__convert__closures_____invoke__hc8af3a46fbf9a387(arg0, arg1, arg2) {
const ret = wasm.wasm_bindgen__convert__closures_____invoke__hc8af3a46fbf9a387(arg0, arg1, arg2);
function wasm_bindgen__convert__closures_____invoke__h9b3b88103f98b444(arg0, arg1, arg2) {
const ret = wasm.wasm_bindgen__convert__closures_____invoke__h9b3b88103f98b444(arg0, arg1, arg2);
if (ret[1]) {
throw takeFromExternrefTable0(ret[0]);
}
}
function wasm_bindgen__convert__closures_____invoke__h0870fb11242d97da(arg0, arg1, arg2, arg3) {
wasm.wasm_bindgen__convert__closures_____invoke__h0870fb11242d97da(arg0, arg1, arg2, arg3);
function wasm_bindgen__convert__closures_____invoke__h7fd80c0d0f68485d(arg0, arg1, arg2, arg3) {
wasm.wasm_bindgen__convert__closures_____invoke__h7fd80c0d0f68485d(arg0, arg1, arg2, arg3);
}
Binary file not shown.
+7 -7
View File
@@ -79,13 +79,13 @@ export const sessionbuilder_username: (a: number, b: number, c: number) => numbe
export const sessionbuilder_webSocketProtocols: (a: number, b: any) => number;
export const sessionterminationinfo_reason: (a: number) => [number, number];
export const setup: (a: number, b: number) => void;
export const wasm_bindgen__convert__closures_____invoke__h0870fb11242d97da: (a: number, b: number, c: any, d: any) => void;
export const wasm_bindgen__convert__closures_____invoke__hc8af3a46fbf9a387: (a: number, b: number, c: any) => [number, number];
export const wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48: (a: number, b: number, c: any) => void;
export const wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_69: (a: number, b: number, c: any) => void;
export const wasm_bindgen__convert__closures_____invoke__h69dcddf96fe0df48_70: (a: number, b: number, c: any) => void;
export const wasm_bindgen__convert__closures_____invoke__hda0c6eb1ba57bb78: (a: number, b: number) => void;
export const wasm_bindgen__convert__closures_____invoke__hed1c9475885aec45: (a: number, b: number) => void;
export const wasm_bindgen__convert__closures_____invoke__h7fd80c0d0f68485d: (a: number, b: number, c: any, d: any) => void;
export const wasm_bindgen__convert__closures_____invoke__h9b3b88103f98b444: (a: number, b: number, c: any) => [number, number];
export const wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74: (a: number, b: number, c: any) => void;
export const wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_69: (a: number, b: number, c: any) => void;
export const wasm_bindgen__convert__closures_____invoke__h151689d2a7caaa74_70: (a: number, b: number, c: any) => void;
export const wasm_bindgen__convert__closures_____invoke__h43f4169ee688cf51: (a: number, b: number) => void;
export const wasm_bindgen__convert__closures_____invoke__h4a921f6235159135: (a: number, b: number) => void;
export const __wbindgen_malloc: (a: number, b: number) => number;
export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
export const __wbindgen_exn_store: (a: number) => void;
+2 -1
View File
@@ -32,7 +32,8 @@
"0001-session-responsiveness.patch",
"0002-load-balance-info-and-shell.patch",
"0003-rdpdr-drives-and-multimonitor.patch",
"0004-standard-rdp-security.patch"
"0004-standard-rdp-security.patch",
"0005-license-request-fallback-public-key.patch"
]
}
}
+5 -2
View File
@@ -116,8 +116,9 @@ run_host_tests() {
echo "Running IronRDP host unit tests (ironrdp-pdu, ironrdp-connector, ironrdp-web)..."
(
cd "${SRC_DIR}"
cargo test -p ironrdp-pdu --lib --locked -- crypto:: gcc::
cargo test -p ironrdp-pdu --lib --locked -- crypto:: gcc:: server_license::
cargo test -p ironrdp-connector --lib --locked
cargo test -p ironrdp-testsuite-core --test integration_tests_core --locked -- pdu::server_license connector::license_exchange
# Run host-compatible unit tests (RDPDR drive PDU marshalling, multi-monitor
# layout validation, load_balance_info, audio/printer/drive channel
# attachment, RDCleanPath, file-transfer marshalling). Clipboard JS bridge
@@ -214,7 +215,8 @@ package_output() {
"0001-session-responsiveness.patch",
"0002-load-balance-info-and-shell.patch",
"0003-rdpdr-drives-and-multimonitor.patch",
"0004-standard-rdp-security.patch"
"0004-standard-rdp-security.patch",
"0005-license-request-fallback-public-key.patch"
]
}
}
@@ -232,6 +234,7 @@ Self-contained WebAssembly build of [Devolutions/IronRDP](https://github.com/Dev
2. \`0002-load-balance-info-and-shell.patch\` — Exposes \`load_balance_info\`, \`alternate_shell\`, and \`work_dir\` extensions on \`SessionBuilder\` for JumpServer Razor and RDS Connection Broker routing.
3. \`0003-rdpdr-drives-and-multimonitor.patch\` — Adds \`WasmDriveBackend\` for MS-RDPEFS drive redirection (\`rdpdr_drives\`, \`rdpdr_request_callback\`, \`rdpdr_response\`, \`rdpdr_add_drive\`, \`rdpdr_remove_drive\`, composing cleanly with audio and printer redirection) and MS-RDPEDISP multi-monitor layout extensions (\`set_monitor_layout\`, \`display_control_caps_callback\`).
4. \`0004-standard-rdp-security.patch\` — Fixes \`ConferenceCreateRequest\` GCC \`connectPDU\` PER length encoding, raises \`ServerSecurityData\` certificate size limits, and adds Standard RDP Security (MS-RDPBCGR 5.3) with 40/56/128-bit RC4 (standard & salted MAC, 4096-packet key update) and FIPS (3DES-EDE3-CBC + HMAC-SHA1) across Slow-Path, Fast-Path, and Deactivation-Reactivation, plus \`security_info_callback\`.
5. \`0005-license-request-fallback-public-key.patch\` — Reuses the server public key from Standard RDP Server Security Data when the Server License Request omits its certificate, for both new and cached license responses.
## Rebuilding
@@ -0,0 +1,537 @@
diff --git a/crates/ironrdp-connector/src/connection.rs b/crates/ironrdp-connector/src/connection.rs
index 35c546e3..3e1329c7 100644
--- a/crates/ironrdp-connector/src/connection.rs
+++ b/crates/ironrdp-connector/src/connection.rs
@@ -491,6 +491,8 @@ pub struct ClientConnector {
pending_standard_security: Option<gcc::ServerSecurityData>,
/// Active Standard RDP Security cipher context once `SecurityExchange` has completed.
standard_rdp_security: Option<StandardRdpSecurity>,
+ /// DER public key retained from the Standard RDP Security exchange for licensing.
+ fallback_server_public_key: Option<Vec<u8>>,
}
impl ClientConnector {
@@ -521,6 +523,7 @@ impl ClientConnector {
license_rng: Arc::new(DefaultLicenseRng),
pending_standard_security: None,
standard_rdp_security: None,
+ fallback_server_public_key: None,
}
}
@@ -1955,6 +1958,14 @@ impl ClientConnector {
)
.map_err(|err| reason_err!("SecurityExchange", "{err}"))?;
+ let certificate = decode::<rdp::server_license::ServerCertificate>(&server_security.server_cert)
+ .map_err(ConnectorError::decode)?;
+ self.fallback_server_public_key = Some(
+ certificate
+ .get_server_security_public_key()
+ .map_err(|err| crate::custom_err!("SecurityExchange", err))?,
+ );
+
info!(
method = ?security.info().encryption_method,
level = ?security.info().encryption_level,
@@ -2016,6 +2027,7 @@ impl ClientConnector {
// the phase. Without a message channel nothing is read and we go
// straight to licensing, as before.
let license_exchange = LicenseExchangeSequence {
+ fallback_server_public_key: self.fallback_server_public_key.take(),
rng: Arc::clone(&self.license_rng),
..LicenseExchangeSequence::new(
io_channel_id,
diff --git a/crates/ironrdp-connector/src/license_exchange.rs b/crates/ironrdp-connector/src/license_exchange.rs
index 3ff98dfa..0f0ca536 100644
--- a/crates/ironrdp-connector/src/license_exchange.rs
+++ b/crates/ironrdp-connector/src/license_exchange.rs
@@ -65,6 +65,8 @@ pub struct LicenseExchangeSequence {
pub hardware_id: [u32; 4],
pub license_cache: Arc<dyn LicenseCache>,
pub rng: Arc<dyn LicenseRng>,
+ /// DER public key from Server Security Data, used only if the license request omits its certificate.
+ pub fallback_server_public_key: Option<Vec<u8>>,
}
// Use RefUnwindSafe so that types that embed LicenseCache remain UnwindSafe
@@ -139,6 +141,7 @@ impl LicenseExchangeSequence {
hardware_id,
license_cache,
rng: Arc::new(DefaultLicenseRng),
+ fallback_server_public_key: None,
}
}
}
@@ -206,6 +209,7 @@ impl Sequence for LicenseExchangeSequence {
if let Some(info) = license_info {
match server_license::ClientLicenseInfo::from_server_license_request(
&license_request,
+ self.fallback_server_public_key.as_deref(),
&client_random,
&premaster_secret,
self.hardware_id,
@@ -237,6 +241,7 @@ impl Sequence for LicenseExchangeSequence {
let hwid = self.hardware_id;
match server_license::ClientNewLicenseRequest::from_server_license_request(
&license_request,
+ self.fallback_server_public_key.as_deref(),
&client_random,
&premaster_secret,
&self.username,
diff --git a/crates/ironrdp-fuzzing/src/oracles/mod.rs b/crates/ironrdp-fuzzing/src/oracles/mod.rs
index 2e2a089b..fcfc8348 100644
--- a/crates/ironrdp-fuzzing/src/oracles/mod.rs
+++ b/crates/ironrdp-fuzzing/src/oracles/mod.rs
@@ -185,6 +185,7 @@ pub fn pdu_decode(data: &[u8]) {
{
let _ = server_license::ClientNewLicenseRequest::from_server_license_request(
&license_request,
+ None,
&[0; 32],
&[0; 48],
"user",
@@ -192,6 +193,7 @@ pub fn pdu_decode(data: &[u8]) {
);
let _ = server_license::ClientLicenseInfo::from_server_license_request(
&license_request,
+ None,
&[0; 32],
&[0; 48],
[0; 4],
diff --git a/crates/ironrdp-pdu/src/rdp/server_license/client_license_info.rs b/crates/ironrdp-pdu/src/rdp/server_license/client_license_info.rs
index 782a6330..6efc617b 100644
--- a/crates/ironrdp-pdu/src/rdp/server_license/client_license_info.rs
+++ b/crates/ironrdp-pdu/src/rdp/server_license/client_license_info.rs
@@ -44,15 +44,17 @@ impl ClientLicenseInfo {
pub fn from_server_license_request(
license_request: &ServerLicenseRequest,
+ fallback_server_public_key: Option<&[u8]>,
client_random: &[u8],
premaster_secret: &[u8],
hardware_data: [u32; 4],
license_info: Vec<u8>,
) -> Result<(Self, LicenseEncryptionData), ServerLicenseError> {
- let public_key = license_request.get_public_key()?
+ let license_public_key = license_request.get_public_key()?;
+ let public_key = license_public_key.as_deref().or(fallback_server_public_key)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData,
"attempted to retrieve the server public key from a server license request message that does not have a certificate"))?;
- let encrypted_premaster_secret = encrypt_with_public_key(premaster_secret, &public_key)?;
+ let encrypted_premaster_secret = encrypt_with_public_key(premaster_secret, public_key)?;
let master_secret = compute_master_secret(
premaster_secret,
diff --git a/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/mod.rs b/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/mod.rs
index 9f0b0d4b..e5e1ed49 100644
--- a/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/mod.rs
+++ b/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/mod.rs
@@ -65,16 +65,18 @@ impl ClientNewLicenseRequest {
pub fn from_server_license_request(
license_request: &ServerLicenseRequest,
+ fallback_server_public_key: Option<&[u8]>,
client_random: &[u8],
premaster_secret: &[u8],
client_username: &str,
client_machine_name: &str,
) -> Result<(Self, LicenseEncryptionData), ServerLicenseError> {
- let public_key = license_request.get_public_key()?
+ let license_public_key = license_request.get_public_key()?;
+ let public_key = license_public_key.as_deref().or(fallback_server_public_key)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData,
"attempted to retrieve the server public key from a server license request message that does not have a certificate"))?;
- let encrypted_premaster_secret = encrypt_with_public_key(premaster_secret, &public_key)?;
+ let encrypted_premaster_secret = encrypt_with_public_key(premaster_secret, public_key)?;
let master_secret = compute_master_secret(
premaster_secret,
diff --git a/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/tests.rs b/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/tests.rs
index ac8eb9cd..ad8158dd 100644
--- a/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/tests.rs
+++ b/crates/ironrdp-pdu/src/rdp/server_license/client_new_license_request/tests.rs
@@ -325,6 +325,7 @@ fn client_new_license_request_creates_correctly() {
LicensePdu::ServerLicenseRequest(license_request) => {
let (client_new_license_request, encryption_data) = ClientNewLicenseRequest::from_server_license_request(
license_request,
+ None,
CLIENT_RANDOM_BUFFER.as_ref(),
PREMASTER_SECRET_BUFFER.as_ref(),
CLIENT_USERNAME,
diff --git a/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/mod.rs b/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/mod.rs
index 7b8bdbc8..b30b1cb4 100644
--- a/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/mod.rs
+++ b/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/mod.rs
@@ -218,6 +218,25 @@ impl ServerCertificate {
const FIXED_PART_SIZE: usize = CERT_VERSION_FIELD_SIZE;
+ /// Extracts the DER public key from a Server Security Data certificate.
+ pub fn get_server_security_public_key(&self) -> Result<Vec<u8>, ServerLicenseError> {
+ use pkcs1::der::Encode as _;
+
+ if let CertificateType::Proprietary(certificate) = &self.certificate {
+ // MCS proprietary RSA integers are little-endian and the modulus includes eight padding bytes.
+ let mut modulus = certificate.public_key.modulus.clone();
+ modulus.truncate(modulus.len().saturating_sub(8));
+ modulus.reverse();
+ let public_exponent = certificate.public_key.public_exponent.to_be_bytes();
+ return Ok(pkcs1::RsaPublicKey {
+ modulus: pkcs1::UintRef::new(&modulus)?,
+ public_exponent: pkcs1::UintRef::new(&public_exponent)?,
+ }
+ .to_der()?);
+ }
+ self.get_public_key()
+ }
+
pub fn get_public_key(&self) -> Result<Vec<u8>, ServerLicenseError> {
use pkcs1::der::Encode as _;
use x509_cert::der::Decode as _;
diff --git a/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/tests.rs b/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/tests.rs
index c5aa22ab..1189f75c 100644
--- a/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/tests.rs
+++ b/crates/ironrdp-pdu/src/rdp/server_license/server_license_request/tests.rs
@@ -638,3 +638,202 @@ fn buffer_length_is_correct_for_x509_certificate_chain() {
assert_eq!(CERT_CHAIN.size(), chain_buffer.len());
}
+
+// oracle: regression Netcatty #4540; encryption is raw RSA with little-endian premaster and eight padding bytes.
+#[test]
+fn license_responses_reuse_the_fallback_public_key_without_a_certificate() {
+ use crate::rdp::server_license::{ClientLicenseInfo, ClientNewLicenseRequest};
+
+ let LicensePdu::ServerLicenseRequest(mut request) =
+ decode::<LicensePdu>(&encode_vec(&*SERVER_LICENSE_REQUEST).unwrap()).unwrap()
+ else {
+ panic!("expected a Server License Request");
+ };
+ let public_key = request.get_public_key().unwrap().unwrap();
+ request.server_certificate = None;
+ // RSA maps the integer one to one for any valid key, so this checks ciphertext independently of the encryptor.
+ let mut premaster = [0; 48];
+ premaster[0] = 1;
+ let mut expected_ciphertext = vec![0; 256 + 8];
+ expected_ciphertext[0] = 1;
+
+ let (new_request, _) = ClientNewLicenseRequest::from_server_license_request(
+ &request,
+ Some(&public_key),
+ &[0x11; 32],
+ &premaster,
+ "user",
+ "machine",
+ )
+ .unwrap();
+ assert_eq!(new_request.encrypted_premaster_secret, expected_ciphertext);
+ let (info, _) = ClientLicenseInfo::from_server_license_request(
+ &request,
+ Some(&public_key),
+ &[0x11; 32],
+ &premaster,
+ [0; 4],
+ vec![0x33; 16],
+ )
+ .unwrap();
+ assert_eq!(info.encrypted_premaster_secret, expected_ciphertext);
+}
+
+// oracle: regression Netcatty #4540; absence of both keys retains the existing missing-certificate error.
+#[test]
+fn license_responses_without_a_certificate_or_fallback_still_fail() {
+ use crate::rdp::server_license::{ClientLicenseInfo, ClientNewLicenseRequest};
+
+ let LicensePdu::ServerLicenseRequest(mut request) =
+ decode::<LicensePdu>(&encode_vec(&*SERVER_LICENSE_REQUEST).unwrap()).unwrap()
+ else {
+ panic!("expected a Server License Request");
+ };
+ request.server_certificate = None;
+ let error = "IO error: attempted to retrieve the server public key from a server license request message that does not have a certificate";
+ assert_eq!(
+ ClientNewLicenseRequest::from_server_license_request(
+ &request,
+ None,
+ &[0x11; 32],
+ &[0x22; 48],
+ "user",
+ "machine",
+ )
+ .unwrap_err()
+ .to_string(),
+ error
+ );
+ assert_eq!(
+ ClientLicenseInfo::from_server_license_request(
+ &request,
+ None,
+ &[0x11; 32],
+ &[0x22; 48],
+ [0; 4],
+ vec![0x33; 16],
+ )
+ .unwrap_err()
+ .to_string(),
+ error
+ );
+}
+
+// oracle: regression Netcatty #4540; the license certificate takes precedence over a fallback key.
+#[test]
+fn license_responses_ignore_fallback_when_the_license_certificate_is_present() {
+ use crate::rdp::server_license::{ClientLicenseInfo, ClientNewLicenseRequest};
+
+ let LicensePdu::ServerLicenseRequest(request) = &*SERVER_LICENSE_REQUEST else {
+ panic!("expected a Server License Request");
+ };
+ // An invalid fallback would fail DER decoding if it were used.
+ assert!(
+ ClientNewLicenseRequest::from_server_license_request(
+ request,
+ Some(&[0]),
+ &[0x11; 32],
+ &[0x22; 48],
+ "user",
+ "machine",
+ )
+ .is_ok()
+ );
+ assert!(
+ ClientLicenseInfo::from_server_license_request(
+ request,
+ Some(&[0]),
+ &[0x11; 32],
+ &[0x22; 48],
+ [0; 4],
+ vec![0x33; 16],
+ )
+ .is_ok()
+ );
+}
+
+// oracle: regression Netcatty #4540; a malformed license certificate must not trigger fallback.
+#[test]
+fn license_responses_do_not_hide_invalid_certificates_with_the_fallback() {
+ use crate::rdp::server_license::{ClientLicenseInfo, ClientNewLicenseRequest};
+
+ let LicensePdu::ServerLicenseRequest(mut request) =
+ decode::<LicensePdu>(&encode_vec(&*SERVER_LICENSE_REQUEST).unwrap()).unwrap()
+ else {
+ panic!("expected a Server License Request");
+ };
+ let public_key = request.get_public_key().unwrap().unwrap();
+ request.server_certificate = Some(ServerCertificate {
+ issued_permanently: true,
+ certificate: CertificateType::X509(X509CertificateChain {
+ certificate_array: vec![vec![0]],
+ }),
+ });
+ assert!(matches!(
+ ClientNewLicenseRequest::from_server_license_request(
+ &request,
+ Some(&public_key),
+ &[0x11; 32],
+ &[0x22; 48],
+ "user",
+ "machine",
+ ),
+ Err(ServerLicenseError::InvalidX509Certificate { .. })
+ ));
+ assert!(matches!(
+ ClientLicenseInfo::from_server_license_request(
+ &request,
+ Some(&public_key),
+ &[0x11; 32],
+ &[0x22; 48],
+ [0; 4],
+ vec![0x33; 16],
+ ),
+ Err(ServerLicenseError::InvalidX509Certificate { .. })
+ ));
+}
+
+// oracle: regression Netcatty #4540; Python pow(int.from_bytes([0x22] * 48, "little"), 65537, n),
+// with n from the proprietary MCS certificate's little-endian modulus (MS-RDPBCGR 4.1.4).
+#[test]
+fn license_fallback_preserves_the_proprietary_mcs_public_key() {
+ use crate::rdp::server_license::{ClientLicenseInfo, ClientNewLicenseRequest};
+
+ let certificate = ServerCertificate {
+ issued_permanently: true,
+ certificate: CertificateType::Proprietary(decode(&encode_vec(&*PROPRIETARY_CERTIFICATE).unwrap()).unwrap()),
+ };
+ let public_key = certificate.get_server_security_public_key().unwrap();
+ let LicensePdu::ServerLicenseRequest(mut request) =
+ decode::<LicensePdu>(&encode_vec(&*SERVER_LICENSE_REQUEST).unwrap()).unwrap()
+ else {
+ panic!("expected a Server License Request");
+ };
+ request.server_certificate = None;
+ let expected_ciphertext = [
+ 0x97, 0xc6, 0x48, 0x9e, 0x02, 0x1c, 0x44, 0xb2, 0x67, 0x54, 0xd4, 0xbe, 0x10, 0x5a, 0x13, 0xfa, 0x9b, 0x02,
+ 0xc9, 0x65, 0xcf, 0xfe, 0x2b, 0x2f, 0x4d, 0xe2, 0x06, 0xee, 0x7c, 0xeb, 0x58, 0x4c, 0xef, 0x70, 0xc8, 0x06,
+ 0xad, 0x9b, 0xa2, 0x23, 0x4c, 0xd0, 0xe0, 0xa4, 0x34, 0x90, 0x90, 0xdc, 0xd5, 0x13, 0x85, 0x4d, 0x75, 0x25,
+ 0x62, 0x14, 0x4d, 0x66, 0x9f, 0xd6, 0x41, 0xb3, 0x2b, 0xa8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ ];
+ let (new_request, _) = ClientNewLicenseRequest::from_server_license_request(
+ &request,
+ Some(&public_key),
+ &[0x11; 32],
+ &[0x22; 48],
+ "user",
+ "machine",
+ )
+ .unwrap();
+ assert_eq!(new_request.encrypted_premaster_secret, expected_ciphertext);
+ let (info, _) = ClientLicenseInfo::from_server_license_request(
+ &request,
+ Some(&public_key),
+ &[0x11; 32],
+ &[0x22; 48],
+ [0; 4],
+ vec![0x33; 16],
+ )
+ .unwrap();
+ assert_eq!(info.encrypted_premaster_secret, expected_ciphertext);
+}
diff --git a/crates/ironrdp-testsuite-core/tests/connector/license_exchange.rs b/crates/ironrdp-testsuite-core/tests/connector/license_exchange.rs
index bb5022e3..5d6c4caf 100644
--- a/crates/ironrdp-testsuite-core/tests/connector/license_exchange.rs
+++ b/crates/ironrdp-testsuite-core/tests/connector/license_exchange.rs
@@ -52,10 +52,17 @@ impl LicenseCache for StoredLicense {
}
/// Enters the licensing exchange and answers a Server License Request.
-fn answer_license_request(mut connector: ClientConnector) -> (Vec<u8>, LicenseEncryptionData) {
+fn answer_license_request(connector: ClientConnector) -> (Vec<u8>, LicenseEncryptionData) {
+ answer_license_request_with_certificate(connector, true)
+}
+
+fn answer_license_request_with_certificate(
+ mut connector: ClientConnector,
+ include_certificate: bool,
+) -> (Vec<u8>, LicenseEncryptionData) {
// A Server License Request on the I/O channel, carrying a proprietary certificate with a 512-bit key.
let server_license_request = {
- let license = LicensePdu::ServerLicenseRequest(ServerLicenseRequest {
+ let mut request = ServerLicenseRequest {
license_header: LicenseHeader {
security_header: BasicSecurityHeader {
flags: BasicSecurityHeaderFlags::LICENSE_PKT,
@@ -83,7 +90,11 @@ fn answer_license_request(mut connector: ClientConnector) -> (Vec<u8>, LicenseEn
}),
// The connector looks a license up once per scope, so a stored license needs one to be found.
scope_list: vec![Scope("microsoft.com".to_owned())],
- });
+ };
+ if !include_certificate {
+ request.server_certificate = None;
+ }
+ let license = LicensePdu::ServerLicenseRequest(request);
encode_vec(&X224(McsMessage::SendDataIndication(SendDataIndication {
initiator_id: USER_CHANNEL_ID,
@@ -208,3 +219,80 @@ fn each_connection_gets_new_values_from_the_default_rng() {
second_encryption_data.premaster_secret
);
}
+
+// oracle: regression Netcatty #4540; MCS carries the key that an encrypted session's license request may omit.
+#[rstest::rstest]
+#[case::new_license(false)]
+#[case::cached_license(true)]
+fn licensing_reuses_the_standard_security_public_key(#[case] cached_license: bool) {
+ use ironrdp_pdu::gcc::{ConferenceCreateResponse, EncryptionLevel, EncryptionMethod, ServerSecurityData};
+ use ironrdp_pdu::mcs::ConnectResponse;
+ use ironrdp_pdu::nego::SecurityProtocol;
+ use ironrdp_pdu::x224::X224Data;
+ use ironrdp_testsuite_core::{gcc::SERVER_GCC_WITHOUT_OPTIONAL_FIELDS, mcs::CONNECT_RESPONSE};
+
+ let mut connector = connector();
+ connector.config.enable_standard_rdp_security = true;
+ if cached_license {
+ connector.config.license_cache = Some(Arc::new(StoredLicense(vec![0x33; 16])));
+ }
+ connector.state = ClientConnectorState::BasicSettingsExchangeSendInitial {
+ selected_protocol: SecurityProtocol::empty(),
+ };
+ let mut output = WriteBuf::new();
+ connector.step(&[], None, &mut output).unwrap();
+ output.clear();
+
+ let certificate = ServerCertificate {
+ issued_permanently: true,
+ certificate: CertificateType::Proprietary(ProprietaryCertificate {
+ public_key: RsaPublicKey {
+ public_exponent: 0x0001_0001,
+ modulus: [vec![0xff; 64], vec![0; 8]].concat(),
+ },
+ signature: vec![0; 72],
+ }),
+ };
+ let mut gcc_blocks = SERVER_GCC_WITHOUT_OPTIONAL_FIELDS.clone();
+ gcc_blocks.security = ServerSecurityData {
+ encryption_method: EncryptionMethod::BIT_128,
+ encryption_level: EncryptionLevel::ClientCompatible,
+ server_random: Some([0x44; 32]),
+ server_cert: encode_vec(&certificate).unwrap(),
+ };
+ let response = ConnectResponse {
+ conference_create_response: ConferenceCreateResponse::new(0x79f3, gcc_blocks).unwrap(),
+ ..CONNECT_RESPONSE.clone()
+ };
+ let response = encode_vec(&X224(X224Data {
+ data: Cow::Owned(encode_vec(&response).unwrap()),
+ }))
+ .unwrap();
+ connector.step(&response, None, &mut output).unwrap();
+
+ // Channel joins carry no security data; enter Security Exchange with the MCS data just received.
+ connector.state = ClientConnectorState::SecurityExchange {
+ io_channel_id: IO_CHANNEL_ID,
+ user_channel_id: USER_CHANNEL_ID,
+ };
+ connector.step(&[], None, &mut output).unwrap();
+ let (response, _) = answer_license_request_with_certificate(connector, false);
+ let mut cursor = ReadCursor::new(&response);
+ let header = LicenseHeader::decode(&mut cursor).unwrap();
+ let encrypted_premaster = match header.preamble_message_type {
+ PreambleType::NewLicenseRequest => {
+ assert!(!cached_license);
+ ClientNewLicenseRequest::decode(header, &mut cursor)
+ .unwrap()
+ .encrypted_premaster_secret
+ }
+ PreambleType::LicenseInfo => {
+ assert!(cached_license);
+ ironrdp_pdu::rdp::server_license::ClientLicenseInfo::decode(header, &mut cursor)
+ .unwrap()
+ .encrypted_premaster_secret
+ }
+ _ => panic!("expected a client licensing response"),
+ };
+ assert_eq!(encrypted_premaster.len(), 64 + 8);
+}
diff --git a/crates/ironrdp-testsuite-core/tests/pdu/server_license.rs b/crates/ironrdp-testsuite-core/tests/pdu/server_license.rs
index 59b6b05c..04aff362 100644
--- a/crates/ironrdp-testsuite-core/tests/pdu/server_license.rs
+++ b/crates/ironrdp-testsuite-core/tests/pdu/server_license.rs
@@ -35,6 +35,7 @@ impl LicenseResponse {
match self {
Self::NewLicenseRequest => ClientNewLicenseRequest::from_server_license_request(
license_request,
+ None,
&client_random,
&premaster_secret,
"user",
@@ -43,6 +44,7 @@ impl LicenseResponse {
.is_ok(),
Self::LicenseInfo => ClientLicenseInfo::from_server_license_request(
license_request,
+ None,
&client_random,
&premaster_secret,
[0; 4],
+1
View File
@@ -170,6 +170,7 @@ declare global {
writeClipboardText?(text: string): Promise<boolean>;
readClipboardFiles?(): Promise<Array<{ path: string; name: string; isDirectory: boolean; size?: number }>>;
readClipboardImage?(): Promise<{ path: string; name: string; mediaType: string; size?: number } | null>;
readClipboardImagePng?(): Promise<Uint8Array | null>;
hasClipboardImage?(): Promise<boolean>;
// Credential encryption (field-level safeStorage for sensitive data at rest)