mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-26 19:07:17 +00:00
Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e94f937570 | ||
|
|
1595d2ed62 | ||
|
|
f4a087e890 | ||
|
|
ac8869884f | ||
|
|
d556e5c5de | ||
|
|
3026be2dc9 | ||
|
|
883fdaf114 |
No files matched your search
@@ -7,12 +7,20 @@ test('plugin theme tokens come from the themed app surface style', () => {
|
||||
assert.deepEqual(selectPluginThemeTokens({
|
||||
'--background': '220 10% 10%',
|
||||
'--foreground': '0 0% 98%',
|
||||
'--card': '220 10% 12%',
|
||||
'--primary': '210 90% 55%',
|
||||
'--destructive': '0 84% 60%',
|
||||
'--radius': '0.5rem',
|
||||
'--font-mono': '"JetBrains Mono", monospace',
|
||||
colorScheme: 'dark',
|
||||
'--unknown-plugin-token': 'ignored',
|
||||
}), {
|
||||
'--background': '220 10% 10%',
|
||||
'--foreground': '0 0% 98%',
|
||||
'--card': '220 10% 12%',
|
||||
'--primary': '210 90% 55%',
|
||||
'--destructive': '0 84% 60%',
|
||||
'--radius': '0.5rem',
|
||||
'--font-mono': '"JetBrains Mono", monospace',
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,26 @@
|
||||
export const PLUGIN_THEME_TOKEN_NAMES = Object.freeze([
|
||||
'--background',
|
||||
'--foreground',
|
||||
'--muted',
|
||||
'--muted-foreground',
|
||||
'--border',
|
||||
'--card',
|
||||
'--card-foreground',
|
||||
'--popover',
|
||||
'--popover-foreground',
|
||||
'--primary',
|
||||
'--primary-foreground',
|
||||
'--secondary',
|
||||
'--secondary-foreground',
|
||||
'--muted',
|
||||
'--muted-foreground',
|
||||
'--accent',
|
||||
'--accent-foreground',
|
||||
'--destructive',
|
||||
'--destructive-foreground',
|
||||
'--border',
|
||||
'--input',
|
||||
'--ring',
|
||||
'--radius',
|
||||
'--font-sans',
|
||||
'--font-mono',
|
||||
] as const);
|
||||
|
||||
export function selectPluginThemeTokens(
|
||||
|
||||
@@ -38,14 +38,23 @@ export class PluginViewSessions {
|
||||
void bridge.openHostDrawnPluginView({ ...request, instanceId: id }).then(() => {
|
||||
if (disposed) void bridge.closeHostDrawnPluginView?.(id).catch(() => {});
|
||||
}).catch(() => dispose(true));
|
||||
const imageCache = new Map<string, Promise<string>>();
|
||||
return {
|
||||
viewId: request.viewId,
|
||||
scope: request.scopeId,
|
||||
image: async (path: string) => {
|
||||
if (disposed || !bridge.getPluginViewResource) throw new Error('Plugin image unavailable');
|
||||
const result = await bridge.getPluginViewResource({ instanceId: id, path });
|
||||
if (disposed) throw new Error('Plugin view closed');
|
||||
return result.url;
|
||||
image: (path: string) => {
|
||||
if (disposed || !bridge.getPluginViewResource) return Promise.reject(new Error('Plugin image unavailable'));
|
||||
const existing = imageCache.get(path);
|
||||
if (existing) return existing;
|
||||
const pending = bridge.getPluginViewResource({ instanceId: id, path }).then((result) => {
|
||||
if (disposed) throw new Error('Plugin view closed');
|
||||
return result.url;
|
||||
}).catch((error) => {
|
||||
if (imageCache.get(path) === pending) imageCache.delete(path);
|
||||
throw error;
|
||||
});
|
||||
imageCache.set(path, pending);
|
||||
return pending;
|
||||
},
|
||||
get idle() { return users === 0; },
|
||||
getSnapshot: () => state,
|
||||
|
||||
@@ -15,6 +15,8 @@ export type ChainProgress = {
|
||||
currentHop: number;
|
||||
totalHops: number;
|
||||
currentHostLabel: string;
|
||||
/** host:port of the hop being connected; absent from older progress events. */
|
||||
currentHostAddress?: string;
|
||||
connectionPhase: string;
|
||||
} | null;
|
||||
|
||||
@@ -117,13 +119,14 @@ export function useHostConnectionTest(input: HostConnectionTestInput) {
|
||||
|
||||
// Subscribe to chain progress for the active attempt.
|
||||
useEffect(() => {
|
||||
const unsub = backend.onChainProgress?.((sessionId, hop, total, label, phase, phaseError) => {
|
||||
const unsub = backend.onChainProgress?.((sessionId, hop, total, label, phase, phaseError, address) => {
|
||||
if (sessionId !== sessionIdRef.current) return;
|
||||
if (total > 1) {
|
||||
setChainProgress({
|
||||
currentHop: hop,
|
||||
totalHops: total,
|
||||
currentHostLabel: label,
|
||||
currentHostAddress: address,
|
||||
connectionPhase: phase,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -24,9 +24,17 @@ type Review = {
|
||||
completionToken?: string;
|
||||
};
|
||||
|
||||
function isHostActionRequestKind(kind: string): boolean {
|
||||
return kind.startsWith('vault.')
|
||||
|| kind === 'network.stream.connectViaHost'
|
||||
|| kind === 'network.stream.confirm'
|
||||
|| kind === 'network.stream.tlsConfirm';
|
||||
}
|
||||
|
||||
export function usePluginHostActions() {
|
||||
const [review, setReview] = useState<Review | null>(null);
|
||||
const [selectedIds, setSelectedIds] = useState<string[]>([]);
|
||||
const [remember, setRemember] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
const current = useRef<Review | null>(null);
|
||||
@@ -44,9 +52,19 @@ export function usePluginHostActions() {
|
||||
|
||||
const assertCurrent = useCallback((entry: Review) => {
|
||||
if (current.current !== entry || Date.now() >= entry.prompt.expiresAt) throw new Error('Host action expired');
|
||||
if (entry.prompt.request.kind === 'network.stream.confirm' || entry.prompt.request.kind === 'network.stream.tlsConfirm') {
|
||||
const lock = getAppAppLockRuntime();
|
||||
if (lock && lock.initialized && lock.locked) throw new Error('App is locked');
|
||||
return;
|
||||
}
|
||||
const vault = getVault();
|
||||
const target = entry.prompt.vaultTarget;
|
||||
if (target && resources.current.resolve(target.resourceId, target.revision) !== entry.host) throw new Error('Selected host changed');
|
||||
if (entry.prompt.durableHostId) {
|
||||
const liveHost = vault.hosts.find((candidate) => candidate.id === entry.prompt.durableHostId);
|
||||
if (!liveHost || liveHost !== entry.host) throw new Error('Saved SSH host changed or was removed');
|
||||
} else if (target && resources.current.resolve(target.resourceId, target.revision) !== entry.host) {
|
||||
throw new Error('Selected host changed');
|
||||
}
|
||||
if ((entry.prompt.request.kind === 'vault.requestConnect' || entry.prompt.request.kind === 'network.stream.connectViaHost') && (vault.groupConfigs !== entry.groups || vault.snippets !== entry.snippets)) {
|
||||
throw new Error('Saved connection settings changed');
|
||||
}
|
||||
@@ -71,7 +89,7 @@ export function usePluginHostActions() {
|
||||
assertCurrent(entry);
|
||||
const request = entry.prompt.request;
|
||||
const target = entry.prompt.vaultTarget;
|
||||
if (request.kind === 'network.stream.connectViaHost' && target && entry.host) {
|
||||
if (request.kind === 'network.stream.connectViaHost' && entry.host && (target || entry.prompt.durableHostId)) {
|
||||
const vault = getVault();
|
||||
const settings = getAppSettingsRuntime();
|
||||
if (!settings || !bridge.openPluginHostStream) throw new Error('Host stream unavailable');
|
||||
@@ -83,7 +101,15 @@ export function usePluginHostActions() {
|
||||
|| latest.hosts !== vault.hosts || latest.knownHosts !== vault.knownHosts || getAppSettingsRuntime()?.terminalSettings !== settings.terminalSettings) throw new Error('Connection settings changed');
|
||||
};
|
||||
assertPrepared();
|
||||
await executePluginHostAction({ kind: 'connect', target }, {
|
||||
if (entry.prompt.durableHostId) {
|
||||
entry.claimed = true;
|
||||
await bridge.openPluginHostStream!({
|
||||
response: { requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action: 'commit' },
|
||||
connectionOptions,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await executePluginHostAction({ kind: 'connect', target: target! }, {
|
||||
getVault, resources: resources.current, assertCurrent: assertPrepared,
|
||||
authorizeCommit: async () => { assertPrepared(); },
|
||||
connect: async () => {
|
||||
@@ -126,12 +152,35 @@ export function usePluginHostActions() {
|
||||
const unsubscribe = bridge.onPluginInteraction((event) => {
|
||||
if ('closed' in event) {
|
||||
if (current.current?.prompt.requestId !== event.requestId) return;
|
||||
current.current = null; setReview(null); setBusy(false); responding.current = false;
|
||||
current.current = null; setReview(null); setRemember(false); setBusy(false); responding.current = false;
|
||||
return;
|
||||
}
|
||||
if (!event.request.kind.startsWith('vault.') && event.request.kind !== 'network.stream.connectViaHost') return;
|
||||
if (!isHostActionRequestKind(event.request.kind)) return;
|
||||
const prompt = event as VaultHostPrompt;
|
||||
try {
|
||||
if (prompt.request.kind === 'network.stream.confirm' || prompt.request.kind === 'network.stream.tlsConfirm') {
|
||||
const entry: Review = {
|
||||
prompt, candidates: [], candidateRevisions: new Map(), customGroups: [],
|
||||
groups: [], snippets: [], managedSources: [], scriptsRun: false, claimed: false,
|
||||
};
|
||||
current.current = entry; setSelectedIds([]); setRemember(false); setBusy(false); setError(false); responding.current = false;
|
||||
setReview(entry);
|
||||
return;
|
||||
}
|
||||
if (prompt.phase === 'commit' && prompt.autoCommit && prompt.durableHostId && prompt.request.kind === 'network.stream.connectViaHost') {
|
||||
const vault = getVault();
|
||||
const host = vault.hosts.find((candidate) => candidate.id === prompt.durableHostId);
|
||||
if (!host) throw new Error('Saved SSH host no longer exists');
|
||||
const entry: Review = {
|
||||
prompt, candidates: [], candidateRevisions: new Map(), customGroups: vault.customGroups,
|
||||
host, groups: vault.groupConfigs, snippets: vault.snippets, managedSources: vault.managedSources,
|
||||
scriptsRun: false, claimed: false,
|
||||
};
|
||||
current.current = entry; setSelectedIds([]); setRemember(false); setBusy(true); setError(false); responding.current = false;
|
||||
setReview(null);
|
||||
void execute(entry);
|
||||
return;
|
||||
}
|
||||
if (prompt.phase === 'commit') {
|
||||
const entry = current.current;
|
||||
if (!entry || entry.prompt.requestId !== prompt.requestId || entry.prompt.request.kind !== prompt.request.kind) throw new Error('Host review is unavailable');
|
||||
@@ -150,7 +199,10 @@ export function usePluginHostActions() {
|
||||
scriptsRun: host ? pluginHostRunsSavedScripts(host, vault.groupConfigs, vault.snippets) : false,
|
||||
claimed: false,
|
||||
};
|
||||
current.current = entry; setSelectedIds([]); setBusy(false); setError(false); responding.current = false;
|
||||
const defaultRemember = prompt.request.kind === 'network.stream.connectViaHost'
|
||||
&& 'durable' in prompt.request
|
||||
&& prompt.request.durable === true;
|
||||
current.current = entry; setSelectedIds([]); setRemember(defaultRemember); setBusy(false); setError(false); responding.current = false;
|
||||
if (prompt.request.kind === 'vault.requestConnect' && prompt.permissionMode === 'allow') {
|
||||
setReview(null);
|
||||
void bridge.respondPluginInteraction?.({ requestId: prompt.requestId, actionToken: prompt.actionToken,
|
||||
@@ -168,7 +220,7 @@ export function usePluginHostActions() {
|
||||
};
|
||||
}, [execute, fail, getVault]);
|
||||
|
||||
const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields) => {
|
||||
const respond = useCallback(async (action: 'cancel' | 'submit', draft?: PluginHostDraftFields, rememberOverride?: boolean) => {
|
||||
const entry = current.current;
|
||||
if (!entry || responding.current || (action === 'cancel' && entry.claimed)) return;
|
||||
responding.current = true; setBusy(true); setError(false);
|
||||
@@ -181,17 +233,24 @@ export function usePluginHostActions() {
|
||||
resources.current.resolve(id, revision);
|
||||
return resources.current.metadata(id);
|
||||
}) : undefined;
|
||||
const includeRemember = action === 'submit' && (
|
||||
request.kind === 'network.stream.connectViaHost'
|
||||
|| request.kind === 'network.stream.confirm'
|
||||
|| request.kind === 'network.stream.tlsConfirm'
|
||||
);
|
||||
const effectiveRemember = rememberOverride ?? remember;
|
||||
await netcattyBridge.require().respondPluginInteraction?.({
|
||||
requestId: entry.prompt.requestId, actionToken: entry.prompt.actionToken, action,
|
||||
...(selected === undefined ? {} : { resources: selected }),
|
||||
...(draft === undefined ? {} : { draft }),
|
||||
...(request.kind === 'vault.requestConnect' && action === 'submit' ? { scriptsRun: entry.scriptsRun } : {}),
|
||||
...(includeRemember && effectiveRemember ? { remember: true } : {}),
|
||||
});
|
||||
} catch { await fail(entry); }
|
||||
finally {
|
||||
if (current.current === entry && entry.prompt.phase === 'request') { responding.current = false; setBusy(false); }
|
||||
}
|
||||
}, [assertCurrent, fail, selectedIds]);
|
||||
}, [assertCurrent, fail, remember, selectedIds]);
|
||||
|
||||
return { review, selectedIds, setSelectedIds, busy, error, respond };
|
||||
return { review, selectedIds, setSelectedIds, remember, setRemember, busy, error, respond };
|
||||
}
|
||||
@@ -419,7 +419,7 @@ export const useTerminalBackend = () => {
|
||||
return bridge.getTelnetEchoMode(sessionId);
|
||||
}, []);
|
||||
|
||||
const onChainProgress = useCallback((cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string) => void) => {
|
||||
const onChainProgress = useCallback((cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string, address?: string) => void) => {
|
||||
const bridge = netcattyBridge.get();
|
||||
return bridge?.onChainProgress?.(cb);
|
||||
}, []);
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import React from 'react';
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
|
||||
import { I18nProvider } from '../application/i18n/I18nProvider';
|
||||
import type { Host } from '../domain/models';
|
||||
import HostDetailsPanel from './HostDetailsPanel';
|
||||
import { HostDetailsConnectionSections } from './HostDetailsConnectionSections';
|
||||
import { LocalShellHostDetailsPanel } from './LocalShellHostDetailsPanel';
|
||||
import { SerialHostDetailsPanel } from './SerialHostDetailsPanel';
|
||||
import { installDomEnvironment } from './test-support/renderReactDom';
|
||||
import { AsidePanelFooter } from './ui/aside-panel';
|
||||
import { Button } from './ui/button';
|
||||
import { Combobox } from './ui/combobox';
|
||||
import { Input } from './ui/input';
|
||||
import { TooltipProvider } from './ui/tooltip';
|
||||
|
||||
type PanelKind = 'ssh' | 'local' | 'serial';
|
||||
const host: Host = {
|
||||
id: 'existing', label: 'Web', hostname: 'web.example.com', username: 'root',
|
||||
password: 'test-password', authMethod: 'password', tags: [], os: 'linux',
|
||||
protocol: 'ssh', group: 'prod / web',
|
||||
};
|
||||
|
||||
async function withPanel(
|
||||
kind: PanelKind,
|
||||
initialData: Host | undefined,
|
||||
run: (editor: {
|
||||
renderer: ReactTestRenderer;
|
||||
save: () => Promise<Host>;
|
||||
created: string[];
|
||||
}) => Promise<void>,
|
||||
groups: string[] = [],
|
||||
) {
|
||||
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);
|
||||
let renderer: ReactTestRenderer | undefined;
|
||||
let saved: Host | undefined;
|
||||
const created: string[] = [];
|
||||
const common = { onSave: (value: Host) => { saved = value; }, onCancel() {}, groups, layout: 'inline' as const };
|
||||
try {
|
||||
await act(async () => {
|
||||
renderer = create(<I18nProvider locale="en"><TooltipProvider>
|
||||
{kind === 'ssh' ? <HostDetailsPanel {...common} initialData={initialData}
|
||||
availableKeys={[]} identities={[]} terminalThemeId="default" terminalFontSize={14}
|
||||
onCreateGroup={(path) => created.push(path)} />
|
||||
: kind === 'local' ? <LocalShellHostDetailsPanel {...common} initialData={initialData} />
|
||||
: <SerialHostDetailsPanel {...common} initialData={initialData!} />}
|
||||
</TooltipProvider></I18nProvider>);
|
||||
});
|
||||
await run({
|
||||
renderer: renderer!, created,
|
||||
save: async () => {
|
||||
saved = undefined;
|
||||
await act(async () => {
|
||||
const buttons = renderer!.root.findByType(AsidePanelFooter).findAllByType(Button);
|
||||
await buttons[buttons.length - 1].props.onClick();
|
||||
});
|
||||
assert.ok(saved, 'the panel must call onSave');
|
||||
return saved;
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
if (renderer) await act(async () => { renderer!.unmount(); });
|
||||
globalThis.requestAnimationFrame = previousRaf;
|
||||
globalThis.cancelAnimationFrame = previousCancelRaf;
|
||||
dom.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
function groupPicker(renderer: ReactTestRenderer, kind: PanelKind) {
|
||||
return renderer.root.findAllByType(Combobox).find((picker) =>
|
||||
kind === 'ssh' ? picker.props.createText === 'Create Group' : picker.props.placeholder === 'Select Group',
|
||||
)!;
|
||||
}
|
||||
|
||||
for (const kind of ['ssh', 'local', 'serial'] as const) {
|
||||
const initialData = { ...host, protocol: kind, ...(kind === 'serial' ? { hostname: 'COM3' } : {}) };
|
||||
test(`${kind} Host Details keeps the exact stored group on a label-only edit`, async () => {
|
||||
for (const group of ['prod / web', ' prod / web ', ' prod/web ']) {
|
||||
await withPanel(kind, { ...initialData, group }, async ({ renderer, save }) => {
|
||||
await act(async () => {
|
||||
renderer.root.findAllByType(Input).find((input) => input.props.value === host.label)!
|
||||
.props.onChange({ target: { value: 'Updated label' } });
|
||||
});
|
||||
const saved = await save();
|
||||
assert.equal(saved.label, 'Updated label');
|
||||
assert.equal(saved.group, group);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test(`${kind} Host Details normalizes an explicitly selected trimmed-equivalent group`, async () => {
|
||||
for (const group of [' prod/web ', ' prod / web ']) {
|
||||
await withPanel(kind, { ...initialData, group }, async ({ renderer, save }) => {
|
||||
await act(async () => { groupPicker(renderer, kind).props.onValueChange(group.trim()); });
|
||||
assert.equal((await save()).group, 'prod/web');
|
||||
}, [group.trim()]);
|
||||
}
|
||||
});
|
||||
|
||||
test(`${kind} Host Details normalizes a changed group and allows clearing it`, async () => {
|
||||
await withPanel(kind, initialData, async ({ renderer, save }) => {
|
||||
const picker = groupPicker(renderer, kind);
|
||||
await act(async () => { picker.props.onValueChange(host.group); });
|
||||
assert.equal((await save()).group, host.group, 'reselecting the original group preserves it');
|
||||
for (const [value, expected] of [[' stage / / web ', 'stage/web'], ['', '']]) {
|
||||
await act(async () => { picker.props.onValueChange(value); });
|
||||
assert.equal((await save()).group, expected);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
for (const kind of ['ssh', 'local'] as const) {
|
||||
test(`${kind} Host Details normalizes a new host's group`, async () => {
|
||||
await withPanel(kind, undefined, async ({ renderer, save }) => {
|
||||
await act(async () => {
|
||||
if (kind === 'ssh') {
|
||||
const { update } = renderer.root.findByType(HostDetailsConnectionSections).props;
|
||||
update('hostname', 'web.example.com');
|
||||
update('password', 'test-password');
|
||||
}
|
||||
groupPicker(renderer, kind).props.onValueChange('prod / web');
|
||||
});
|
||||
assert.equal((await save()).group, 'prod/web');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test('Create Group normalizes paths before creation and selection, including the Combobox follow-up', async () => {
|
||||
const values = ['prod / web', 'prod//web', 'prod\\web', ' prod / web ', '/ prod / / web //'];
|
||||
for (const groups of [[], ['prod/web']]) {
|
||||
await withPanel('ssh', host, async ({ renderer, save, created }) => {
|
||||
for (const value of values) {
|
||||
const picker = groupPicker(renderer, 'ssh');
|
||||
await act(async () => { picker.props.onCreateNew(value); });
|
||||
assert.equal(groupPicker(renderer, 'ssh').props.value, 'prod/web');
|
||||
// Combobox calls both callbacks with the original input when creating.
|
||||
await act(async () => { picker.props.onValueChange(value); });
|
||||
assert.equal(groupPicker(renderer, 'ssh').props.value, 'prod/web');
|
||||
assert.equal((await save()).group, 'prod/web');
|
||||
}
|
||||
assert.deepEqual(created, groups.length ? [] : values.map(() => 'prod/web'));
|
||||
await act(async () => { groupPicker(renderer, 'ssh').props.onCreateNew(' / / \\ '); });
|
||||
assert.equal(created.length, groups.length ? 0 : values.length);
|
||||
}, groups);
|
||||
}
|
||||
});
|
||||
|
||||
test('new-group sub-panel passes both parent and name through the same creation handler', () => {
|
||||
const source = readFileSync(new URL('./HostDetailsPanel.tsx', import.meta.url), 'utf8');
|
||||
assert.match(source, /createAndSelectGroup\(`\$\{newGroupParent\}\/\$\{newGroupName\}`\)/);
|
||||
assert.match(source, /onSave=\{handleCreateGroup\}/);
|
||||
assert.match(source, /onCreateNew=\{createAndSelectGroup\}/);
|
||||
});
|
||||
@@ -14,6 +14,7 @@ import React, { useEffect, useMemo, useState, useCallback, useRef } from "react"
|
||||
import { useI18n } from "../application/i18n/I18nProvider";
|
||||
import { useApplicationBackend, type SshAgentStatus } from "../application/state/useApplicationBackend";
|
||||
import { applyGroupDefaults, resolveGroupDefaults, resolveGroupTerminalThemeId } from "../domain/groupConfig";
|
||||
import { normalizeGroupTargetPath, resolveHostGroupForSave } from "../domain/hostGroupPathMutations";
|
||||
import {
|
||||
getEffectiveHostDistro,
|
||||
normalizePrimaryTelnetState,
|
||||
@@ -281,6 +282,8 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
}, [form.agentForwarding, form.identityAgent, form.hostname, form.port, form.username, checkSshAgent]);
|
||||
|
||||
const [groupInputValue, setGroupInputValue] = useState(form.group || "");
|
||||
const originalGroupRef = useRef(initialData ? initialData.group || "" : undefined);
|
||||
const createdGroupInputRef = useRef<string | null>(null);
|
||||
|
||||
const initialHostId = initialData?.id;
|
||||
|
||||
@@ -315,6 +318,8 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
}, [initialData, snippets]);
|
||||
|
||||
useEffect(() => {
|
||||
originalGroupRef.current = initialData ? initialData.group || "" : undefined;
|
||||
createdGroupInputRef.current = null;
|
||||
if (!initialData) return;
|
||||
const normalized = normalizePrimaryTelnetState(initialData);
|
||||
setForm(
|
||||
@@ -578,7 +583,11 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
}
|
||||
const normalizedProxyConfig = proxySave.normalizedProxyConfig;
|
||||
let finalLabel = form.label?.trim() || hostname;
|
||||
const finalGroup = groupInputValue.trim() || form.group || "";
|
||||
const finalGroup = resolveHostGroupForSave(
|
||||
groupInputValue.trim() || form.group || "",
|
||||
originalGroupRef.current,
|
||||
groupInputValue !== originalGroupRef.current,
|
||||
);
|
||||
|
||||
const targetManagedSource = managedSources
|
||||
.filter(s => finalGroup === s.groupName || finalGroup.startsWith(s.groupName + "/"))
|
||||
@@ -761,14 +770,18 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateGroup = () => {
|
||||
if (!newGroupName.trim()) return;
|
||||
const fullPath = newGroupParent
|
||||
? `${newGroupParent}/${newGroupName.trim()}`
|
||||
: newGroupName.trim();
|
||||
onCreateGroup?.(fullPath);
|
||||
const createAndSelectGroup = (value: string) => {
|
||||
const fullPath = normalizeGroupTargetPath(value);
|
||||
if (!fullPath) return;
|
||||
createdGroupInputRef.current = value;
|
||||
if (!groups.includes(fullPath)) onCreateGroup?.(fullPath);
|
||||
setGroupInputValue(fullPath);
|
||||
update("group", fullPath);
|
||||
};
|
||||
|
||||
const handleCreateGroup = () => {
|
||||
if (!newGroupName.trim()) return;
|
||||
createAndSelectGroup(`${newGroupParent}/${newGroupName}`);
|
||||
setNewGroupName("");
|
||||
setNewGroupParent("");
|
||||
setActiveSubPanel("none");
|
||||
@@ -1117,16 +1130,18 @@ const HostDetailsPanel: React.FC<HostDetailsPanelPropsWithResize> = ({
|
||||
options={groupOptions}
|
||||
value={form.group || ""}
|
||||
onValueChange={(val) => {
|
||||
update("group", val);
|
||||
setGroupInputValue(val);
|
||||
// Creation also calls onValueChange with the raw input. Keep that
|
||||
// path normalized while preserving a reselected legacy group.
|
||||
const groupPath = val === createdGroupInputRef.current
|
||||
? normalizeGroupTargetPath(val)
|
||||
: resolveHostGroupForSave(val, originalGroupRef.current, val !== originalGroupRef.current);
|
||||
createdGroupInputRef.current = null;
|
||||
update("group", groupPath);
|
||||
setGroupInputValue(groupPath);
|
||||
}}
|
||||
placeholder={t("hostDetails.group.placeholder")}
|
||||
allowCreate={true}
|
||||
onCreateNew={(val) => {
|
||||
onCreateGroup?.(val);
|
||||
update("group", val);
|
||||
setGroupInputValue(val);
|
||||
}}
|
||||
onCreateNew={createAndSelectGroup}
|
||||
createText="Create Group"
|
||||
triggerClassName="flex-1 h-10"
|
||||
/>
|
||||
|
||||
@@ -5,12 +5,13 @@
|
||||
* into vault groups next to their SSH hosts (issue #3615).
|
||||
*/
|
||||
import { Save, TerminalSquare, X } from 'lucide-react';
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import React, { useMemo, useRef, useState } from 'react';
|
||||
import { useI18n } from '../application/i18n/I18nProvider';
|
||||
import { useDiscoveredShells } from '../lib/useDiscoveredShells';
|
||||
import { detectLocalOs } from '../lib/localShell';
|
||||
import type { Host } from '../domain/models';
|
||||
import { createLocalShellHost } from '../domain/localShellHost';
|
||||
import { resolveHostGroupForSave } from '../domain/hostGroupPathMutations';
|
||||
|
||||
import { Button } from './ui/button';
|
||||
import { Combobox, ComboboxOption } from './ui/combobox';
|
||||
@@ -68,6 +69,7 @@ export const LocalShellHostDetailsPanel: React.FC<LocalShellHostDetailsPanelProp
|
||||
const [group, setGroup] = useState(
|
||||
initialData ? initialData.group ?? '' : defaultGroup ?? '',
|
||||
);
|
||||
const originalGroupRef = useRef(initialData ? initialData.group ?? '' : undefined);
|
||||
|
||||
const matchedShell = useMemo(
|
||||
() => discoveredShells.find((candidate) => candidate.id === shell),
|
||||
@@ -128,12 +130,12 @@ export const LocalShellHostDetailsPanel: React.FC<LocalShellHostDetailsPanelProp
|
||||
shellIcon: shellMeta?.icon,
|
||||
startDir,
|
||||
startupCommand,
|
||||
// Save the controlled value directly: '' means the user explicitly
|
||||
// cleared the group, which persists at the vault root.
|
||||
group: group,
|
||||
group,
|
||||
tags: initialData?.tags,
|
||||
notes: initialData?.notes,
|
||||
});
|
||||
// Apply after the factory's outer trim to retain unchanged legacy paths exactly.
|
||||
host.group = resolveHostGroupForSave(group, originalGroupRef.current, group !== originalGroupRef.current);
|
||||
// On edits, merge over the existing host so fields this form does not
|
||||
// expose (pinned, lastConnectedAt, order, ...) and the original
|
||||
// creation timestamp survive a save.
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
* A dedicated editor for serial port hosts (distinct from SSH HostDetailsPanel)
|
||||
*/
|
||||
import { Eye, EyeOff, Save, Tag, X } from 'lucide-react';
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import React, { useMemo, useRef, useState } from 'react';
|
||||
import { useI18n } from '../application/i18n/I18nProvider';
|
||||
import type { GroupConfig, Host, SerialConfig, SerialFlowControl, SerialParity } from '../domain/models';
|
||||
import { resolveHostGroupForSave } from '../domain/hostGroupPathMutations';
|
||||
import {
|
||||
resolveSerialBackspaceFormValue,
|
||||
resolveSerialBackspaceOverrideOnSave,
|
||||
@@ -97,6 +98,7 @@ export const SerialHostDetailsPanel: React.FC<SerialHostDetailsPanelPropsWithRes
|
||||
const [charset, setCharset] = useState(initialData.charset || 'UTF-8');
|
||||
const [tags, setTags] = useState<string[]>(initialData.tags || []);
|
||||
const [group, setGroup] = useState(initialData.group || '');
|
||||
const originalGroupRef = useRef(initialData.group || '');
|
||||
const [notes, setNotes] = useState(initialData.notes ?? '');
|
||||
|
||||
const handleSave = () => {
|
||||
@@ -136,7 +138,7 @@ export const SerialHostDetailsPanel: React.FC<SerialHostDetailsPanelPropsWithRes
|
||||
? (passwordCleared ? undefined : password)
|
||||
: (initialData.password ?? undefined),
|
||||
tags,
|
||||
group,
|
||||
group: resolveHostGroupForSave(group, originalGroupRef.current, group !== originalGroupRef.current),
|
||||
charset,
|
||||
serialConfig: config,
|
||||
backspaceBehavior: undefined,
|
||||
|
||||
@@ -1020,6 +1020,7 @@ const TerminalComponent: React.FC<TerminalProps> = ({
|
||||
currentHop: number;
|
||||
totalHops: number;
|
||||
currentHostLabel: string;
|
||||
currentHostAddress?: string;
|
||||
connectionPhase: string;
|
||||
} | null>(null);
|
||||
const [isConnectionAwaitingUserInput, setIsConnectionAwaitingUserInput] = useState(false);
|
||||
|
||||
@@ -3,18 +3,23 @@ import {
|
||||
Box,
|
||||
Code,
|
||||
Command,
|
||||
Database,
|
||||
FileText,
|
||||
Folder,
|
||||
Globe,
|
||||
HardDrive,
|
||||
Key,
|
||||
Layers,
|
||||
LayoutPanelLeft,
|
||||
List,
|
||||
Network,
|
||||
Palette,
|
||||
Play,
|
||||
Puzzle,
|
||||
Server,
|
||||
Settings,
|
||||
Shield,
|
||||
Sparkles,
|
||||
Table,
|
||||
Terminal,
|
||||
Wrench,
|
||||
@@ -30,17 +35,22 @@ const THEME_ICONS: Readonly<Record<string, LucideIcon>> = Object.freeze({
|
||||
box: Box,
|
||||
code: Code,
|
||||
command: Command,
|
||||
database: Database,
|
||||
file: FileText,
|
||||
folder: Folder,
|
||||
globe: Globe,
|
||||
'hard-drive': HardDrive,
|
||||
key: Key,
|
||||
layers: Layers,
|
||||
'layout-panel': LayoutPanelLeft,
|
||||
list: List,
|
||||
network: Network,
|
||||
palette: Palette,
|
||||
play: Play,
|
||||
server: Server,
|
||||
settings: Settings,
|
||||
shield: Shield,
|
||||
sparkles: Sparkles,
|
||||
table: Table,
|
||||
terminal: Terminal,
|
||||
wrench: Wrench,
|
||||
|
||||
@@ -15,13 +15,27 @@ export function PluginHostActionHost() {
|
||||
const request = entry.prompt.request;
|
||||
const selection = request.kind === 'vault.selectHosts';
|
||||
const stream = request.kind === 'network.stream.connectViaHost';
|
||||
const directStreamConfirm = request.kind === 'network.stream.confirm';
|
||||
const tlsConfirm = request.kind === 'network.stream.tlsConfirm';
|
||||
const connection = request.kind === 'vault.requestConnect' || stream;
|
||||
const effective = entry.host ? applyGroupDefaults(entry.host, entry.host.group ? resolveGroupDefaults(entry.host.group, entry.groups) : {}) : undefined;
|
||||
const protocol = effective ? resolveEffectiveTerminalProtocol(effective) : undefined;
|
||||
const dialogTitle = selection
|
||||
? t('plugins.hostActions.select')
|
||||
: directStreamConfirm
|
||||
? 'Confirm Network Connection'
|
||||
: tlsConfirm
|
||||
? 'Verify TLS Certificate'
|
||||
: connection
|
||||
? t('plugins.hostActions.connect')
|
||||
: entry.host
|
||||
? t('plugins.hostActions.edit')
|
||||
: t('plugins.hostActions.create');
|
||||
|
||||
return <Dialog open onOpenChange={(open) => { if (!open) void state.respond('cancel'); }}>
|
||||
<DialogContent className={selection ? 'max-w-md h-[min(85vh,640px)] flex flex-col p-0 gap-0 overflow-hidden' : 'sm:max-w-[560px] max-h-[85vh] overflow-y-auto'} hideCloseButton>
|
||||
<DialogHeader className={selection ? 'px-4 pt-4 pb-2 shrink-0 border-b border-border/60' : undefined}>
|
||||
<DialogTitle>{t(selection ? 'plugins.hostActions.select' : connection ? 'plugins.hostActions.connect' : entry.host ? 'plugins.hostActions.edit' : 'plugins.hostActions.create')}</DialogTitle>
|
||||
<DialogTitle>{dialogTitle}</DialogTitle>
|
||||
<DialogDescription className="break-all">{entry.prompt.pluginId} · {entry.prompt.pluginVersion}</DialogDescription>
|
||||
</DialogHeader>
|
||||
{selection ? <>
|
||||
@@ -29,17 +43,89 @@ export function PluginHostActionHost() {
|
||||
<p className="px-4 pt-2 text-sm font-medium break-words">{request.title}</p>
|
||||
{state.selectedIds.length > 50 && <p role="alert" className="px-4 text-sm text-destructive">{t('plugins.hostActions.selectionLimit')}</p>}
|
||||
<SelectHostPanelContent hosts={entry.candidates} customGroups={entry.customGroups} selectedHostIds={state.selectedIds} multiSelect className="flex-1 min-h-0" confirmDisabled={state.busy || state.selectedIds.length > 50} onSelect={(host) => state.setSelectedIds((ids) => ids.includes(host.id) ? ids.filter((id) => id !== host.id) : [...ids, host.id])} onSelectionChange={state.setSelectedIds} onConfirm={() => { if (!state.busy && state.selectedIds.length <= 50) void state.respond('submit'); }} />
|
||||
</> : connection && effective ? <>
|
||||
</> : directStreamConfirm ? <div className="space-y-3">
|
||||
<div className="rounded-md border border-border/60 bg-muted/30 p-3 space-y-1">
|
||||
<p className="text-xs text-muted-foreground">Destination Endpoint</p>
|
||||
<p className="font-mono text-sm font-medium break-all">{request.endpoint}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{request.transport.toUpperCase()} · {request.host}:{request.port}
|
||||
{request.isLocal ? ' · Local / Private Network' : ''}
|
||||
</p>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
This plugin is requesting a direct {request.transport.toUpperCase()} connection to this endpoint. Netcatty's internal control ports remain blocked.
|
||||
</p>
|
||||
<label className="flex items-center gap-2 text-sm select-none cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={state.remember}
|
||||
disabled={state.busy}
|
||||
onChange={(event) => state.setRemember(event.target.checked)}
|
||||
/>
|
||||
<span>Remember for this endpoint</span>
|
||||
</label>
|
||||
</div> : tlsConfirm ? <div className="space-y-3">
|
||||
<p className="text-sm text-amber-600 dark:text-amber-400 font-medium">
|
||||
The server certificate could not be verified ({request.reason}).
|
||||
</p>
|
||||
<div className="rounded-md border border-border/60 bg-muted/30 p-3 space-y-1.5 text-xs">
|
||||
<div>
|
||||
<span className="text-muted-foreground">Endpoint: </span>
|
||||
<span className="font-mono break-all">{request.endpoint}</span>
|
||||
</div>
|
||||
{request.subject && <div>
|
||||
<span className="text-muted-foreground">Subject: </span>
|
||||
<span className="font-mono break-all">{request.subject}</span>
|
||||
</div>}
|
||||
{request.issuer && <div>
|
||||
<span className="text-muted-foreground">Issuer: </span>
|
||||
<span className="font-mono break-all">{request.issuer}</span>
|
||||
</div>}
|
||||
{request.validTo && <div>
|
||||
<span className="text-muted-foreground">Valid Until: </span>
|
||||
<span className="font-mono">{request.validTo}</span>
|
||||
</div>}
|
||||
<div>
|
||||
<span className="text-muted-foreground">SHA-256 Fingerprint: </span>
|
||||
<code className="block mt-1 font-mono text-[11px] break-all rounded bg-background/60 p-1.5 border border-border/40">
|
||||
{request.fingerprint256}
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
<label className="flex items-center gap-2 text-sm select-none cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={state.remember}
|
||||
disabled={state.busy}
|
||||
onChange={(event) => state.setRemember(event.target.checked)}
|
||||
/>
|
||||
<span>Trust & remember this certificate fingerprint</span>
|
||||
</label>
|
||||
</div> : connection && effective ? <>
|
||||
<p className="break-all text-sm font-medium">{effective.label}</p>
|
||||
<p className="break-all text-sm">{protocol !== 'local' && effective.username ? `${effective.username}@` : ''}{effective.hostname}{protocol !== 'local' && effective.port ? `:${effective.port}` : ''} ({protocol})</p>
|
||||
{protocol === 'local' && <p className="text-sm font-medium" role="note">{t('plugins.hostActions.localExecution')}</p>}
|
||||
{stream ? <><p className="text-sm font-medium break-all">{request.endpoint}</p><p className="text-sm">{t('plugins.hostActions.streamNote')}</p></> : <>
|
||||
{stream ? <>
|
||||
<p className="text-sm font-medium break-all">{request.endpoint}</p>
|
||||
<p className="text-sm">{t('plugins.hostActions.streamNote')}</p>
|
||||
<label className="flex items-center gap-2 text-sm select-none cursor-pointer pt-1">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={state.remember}
|
||||
disabled={state.busy}
|
||||
onChange={(event) => state.setRemember(event.target.checked)}
|
||||
/>
|
||||
<span>Remember this SSH tunnel binding</span>
|
||||
</label>
|
||||
</> : <>
|
||||
<p className="text-sm" role="note">{t(entry.scriptsRun ? 'plugins.hostActions.scriptsRun' : 'plugins.hostActions.noScripts')}</p>
|
||||
<p className="text-xs text-muted-foreground">{t('plugins.hostActions.connectionNote')}</p></>}
|
||||
</> : request.kind === 'vault.requestHostDraft' ? <PluginHostDraftPreview key={entry.prompt.requestId} before={entry.host} draft={request.draft} managedSources={entry.managedSources} busy={state.busy} onConfirm={(draft) => void state.respond('submit', draft)} /> : null}
|
||||
{state.error && <p role="alert" className="text-sm text-destructive">{t('plugins.hostActions.failed')}</p>}
|
||||
<DialogFooter className={selection ? 'p-3 border-t' : undefined}>
|
||||
<Button variant="outline" disabled={state.busy} onClick={() => void state.respond('cancel')}>{t('common.cancel')}</Button>
|
||||
{directStreamConfirm && <Button disabled={state.busy} onClick={() => void state.respond('submit')}>{t('common.connect')}</Button>}
|
||||
{tlsConfirm && <Button disabled={state.busy} onClick={() => void state.respond('submit')}>Trust & Continue</Button>}
|
||||
{connection && <Button disabled={state.busy || (stream && protocol !== 'ssh')} onClick={() => void state.respond('submit')}>{t('common.connect')}</Button>}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -7,14 +7,39 @@ export type PluginHostDrawnPageProps = Parameters<typeof useHostDrawnPluginView>
|
||||
pluginId: string;
|
||||
};
|
||||
|
||||
type MinimalTreeNode = {
|
||||
type?: number;
|
||||
attributes?: Record<string, string>;
|
||||
children?: MinimalTreeNode[];
|
||||
};
|
||||
|
||||
function hasFullBleedChrome(tree: unknown): boolean {
|
||||
if (!tree || typeof tree !== 'object') return false;
|
||||
const children = (tree as { children?: MinimalTreeNode[] }).children;
|
||||
if (!Array.isArray(children)) return false;
|
||||
// Check root and immediate child (hostDom wraps React trees in a mountRoot div).
|
||||
const check = (nodes: MinimalTreeNode[], depth: number): boolean => {
|
||||
for (const node of nodes) {
|
||||
if (node?.type !== 1) continue;
|
||||
if (node.attributes?.['data-plugin-chrome'] === 'full-bleed') return true;
|
||||
if (depth < 2 && Array.isArray(node.children) && check(node.children, depth + 1)) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
return check(children, 0);
|
||||
}
|
||||
|
||||
export function PluginHostDrawnPage(props: PluginHostDrawnPageProps) {
|
||||
const view = useHostDrawnPluginView(props);
|
||||
if (!view.visible) return null;
|
||||
if (view.loading) return <p data-plugin-view-slot={props.slot.split(':')[0]} role="status" className="p-4 text-sm text-muted-foreground">{props.loadingLabel}</p>;
|
||||
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={props.slot.split(':')[0]}>
|
||||
const fullBleed = hasFullBleedChrome(view.tree);
|
||||
return <div className="relative isolate h-full min-h-0 w-full flex-1" data-plugin-view-slot={props.slot.split(':')[0]} data-plugin-chrome={fullBleed ? 'full-bleed' : undefined}>
|
||||
<PluginRemoteSurface key={`${props.viewId}:${props.version}:${props.slot}`} tree={view.tree} css={view.css} settled={view.settled} loadImage={view.loadImage} onEvent={view.sendEvent} />
|
||||
<div className="absolute right-3 top-3 z-10" data-plugin-settings-entry="">
|
||||
<PluginSettingsEntry key={`${props.pluginId}:${props.version}`} pluginId={props.pluginId} />
|
||||
</div>
|
||||
{!fullBleed && (
|
||||
<div className="absolute right-3 top-3 z-10" data-plugin-settings-entry="">
|
||||
<PluginSettingsEntry key={`${props.pluginId}:${props.version}`} pluginId={props.pluginId} />
|
||||
</div>
|
||||
)}
|
||||
</div>;
|
||||
}
|
||||
@@ -31,7 +31,7 @@ test('plugin surface forwards its own input and contains malformed updates and r
|
||||
assert.deepEqual(events, [{ nodeId: '2', type: 'click' }]);
|
||||
const input = captured!.querySelector('input')!; input.value = 'typed';
|
||||
await act(async () => { input.dispatchEvent(new dom.window.Event('input', { bubbles: true })); });
|
||||
assert.deepEqual(events.at(-1), { nodeId: '4', type: 'input', value: 'typed' });
|
||||
assert.deepEqual(events.at(-1), { nodeId: '4', type: 'input', value: 'typed', selectionStart: 5, selectionEnd: 5 });
|
||||
await act(async () => { document.getElementById('host')!.dispatchEvent(new dom.window.Event('input', { bubbles: true })); });
|
||||
assert.equal(events.length, 2);
|
||||
await act(async () => { root.render(<PluginRemoteSurface tree={tree} css="@import 'https://bad.example/x';" onEvent={() => {}} />); });
|
||||
@@ -254,3 +254,219 @@ test('PluginRemoteSurface avoids JSON/form hook work on text and plain elements
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
}
|
||||
});
|
||||
|
||||
test('PluginRemoteSurface forwards dblclick, contextmenu, throttled scroll, cursor popover, and host-rendered widgets', 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', 'PointerEvent', 'ShadowRoot']) {
|
||||
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
const val = key === 'window' ? dom.window : key === 'PointerEvent' ? dom.window.MouseEvent : dom.window[key as keyof typeof dom.window];
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: val });
|
||||
}
|
||||
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() {}
|
||||
},
|
||||
PointerEvent: dom.window.MouseEvent,
|
||||
});
|
||||
dom.window.HTMLElement.prototype.getBoundingClientRect = () => ({
|
||||
x: 100, y: 50, width: 800, height: 600, top: 50, left: 100, right: 900, bottom: 650, toJSON() {},
|
||||
});
|
||||
|
||||
const shadows: ShadowRoot[] = [];
|
||||
const nativeAttach = dom.window.Element.prototype.attachShadow;
|
||||
dom.window.Element.prototype.attachShadow = function (options) {
|
||||
const s = nativeAttach.call(this, options);
|
||||
shadows.push(s as unknown as ShadowRoot);
|
||||
return s;
|
||||
};
|
||||
|
||||
const { act } = await import('react');
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
|
||||
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
const gridProps = {
|
||||
columns: [
|
||||
{ name: 'id', type: 'int4', primaryKey: true },
|
||||
{ name: 'name', type: 'varchar', nullable: true },
|
||||
],
|
||||
rows: [
|
||||
{ id: 1, name: 'Alice' },
|
||||
{ id: 2, name: null },
|
||||
],
|
||||
dirtyCells: { '0:name': 'Alicia' },
|
||||
editable: true,
|
||||
};
|
||||
const erProps = {
|
||||
tables: [
|
||||
{ name: 'users', columns: [{ name: 'id', type: 'int', isPk: true }] },
|
||||
{ name: 'orders', columns: [{ name: 'id', type: 'int', isPk: true }, { name: 'user_id', type: 'int', isFk: true }] },
|
||||
],
|
||||
relations: [{ fromTable: 'orders', fromColumn: 'user_id', toTable: 'users', toColumn: 'id' }],
|
||||
};
|
||||
const tree = {
|
||||
children: [
|
||||
{
|
||||
id: 'scroller',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { class: 'list' },
|
||||
children: [{ id: 'item', type: 1, element: 'button', attributes: { type: 'button' }, children: [{ id: 'it', type: 3, data: 'Row' }] }],
|
||||
},
|
||||
{
|
||||
id: 'ctx-popover',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {
|
||||
'data-plugin-popover': 'true',
|
||||
'data-plugin-anchor-x': '120',
|
||||
'data-plugin-anchor-y': '80',
|
||||
'data-plugin-popover-width': '260',
|
||||
'data-plugin-popover-max-height': '320',
|
||||
open: '',
|
||||
},
|
||||
children: [{ id: 'pop-item', type: 1, element: 'span', attributes: {}, children: [{ id: 'pt', type: 3, data: 'Menu' }] }],
|
||||
},
|
||||
{
|
||||
id: 'split',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: {
|
||||
'data-plugin-widget': 'split-pane',
|
||||
'data-plugin-widget-props': JSON.stringify({ direction: 'horizontal', initialSize: 220, minSize: 120, maxSize: 400 }),
|
||||
},
|
||||
children: [
|
||||
{ id: 'pane-a', type: 1, element: 'div', attributes: {}, children: [{ id: 'pa', type: 3, data: 'Left' }] },
|
||||
{ id: 'pane-b', type: 1, element: 'div', attributes: {}, children: [{ id: 'pb', type: 3, data: 'Right' }] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'grid',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { 'data-plugin-widget': 'data-grid', 'data-plugin-widget-props': JSON.stringify(gridProps) },
|
||||
children: [],
|
||||
},
|
||||
{
|
||||
id: 'er',
|
||||
type: 1,
|
||||
element: 'div',
|
||||
attributes: { 'data-plugin-widget': 'er-canvas', 'data-plugin-widget-props': JSON.stringify(erProps) },
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
try {
|
||||
await act(async () => {
|
||||
root.render(<PluginRemoteSurface tree={tree} css="" onEvent={(e) => events.push(e as unknown as Record<string, unknown>)} />);
|
||||
});
|
||||
|
||||
const mainShadow = shadows[0];
|
||||
assert.ok(mainShadow, 'main shadow mounted');
|
||||
|
||||
// 1. dblclick & contextmenu with surface-relative coordinates + preventDefault
|
||||
const btn = mainShadow.querySelector('button')!;
|
||||
const ctxEvent = new dom.window.MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 250, clientY: 170 });
|
||||
await act(async () => {
|
||||
btn.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true, cancelable: true, clientX: 180, clientY: 90 }));
|
||||
btn.dispatchEvent(ctxEvent);
|
||||
});
|
||||
assert.equal(ctxEvent.defaultPrevented, true, 'contextmenu must call preventDefault');
|
||||
assert.deepEqual(events[0], { nodeId: 'item', type: 'dblclick', x: 80, y: 40 });
|
||||
assert.deepEqual(events[1], { nodeId: 'item', type: 'contextmenu', x: 150, y: 120 });
|
||||
|
||||
// 2. throttled scroll
|
||||
const scroller = mainShadow.querySelector('.list') as HTMLElement;
|
||||
scroller.scrollTop = 140;
|
||||
scroller.scrollLeft = 20;
|
||||
await act(async () => {
|
||||
scroller.dispatchEvent(new dom.window.Event('scroll', { bubbles: false }));
|
||||
await new Promise((resolve) => setTimeout(resolve, 90));
|
||||
});
|
||||
const scrollEvt = events.find((e) => e.type === 'scroll');
|
||||
assert.ok(scrollEvt, 'scroll event emitted');
|
||||
assert.equal(scrollEvt!.scrollTop, 140);
|
||||
assert.equal(scrollEvt!.scrollLeft, 20);
|
||||
|
||||
// 3. cursor-anchored popover positioned within surface bounds with custom width & maxHeight
|
||||
const popoverEl = document.querySelector('[data-plugin-view-popover]') as HTMLElement | null;
|
||||
assert.ok(popoverEl, 'cursor-anchored popover rendered');
|
||||
assert.equal(popoverEl!.style.width, '260px');
|
||||
assert.equal(popoverEl!.style.maxHeight, '320px');
|
||||
assert.equal(popoverEl!.style.left, '220px'); // surface.left (100) + anchorX (120)
|
||||
|
||||
// 4. SplitPane rendered inside shadow root with two panes and drag handle
|
||||
const splitEl = mainShadow.querySelector('[data-plugin-widget="split-pane"]') as HTMLElement | null;
|
||||
assert.ok(splitEl, 'split-pane rendered in shadow root');
|
||||
assert.equal(splitEl!.querySelectorAll('[data-split-pane]').length, 2);
|
||||
const handle = splitEl!.querySelector('[data-split-handle]') as HTMLElement;
|
||||
await act(async () => {
|
||||
handle.dispatchEvent(new dom.window.MouseEvent('pointerdown', { bubbles: true, clientX: 220 }));
|
||||
dom.window.dispatchEvent(new dom.window.MouseEvent('pointermove', { bubbles: true, clientX: 280 }));
|
||||
dom.window.dispatchEvent(new dom.window.MouseEvent('pointerup', { bubbles: true, clientX: 280 }));
|
||||
});
|
||||
assert.deepEqual(
|
||||
events.find((e) => e.nodeId === 'split' && e.widgetEvent === 'resizeEnd'),
|
||||
{ nodeId: 'split', type: 'widget', widgetEvent: 'resizeEnd', detail: { size: 280, collapsed: false } },
|
||||
);
|
||||
|
||||
// 5. DataGrid slotted in Light DOM: renders dirty cell, NULL pill, inline edit & sort
|
||||
const gridHost = document.querySelector('[data-plugin-widget-host="data-grid"]') as HTMLElement | null;
|
||||
assert.ok(gridHost, 'data-grid slotted in shadow host Light DOM');
|
||||
assert.ok(gridHost!.textContent?.includes('Alicia'), 'dirty cell value rendered');
|
||||
assert.ok(gridHost!.textContent?.includes('NULL'), 'NULL pill rendered');
|
||||
const nameHeaderBtn = gridHost!.querySelector('[data-col-name="name"] button') as HTMLButtonElement;
|
||||
await act(async () => { nameHeaderBtn.click(); });
|
||||
assert.deepEqual(
|
||||
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'sortChange'),
|
||||
{ nodeId: 'grid', type: 'widget', widgetEvent: 'sortChange', detail: { column: 'name', direction: 'asc' } },
|
||||
);
|
||||
const cell = gridHost!.querySelector('[role="gridcell"][data-row-index="0"][data-col-name="name"]') as HTMLElement;
|
||||
await act(async () => {
|
||||
cell.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
|
||||
});
|
||||
const editorInput = cell.querySelector('input') as HTMLInputElement;
|
||||
assert.ok(editorInput, 'double-click opens inline cell editor');
|
||||
await act(async () => {
|
||||
const setter = Object.getOwnPropertyDescriptor(dom.window.HTMLInputElement.prototype, 'value')!.set!;
|
||||
setter.call(editorInput, 'Bob');
|
||||
editorInput.dispatchEvent(new dom.window.Event('input', { bubbles: true }));
|
||||
});
|
||||
await act(async () => {
|
||||
editorInput.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
|
||||
});
|
||||
assert.deepEqual(
|
||||
events.find((e) => e.nodeId === 'grid' && e.widgetEvent === 'cellEdit'),
|
||||
{ nodeId: 'grid', type: 'widget', widgetEvent: 'cellEdit', detail: { rowIndex: 0, colName: 'name', value: 'Bob', isNull: false } },
|
||||
);
|
||||
|
||||
// 6. ER Canvas slotted in Light DOM: renders tables + FK curve + emits tableClick
|
||||
const erHost = document.querySelector('[data-plugin-widget-host="er-canvas"]') as HTMLElement | null;
|
||||
assert.ok(erHost, 'er-canvas slotted in shadow host Light DOM');
|
||||
const usersCard = erHost!.querySelector('[data-er-table="users"]') as Element | null;
|
||||
assert.ok(usersCard, 'users table card rendered');
|
||||
await act(async () => {
|
||||
usersCard!.dispatchEvent(new dom.window.MouseEvent('pointerdown', { bubbles: true, button: 0, clientX: 10, clientY: 10 }));
|
||||
dom.window.dispatchEvent(new dom.window.MouseEvent('pointerup', { bubbles: true, button: 0, clientX: 10, clientY: 10 }));
|
||||
});
|
||||
assert.deepEqual(
|
||||
events.find((e) => e.nodeId === 'er' && e.widgetEvent === 'tableClick'),
|
||||
{ nodeId: 'er', type: 'widget', widgetEvent: 'tableClick', detail: { table: 'users' } },
|
||||
);
|
||||
} 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');
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,9 @@
|
||||
import React, { createContext, memo, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import React, { createContext, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { LazyLoadBoundary } from '../ui/lazy-load-boundary';
|
||||
import { PluginViewPopover } from './PluginViewPopover';
|
||||
import { PluginSplitPane } from './primitives/PluginSplitPane';
|
||||
import { parseWidgetPropsJson, PluginSlottedWidget, type SlottedWidgetKind } from './primitives/PluginWidgetRenderer';
|
||||
import type { PluginSplitPaneWidgetProps } from './primitives/types';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs';
|
||||
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
|
||||
@@ -9,16 +12,44 @@ type RemoteElementNode = {
|
||||
id: string; type: 1; element: string; attributes: Record<string, string>; children: RemoteNode[];
|
||||
};
|
||||
type RemoteNode = { id: string; type: 3; data: string } | { id: string; type: 8; data: string } | RemoteElementNode;
|
||||
|
||||
export type PluginSurfaceEvent = import('@netcatty/plugin-contract').HostDrawnViewEvent;
|
||||
|
||||
const MAX_EVENT_VALUE_LENGTH = 131072;
|
||||
const SCROLL_THROTTLE_MS = 60;
|
||||
const SURFACE_EVENTS = [
|
||||
'click', 'dblclick', 'contextmenu',
|
||||
'input', 'change',
|
||||
'keydown', 'keyup',
|
||||
'focusin', 'focusout',
|
||||
'compositionstart', 'compositionupdate', 'compositionend',
|
||||
'submit', 'reset',
|
||||
'scroll',
|
||||
] as const;
|
||||
const SURFACE_EVENT_SET = new Set<string>(SURFACE_EVENTS);
|
||||
const SLOTTED_WIDGET_KINDS = new Set<string>(['code-editor', 'data-grid', 'er-canvas']);
|
||||
|
||||
const ATTRIBUTE_NAMES: Record<string, string> = { class: 'className', for: 'htmlFor', readonly: 'readOnly', tabindex: 'tabIndex', maxlength: 'maxLength', minlength: 'minLength', colspan: 'colSpan', rowspan: 'rowSpan', autocomplete: 'autoComplete' };
|
||||
const BOOLEAN_ATTRIBUTES = new Set(['checked', 'disabled', 'readonly', 'required', 'multiple', 'selected', 'open']);
|
||||
const preventFormSubmit = (event: React.FormEvent) => event.preventDefault();
|
||||
|
||||
const SurfaceContext = createContext<{ css: string; onEvent(event: PluginSurfaceEvent): void; depth: number }>({ css: '', onEvent: () => {}, depth: 0 });
|
||||
const SurfaceContext = createContext<{
|
||||
css: string;
|
||||
onEvent(event: PluginSurfaceEvent): void;
|
||||
depth: number;
|
||||
shadowHost: HTMLDivElement | null;
|
||||
}>({ css: '', onEvent: () => {}, depth: 0, shadowHost: null });
|
||||
|
||||
function remoteText(nodes: RemoteNode[]): string {
|
||||
return nodes.map((node) => (node.type === 3 ? node.data : node.type === 1 ? remoteText(node.children) : '')).join('');
|
||||
}
|
||||
|
||||
function parseOptionalNumber(raw: string | undefined): number | undefined {
|
||||
if (raw === undefined || raw === '') return undefined;
|
||||
const parsed = Number(raw);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
|
||||
const ResourceLoader = createContext<((path: string) => Promise<string>) | undefined>(undefined);
|
||||
|
||||
function buildRemoteElementProps(node: RemoteElementNode): Record<string, unknown> {
|
||||
@@ -41,17 +72,166 @@ const RemotePopoverElement = memo(function RemotePopoverElement({ node, settled
|
||||
const loadImage = useContext(ResourceLoader);
|
||||
if (surface.depth >= 1) return null;
|
||||
const attrs = node.attributes;
|
||||
return <PluginViewPopover anchor={attrs['data-plugin-anchor'] ?? ''} open={Object.hasOwn(attrs, 'open')} dismiss={() => surface.onEvent({ nodeId: node.id, type: 'dismiss' })}><PluginRemoteSurface tree={{ children: node.children }} css={surface.css} onEvent={surface.onEvent} settled={settled} loadImage={loadImage} depth={surface.depth + 1} /></PluginViewPopover>;
|
||||
return (
|
||||
<PluginViewPopover
|
||||
anchor={attrs['data-plugin-anchor'] ?? ''}
|
||||
anchorX={parseOptionalNumber(attrs['data-plugin-anchor-x'])}
|
||||
anchorY={parseOptionalNumber(attrs['data-plugin-anchor-y'])}
|
||||
width={parseOptionalNumber(attrs['data-plugin-popover-width'])}
|
||||
maxHeight={parseOptionalNumber(attrs['data-plugin-popover-max-height'])}
|
||||
open={Object.hasOwn(attrs, 'open')}
|
||||
dismiss={() => surface.onEvent({ nodeId: node.id, type: 'dismiss' })}
|
||||
>
|
||||
<PluginRemoteSurface
|
||||
tree={{ children: node.children }}
|
||||
css={surface.css}
|
||||
onEvent={surface.onEvent}
|
||||
settled={settled}
|
||||
loadImage={loadImage}
|
||||
depth={surface.depth + 1}
|
||||
/>
|
||||
</PluginViewPopover>
|
||||
);
|
||||
});
|
||||
|
||||
const RemoteSplitPaneElement = memo(function RemoteSplitPaneElement({ node, settled }: { node: RemoteElementNode; settled: boolean }): React.ReactNode {
|
||||
const surface = useContext(SurfaceContext);
|
||||
const parsed = useMemo(
|
||||
() => parseWidgetPropsJson<PluginSplitPaneWidgetProps>(node.attributes['data-plugin-widget-props']),
|
||||
[node.attributes['data-plugin-widget-props']],
|
||||
);
|
||||
const elementChildren = node.children.filter((child) => child.type === 1 || (child.type === 3 && child.data.length > 0));
|
||||
const firstChild = elementChildren[0] ? renderRemoteNode(elementChildren[0], settled) : null;
|
||||
const secondChild = elementChildren[1] ? renderRemoteNode(elementChildren[1], settled) : null;
|
||||
const emit = useCallback(
|
||||
(widgetEvent: string, detail?: Record<string, unknown>) => {
|
||||
surface.onEvent({
|
||||
nodeId: node.id,
|
||||
type: 'widget',
|
||||
widgetEvent,
|
||||
detail: detail as PluginSurfaceEvent['detail'],
|
||||
});
|
||||
},
|
||||
[surface.onEvent, node.id],
|
||||
);
|
||||
return (
|
||||
<PluginSplitPane
|
||||
{...parsed}
|
||||
nodeId={node.id}
|
||||
className={node.attributes.class}
|
||||
inlineStyle={node.attributes.style}
|
||||
firstChild={firstChild}
|
||||
secondChild={secondChild}
|
||||
onWidgetEvent={emit}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
const RemoteSlottedWidgetElement = memo(function RemoteSlottedWidgetElement({ node, kind }: { node: RemoteElementNode; kind: SlottedWidgetKind }): React.ReactNode {
|
||||
const surface = useContext(SurfaceContext);
|
||||
const slotName = `nc-widget-${node.id}`;
|
||||
const emit = useCallback(
|
||||
(widgetEvent: string, detail?: Record<string, unknown>) => {
|
||||
surface.onEvent({
|
||||
nodeId: node.id,
|
||||
type: 'widget',
|
||||
widgetEvent,
|
||||
detail: detail as PluginSurfaceEvent['detail'],
|
||||
});
|
||||
},
|
||||
[surface.onEvent, node.id],
|
||||
);
|
||||
|
||||
const wrapperProps = buildRemoteElementProps(node);
|
||||
const origRef = wrapperProps.ref as ((el: HTMLElement | null) => void) | undefined;
|
||||
const hasExplicitStyle = Object.hasOwn(node.attributes, 'style');
|
||||
wrapperProps.ref = (el: HTMLElement | null) => {
|
||||
origRef?.(el);
|
||||
if (el && !hasExplicitStyle) {
|
||||
el.setAttribute('style', 'display:flex;flex-direction:column;width:100%;height:100%;min-width:0;min-height:0;overflow:hidden');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{React.createElement(
|
||||
'div',
|
||||
wrapperProps,
|
||||
React.createElement('slot', { name: slotName, style: { display: 'contents' } }),
|
||||
)}
|
||||
{surface.shadowHost && createPortal(
|
||||
<div
|
||||
slot={slotName}
|
||||
data-plugin-widget-host={kind}
|
||||
data-plugin-widget-node={node.id}
|
||||
className="flex h-full w-full min-h-0 min-w-0 flex-col overflow-hidden"
|
||||
>
|
||||
<PluginSlottedWidget
|
||||
kind={kind}
|
||||
rawProps={node.attributes['data-plugin-widget-props']}
|
||||
onWidgetEvent={emit}
|
||||
/>
|
||||
</div>,
|
||||
surface.shadowHost,
|
||||
)}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
const resolvedImageCache = new WeakMap<(path: string) => Promise<string>, Map<string, string>>();
|
||||
const IMAGE_RETRY_DELAYS_MS = [200, 600] as const;
|
||||
|
||||
function getCachedImageUrl(loader: ((path: string) => Promise<string>) | undefined, imagePath: string | undefined): string | undefined {
|
||||
if (!loader || !imagePath) return undefined;
|
||||
return resolvedImageCache.get(loader)?.get(imagePath);
|
||||
}
|
||||
|
||||
function setCachedImageUrl(loader: (path: string) => Promise<string>, imagePath: string, url: string) {
|
||||
let map = resolvedImageCache.get(loader);
|
||||
if (!map) {
|
||||
map = new Map();
|
||||
resolvedImageCache.set(loader, map);
|
||||
}
|
||||
if (map.size >= 256) {
|
||||
const oldest = map.keys().next().value;
|
||||
if (oldest !== undefined) map.delete(oldest);
|
||||
}
|
||||
map.set(imagePath, url);
|
||||
}
|
||||
|
||||
const RemoteImageElement = memo(function RemoteImageElement({ node }: { node: RemoteElementNode }): React.ReactNode {
|
||||
const loadImage = useContext(ResourceLoader);
|
||||
const imagePath = node.attributes.src?.slice(6);
|
||||
const [imageUrl, setImageUrl] = useState<string | undefined>();
|
||||
const [imageUrl, setImageUrl] = useState<string | undefined>(() => getCachedImageUrl(loadImage, imagePath));
|
||||
useEffect(() => {
|
||||
let cancelled = false; setImageUrl(undefined);
|
||||
if (imagePath && loadImage) void loadImage(imagePath).then((url) => { if (!cancelled) setImageUrl(url); }).catch(() => {});
|
||||
return () => { cancelled = true; };
|
||||
let cancelled = false;
|
||||
let retryTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const cached = getCachedImageUrl(loadImage, imagePath);
|
||||
if (cached) {
|
||||
setImageUrl(cached);
|
||||
return () => { cancelled = true; };
|
||||
}
|
||||
setImageUrl(undefined);
|
||||
if (imagePath && loadImage) {
|
||||
const attemptLoad = (attempt: number) => {
|
||||
void loadImage(imagePath).then((url) => {
|
||||
if (cancelled) return;
|
||||
setCachedImageUrl(loadImage, imagePath, url);
|
||||
setImageUrl(url);
|
||||
}).catch(() => {
|
||||
if (cancelled) return;
|
||||
const delay = IMAGE_RETRY_DELAYS_MS[attempt];
|
||||
if (delay !== undefined) {
|
||||
retryTimer = setTimeout(() => { if (!cancelled) attemptLoad(attempt + 1); }, delay);
|
||||
}
|
||||
});
|
||||
};
|
||||
attemptLoad(0);
|
||||
}
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (retryTimer !== undefined) clearTimeout(retryTimer);
|
||||
};
|
||||
}, [imagePath, loadImage]);
|
||||
const props = buildRemoteElementProps(node);
|
||||
props.src = imageUrl;
|
||||
@@ -111,12 +291,40 @@ function renderRemoteNode(node: RemoteNode, settled: boolean): React.ReactNode {
|
||||
if (node.type === 3) return node.data;
|
||||
if (node.type === 8) return null;
|
||||
if (node.attributes['data-plugin-popover'] === 'true') return <RemotePopoverElement key={node.id} node={node} settled={settled} />;
|
||||
const widgetKind = node.attributes['data-plugin-widget'];
|
||||
if (widgetKind === 'split-pane') return <RemoteSplitPaneElement key={node.id} node={node} settled={settled} />;
|
||||
if (widgetKind && SLOTTED_WIDGET_KINDS.has(widgetKind)) {
|
||||
return <RemoteSlottedWidgetElement key={node.id} node={node} kind={widgetKind as SlottedWidgetKind} />;
|
||||
}
|
||||
if (node.element === 'img') return <RemoteImageElement key={node.id} node={node} />;
|
||||
if (node.element === 'select') return <RemoteSelectElement key={node.id} node={node} settled={settled} />;
|
||||
if (node.element === 'input' || node.element === 'textarea') return <RemoteInputElement key={node.id} node={node} settled={settled} />;
|
||||
return <RemotePlainElement key={node.id} node={node} settled={settled} />;
|
||||
}
|
||||
|
||||
function readSelectionRange(
|
||||
target: HTMLElement,
|
||||
view: Window & typeof globalThis,
|
||||
): { selectionStart: number; selectionEnd: number } | undefined {
|
||||
const isTextInput =
|
||||
target instanceof view.HTMLTextAreaElement
|
||||
|| (target instanceof view.HTMLInputElement && ['text', 'search', 'url', 'tel', 'password', ''].includes(target.type));
|
||||
if (!isTextInput) return undefined;
|
||||
try {
|
||||
const start = target.selectionStart;
|
||||
const end = target.selectionEnd;
|
||||
if (typeof start === 'number' && typeof end === 'number' && Number.isFinite(start) && Number.isFinite(end)) {
|
||||
return {
|
||||
selectionStart: Math.max(0, Math.min(MAX_EVENT_VALUE_LENGTH, Math.floor(start))),
|
||||
selectionEnd: Math.max(0, Math.min(MAX_EVENT_VALUE_LENGTH, Math.floor(end))),
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Non-selectable input types throw InvalidStateError.
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Host-owned DOM, kept inside a closed shadow root and a clipped stacking context. */
|
||||
export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadImage, depth = 0 }: { depth?: number; tree: unknown; css: string; settled?: boolean; loadImage?(path: string): Promise<string>; onEvent(event: PluginSurfaceEvent): void }) {
|
||||
const checked = useMemo(() => {
|
||||
@@ -125,20 +333,32 @@ export function PluginRemoteSurface({ tree, css, onEvent, settled = true, loadIm
|
||||
return { tree: tree as { children: RemoteNode[] }, css: validatePluginStylesheet(css) };
|
||||
} catch { return null; }
|
||||
}, [tree, css]);
|
||||
const checkedCss = checked?.css;
|
||||
const surfaceContextValue = useMemo(
|
||||
() => (checkedCss !== undefined ? { css: checkedCss, onEvent, depth } : null),
|
||||
[checkedCss, onEvent, depth],
|
||||
if (!checked) return <p role="alert" className="p-4 text-sm text-destructive">Unable to display plugin view.</p>;
|
||||
return (
|
||||
<LazyLoadBoundary name="Plugin view" fallback={<p role="alert" className="p-4 text-sm text-destructive">Unable to display plugin view.</p>}>
|
||||
<ResourceLoader.Provider value={loadImage}>
|
||||
<ValidatedPluginRemoteSurface tree={checked.tree} css={checked.css} onEvent={onEvent} settled={settled} depth={depth} />
|
||||
</ResourceLoader.Provider>
|
||||
</LazyLoadBoundary>
|
||||
);
|
||||
if (!checked || !surfaceContextValue) return <p role="alert" className="p-4 text-sm text-destructive">Unable to display plugin view.</p>;
|
||||
return <LazyLoadBoundary name="Plugin view" fallback={<p role="alert" className="p-4 text-sm text-destructive">Unable to display plugin view.</p>}><SurfaceContext.Provider value={surfaceContextValue}><ResourceLoader.Provider value={loadImage}><ValidatedPluginRemoteSurface tree={checked.tree} css={checked.css} onEvent={onEvent} settled={settled} /></ResourceLoader.Provider></SurfaceContext.Provider></LazyLoadBoundary>;
|
||||
}
|
||||
|
||||
function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled }: { settled: boolean; tree: { children: RemoteNode[] }; css: string; onEvent(event: PluginSurfaceEvent): void }) {
|
||||
const SHADOW_BASE_SCROLLBAR_CSS = [
|
||||
'*::-webkit-scrollbar{width:6px;height:6px}',
|
||||
'*::-webkit-scrollbar-track,*::-webkit-scrollbar-corner{background:transparent}',
|
||||
'*::-webkit-scrollbar-thumb{min-height:28px;border:1px solid transparent;border-radius:999px;background-color:transparent;background-clip:content-box}',
|
||||
'*:hover::-webkit-scrollbar-thumb{background-color:hsl(var(--muted-foreground) / 0.24)}',
|
||||
'*::-webkit-scrollbar-thumb:hover{background-color:hsl(var(--muted-foreground) / 0.45)}',
|
||||
].join('');
|
||||
|
||||
function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled, depth }: { settled: boolean; depth: number; tree: { children: RemoteNode[] }; css: string; onEvent(event: PluginSurfaceEvent): void }) {
|
||||
const surfaceRef = useRef<HTMLDivElement>(null);
|
||||
const hostRef = useRef<HTMLDivElement>(null);
|
||||
const onEventRef = useRef(onEvent); onEventRef.current = onEvent;
|
||||
const shadowRef = useRef<ShadowRoot | null>(null);
|
||||
const [shadow, setShadow] = useState<ShadowRoot | null>(null);
|
||||
const [shadowHost, setShadowHost] = useState<HTMLDivElement | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const host = hostRef.current;
|
||||
if (!host) return;
|
||||
@@ -146,32 +366,118 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled }: { settled
|
||||
const root = shadowRef.current ?? host.attachShadow({ mode: 'closed' });
|
||||
shadowRef.current = root;
|
||||
setShadow(root);
|
||||
setShadowHost(host);
|
||||
}, []);
|
||||
|
||||
const surfaceContextValue = useMemo(
|
||||
() => ({ css, onEvent, depth, shadowHost }),
|
||||
[css, onEvent, depth, shadowHost],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!shadow) return;
|
||||
const scrollTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
const pendingScroll = new Map<string, PluginSurfaceEvent>();
|
||||
|
||||
const flushScroll = (nodeId: string) => {
|
||||
scrollTimers.delete(nodeId);
|
||||
const evt = pendingScroll.get(nodeId);
|
||||
if (evt) {
|
||||
pendingScroll.delete(nodeId);
|
||||
onEventRef.current(evt);
|
||||
}
|
||||
};
|
||||
|
||||
const listener = (event: Event) => {
|
||||
const target = event.target;
|
||||
const view = shadow.ownerDocument.defaultView;
|
||||
if (!view || !(target instanceof view.HTMLElement) || !['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset'].includes(event.type)) return;
|
||||
if (!view || !(target instanceof view.HTMLElement) || !SURFACE_EVENT_SET.has(event.type)) return;
|
||||
|
||||
// Closed-shadow events hide their editable target from window capture.
|
||||
if (event.type === 'focusin') hostRef.current?.toggleAttribute('data-plugin-editing', target.matches('input, textarea, select, [contenteditable]'));
|
||||
if (event.type === 'focusin') {
|
||||
hostRef.current?.toggleAttribute(
|
||||
'data-plugin-editing',
|
||||
target.matches('input, textarea, select, [contenteditable]') || Boolean(target.closest('.monaco-editor')),
|
||||
);
|
||||
}
|
||||
if (event.type === 'focusout') hostRef.current?.removeAttribute('data-plugin-editing');
|
||||
|
||||
// Internal events inside slotted host-rendered widgets are handled by the widget itself.
|
||||
if (target.closest('[data-plugin-widget-host]')) return;
|
||||
|
||||
if (event.type === 'submit') event.preventDefault();
|
||||
if (event.type === 'contextmenu') event.preventDefault();
|
||||
|
||||
const nodeId = target.dataset.netcattyRemoteNode;
|
||||
if (!nodeId) return;
|
||||
|
||||
if (event.type === 'scroll') {
|
||||
const scrollEvent: PluginSurfaceEvent = {
|
||||
nodeId,
|
||||
type: 'scroll' as PluginSurfaceEvent['type'],
|
||||
scrollTop: Math.max(0, Math.round(target.scrollTop)),
|
||||
scrollLeft: Math.max(0, Math.round(target.scrollLeft)),
|
||||
clientHeight: Math.max(0, Math.round(target.clientHeight)),
|
||||
clientWidth: Math.max(0, Math.round(target.clientWidth)),
|
||||
};
|
||||
pendingScroll.set(nodeId, scrollEvent);
|
||||
if (!scrollTimers.has(nodeId)) {
|
||||
scrollTimers.set(nodeId, setTimeout(() => flushScroll(nodeId), SCROLL_THROTTLE_MS));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const value = target instanceof view.HTMLInputElement || target instanceof view.HTMLTextAreaElement || target instanceof view.HTMLSelectElement ? target.value : undefined;
|
||||
const values = target instanceof view.HTMLSelectElement && target.multiple ? [...target.selectedOptions].map((option) => option.value) : undefined;
|
||||
const checkedValue = target instanceof view.HTMLInputElement && ['checkbox', 'radio'].includes(target.type) ? target.checked : undefined;
|
||||
if (value !== undefined && value.length > 8192) return;
|
||||
if (value !== undefined && value.length > MAX_EVENT_VALUE_LENGTH) return;
|
||||
|
||||
const keyboard = event instanceof view.KeyboardEvent && event.key.length <= 64
|
||||
? { key: event.key, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey } : {};
|
||||
onEventRef.current({ nodeId, type: event.type as PluginSurfaceEvent['type'], ...(value === undefined ? {} : { value }), ...(checkedValue === undefined ? {} : { checked: checkedValue }), ...keyboard, ...(values ? { values } : {}), ...(event instanceof view.CompositionEvent ? { data: event.data.slice(0, 8192) } : {}) });
|
||||
? { key: event.key, ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey }
|
||||
: {};
|
||||
|
||||
let pointerCoords: { x: number; y: number } | undefined;
|
||||
if ((event.type === 'dblclick' || event.type === 'contextmenu') && event instanceof view.MouseEvent) {
|
||||
const rect = (surfaceRef.current ?? hostRef.current)?.getBoundingClientRect();
|
||||
pointerCoords = {
|
||||
x: Math.round(rect ? event.clientX - rect.left : event.clientX),
|
||||
y: Math.round(rect ? event.clientY - rect.top : event.clientY),
|
||||
};
|
||||
}
|
||||
|
||||
const selection =
|
||||
event.type === 'input' || event.type === 'change' || event.type === 'keyup' || event.type === 'keydown'
|
||||
? readSelectionRange(target, view)
|
||||
: undefined;
|
||||
|
||||
onEventRef.current({
|
||||
nodeId,
|
||||
type: event.type as PluginSurfaceEvent['type'],
|
||||
...(value === undefined ? {} : { value }),
|
||||
...(checkedValue === undefined ? {} : { checked: checkedValue }),
|
||||
...keyboard,
|
||||
...(pointerCoords ?? {}),
|
||||
...(selection ?? {}),
|
||||
...(values ? { values } : {}),
|
||||
...(event instanceof view.CompositionEvent ? { data: event.data.slice(0, 8192) } : {}),
|
||||
});
|
||||
};
|
||||
|
||||
for (const event of SURFACE_EVENTS) shadow.addEventListener(event, listener, true);
|
||||
return () => {
|
||||
for (const timer of scrollTimers.values()) clearTimeout(timer);
|
||||
scrollTimers.clear();
|
||||
pendingScroll.clear();
|
||||
for (const event of SURFACE_EVENTS) shadow.removeEventListener(event, listener, true);
|
||||
};
|
||||
for (const event of ['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset']) shadow.addEventListener(event, listener, true);
|
||||
return () => { for (const event of ['click', 'input', 'change', 'keydown', 'keyup', 'focusin', 'focusout', 'compositionstart', 'compositionupdate', 'compositionend', 'submit', 'reset']) shadow.removeEventListener(event, listener, true); };
|
||||
}, [shadow]);
|
||||
return <div className="h-full w-full min-h-0 min-w-0 overflow-hidden [contain:paint] isolate relative" data-plugin-remote-surface>
|
||||
<div ref={hostRef} className="h-full min-h-0 overflow-auto [container-type:inline-size]" />
|
||||
{shadow && createPortal(<><style>{css}</style>{tree.children.map((node) => renderRemoteNode(node, settled))}</>, shadow)}
|
||||
</div>;
|
||||
|
||||
return (
|
||||
<SurfaceContext.Provider value={surfaceContextValue}>
|
||||
<div ref={surfaceRef} className="h-full w-full min-h-0 min-w-0 overflow-hidden [contain:paint] isolate relative" data-plugin-remote-surface>
|
||||
<div ref={hostRef} className="h-full min-h-0 overflow-auto [container-type:inline-size] [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-corner]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-transparent hover:[&::-webkit-scrollbar-thumb]:bg-muted-foreground/25" />
|
||||
{shadow && createPortal(<><style>{SHADOW_BASE_SCROLLBAR_CSS}</style><style>{css}</style>{tree.children.map((node) => renderRemoteNode(node, settled))}</>, shadow)}
|
||||
</div>
|
||||
</SurfaceContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,41 +1,235 @@
|
||||
import React, { useLayoutEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
|
||||
const MIN_POPOVER_WIDTH = 160;
|
||||
const MAX_POPOVER_WIDTH = 480;
|
||||
const DEFAULT_POPOVER_WIDTH = 240;
|
||||
const MIN_POPOVER_HEIGHT = 80;
|
||||
const MAX_POPOVER_HEIGHT = 420;
|
||||
|
||||
export interface PluginViewPopoverProps {
|
||||
anchor?: string;
|
||||
anchorX?: number;
|
||||
anchorY?: number;
|
||||
width?: number;
|
||||
maxHeight?: number;
|
||||
open: boolean;
|
||||
dismiss(): void;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/** Geometry and dismissal belong to the host; content belongs to the plugin. */
|
||||
export function PluginViewPopover({ anchor, open, dismiss, children }: {
|
||||
anchor: string; open: boolean; dismiss(): void; children: React.ReactNode;
|
||||
}) {
|
||||
export function PluginViewPopover({
|
||||
anchor,
|
||||
anchorX,
|
||||
anchorY,
|
||||
width: requestedWidth,
|
||||
maxHeight: requestedMaxHeight,
|
||||
open,
|
||||
dismiss,
|
||||
children,
|
||||
}: PluginViewPopoverProps) {
|
||||
const marker = useRef<HTMLSpanElement>(null);
|
||||
const panel = useRef<HTMLDivElement>(null);
|
||||
const dismissRef = useRef(dismiss); dismissRef.current = dismiss;
|
||||
const [position, setPosition] = useState<{ left: number; top: number; width: number } | null>(null);
|
||||
const dismissRef = useRef(dismiss);
|
||||
dismissRef.current = dismiss;
|
||||
|
||||
const [position, setPosition] = useState<{
|
||||
left: number;
|
||||
top: number;
|
||||
width: number;
|
||||
maxHeight: number;
|
||||
} | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!open || !marker.current) { setPosition(null); return; }
|
||||
if (!open || !marker.current) {
|
||||
setPosition(null);
|
||||
return;
|
||||
}
|
||||
const root = marker.current.getRootNode() as ShadowRoot;
|
||||
const target = root.getElementById(anchor);
|
||||
if (!(target instanceof marker.current.ownerDocument.defaultView!.HTMLElement)) return;
|
||||
const doc = target.ownerDocument; const win = doc.defaultView!;
|
||||
const doc = marker.current.ownerDocument;
|
||||
const win = doc.defaultView!;
|
||||
const surface = root.host instanceof win.HTMLElement
|
||||
? root.host.closest('[data-plugin-remote-surface]')
|
||||
: null;
|
||||
|
||||
const hasCursorCoords =
|
||||
typeof anchorX === 'number' && Number.isFinite(anchorX)
|
||||
&& typeof anchorY === 'number' && Number.isFinite(anchorY);
|
||||
|
||||
const target = anchor ? root.getElementById(anchor) : null;
|
||||
const targetEl = target instanceof win.HTMLElement ? target : null;
|
||||
if (!hasCursorCoords && !targetEl) {
|
||||
setPosition(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const resolveSurfaceBounds = () => {
|
||||
const vp = {
|
||||
left: 8,
|
||||
top: 8,
|
||||
right: Math.max(8, win.innerWidth - 8),
|
||||
bottom: Math.max(8, win.innerHeight - 8),
|
||||
};
|
||||
if (!surface) return vp;
|
||||
const sr = surface.getBoundingClientRect();
|
||||
if (sr.width <= 0 || sr.height <= 0) return vp;
|
||||
return {
|
||||
left: Math.max(vp.left, sr.left + 4),
|
||||
top: Math.max(vp.top, sr.top + 4),
|
||||
right: Math.min(vp.right, sr.right - 4),
|
||||
bottom: Math.min(vp.bottom, sr.bottom - 4),
|
||||
};
|
||||
};
|
||||
|
||||
const update = () => {
|
||||
const bounds = target.getBoundingClientRect();
|
||||
if (!bounds.width || !bounds.height) { setPosition(null); dismissRef.current(); return; }
|
||||
const width = Math.min(360, Math.max(220, bounds.width), win.innerWidth - 16);
|
||||
setPosition({ left: Math.max(8, Math.min(bounds.left, win.innerWidth - width - 8)), top: Math.max(8, Math.min(bounds.bottom + 4, win.innerHeight - 248)), width });
|
||||
const clip = resolveSurfaceBounds();
|
||||
const availableW = Math.max(MIN_POPOVER_WIDTH, clip.right - clip.left);
|
||||
const availableH = Math.max(MIN_POPOVER_HEIGHT, clip.bottom - clip.top);
|
||||
const boundedMaxHeight = Math.min(
|
||||
availableH,
|
||||
Math.max(
|
||||
MIN_POPOVER_HEIGHT,
|
||||
Math.min(
|
||||
MAX_POPOVER_HEIGHT,
|
||||
typeof requestedMaxHeight === 'number' && Number.isFinite(requestedMaxHeight)
|
||||
? Math.round(requestedMaxHeight)
|
||||
: MAX_POPOVER_HEIGHT,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
let width: number;
|
||||
let rawLeft: number;
|
||||
let rawTop: number;
|
||||
let anchorTop: number;
|
||||
|
||||
if (hasCursorCoords) {
|
||||
const sr = surface?.getBoundingClientRect();
|
||||
const originLeft = sr && sr.width > 0 ? sr.left : 0;
|
||||
const originTop = sr && sr.height > 0 ? sr.top : 0;
|
||||
const desiredW =
|
||||
typeof requestedWidth === 'number' && Number.isFinite(requestedWidth)
|
||||
? requestedWidth
|
||||
: DEFAULT_POPOVER_WIDTH;
|
||||
width = Math.min(availableW, Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(desiredW))));
|
||||
rawLeft = originLeft + anchorX!;
|
||||
rawTop = originTop + anchorY! + 2;
|
||||
anchorTop = originTop + anchorY!;
|
||||
} else {
|
||||
const bounds = targetEl!.getBoundingClientRect();
|
||||
if (!bounds.width || !bounds.height) {
|
||||
setPosition(null);
|
||||
dismissRef.current();
|
||||
return;
|
||||
}
|
||||
const desiredW =
|
||||
typeof requestedWidth === 'number' && Number.isFinite(requestedWidth)
|
||||
? requestedWidth
|
||||
: Math.min(360, Math.max(220, bounds.width));
|
||||
width = Math.min(availableW, Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(desiredW))));
|
||||
rawLeft = bounds.left;
|
||||
rawTop = bounds.bottom + 4;
|
||||
anchorTop = bounds.top;
|
||||
}
|
||||
|
||||
const left = Math.max(clip.left, Math.min(rawLeft, clip.right - width));
|
||||
const measuredHeight = panel.current?.getBoundingClientRect().height || 0;
|
||||
const estimatedHeight = measuredHeight > 0 ? Math.min(measuredHeight, boundedMaxHeight) : Math.min(240, boundedMaxHeight);
|
||||
|
||||
let top = rawTop;
|
||||
let effectiveMaxHeight = boundedMaxHeight;
|
||||
const spaceBelow = clip.bottom - rawTop;
|
||||
const spaceAbove = anchorTop - 4 - clip.top;
|
||||
|
||||
if (spaceBelow < estimatedHeight && spaceAbove > spaceBelow) {
|
||||
effectiveMaxHeight = Math.min(boundedMaxHeight, Math.max(MIN_POPOVER_HEIGHT, Math.floor(spaceAbove)));
|
||||
top = Math.max(clip.top, anchorTop - 4 - Math.min(estimatedHeight, effectiveMaxHeight));
|
||||
} else {
|
||||
effectiveMaxHeight = Math.min(boundedMaxHeight, Math.max(MIN_POPOVER_HEIGHT, Math.floor(spaceBelow)));
|
||||
top = Math.max(clip.top, Math.min(rawTop, clip.bottom - Math.min(estimatedHeight, effectiveMaxHeight)));
|
||||
}
|
||||
|
||||
setPosition({ left: Math.round(left), top: Math.round(top), width: Math.round(width), maxHeight: Math.round(effectiveMaxHeight) });
|
||||
};
|
||||
|
||||
const dismissNow = () => {
|
||||
setPosition(null);
|
||||
dismissRef.current();
|
||||
};
|
||||
const key = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
dismissNow();
|
||||
targetEl?.focus();
|
||||
}
|
||||
};
|
||||
const outside = (event: PointerEvent) => {
|
||||
const path = event.composedPath();
|
||||
if (targetEl && path.includes(targetEl)) return;
|
||||
if (panel.current && path.includes(panel.current)) return;
|
||||
dismissNow();
|
||||
};
|
||||
const dismissNow = () => { setPosition(null); dismissRef.current(); };
|
||||
const key = (event: KeyboardEvent) => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); dismissNow(); target.focus(); } };
|
||||
const outside = (event: PointerEvent) => { if (!event.composedPath().includes(target) && (!panel.current || !event.composedPath().includes(panel.current))) dismissNow(); };
|
||||
const blocked = () => [...doc.querySelectorAll('[role=dialog][aria-modal=true]:not([data-plugin-dialog])')].some((dialog) => {
|
||||
const rect = dialog.getBoundingClientRect(); return rect.width > 0 && rect.height > 0;
|
||||
const rect = dialog.getBoundingClientRect();
|
||||
return rect.width > 0 && rect.height > 0;
|
||||
});
|
||||
if (blocked()) { dismissNow(); return; }
|
||||
const dialogs = new win.MutationObserver(() => { if (blocked()) dismissNow(); });
|
||||
dialogs.observe(doc.body, { subtree: true, childList: true, attributes: true, attributeFilter: ['aria-modal', 'hidden', 'data-state'] });
|
||||
const resize = new win.ResizeObserver(update); resize.observe(target); update();
|
||||
win.addEventListener('resize', update); doc.addEventListener('scroll', update, true);
|
||||
doc.addEventListener('keydown', key, true); doc.addEventListener('pointerdown', outside, true);
|
||||
return () => { dialogs.disconnect(); resize.disconnect(); win.removeEventListener('resize', update); doc.removeEventListener('scroll', update, true); doc.removeEventListener('keydown', key, true); doc.removeEventListener('pointerdown', outside, true); };
|
||||
}, [anchor, open]);
|
||||
return <><span ref={marker} hidden />{open && position && marker.current && createPortal(
|
||||
<div ref={panel} role="region" aria-label="Plugin menu" data-plugin-view-popover className="fixed z-[45] overflow-hidden rounded-lg border border-border bg-background shadow-xl" style={{ ...position, height: 240, maxHeight: 'calc(100vh - 16px)', contain: 'paint', isolation: 'isolate' }}>{children}</div>, marker.current.ownerDocument.body,
|
||||
)}</>;
|
||||
if (blocked()) {
|
||||
dismissNow();
|
||||
return;
|
||||
}
|
||||
|
||||
const dialogs = new win.MutationObserver(() => {
|
||||
if (blocked()) dismissNow();
|
||||
});
|
||||
dialogs.observe(doc.body, {
|
||||
subtree: true,
|
||||
childList: true,
|
||||
attributes: true,
|
||||
attributeFilter: ['aria-modal', 'hidden', 'data-state'],
|
||||
});
|
||||
const resize = new win.ResizeObserver(update);
|
||||
if (targetEl) resize.observe(targetEl);
|
||||
if (surface) resize.observe(surface);
|
||||
update();
|
||||
win.addEventListener('resize', update);
|
||||
doc.addEventListener('scroll', update, true);
|
||||
doc.addEventListener('keydown', key, true);
|
||||
doc.addEventListener('pointerdown', outside, true);
|
||||
return () => {
|
||||
dialogs.disconnect();
|
||||
resize.disconnect();
|
||||
win.removeEventListener('resize', update);
|
||||
doc.removeEventListener('scroll', update, true);
|
||||
doc.removeEventListener('keydown', key, true);
|
||||
doc.removeEventListener('pointerdown', outside, true);
|
||||
};
|
||||
}, [anchor, anchorX, anchorY, requestedWidth, requestedMaxHeight, open]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<span ref={marker} hidden />
|
||||
{open && position && marker.current && createPortal(
|
||||
<div
|
||||
ref={panel}
|
||||
role="region"
|
||||
aria-label="Plugin menu"
|
||||
data-plugin-view-popover=""
|
||||
className="fixed z-[45] overflow-auto rounded-lg border border-border bg-popover text-popover-foreground shadow-xl"
|
||||
style={{
|
||||
left: position.left,
|
||||
top: position.top,
|
||||
width: position.width,
|
||||
maxHeight: position.maxHeight,
|
||||
contain: 'paint',
|
||||
isolation: 'isolate',
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>,
|
||||
marker.current.ownerDocument.body,
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import React, { Suspense, lazy } from 'react';
|
||||
import { LazyLoadBoundary } from '../../ui/lazy-load-boundary';
|
||||
import type { PluginCodeEditorWidgetProps, PluginWidgetEventCallback } from './types';
|
||||
|
||||
const LazyPluginCodeEditorInner = lazy(() => import('./PluginCodeEditorInner'));
|
||||
|
||||
export interface PluginCodeEditorProps extends PluginCodeEditorWidgetProps {
|
||||
onWidgetEvent: PluginWidgetEventCallback;
|
||||
}
|
||||
|
||||
export function PluginCodeEditor(props: PluginCodeEditorProps) {
|
||||
return (
|
||||
<LazyLoadBoundary
|
||||
name="Plugin SQL Editor"
|
||||
fallback={<div className="flex h-full w-full items-center justify-center p-4 text-xs text-destructive">Unable to load code editor.</div>}
|
||||
>
|
||||
<Suspense
|
||||
fallback={(
|
||||
<div className="flex h-full w-full items-center justify-center bg-background text-muted-foreground">
|
||||
<Loader2 size={18} className="animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
<LazyPluginCodeEditorInner {...props} />
|
||||
</Suspense>
|
||||
</LazyLoadBoundary>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
import Editor, { loader, type Monaco, type OnMount, useMonaco } from '@monaco-editor/react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import React, { useCallback, useEffect, useId, useRef } from 'react';
|
||||
import { useClipboardBackend } from '@/application/state/useClipboardBackend';
|
||||
import {
|
||||
buildMonacoPasteEdits,
|
||||
pasteForMonacoEditorCommand,
|
||||
readClipboardTextWithFallbacks,
|
||||
} from '@/infrastructure/monaco/monacoClipboardPaste';
|
||||
import { useNetcattyMonacoTheme } from '@/infrastructure/monaco/useNetcattyMonacoTheme';
|
||||
import { extractCurrentSqlStatement, extractSqlTableAliases } from './sqlStatement';
|
||||
import type {
|
||||
PluginCodeEditorCompletionSchema,
|
||||
PluginCodeEditorDiagnostic,
|
||||
PluginCodeEditorWidgetProps,
|
||||
PluginWidgetEventCallback,
|
||||
} from './types';
|
||||
|
||||
const viteEnv = (import.meta.env ?? { BASE_URL: '/', DEV: false }) as { BASE_URL?: string; DEV?: boolean };
|
||||
const monacoBasePath = viteEnv.DEV
|
||||
? './node_modules/monaco-editor/min/vs'
|
||||
: `${viteEnv.BASE_URL ?? '/'}monaco/vs`;
|
||||
loader.config({ paths: { vs: monacoBasePath } });
|
||||
|
||||
const DEFAULT_SQL_KEYWORDS = [
|
||||
'SELECT', 'FROM', 'WHERE', 'INSERT', 'INTO', 'VALUES', 'UPDATE', 'SET', 'DELETE',
|
||||
'CREATE', 'ALTER', 'DROP', 'TABLE', 'INDEX', 'VIEW', 'JOIN', 'LEFT JOIN', 'RIGHT JOIN',
|
||||
'INNER JOIN', 'FULL OUTER JOIN', 'ON', 'GROUP BY', 'ORDER BY', 'HAVING', 'LIMIT',
|
||||
'OFFSET', 'DISTINCT', 'AS', 'AND', 'OR', 'NOT', 'IN', 'IS NULL', 'IS NOT NULL',
|
||||
'BETWEEN', 'LIKE', 'ILIKE', 'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'UNION', 'UNION ALL',
|
||||
'WITH', 'EXPLAIN', 'ANALYZE', 'BEGIN', 'COMMIT', 'ROLLBACK', 'RETURNING', 'PRIMARY KEY',
|
||||
'FOREIGN KEY', 'REFERENCES', 'DEFAULT', 'CASCADE', 'COUNT', 'SUM', 'AVG', 'MIN', 'MAX',
|
||||
];
|
||||
|
||||
const SEVERITY_MAP: Record<NonNullable<PluginCodeEditorDiagnostic['severity']>, number> = {
|
||||
hint: 1,
|
||||
info: 2,
|
||||
warning: 4,
|
||||
error: 8,
|
||||
};
|
||||
|
||||
export interface PluginCodeEditorInnerProps extends PluginCodeEditorWidgetProps {
|
||||
onWidgetEvent: PluginWidgetEventCallback;
|
||||
}
|
||||
|
||||
export default function PluginCodeEditorInner({
|
||||
value = '',
|
||||
language = 'sql',
|
||||
readOnly = false,
|
||||
placeholder,
|
||||
lineNumbers = 'on',
|
||||
minimap = false,
|
||||
wordWrap = 'off',
|
||||
completionSchema,
|
||||
diagnostics,
|
||||
height = '100%',
|
||||
onWidgetEvent,
|
||||
}: PluginCodeEditorInnerProps) {
|
||||
const monaco = useMonaco();
|
||||
const themeName = useNetcattyMonacoTheme(monaco ?? undefined);
|
||||
const { readClipboardText: readClipboardTextFromBridge } = useClipboardBackend();
|
||||
const editorId = useId();
|
||||
const modelPath = `inmemory://netcatty-plugin-editor/${editorId.replace(/[^a-zA-Z0-9_-]/g, '_')}.${language}`;
|
||||
|
||||
const editorRef = useRef<Parameters<OnMount>[0] | null>(null);
|
||||
const monacoRef = useRef<Monaco | null>(null);
|
||||
const disposablesRef = useRef<Array<{ dispose(): void }>>([]);
|
||||
const onWidgetEventRef = useRef(onWidgetEvent);
|
||||
onWidgetEventRef.current = onWidgetEvent;
|
||||
const schemaRef = useRef<PluginCodeEditorCompletionSchema | undefined>(completionSchema);
|
||||
schemaRef.current = completionSchema;
|
||||
const lastEmittedValueRef = useRef<string>(value);
|
||||
const changeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const selectionTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const readClipboardRef = useRef<() => Promise<string | null>>(() => Promise.resolve(null));
|
||||
|
||||
const readClipboardText = useCallback(async (): Promise<string | null> => (
|
||||
readClipboardTextWithFallbacks({
|
||||
readNavigator: navigator.clipboard?.readText
|
||||
? () => navigator.clipboard.readText()
|
||||
: undefined,
|
||||
readBridge: readClipboardTextFromBridge,
|
||||
})
|
||||
), [readClipboardTextFromBridge]);
|
||||
readClipboardRef.current = readClipboardText;
|
||||
|
||||
// Sync external value changes without disrupting cursor when value echoes local edits.
|
||||
useEffect(() => {
|
||||
const editor = editorRef.current;
|
||||
if (!editor) return;
|
||||
if (value === lastEmittedValueRef.current) return;
|
||||
const model = editor.getModel();
|
||||
if (!model || model.getValue() === value) {
|
||||
lastEmittedValueRef.current = value;
|
||||
return;
|
||||
}
|
||||
lastEmittedValueRef.current = value;
|
||||
model.setValue(value);
|
||||
}, [value]);
|
||||
|
||||
// Sync diagnostics markers cleanly.
|
||||
useEffect(() => {
|
||||
const editor = editorRef.current;
|
||||
const monacoInstance = monacoRef.current ?? monaco;
|
||||
if (!editor || !monacoInstance) return;
|
||||
const model = editor.getModel();
|
||||
if (!model) return;
|
||||
const markers = (diagnostics ?? []).map((diag) => ({
|
||||
startLineNumber: Math.max(1, Math.floor(diag.line || 1)),
|
||||
startColumn: Math.max(1, Math.floor(diag.column || 1)),
|
||||
endLineNumber: Math.max(1, Math.floor(diag.endLine ?? diag.line ?? 1)),
|
||||
endColumn: Math.max(1, Math.floor(diag.endColumn ?? (diag.column ? diag.column + 1 : 2))),
|
||||
message: diag.message,
|
||||
severity: SEVERITY_MAP[diag.severity ?? 'error'] ?? 8,
|
||||
}));
|
||||
monacoInstance.editor.setModelMarkers(model, 'netcatty-plugin-diagnostics', markers);
|
||||
}, [diagnostics, monaco]);
|
||||
|
||||
// Register local schema-aware CompletionItemProvider scoped to this editor's model URI.
|
||||
useEffect(() => {
|
||||
if (!monaco) return;
|
||||
if (!['sql', 'pgsql', 'mysql'].includes(language)) return;
|
||||
const disposable = monaco.languages.registerCompletionItemProvider(language, {
|
||||
triggerCharacters: ['.', ' '],
|
||||
provideCompletionItems(model, position) {
|
||||
if (model.uri.toString() !== modelPath) return { suggestions: [] };
|
||||
const word = model.getWordUntilPosition(position);
|
||||
const range = {
|
||||
startLineNumber: position.lineNumber,
|
||||
endLineNumber: position.lineNumber,
|
||||
startColumn: word.startColumn,
|
||||
endColumn: word.endColumn,
|
||||
};
|
||||
const linePrefix = model.getLineContent(position.lineNumber).slice(0, position.column - 1);
|
||||
const dotMatch = /["`]?([a-zA-Z_][\w$]*)["`]?\.\s*[\w$]*$/u.exec(linePrefix);
|
||||
const schema = schemaRef.current;
|
||||
const tables = schema?.tables ?? [];
|
||||
const suggestions: Parameters<typeof monaco.languages.registerCompletionItemProvider>[1] extends {
|
||||
provideCompletionItems: (...args: never[]) => infer R;
|
||||
}
|
||||
? R extends { suggestions: infer S }
|
||||
? S
|
||||
: never
|
||||
: never = [] as never;
|
||||
const list = suggestions as Array<{
|
||||
label: string;
|
||||
kind: number;
|
||||
insertText: string;
|
||||
detail?: string;
|
||||
sortText?: string;
|
||||
range: typeof range;
|
||||
}>;
|
||||
|
||||
if (dotMatch) {
|
||||
const qualifier = dotMatch[1].toLowerCase();
|
||||
const aliases = extractSqlTableAliases(model.getValue());
|
||||
const resolvedTableName = aliases.get(qualifier) ?? qualifier;
|
||||
// Match either schema.table or table/alias.column
|
||||
for (const tbl of tables) {
|
||||
if (tbl.schema && tbl.schema.toLowerCase() === qualifier) {
|
||||
list.push({
|
||||
label: tbl.name,
|
||||
kind: monaco.languages.CompletionItemKind.Struct,
|
||||
insertText: tbl.name,
|
||||
detail: `${tbl.schema} table`,
|
||||
sortText: `0_${tbl.name}`,
|
||||
range,
|
||||
});
|
||||
}
|
||||
if (tbl.name.toLowerCase() === resolvedTableName.toLowerCase()) {
|
||||
for (const col of tbl.columns ?? []) {
|
||||
list.push({
|
||||
label: col.name,
|
||||
kind: monaco.languages.CompletionItemKind.Field,
|
||||
insertText: col.name,
|
||||
detail: col.type ? `${tbl.name}.${col.name} (${col.type})` : `${tbl.name}.${col.name}`,
|
||||
sortText: `0_${col.name}`,
|
||||
range,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return { suggestions: list as never };
|
||||
}
|
||||
|
||||
const seenColumns = new Set<string>();
|
||||
for (const tbl of tables) {
|
||||
const label = tbl.schema ? `${tbl.schema}.${tbl.name}` : tbl.name;
|
||||
list.push({
|
||||
label,
|
||||
kind: monaco.languages.CompletionItemKind.Struct,
|
||||
insertText: label,
|
||||
detail: tbl.schema ? `Table (${tbl.schema})` : 'Table',
|
||||
sortText: `1_${tbl.name}`,
|
||||
range,
|
||||
});
|
||||
if (tbl.schema) {
|
||||
list.push({
|
||||
label: tbl.name,
|
||||
kind: monaco.languages.CompletionItemKind.Struct,
|
||||
insertText: tbl.name,
|
||||
detail: `Table (${tbl.schema})`,
|
||||
sortText: `1_${tbl.name}`,
|
||||
range,
|
||||
});
|
||||
}
|
||||
for (const col of tbl.columns ?? []) {
|
||||
const key = `${col.name}:${tbl.name}`;
|
||||
if (seenColumns.has(key)) continue;
|
||||
seenColumns.add(key);
|
||||
list.push({
|
||||
label: col.name,
|
||||
kind: monaco.languages.CompletionItemKind.Field,
|
||||
insertText: col.name,
|
||||
detail: col.type ? `${tbl.name} (${col.type})` : tbl.name,
|
||||
sortText: `2_${col.name}`,
|
||||
range,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for (const fn of schema?.functions ?? []) {
|
||||
list.push({
|
||||
label: fn.name,
|
||||
kind: monaco.languages.CompletionItemKind.Function,
|
||||
insertText: fn.insertText ?? `${fn.name}()`,
|
||||
detail: fn.detail ?? 'Function',
|
||||
sortText: `3_${fn.name}`,
|
||||
range,
|
||||
});
|
||||
}
|
||||
|
||||
const keywords = schema?.keywords?.length ? schema.keywords : DEFAULT_SQL_KEYWORDS;
|
||||
for (const kw of keywords) {
|
||||
list.push({
|
||||
label: kw,
|
||||
kind: monaco.languages.CompletionItemKind.Keyword,
|
||||
insertText: kw,
|
||||
detail: 'Keyword',
|
||||
sortText: `4_${kw}`,
|
||||
range,
|
||||
});
|
||||
}
|
||||
|
||||
return { suggestions: list as never };
|
||||
},
|
||||
});
|
||||
return () => disposable.dispose();
|
||||
}, [language, modelPath, monaco]);
|
||||
|
||||
useEffect(() => () => {
|
||||
if (changeTimerRef.current) clearTimeout(changeTimerRef.current);
|
||||
if (selectionTimerRef.current) clearTimeout(selectionTimerRef.current);
|
||||
for (const d of disposablesRef.current.splice(0)) {
|
||||
try { d.dispose(); } catch {}
|
||||
}
|
||||
editorRef.current = null;
|
||||
}, []);
|
||||
|
||||
const handleMount: OnMount = useCallback((editor, monacoInstance) => {
|
||||
for (const d of disposablesRef.current.splice(0)) {
|
||||
try { d.dispose(); } catch {}
|
||||
}
|
||||
editorRef.current = editor;
|
||||
monacoRef.current = monacoInstance;
|
||||
|
||||
const emitExecute = () => {
|
||||
const model = editor.getModel();
|
||||
if (!model) return;
|
||||
const fullValue = model.getValue();
|
||||
const sel = editor.getSelection();
|
||||
const selectedText = sel && !sel.isEmpty() ? model.getValueInRange(sel) : '';
|
||||
const cursorOffset = sel ? model.getOffsetAt(sel.getPosition()) : 0;
|
||||
const currentStatement = selectedText.trim()
|
||||
? selectedText.trim()
|
||||
: extractCurrentSqlStatement(fullValue, cursorOffset);
|
||||
onWidgetEventRef.current('execute', {
|
||||
value: fullValue,
|
||||
selectedText,
|
||||
currentStatement,
|
||||
});
|
||||
};
|
||||
|
||||
const emitFormat = () => {
|
||||
const model = editor.getModel();
|
||||
if (!model) return;
|
||||
onWidgetEventRef.current('format', { value: model.getValue() });
|
||||
};
|
||||
|
||||
const handlePaste = async () => {
|
||||
const text = await readClipboardRef.current();
|
||||
if (text === null) {
|
||||
editor.trigger('keyboard', 'editor.action.clipboardPasteAction', null);
|
||||
return;
|
||||
}
|
||||
if (!text) return;
|
||||
const selections = editor.getSelections();
|
||||
if (!selections || selections.length === 0) return;
|
||||
editor.executeEdits('netcatty-plugin-paste', buildMonacoPasteEdits(text, selections));
|
||||
editor.focus();
|
||||
};
|
||||
|
||||
disposablesRef.current.push(
|
||||
editor.addAction({
|
||||
id: 'netcatty.pluginCodeEditor.execute',
|
||||
label: 'Run Query',
|
||||
keybindings: [monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.Enter],
|
||||
run: emitExecute,
|
||||
}),
|
||||
editor.addAction({
|
||||
id: 'netcatty.pluginCodeEditor.formatAlt',
|
||||
label: 'Format Query',
|
||||
keybindings: [
|
||||
monacoInstance.KeyMod.Shift | monacoInstance.KeyMod.Alt | monacoInstance.KeyCode.KeyF,
|
||||
monacoInstance.KeyMod.Shift | monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyF,
|
||||
],
|
||||
run: emitFormat,
|
||||
}),
|
||||
editor.addAction({
|
||||
id: 'netcatty.pluginCodeEditor.paste',
|
||||
label: 'Paste',
|
||||
keybindings: [monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyV],
|
||||
run: () => {
|
||||
void pasteForMonacoEditorCommand({
|
||||
activeElement: document.activeElement,
|
||||
readClipboardText: () => readClipboardRef.current(),
|
||||
pasteIntoEditor: () => handlePaste(),
|
||||
});
|
||||
},
|
||||
}),
|
||||
editor.onDidChangeCursorSelection(() => {
|
||||
if (selectionTimerRef.current) clearTimeout(selectionTimerRef.current);
|
||||
selectionTimerRef.current = setTimeout(() => {
|
||||
const model = editor.getModel();
|
||||
const sel = editor.getSelection();
|
||||
if (!model || !sel) return;
|
||||
const selectionStart = model.getOffsetAt(sel.getStartPosition());
|
||||
const selectionEnd = model.getOffsetAt(sel.getEndPosition());
|
||||
const selectedText = sel.isEmpty() ? '' : model.getValueInRange(sel);
|
||||
onWidgetEventRef.current('selection', { selectionStart, selectionEnd, selectedText });
|
||||
}, 60);
|
||||
}),
|
||||
);
|
||||
|
||||
requestAnimationFrame(() => editor.layout());
|
||||
}, []);
|
||||
|
||||
const handleChange = useCallback((nextValue: string | undefined) => {
|
||||
const next = nextValue ?? '';
|
||||
lastEmittedValueRef.current = next;
|
||||
if (changeTimerRef.current) clearTimeout(changeTimerRef.current);
|
||||
changeTimerRef.current = setTimeout(() => {
|
||||
onWidgetEventRef.current('change', { value: next });
|
||||
}, 80);
|
||||
}, []);
|
||||
|
||||
const resolvedHeight = typeof height === 'number' ? `${height}px` : height;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="relative h-full w-full min-h-0 min-w-0 overflow-hidden bg-background"
|
||||
style={resolvedHeight !== '100%' ? { height: resolvedHeight } : undefined}
|
||||
data-plugin-code-editor=""
|
||||
>
|
||||
<Editor
|
||||
path={modelPath}
|
||||
height={resolvedHeight}
|
||||
language={language}
|
||||
defaultValue={value}
|
||||
onChange={handleChange}
|
||||
onMount={handleMount}
|
||||
theme={themeName}
|
||||
loading={(
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background">
|
||||
<Loader2 size={18} className="animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
options={{
|
||||
readOnly,
|
||||
contextmenu: false,
|
||||
minimap: { enabled: minimap },
|
||||
fontFamily: '"JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
|
||||
fontSize: 13,
|
||||
fontLigatures: true,
|
||||
lineNumbers,
|
||||
wordWrap,
|
||||
scrollBeyondLastLine: false,
|
||||
automaticLayout: true,
|
||||
tabSize: 2,
|
||||
insertSpaces: true,
|
||||
folding: true,
|
||||
renderLineHighlight: 'line',
|
||||
padding: { top: 8, bottom: 8 },
|
||||
bracketPairColorization: { enabled: true },
|
||||
quickSuggestions: { other: true, comments: false, strings: false },
|
||||
suggestOnTriggerCharacters: true,
|
||||
}}
|
||||
/>
|
||||
{placeholder && !value ? (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute left-[56px] top-2 z-10 font-mono text-[13px] text-muted-foreground/70"
|
||||
>
|
||||
{placeholder}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,551 @@
|
||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
import { ArrowDown, ArrowUp, ArrowUpDown, KeyRound, Loader2 } from 'lucide-react';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type {
|
||||
PluginDataGridColumn,
|
||||
PluginDataGridRow,
|
||||
PluginDataGridWidgetProps,
|
||||
PluginWidgetEventCallback,
|
||||
} from './types';
|
||||
|
||||
const ROW_HEIGHT = 30;
|
||||
const HEADER_HEIGHT = 34;
|
||||
const GUTTER_WIDTH = 64;
|
||||
const DEFAULT_COL_WIDTH = 156;
|
||||
const MIN_COL_WIDTH = 68;
|
||||
const MAX_COL_WIDTH = 640;
|
||||
|
||||
export interface PluginDataGridProps extends PluginDataGridWidgetProps {
|
||||
onWidgetEvent: PluginWidgetEventCallback;
|
||||
}
|
||||
|
||||
function readCellValue(row: PluginDataGridRow, col: PluginDataGridColumn, colIndex: number): unknown {
|
||||
if (Array.isArray(row)) return row[colIndex];
|
||||
if (row && typeof row === 'object') return row[col.name];
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function formatCellDisplay(value: unknown): string {
|
||||
if (value === null || value === undefined) return '';
|
||||
if (typeof value === 'string') return value;
|
||||
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
function isNumericColumn(col: PluginDataGridColumn, value: unknown): boolean {
|
||||
if (typeof value === 'number') return true;
|
||||
if (!col.type) return false;
|
||||
return /\b(int|bigint|smallint|tinyint|decimal|numeric|float|double|real|number|serial)\b/i.test(col.type);
|
||||
}
|
||||
|
||||
export function PluginDataGrid({
|
||||
columns = [],
|
||||
rows = [],
|
||||
dirtyCells,
|
||||
deletedRowIndices,
|
||||
insertedRows = [],
|
||||
selectedRowIndices,
|
||||
sort = null,
|
||||
editable = false,
|
||||
loading = false,
|
||||
emptyMessage = 'No rows returned',
|
||||
onWidgetEvent,
|
||||
}: PluginDataGridProps) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const editInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [colWidths, setColWidths] = useState<Record<string, number>>({});
|
||||
const [activeCell, setActiveCell] = useState<{ rowIndex: number; colIndex: number } | null>(null);
|
||||
const [editingCell, setEditingCell] = useState<{
|
||||
rowIndex: number;
|
||||
colIndex: number;
|
||||
colName: string;
|
||||
draft: string;
|
||||
} | null>(null);
|
||||
const [lastSelectedRow, setLastSelectedRow] = useState<number | null>(null);
|
||||
|
||||
const deletedSet = useMemo(() => new Set(deletedRowIndices ?? []), [deletedRowIndices]);
|
||||
const selectedSet = useMemo(() => new Set(selectedRowIndices ?? []), [selectedRowIndices]);
|
||||
const totalRows = rows.length + insertedRows.length;
|
||||
|
||||
const getColWidth = useCallback((col: PluginDataGridColumn): number => {
|
||||
const custom = colWidths[col.name];
|
||||
if (custom !== undefined) return custom;
|
||||
if (typeof col.width === 'number' && Number.isFinite(col.width)) {
|
||||
return Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH, Math.round(col.width)));
|
||||
}
|
||||
return DEFAULT_COL_WIDTH;
|
||||
}, [colWidths]);
|
||||
|
||||
const rowVirtualizer = useVirtualizer({
|
||||
count: totalRows,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: () => ROW_HEIGHT,
|
||||
overscan: 8,
|
||||
initialRect: { width: 960, height: 420 },
|
||||
});
|
||||
|
||||
const colVirtualizer = useVirtualizer({
|
||||
horizontal: true,
|
||||
count: columns.length,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: (index) => (columns[index] ? getColWidth(columns[index]) : DEFAULT_COL_WIDTH),
|
||||
overscan: 4,
|
||||
initialRect: { width: 960, height: 420 },
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
colVirtualizer.measure();
|
||||
}, [colWidths, columns, colVirtualizer]);
|
||||
|
||||
useEffect(() => {
|
||||
if (editingCell) {
|
||||
const focusInput = () => {
|
||||
editInputRef.current?.focus();
|
||||
editInputRef.current?.select();
|
||||
};
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
requestAnimationFrame(focusInput);
|
||||
} else {
|
||||
focusInput();
|
||||
}
|
||||
}
|
||||
}, [editingCell?.rowIndex, editingCell?.colIndex]);
|
||||
|
||||
const getRowAt = useCallback((rowIndex: number): { row: PluginDataGridRow; isInserted: boolean } | null => {
|
||||
if (rowIndex < rows.length) return { row: rows[rowIndex], isInserted: false };
|
||||
const insertedIdx = rowIndex - rows.length;
|
||||
if (insertedIdx >= 0 && insertedIdx < insertedRows.length) {
|
||||
return { row: insertedRows[insertedIdx], isInserted: true };
|
||||
}
|
||||
return null;
|
||||
}, [rows, insertedRows]);
|
||||
|
||||
const getEffectiveValue = useCallback((rowIndex: number, col: PluginDataGridColumn, colIndex: number) => {
|
||||
const dirtyKey = `${rowIndex}:${col.name}`;
|
||||
const isDirty = Boolean(dirtyCells && Object.prototype.hasOwnProperty.call(dirtyCells, dirtyKey));
|
||||
const entry = getRowAt(rowIndex);
|
||||
const rawValue = entry ? readCellValue(entry.row, col, colIndex) : undefined;
|
||||
return {
|
||||
value: isDirty ? dirtyCells![dirtyKey] : rawValue,
|
||||
isDirty,
|
||||
isInserted: entry?.isInserted ?? false,
|
||||
};
|
||||
}, [dirtyCells, getRowAt]);
|
||||
|
||||
const commitEdit = useCallback((cell: { rowIndex: number; colIndex: number; colName: string; draft: string }, asNull = false) => {
|
||||
setEditingCell(null);
|
||||
onWidgetEvent('cellEdit', {
|
||||
rowIndex: cell.rowIndex,
|
||||
colName: cell.colName,
|
||||
value: asNull ? null : cell.draft,
|
||||
isNull: asNull,
|
||||
});
|
||||
}, [onWidgetEvent]);
|
||||
|
||||
const beginEdit = useCallback((rowIndex: number, colIndex: number) => {
|
||||
if (!editable || deletedSet.has(rowIndex)) return;
|
||||
const col = columns[colIndex];
|
||||
if (!col) return;
|
||||
const { value } = getEffectiveValue(rowIndex, col, colIndex);
|
||||
setActiveCell({ rowIndex, colIndex });
|
||||
setEditingCell({
|
||||
rowIndex,
|
||||
colIndex,
|
||||
colName: col.name,
|
||||
draft: value === null || value === undefined ? '' : formatCellDisplay(value),
|
||||
});
|
||||
}, [editable, deletedSet, columns, getEffectiveValue]);
|
||||
|
||||
const toggleRowSelection = useCallback((rowIndex: number, shiftKey: boolean) => {
|
||||
const next = new Set(selectedSet);
|
||||
if (shiftKey && lastSelectedRow !== null) {
|
||||
const lo = Math.min(lastSelectedRow, rowIndex);
|
||||
const hi = Math.max(lastSelectedRow, rowIndex);
|
||||
for (let i = lo; i <= hi; i += 1) next.add(i);
|
||||
} else if (next.has(rowIndex)) {
|
||||
next.delete(rowIndex);
|
||||
} else {
|
||||
next.add(rowIndex);
|
||||
}
|
||||
setLastSelectedRow(rowIndex);
|
||||
onWidgetEvent('rowSelect', { selectedRowIndices: [...next].sort((a, b) => a - b) });
|
||||
}, [selectedSet, lastSelectedRow, onWidgetEvent]);
|
||||
|
||||
const toggleSelectAll = useCallback(() => {
|
||||
if (totalRows === 0) return;
|
||||
const allSelected = selectedSet.size >= totalRows;
|
||||
const next = allSelected ? [] : Array.from({ length: totalRows }, (_, i) => i);
|
||||
onWidgetEvent('rowSelect', { selectedRowIndices: next });
|
||||
}, [totalRows, selectedSet.size, onWidgetEvent]);
|
||||
|
||||
const handleSortClick = useCallback((col: PluginDataGridColumn) => {
|
||||
if (col.sortable === false) return;
|
||||
const nextDirection = sort?.column === col.name && sort.direction === 'asc' ? 'desc' : 'asc';
|
||||
onWidgetEvent('sortChange', { column: col.name, direction: nextDirection });
|
||||
}, [sort, onWidgetEvent]);
|
||||
|
||||
const startResizeColumn = useCallback((event: React.PointerEvent<HTMLDivElement>, col: PluginDataGridColumn) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const startX = event.clientX;
|
||||
const startWidth = getColWidth(col);
|
||||
const target = event.currentTarget;
|
||||
try { target.setPointerCapture(event.pointerId); } catch {}
|
||||
const onMove = (moveEvent: PointerEvent) => {
|
||||
const nextWidth = Math.max(MIN_COL_WIDTH, Math.min(MAX_COL_WIDTH, Math.round(startWidth + (moveEvent.clientX - startX))));
|
||||
setColWidths((prev) => (prev[col.name] === nextWidth ? prev : { ...prev, [col.name]: nextWidth }));
|
||||
};
|
||||
const onUp = () => {
|
||||
try { target.releasePointerCapture(event.pointerId); } catch {}
|
||||
window.removeEventListener('pointermove', onMove);
|
||||
window.removeEventListener('pointerup', onUp);
|
||||
window.removeEventListener('pointercancel', onUp);
|
||||
};
|
||||
window.addEventListener('pointermove', onMove);
|
||||
window.addEventListener('pointerup', onUp);
|
||||
window.addEventListener('pointercancel', onUp);
|
||||
}, [getColWidth]);
|
||||
|
||||
const handleCellContextMenu = useCallback((
|
||||
event: React.MouseEvent,
|
||||
rowIndex: number,
|
||||
colName: string,
|
||||
) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const surface = scrollRef.current?.closest('[data-plugin-remote-surface]');
|
||||
const rect = surface?.getBoundingClientRect();
|
||||
const x = Math.round(rect ? event.clientX - rect.left : event.clientX);
|
||||
const y = Math.round(rect ? event.clientY - rect.top : event.clientY);
|
||||
onWidgetEvent('cellContextMenu', { rowIndex, colName, x, y });
|
||||
}, [onWidgetEvent]);
|
||||
|
||||
const handleGridKeyDown = useCallback((event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (editingCell || !activeCell || columns.length === 0 || totalRows === 0) return;
|
||||
const { rowIndex, colIndex } = activeCell;
|
||||
if (event.key === 'ArrowDown' && rowIndex + 1 < totalRows) {
|
||||
event.preventDefault();
|
||||
setActiveCell({ rowIndex: rowIndex + 1, colIndex });
|
||||
rowVirtualizer.scrollToIndex(rowIndex + 1);
|
||||
} else if (event.key === 'ArrowUp' && rowIndex > 0) {
|
||||
event.preventDefault();
|
||||
setActiveCell({ rowIndex: rowIndex - 1, colIndex });
|
||||
rowVirtualizer.scrollToIndex(rowIndex - 1);
|
||||
} else if (event.key === 'ArrowRight' && colIndex + 1 < columns.length) {
|
||||
event.preventDefault();
|
||||
setActiveCell({ rowIndex, colIndex: colIndex + 1 });
|
||||
colVirtualizer.scrollToIndex(colIndex + 1);
|
||||
} else if (event.key === 'ArrowLeft' && colIndex > 0) {
|
||||
event.preventDefault();
|
||||
setActiveCell({ rowIndex, colIndex: colIndex - 1 });
|
||||
colVirtualizer.scrollToIndex(colIndex - 1);
|
||||
} else if (event.key === 'Enter' && editable) {
|
||||
event.preventDefault();
|
||||
beginEdit(rowIndex, colIndex);
|
||||
}
|
||||
}, [editingCell, activeCell, columns.length, totalRows, rowVirtualizer, colVirtualizer, editable, beginEdit]);
|
||||
|
||||
const virtualRows = rowVirtualizer.getVirtualItems();
|
||||
const virtualCols = colVirtualizer.getVirtualItems();
|
||||
const totalWidth = GUTTER_WIDTH + colVirtualizer.getTotalSize();
|
||||
const totalHeight = rowVirtualizer.getTotalSize();
|
||||
const allSelected = totalRows > 0 && selectedSet.size >= totalRows;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="relative flex h-full w-full min-h-0 min-w-0 flex-col overflow-hidden bg-background text-foreground select-none"
|
||||
data-plugin-data-grid=""
|
||||
tabIndex={0}
|
||||
onKeyDown={handleGridKeyDown}
|
||||
>
|
||||
{loading && (
|
||||
<div className="pointer-events-none absolute inset-x-0 top-0 z-30 flex items-center justify-end px-2 py-1">
|
||||
<span className="inline-flex items-center gap-1.5 rounded-md border border-border bg-background/95 px-2 py-0.5 text-[11px] text-muted-foreground shadow-sm">
|
||||
<Loader2 size={12} className="animate-spin" />
|
||||
Loading...
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="relative h-full w-full min-h-0 flex-1 overflow-auto [&::-webkit-scrollbar]:w-1.5 [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-corner]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-muted-foreground/20 hover:[&::-webkit-scrollbar-thumb]:bg-muted-foreground/40"
|
||||
>
|
||||
{columns.length === 0 ? (
|
||||
<div className="flex h-full w-full items-center justify-center p-6 text-xs text-muted-foreground">
|
||||
{emptyMessage}
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ width: totalWidth, minWidth: '100%', position: 'relative' }}>
|
||||
{/* Sticky Header */}
|
||||
<div
|
||||
role="row"
|
||||
className="sticky top-0 z-30 flex border-b border-border bg-muted text-[11px] font-medium text-foreground"
|
||||
style={{ height: HEADER_HEIGHT, width: totalWidth, minWidth: '100%' }}
|
||||
>
|
||||
<div
|
||||
className="sticky left-0 z-40 flex shrink-0 items-center justify-between border-r border-border bg-muted px-2 text-[10px] text-muted-foreground"
|
||||
style={{ width: GUTTER_WIDTH, height: HEADER_HEIGHT }}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label="Select all rows"
|
||||
checked={allSelected}
|
||||
onChange={toggleSelectAll}
|
||||
className="h-3.5 w-3.5 rounded border-border accent-primary cursor-pointer"
|
||||
/>
|
||||
<span className="font-mono">#</span>
|
||||
</div>
|
||||
|
||||
<div className="relative flex-1" style={{ height: HEADER_HEIGHT }}>
|
||||
{virtualCols.map((vCol) => {
|
||||
const col = columns[vCol.index];
|
||||
if (!col) return null;
|
||||
const isSorted = sort?.column === col.name;
|
||||
const sortable = col.sortable !== false;
|
||||
return (
|
||||
<div
|
||||
key={col.name}
|
||||
role="columnheader"
|
||||
data-col-name={col.name}
|
||||
className="group absolute top-0 bottom-0 flex items-center justify-between gap-1 border-r border-border/70 px-2.5"
|
||||
style={{
|
||||
left: vCol.start,
|
||||
width: vCol.size,
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!sortable}
|
||||
onClick={() => handleSortClick(col)}
|
||||
className={`flex min-w-0 flex-1 items-center gap-1.5 text-left ${sortable ? 'cursor-pointer hover:text-primary' : 'cursor-default'}`}
|
||||
title={col.type ? `${col.name} (${col.type})` : col.name}
|
||||
>
|
||||
{col.primaryKey && (
|
||||
<KeyRound size={11} className="shrink-0 text-amber-500" aria-label="Primary key" />
|
||||
)}
|
||||
<span className="truncate font-medium">{col.name}</span>
|
||||
{col.type && (
|
||||
<span className="truncate font-mono text-[10px] font-normal text-muted-foreground">
|
||||
{col.type}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{sortable && (
|
||||
<span className="shrink-0 text-muted-foreground/70">
|
||||
{isSorted ? (
|
||||
sort.direction === 'asc' ? <ArrowUp size={11} className="text-primary" /> : <ArrowDown size={11} className="text-primary" />
|
||||
) : (
|
||||
<ArrowUpDown size={10} className="opacity-0 group-hover:opacity-70 transition-opacity" />
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
onPointerDown={(e) => startResizeColumn(e, col)}
|
||||
className="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/60"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Virtualized Rows Body */}
|
||||
{totalRows === 0 ? (
|
||||
<div className="flex h-40 w-full items-center justify-center text-xs text-muted-foreground">
|
||||
{emptyMessage}
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ height: totalHeight, width: totalWidth, minWidth: '100%', position: 'relative' }}>
|
||||
{virtualRows.map((vRow) => {
|
||||
const rowIndex = vRow.index;
|
||||
const entry = getRowAt(rowIndex);
|
||||
if (!entry) return null;
|
||||
const isDeleted = deletedSet.has(rowIndex);
|
||||
const isSelected = selectedSet.has(rowIndex);
|
||||
const isInserted = entry.isInserted;
|
||||
|
||||
const rowBg = isDeleted
|
||||
? 'bg-destructive/10 text-destructive/80 line-through'
|
||||
: isInserted
|
||||
? 'bg-emerald-500/10'
|
||||
: isSelected
|
||||
? 'bg-primary/10'
|
||||
: rowIndex % 2 === 1
|
||||
? 'bg-muted/20'
|
||||
: 'bg-background';
|
||||
|
||||
return (
|
||||
<div
|
||||
key={rowIndex}
|
||||
role="row"
|
||||
data-row-index={rowIndex}
|
||||
className={`absolute left-0 flex border-b border-border/50 hover:bg-muted/50 ${rowBg}`}
|
||||
style={{
|
||||
top: vRow.start,
|
||||
height: vRow.size,
|
||||
width: totalWidth,
|
||||
minWidth: '100%',
|
||||
}}
|
||||
>
|
||||
{/* Sticky Gutter */}
|
||||
<div
|
||||
className="sticky left-0 z-10 flex shrink-0 items-center justify-between border-r border-border/70 bg-background px-2 font-mono text-[10px] tabular-nums text-muted-foreground"
|
||||
style={{ width: GUTTER_WIDTH, height: ROW_HEIGHT }}
|
||||
onContextMenu={(e) => handleCellContextMenu(e, rowIndex, columns[0]?.name ?? '')}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`Select row ${rowIndex + 1}`}
|
||||
checked={isSelected}
|
||||
onChange={() => {}}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
toggleRowSelection(rowIndex, e.shiftKey);
|
||||
}}
|
||||
className="h-3.5 w-3.5 rounded border-border accent-primary cursor-pointer"
|
||||
/>
|
||||
<span className={isInserted ? 'font-bold text-emerald-500' : ''}>
|
||||
{isInserted ? '+' : rowIndex + 1}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Virtualized Cells */}
|
||||
<div className="relative z-0 flex-1 overflow-hidden" style={{ height: ROW_HEIGHT }}>
|
||||
{virtualCols.map((vCol) => {
|
||||
const colIndex = vCol.index;
|
||||
const col = columns[colIndex];
|
||||
if (!col) return null;
|
||||
const { value, isDirty } = getEffectiveValue(rowIndex, col, colIndex);
|
||||
const isEditing = editingCell?.rowIndex === rowIndex && editingCell?.colIndex === colIndex;
|
||||
const isActive = activeCell?.rowIndex === rowIndex && activeCell?.colIndex === colIndex;
|
||||
const isNull = value === null || value === undefined;
|
||||
const numeric = !isNull && isNumericColumn(col, value);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={col.name}
|
||||
role="gridcell"
|
||||
data-row-index={rowIndex}
|
||||
data-col-name={col.name}
|
||||
data-dirty={isDirty ? 'true' : undefined}
|
||||
className={`absolute top-0 bottom-0 flex items-center border-r border-border/50 px-2.5 font-mono text-[12px] tabular-nums overflow-hidden ${
|
||||
isDirty ? 'bg-amber-500/15 ring-1 ring-inset ring-amber-500/50' : ''
|
||||
} ${isActive ? 'ring-2 ring-inset ring-primary z-[5]' : ''} ${
|
||||
numeric ? 'justify-end' : 'justify-start'
|
||||
}`}
|
||||
style={{ left: vCol.start, width: vCol.size }}
|
||||
onClick={() => {
|
||||
setActiveCell({ rowIndex, colIndex });
|
||||
onWidgetEvent('cellSelect', {
|
||||
rowIndex,
|
||||
colName: col.name,
|
||||
value: value === undefined ? null : value,
|
||||
});
|
||||
}}
|
||||
onDoubleClick={() => beginEdit(rowIndex, colIndex)}
|
||||
onContextMenu={(e) => handleCellContextMenu(e, rowIndex, col.name)}
|
||||
>
|
||||
{isEditing ? (
|
||||
<div
|
||||
className="flex h-full w-full items-center gap-1"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onDoubleClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<input
|
||||
ref={editInputRef}
|
||||
type="text"
|
||||
value={editingCell.draft}
|
||||
onChange={(e) => setEditingCell({ ...editingCell, draft: e.target.value })}
|
||||
onKeyDown={(e) => {
|
||||
e.stopPropagation();
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
commitEdit(editingCell, false);
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
setEditingCell(null);
|
||||
} else if (e.key === 'Tab') {
|
||||
e.preventDefault();
|
||||
commitEdit(editingCell, false);
|
||||
const nextCol = e.shiftKey ? colIndex - 1 : colIndex + 1;
|
||||
if (nextCol >= 0 && nextCol < columns.length) {
|
||||
beginEdit(rowIndex, nextCol);
|
||||
}
|
||||
}
|
||||
}}
|
||||
onBlur={() => {
|
||||
// Delay slightly so clicking the inline NULL button wins over blur.
|
||||
const snapshot = editingCell;
|
||||
setTimeout(() => {
|
||||
setEditingCell((curr) => {
|
||||
if (curr && curr.rowIndex === snapshot.rowIndex && curr.colIndex === snapshot.colIndex) {
|
||||
onWidgetEvent('cellEdit', {
|
||||
rowIndex: curr.rowIndex,
|
||||
colName: curr.colName,
|
||||
value: curr.draft,
|
||||
isNull: false,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
return curr;
|
||||
});
|
||||
}, 0);
|
||||
}}
|
||||
className="h-6 min-w-0 flex-1 rounded border border-primary bg-background px-1.5 font-mono text-[12px] text-foreground outline-none"
|
||||
/>
|
||||
{col.nullable !== false && (
|
||||
<button
|
||||
type="button"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
commitEdit(editingCell, true);
|
||||
}}
|
||||
className="shrink-0 rounded border border-border bg-muted px-1 py-0.5 text-[10px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
title="Set value to NULL"
|
||||
>
|
||||
NULL
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
) : isNull ? (
|
||||
<span className="inline-flex items-center rounded bg-muted px-1.5 py-0.5 text-[10px] italic text-muted-foreground">
|
||||
NULL
|
||||
</span>
|
||||
) : typeof value === 'boolean' ? (
|
||||
<span
|
||||
className={`inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium ${
|
||||
value
|
||||
? 'bg-emerald-500/15 text-emerald-600 dark:text-emerald-400'
|
||||
: 'bg-muted text-muted-foreground'
|
||||
}`}
|
||||
>
|
||||
{value ? 'true' : 'false'}
|
||||
</span>
|
||||
) : (
|
||||
<span className="truncate" title={formatCellDisplay(value)}>
|
||||
{formatCellDisplay(value)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
import { Maximize2, RotateCcw, ZoomIn, ZoomOut } from 'lucide-react';
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type {
|
||||
PluginErCanvasWidgetProps,
|
||||
PluginErTable,
|
||||
PluginWidgetEventCallback,
|
||||
} from './types';
|
||||
|
||||
const CARD_WIDTH = 236;
|
||||
const CARD_HEADER_HEIGHT = 34;
|
||||
const CARD_ROW_HEIGHT = 24;
|
||||
const CARD_FOOTER_PADDING = 8;
|
||||
const GRID_GAP_X = 76;
|
||||
const GRID_GAP_Y = 56;
|
||||
const MIN_ZOOM = 0.25;
|
||||
const MAX_ZOOM = 2.5;
|
||||
|
||||
export interface PluginErCanvasProps extends PluginErCanvasWidgetProps {
|
||||
onWidgetEvent: PluginWidgetEventCallback;
|
||||
}
|
||||
|
||||
function tableKey(table: Pick<PluginErTable, 'name' | 'schema'>): string {
|
||||
return table.schema ? `${table.schema}.${table.name}` : table.name;
|
||||
}
|
||||
|
||||
function cardHeight(table: PluginErTable): number {
|
||||
return CARD_HEADER_HEIGHT + Math.max(1, table.columns.length) * CARD_ROW_HEIGHT + CARD_FOOTER_PADDING;
|
||||
}
|
||||
|
||||
function computeInitialPositions(tables: PluginErTable[]): Record<string, { x: number; y: number }> {
|
||||
const result: Record<string, { x: number; y: number }> = {};
|
||||
const colsPerRow = Math.max(1, Math.min(4, Math.ceil(Math.sqrt(tables.length || 1))));
|
||||
const colY = Array.from({ length: colsPerRow }, () => 40);
|
||||
|
||||
tables.forEach((table, index) => {
|
||||
const key = tableKey(table);
|
||||
if (typeof table.x === 'number' && Number.isFinite(table.x) && typeof table.y === 'number' && Number.isFinite(table.y)) {
|
||||
result[key] = { x: table.x, y: table.y };
|
||||
return;
|
||||
}
|
||||
const colIdx = index % colsPerRow;
|
||||
const x = 40 + colIdx * (CARD_WIDTH + GRID_GAP_X);
|
||||
const y = colY[colIdx];
|
||||
result[key] = { x, y };
|
||||
colY[colIdx] = y + cardHeight(table) + GRID_GAP_Y;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function PluginErCanvas({
|
||||
tables = [],
|
||||
relations = [],
|
||||
onWidgetEvent,
|
||||
}: PluginErCanvasProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [positions, setPositions] = useState<Record<string, { x: number; y: number }>>(() => computeInitialPositions(tables));
|
||||
const [viewport, setViewport] = useState({ x: 0, y: 0, zoom: 1 });
|
||||
const [selectedTable, setSelectedTable] = useState<string | null>(null);
|
||||
const [hoveredRelation, setHoveredRelation] = useState<number | null>(null);
|
||||
const [panning, setPanning] = useState(false);
|
||||
|
||||
const tableSignature = useMemo(
|
||||
() => tables.map((t) => `${tableKey(t)}:${t.x ?? ''}:${t.y ?? ''}`).join('|'),
|
||||
[tables],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setPositions((prev) => {
|
||||
const defaults = computeInitialPositions(tables);
|
||||
const next: Record<string, { x: number; y: number }> = {};
|
||||
for (const tbl of tables) {
|
||||
const key = tableKey(tbl);
|
||||
next[key] = prev[key] ?? defaults[key];
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, [tableSignature, tables]);
|
||||
|
||||
const tableLookup = useMemo(() => {
|
||||
const byKey = new Map<string, PluginErTable>();
|
||||
const byName = new Map<string, PluginErTable>();
|
||||
for (const tbl of tables) {
|
||||
byKey.set(tableKey(tbl), tbl);
|
||||
if (!byName.has(tbl.name)) byName.set(tbl.name, tbl);
|
||||
}
|
||||
return { byKey, byName };
|
||||
}, [tables]);
|
||||
|
||||
const resolveTable = useCallback((ref: string): PluginErTable | undefined => (
|
||||
tableLookup.byKey.get(ref) ?? tableLookup.byName.get(ref)
|
||||
), [tableLookup]);
|
||||
|
||||
const fitToView = useCallback(() => {
|
||||
const el = containerRef.current;
|
||||
if (!el || tables.length === 0) {
|
||||
setViewport({ x: 0, y: 0, zoom: 1 });
|
||||
return;
|
||||
}
|
||||
const rect = el.getBoundingClientRect();
|
||||
if (!rect.width || !rect.height) return;
|
||||
let minX = Infinity;
|
||||
let minY = Infinity;
|
||||
let maxX = -Infinity;
|
||||
let maxY = -Infinity;
|
||||
for (const tbl of tables) {
|
||||
const pos = positions[tableKey(tbl)] ?? { x: 0, y: 0 };
|
||||
minX = Math.min(minX, pos.x);
|
||||
minY = Math.min(minY, pos.y);
|
||||
maxX = Math.max(maxX, pos.x + CARD_WIDTH);
|
||||
maxY = Math.max(maxY, pos.y + cardHeight(tbl));
|
||||
}
|
||||
const contentW = Math.max(1, maxX - minX);
|
||||
const contentH = Math.max(1, maxY - minY);
|
||||
const pad = 48;
|
||||
const zoom = Math.max(
|
||||
MIN_ZOOM,
|
||||
Math.min(1.15, Math.min((rect.width - pad * 2) / contentW, (rect.height - pad * 2) / contentH)),
|
||||
);
|
||||
const x = (rect.width - contentW * zoom) / 2 - minX * zoom;
|
||||
const y = (rect.height - contentH * zoom) / 2 - minY * zoom;
|
||||
setViewport({ x, y, zoom });
|
||||
}, [tables, positions]);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof requestAnimationFrame !== 'function') {
|
||||
fitToView();
|
||||
return;
|
||||
}
|
||||
const frame = requestAnimationFrame(fitToView);
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [tableSignature]);
|
||||
|
||||
const handleWheel = useCallback((event: React.WheelEvent<HTMLDivElement>) => {
|
||||
event.preventDefault();
|
||||
const el = containerRef.current;
|
||||
if (!el) return;
|
||||
const rect = el.getBoundingClientRect();
|
||||
const mouseX = event.clientX - rect.left;
|
||||
const mouseY = event.clientY - rect.top;
|
||||
const factor = event.deltaY < 0 ? 1.1 : 0.9;
|
||||
setViewport((prev) => {
|
||||
const nextZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, prev.zoom * factor));
|
||||
const scale = nextZoom / prev.zoom;
|
||||
return {
|
||||
zoom: nextZoom,
|
||||
x: mouseX - (mouseX - prev.x) * scale,
|
||||
y: mouseY - (mouseY - prev.y) * scale,
|
||||
};
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleCanvasPointerDown = useCallback((event: React.PointerEvent<SVGSVGElement>) => {
|
||||
if (event.button !== 0) return;
|
||||
if ((event.target as Element).closest?.('[data-er-table]')) return;
|
||||
event.preventDefault();
|
||||
const startX = event.clientX;
|
||||
const startY = event.clientY;
|
||||
const initialX = viewport.x;
|
||||
const initialY = viewport.y;
|
||||
setPanning(true);
|
||||
const onMove = (moveEvent: PointerEvent) => {
|
||||
setViewport((prev) => ({
|
||||
...prev,
|
||||
x: initialX + (moveEvent.clientX - startX),
|
||||
y: initialY + (moveEvent.clientY - startY),
|
||||
}));
|
||||
};
|
||||
const onUp = () => {
|
||||
setPanning(false);
|
||||
window.removeEventListener('pointermove', onMove);
|
||||
window.removeEventListener('pointerup', onUp);
|
||||
window.removeEventListener('pointercancel', onUp);
|
||||
};
|
||||
window.addEventListener('pointermove', onMove);
|
||||
window.addEventListener('pointerup', onUp);
|
||||
window.addEventListener('pointercancel', onUp);
|
||||
}, [viewport.x, viewport.y]);
|
||||
|
||||
const startCardDrag = useCallback((event: React.PointerEvent<SVGGElement>, table: PluginErTable) => {
|
||||
if (event.button !== 0) return;
|
||||
event.stopPropagation();
|
||||
const key = tableKey(table);
|
||||
const startX = event.clientX;
|
||||
const startY = event.clientY;
|
||||
const origin = positions[key] ?? { x: 0, y: 0 };
|
||||
const zoom = viewport.zoom;
|
||||
let moved = false;
|
||||
|
||||
const onMove = (moveEvent: PointerEvent) => {
|
||||
const dx = moveEvent.clientX - startX;
|
||||
const dy = moveEvent.clientY - startY;
|
||||
if (Math.abs(dx) > 3 || Math.abs(dy) > 3) moved = true;
|
||||
if (!moved) return;
|
||||
setPositions((prev) => ({
|
||||
...prev,
|
||||
[key]: { x: Math.round(origin.x + dx / zoom), y: Math.round(origin.y + dy / zoom) },
|
||||
}));
|
||||
};
|
||||
|
||||
const onUp = () => {
|
||||
window.removeEventListener('pointermove', onMove);
|
||||
window.removeEventListener('pointerup', onUp);
|
||||
window.removeEventListener('pointercancel', onUp);
|
||||
if (!moved) {
|
||||
setSelectedTable(key);
|
||||
onWidgetEvent('tableClick', {
|
||||
table: table.name,
|
||||
...(table.schema ? { schema: table.schema } : {}),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('pointermove', onMove);
|
||||
window.addEventListener('pointerup', onUp);
|
||||
window.addEventListener('pointercancel', onUp);
|
||||
}, [positions, viewport.zoom, onWidgetEvent]);
|
||||
|
||||
const zoomBy = useCallback((factor: number) => {
|
||||
const el = containerRef.current;
|
||||
const rect = el?.getBoundingClientRect();
|
||||
const cx = rect ? rect.width / 2 : 300;
|
||||
const cy = rect ? rect.height / 2 : 200;
|
||||
setViewport((prev) => {
|
||||
const nextZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, prev.zoom * factor));
|
||||
const scale = nextZoom / prev.zoom;
|
||||
return {
|
||||
zoom: nextZoom,
|
||||
x: cx - (cx - prev.x) * scale,
|
||||
y: cy - (cy - prev.y) * scale,
|
||||
};
|
||||
});
|
||||
}, []);
|
||||
|
||||
const resetLayout = useCallback(() => {
|
||||
setPositions(computeInitialPositions(tables));
|
||||
requestAnimationFrame(fitToView);
|
||||
}, [tables, fitToView]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
data-plugin-er-canvas=""
|
||||
onWheel={handleWheel}
|
||||
className="relative h-full w-full min-h-0 min-w-0 overflow-hidden bg-background text-foreground select-none"
|
||||
>
|
||||
{/* Floating Canvas Controls */}
|
||||
<div className="absolute right-3 top-3 z-20 flex items-center gap-1 rounded-lg border border-border bg-background/95 p-1 shadow-sm backdrop-blur-sm">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => zoomBy(1.2)}
|
||||
aria-label="Zoom in"
|
||||
title="Zoom in"
|
||||
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-accent text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ZoomIn size={13} />
|
||||
</button>
|
||||
<span className="min-w-[40px] text-center font-mono text-[11px] tabular-nums text-muted-foreground">
|
||||
{Math.round(viewport.zoom * 100)}%
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => zoomBy(1 / 1.2)}
|
||||
aria-label="Zoom out"
|
||||
title="Zoom out"
|
||||
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-accent text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ZoomOut size={13} />
|
||||
</button>
|
||||
<div className="mx-0.5 h-4 w-px bg-border" />
|
||||
<button
|
||||
type="button"
|
||||
onClick={fitToView}
|
||||
aria-label="Fit to view"
|
||||
title="Fit to view"
|
||||
className="inline-flex h-6 items-center gap-1 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
<Maximize2 size={12} />
|
||||
Fit
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={resetLayout}
|
||||
aria-label="Reset layout"
|
||||
title="Reset layout"
|
||||
className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-accent text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<RotateCcw size={12} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{tables.length === 0 ? (
|
||||
<div className="flex h-full w-full items-center justify-center text-xs text-muted-foreground">
|
||||
No tables to visualize
|
||||
</div>
|
||||
) : (
|
||||
<svg
|
||||
className={`h-full w-full ${panning ? 'cursor-grabbing' : 'cursor-grab'}`}
|
||||
onPointerDown={handleCanvasPointerDown}
|
||||
>
|
||||
<defs>
|
||||
<pattern id="nc-er-dots" width="20" height="20" patternUnits="userSpaceOnUse">
|
||||
<circle cx="1" cy="1" r="1" fill="hsl(var(--border))" opacity="0.55" />
|
||||
</pattern>
|
||||
<filter id="nc-er-shadow" x="-10%" y="-10%" width="120%" height="125%">
|
||||
<feDropShadow dx="0" dy="2" stdDeviation="3" floodColor="#000000" floodOpacity="0.14" />
|
||||
</filter>
|
||||
</defs>
|
||||
<rect width="100%" height="100%" fill="url(#nc-er-dots)" />
|
||||
|
||||
<g transform={`translate(${viewport.x}, ${viewport.y}) scale(${viewport.zoom})`}>
|
||||
{/* Foreign Key Bezier Curves */}
|
||||
{relations.map((rel, idx) => {
|
||||
const fromTable = resolveTable(rel.fromTable);
|
||||
const toTable = resolveTable(rel.toTable);
|
||||
if (!fromTable || !toTable) return null;
|
||||
const fromKey = tableKey(fromTable);
|
||||
const toKey = tableKey(toTable);
|
||||
const fromPos = positions[fromKey] ?? { x: 0, y: 0 };
|
||||
const toPos = positions[toKey] ?? { x: 0, y: 0 };
|
||||
const fromColIdx = Math.max(0, fromTable.columns.findIndex((c) => c.name === rel.fromColumn));
|
||||
const toColIdx = Math.max(0, toTable.columns.findIndex((c) => c.name === rel.toColumn));
|
||||
const y1 = fromPos.y + CARD_HEADER_HEIGHT + fromColIdx * CARD_ROW_HEIGHT + CARD_ROW_HEIGHT / 2;
|
||||
const y2 = toPos.y + CARD_HEADER_HEIGHT + toColIdx * CARD_ROW_HEIGHT + CARD_ROW_HEIGHT / 2;
|
||||
const fromCenter = fromPos.x + CARD_WIDTH / 2;
|
||||
const toCenter = toPos.x + CARD_WIDTH / 2;
|
||||
const goRight = toCenter >= fromCenter;
|
||||
const x1 = goRight ? fromPos.x + CARD_WIDTH : fromPos.x;
|
||||
const x2 = goRight ? toPos.x : toPos.x + CARD_WIDTH;
|
||||
const dx = Math.max(48, Math.abs(x2 - x1) * 0.45);
|
||||
const c1x = goRight ? x1 + dx : x1 - dx;
|
||||
const c2x = goRight ? x2 - dx : x2 + dx;
|
||||
const highlighted = hoveredRelation === idx || selectedTable === fromKey || selectedTable === toKey;
|
||||
const stroke = highlighted ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))';
|
||||
|
||||
return (
|
||||
<g
|
||||
key={rel.name ?? `${fromKey}.${rel.fromColumn}->${toKey}.${rel.toColumn}:${idx}`}
|
||||
onPointerEnter={() => setHoveredRelation(idx)}
|
||||
onPointerLeave={() => setHoveredRelation(null)}
|
||||
>
|
||||
<path
|
||||
d={`M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}`}
|
||||
fill="none"
|
||||
stroke="transparent"
|
||||
strokeWidth={12}
|
||||
/>
|
||||
<path
|
||||
d={`M ${x1} ${y1} C ${c1x} ${y1}, ${c2x} ${y2}, ${x2} ${y2}`}
|
||||
fill="none"
|
||||
stroke={stroke}
|
||||
strokeWidth={highlighted ? 2.2 : 1.4}
|
||||
strokeOpacity={highlighted ? 1 : 0.65}
|
||||
/>
|
||||
<circle cx={x1} cy={y1} r={3.5} fill={stroke} />
|
||||
<circle cx={x2} cy={y2} r={3.5} fill="hsl(var(--background))" stroke={stroke} strokeWidth={1.8} />
|
||||
{rel.name && highlighted && (
|
||||
<text
|
||||
x={(x1 + x2) / 2}
|
||||
y={(y1 + y2) / 2 - 6}
|
||||
textAnchor="middle"
|
||||
fontSize={10}
|
||||
fontFamily="var(--font-mono)"
|
||||
fill="hsl(var(--primary))"
|
||||
>
|
||||
{rel.name}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Table Cards */}
|
||||
{tables.map((table) => {
|
||||
const key = tableKey(table);
|
||||
const pos = positions[key] ?? { x: 0, y: 0 };
|
||||
const height = cardHeight(table);
|
||||
const isSelected = selectedTable === key;
|
||||
|
||||
return (
|
||||
<g
|
||||
key={key}
|
||||
data-er-table={table.name}
|
||||
transform={`translate(${pos.x}, ${pos.y})`}
|
||||
onPointerDown={(e) => startCardDrag(e, table)}
|
||||
className="cursor-pointer"
|
||||
filter="url(#nc-er-shadow)"
|
||||
>
|
||||
<rect
|
||||
width={CARD_WIDTH}
|
||||
height={height}
|
||||
rx={8}
|
||||
fill="hsl(var(--card))"
|
||||
stroke={isSelected ? 'hsl(var(--primary))' : 'hsl(var(--border))'}
|
||||
strokeWidth={isSelected ? 2 : 1}
|
||||
/>
|
||||
{/* Header band */}
|
||||
<path
|
||||
d={`M 0 8 Q 0 0 8 0 L ${CARD_WIDTH - 8} 0 Q ${CARD_WIDTH} 0 ${CARD_WIDTH} 8 L ${CARD_WIDTH} ${CARD_HEADER_HEIGHT} L 0 ${CARD_HEADER_HEIGHT} Z`}
|
||||
fill="hsl(var(--muted))"
|
||||
/>
|
||||
<line
|
||||
x1={0}
|
||||
y1={CARD_HEADER_HEIGHT}
|
||||
x2={CARD_WIDTH}
|
||||
y2={CARD_HEADER_HEIGHT}
|
||||
stroke="hsl(var(--border))"
|
||||
strokeWidth={1}
|
||||
/>
|
||||
<text
|
||||
x={12}
|
||||
y={21}
|
||||
fontSize={12}
|
||||
fontWeight={600}
|
||||
fontFamily="var(--font-sans)"
|
||||
fill="hsl(var(--card-foreground))"
|
||||
>
|
||||
{table.schema ? `${table.schema}.${table.name}` : table.name}
|
||||
</text>
|
||||
|
||||
{/* Columns */}
|
||||
{table.columns.map((col, colIdx) => {
|
||||
const rowY = CARD_HEADER_HEIGHT + colIdx * CARD_ROW_HEIGHT;
|
||||
const badgeOffset = (col.isPk ? 26 : 0) + (col.isFk ? 26 : 0);
|
||||
return (
|
||||
<g key={col.name} transform={`translate(0, ${rowY})`}>
|
||||
{colIdx > 0 && (
|
||||
<line
|
||||
x1={8}
|
||||
y1={0}
|
||||
x2={CARD_WIDTH - 8}
|
||||
y2={0}
|
||||
stroke="hsl(var(--border))"
|
||||
strokeOpacity={0.45}
|
||||
strokeWidth={0.75}
|
||||
/>
|
||||
)}
|
||||
{col.isPk && (
|
||||
<g transform="translate(8, 5)">
|
||||
<rect width={22} height={14} rx={3} fill="#f59e0b" fillOpacity={0.2} />
|
||||
<text x={11} y={10.5} textAnchor="middle" fontSize={9} fontWeight={700} fill="#d97706">
|
||||
PK
|
||||
</text>
|
||||
</g>
|
||||
)}
|
||||
{col.isFk && (
|
||||
<g transform={`translate(${col.isPk ? 34 : 8}, 5)`}>
|
||||
<rect width={22} height={14} rx={3} fill="#3b82f6" fillOpacity={0.2} />
|
||||
<text x={11} y={10.5} textAnchor="middle" fontSize={9} fontWeight={700} fill="#2563eb">
|
||||
FK
|
||||
</text>
|
||||
</g>
|
||||
)}
|
||||
<text
|
||||
x={10 + badgeOffset}
|
||||
y={16}
|
||||
fontSize={11}
|
||||
fontFamily="var(--font-mono)"
|
||||
fill="hsl(var(--card-foreground))"
|
||||
>
|
||||
{col.name.length > 18 ? `${col.name.slice(0, 17)}…` : col.name}
|
||||
</text>
|
||||
<text
|
||||
x={CARD_WIDTH - 10}
|
||||
y={16}
|
||||
textAnchor="end"
|
||||
fontSize={10}
|
||||
fontFamily="var(--font-mono)"
|
||||
fill="hsl(var(--muted-foreground))"
|
||||
>
|
||||
{`${col.type}${col.nullable ? '?' : ''}`.slice(0, 14)}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { PluginSplitPaneWidgetProps, PluginWidgetEventCallback } from './types';
|
||||
|
||||
export interface PluginSplitPaneProps extends PluginSplitPaneWidgetProps {
|
||||
firstChild: React.ReactNode;
|
||||
secondChild: React.ReactNode;
|
||||
nodeId: string;
|
||||
className?: string;
|
||||
inlineStyle?: string;
|
||||
onWidgetEvent: PluginWidgetEventCallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 60fps host-managed 2-child split container rendered inside the shadow root so
|
||||
* child plugin trees keep full plugin CSS scoping and can nest freely.
|
||||
*/
|
||||
export function PluginSplitPane({
|
||||
direction = 'horizontal',
|
||||
initialSize = 260,
|
||||
minSize = 120,
|
||||
maxSize = 900,
|
||||
collapsible = false,
|
||||
collapsed: controlledCollapsed,
|
||||
firstChild,
|
||||
secondChild,
|
||||
nodeId,
|
||||
className,
|
||||
inlineStyle,
|
||||
onWidgetEvent,
|
||||
}: PluginSplitPaneProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const clampSize = useCallback(
|
||||
(raw: number) => Math.max(minSize, Math.min(maxSize, Math.round(raw))),
|
||||
[minSize, maxSize],
|
||||
);
|
||||
|
||||
const [size, setSize] = useState<number>(() => clampSize(initialSize));
|
||||
const [collapsed, setCollapsed] = useState<boolean>(Boolean(controlledCollapsed));
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const sizeRef = useRef(size);
|
||||
sizeRef.current = size;
|
||||
|
||||
useEffect(() => {
|
||||
if (controlledCollapsed !== undefined) setCollapsed(controlledCollapsed);
|
||||
}, [controlledCollapsed]);
|
||||
|
||||
const isHorizontal = direction !== 'vertical';
|
||||
|
||||
const handlePointerDown = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const target = event.currentTarget;
|
||||
const startCoord = isHorizontal ? event.clientX : event.clientY;
|
||||
const startSize = collapsed ? minSize : sizeRef.current;
|
||||
setDragging(true);
|
||||
try { target.setPointerCapture(event.pointerId); } catch {}
|
||||
|
||||
let latestSize = startSize;
|
||||
let latestCollapsed = collapsed;
|
||||
|
||||
const onMove = (moveEvent: PointerEvent) => {
|
||||
const containerRect = containerRef.current?.getBoundingClientRect();
|
||||
const maxFromContainer = containerRect
|
||||
? Math.max(minSize, (isHorizontal ? containerRect.width : containerRect.height) - 64)
|
||||
: maxSize;
|
||||
const effectiveMax = Math.min(maxSize, maxFromContainer);
|
||||
const delta = (isHorizontal ? moveEvent.clientX : moveEvent.clientY) - startCoord;
|
||||
const raw = startSize + delta;
|
||||
if (collapsible && raw < minSize * 0.5) {
|
||||
latestCollapsed = true;
|
||||
setCollapsed(true);
|
||||
} else {
|
||||
latestCollapsed = false;
|
||||
latestSize = Math.max(minSize, Math.min(effectiveMax, Math.round(raw)));
|
||||
setCollapsed(false);
|
||||
setSize(latestSize);
|
||||
}
|
||||
};
|
||||
|
||||
const onUp = () => {
|
||||
setDragging(false);
|
||||
try { target.releasePointerCapture(event.pointerId); } catch {}
|
||||
window.removeEventListener('pointermove', onMove);
|
||||
window.removeEventListener('pointerup', onUp);
|
||||
window.removeEventListener('pointercancel', onUp);
|
||||
onWidgetEvent('resizeEnd', {
|
||||
size: latestCollapsed ? 0 : latestSize,
|
||||
collapsed: latestCollapsed,
|
||||
});
|
||||
};
|
||||
|
||||
window.addEventListener('pointermove', onMove);
|
||||
window.addEventListener('pointerup', onUp);
|
||||
window.addEventListener('pointercancel', onUp);
|
||||
}, [isHorizontal, collapsed, minSize, maxSize, collapsible, onWidgetEvent]);
|
||||
|
||||
const handleDoubleClick = useCallback(() => {
|
||||
if (!collapsible) return;
|
||||
const nextCollapsed = !collapsed;
|
||||
setCollapsed(nextCollapsed);
|
||||
onWidgetEvent('resizeEnd', {
|
||||
size: nextCollapsed ? 0 : sizeRef.current,
|
||||
collapsed: nextCollapsed,
|
||||
});
|
||||
}, [collapsible, collapsed, onWidgetEvent]);
|
||||
|
||||
const setContainerRef = useCallback((el: HTMLDivElement | null) => {
|
||||
containerRef.current = el;
|
||||
if (!el) return;
|
||||
if (inlineStyle) {
|
||||
el.setAttribute('style', `${inlineStyle};display:flex;flex-direction:${isHorizontal ? 'row' : 'column'};width:100%;height:100%;min-width:0;min-height:0;overflow:hidden`);
|
||||
}
|
||||
}, [inlineStyle, isHorizontal]);
|
||||
|
||||
const dividerActive = dragging || hovered;
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setContainerRef}
|
||||
data-netcatty-remote-node={nodeId}
|
||||
data-plugin-widget="split-pane"
|
||||
data-direction={isHorizontal ? 'horizontal' : 'vertical'}
|
||||
className={className}
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: isHorizontal ? 'row' : 'column',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
minWidth: 0,
|
||||
minHeight: 0,
|
||||
overflow: 'hidden',
|
||||
userSelect: dragging ? 'none' : undefined,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
data-split-pane="first"
|
||||
style={{
|
||||
flex: collapsed ? '0 0 0px' : `0 0 ${size}px`,
|
||||
display: collapsed ? 'none' : 'flex',
|
||||
flexDirection: 'column',
|
||||
minWidth: 0,
|
||||
minHeight: 0,
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{firstChild}
|
||||
</div>
|
||||
|
||||
<div
|
||||
role="separator"
|
||||
aria-orientation={isHorizontal ? 'vertical' : 'horizontal'}
|
||||
aria-valuenow={collapsed ? 0 : size}
|
||||
aria-valuemin={minSize}
|
||||
aria-valuemax={maxSize}
|
||||
data-split-handle=""
|
||||
onPointerDown={handlePointerDown}
|
||||
onDoubleClick={handleDoubleClick}
|
||||
onPointerEnter={() => setHovered(true)}
|
||||
onPointerLeave={() => setHovered(false)}
|
||||
style={{
|
||||
position: 'relative',
|
||||
flex: isHorizontal ? '0 0 5px' : '0 0 5px',
|
||||
cursor: isHorizontal ? 'col-resize' : 'row-resize',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: 'transparent',
|
||||
zIndex: 5,
|
||||
touchAction: 'none',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: isHorizontal ? (dividerActive ? '2px' : '1px') : '100%',
|
||||
height: isHorizontal ? '100%' : (dividerActive ? '2px' : '1px'),
|
||||
background: dividerActive ? 'hsl(var(--primary))' : 'hsl(var(--border))',
|
||||
transition: 'background 120ms ease',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
data-split-pane="second"
|
||||
style={{
|
||||
flex: '1 1 0%',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
minWidth: 0,
|
||||
minHeight: 0,
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{secondChild}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { LazyLoadBoundary } from '../../ui/lazy-load-boundary';
|
||||
import { PluginCodeEditor } from './PluginCodeEditor';
|
||||
import { PluginDataGrid } from './PluginDataGrid';
|
||||
import { PluginErCanvas } from './PluginErCanvas';
|
||||
import type {
|
||||
PluginCodeEditorWidgetProps,
|
||||
PluginDataGridWidgetProps,
|
||||
PluginErCanvasWidgetProps,
|
||||
PluginWidgetEventCallback,
|
||||
} from './types';
|
||||
|
||||
export type SlottedWidgetKind = 'code-editor' | 'data-grid' | 'er-canvas';
|
||||
|
||||
export function parseWidgetPropsJson<T extends object>(raw: string | undefined): T {
|
||||
if (!raw) return {} as T;
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed as T;
|
||||
}
|
||||
} catch {
|
||||
// Policy already validates widget props; fall back to empty props defensively.
|
||||
}
|
||||
return {} as T;
|
||||
}
|
||||
|
||||
export function PluginSlottedWidget({
|
||||
kind,
|
||||
rawProps,
|
||||
onWidgetEvent,
|
||||
}: {
|
||||
kind: SlottedWidgetKind;
|
||||
rawProps: string | undefined;
|
||||
onWidgetEvent: PluginWidgetEventCallback;
|
||||
}) {
|
||||
const parsedProps = useMemo(() => parseWidgetPropsJson<Record<string, unknown>>(rawProps), [rawProps]);
|
||||
|
||||
return (
|
||||
<LazyLoadBoundary
|
||||
name={`Plugin ${kind}`}
|
||||
fallback={<div className="flex h-full w-full items-center justify-center p-4 text-xs text-destructive">Unable to render plugin widget.</div>}
|
||||
>
|
||||
{kind === 'code-editor' && (
|
||||
<PluginCodeEditor {...(parsedProps as PluginCodeEditorWidgetProps)} onWidgetEvent={onWidgetEvent} />
|
||||
)}
|
||||
{kind === 'data-grid' && (
|
||||
<PluginDataGrid {...(parsedProps as PluginDataGridWidgetProps)} onWidgetEvent={onWidgetEvent} />
|
||||
)}
|
||||
{kind === 'er-canvas' && (
|
||||
<PluginErCanvas {...(parsedProps as PluginErCanvasWidgetProps)} onWidgetEvent={onWidgetEvent} />
|
||||
)}
|
||||
</LazyLoadBoundary>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { extractCurrentSqlStatement, extractSqlTableAliases } from './sqlStatement';
|
||||
|
||||
test('extractCurrentSqlStatement splits statements respecting strings, comments, and PG dollar quotes', () => {
|
||||
const sql = [
|
||||
"-- first query; not a split",
|
||||
"SELECT 'semi;colon' AS a;",
|
||||
"CREATE FUNCTION f() RETURNS text AS $$ BEGIN RETURN 'x;y'; END; $$ LANGUAGE plpgsql;",
|
||||
"SELECT /* block; comment */ * FROM orders WHERE id = 1",
|
||||
].join('\n');
|
||||
|
||||
const firstIdx = sql.indexOf("SELECT 'semi");
|
||||
assert.equal(extractCurrentSqlStatement(sql, firstIdx + 5), "-- first query; not a split\nSELECT 'semi;colon' AS a");
|
||||
|
||||
const fnIdx = sql.indexOf("RETURN 'x;y'");
|
||||
assert.equal(
|
||||
extractCurrentSqlStatement(sql, fnIdx),
|
||||
"CREATE FUNCTION f() RETURNS text AS $$ BEGIN RETURN 'x;y'; END; $$ LANGUAGE plpgsql",
|
||||
);
|
||||
|
||||
const lastIdx = sql.indexOf('FROM orders');
|
||||
assert.equal(
|
||||
extractCurrentSqlStatement(sql, lastIdx),
|
||||
'SELECT /* block; comment */ * FROM orders WHERE id = 1',
|
||||
);
|
||||
});
|
||||
|
||||
test('extractSqlTableAliases resolves table names and aliases across FROM and JOIN clauses', () => {
|
||||
const sql = 'SELECT o.id, u.email FROM public.orders AS o INNER JOIN users u ON u.id = o.user_id WHERE o.status = 1';
|
||||
const aliases = extractSqlTableAliases(sql);
|
||||
assert.equal(aliases.get('o'), 'orders');
|
||||
assert.equal(aliases.get('orders'), 'orders');
|
||||
assert.equal(aliases.get('u'), 'users');
|
||||
assert.equal(aliases.get('users'), 'users');
|
||||
assert.equal(aliases.has('where'), false);
|
||||
});
|
||||
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* Pure SQL statement and alias helpers used by PluginCodeEditor.
|
||||
* Runs synchronously in the host renderer with zero IPC overhead.
|
||||
*/
|
||||
|
||||
export function extractCurrentSqlStatement(sql: string, cursorOffset: number): string {
|
||||
if (!sql) return '';
|
||||
const clampedCursor = Math.max(0, Math.min(cursorOffset, sql.length));
|
||||
const statements: Array<{ start: number; end: number; text: string }> = [];
|
||||
|
||||
let start = 0;
|
||||
let i = 0;
|
||||
let inSingle = false;
|
||||
let inDouble = false;
|
||||
let inBacktick = false;
|
||||
let inLineComment = false;
|
||||
let inBlockComment = false;
|
||||
let dollarTag: string | null = null;
|
||||
|
||||
while (i < sql.length) {
|
||||
const ch = sql[i];
|
||||
const next = sql[i + 1];
|
||||
|
||||
if (inLineComment) {
|
||||
if (ch === '\n') inLineComment = false;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (inBlockComment) {
|
||||
if (ch === '*' && next === '/') {
|
||||
inBlockComment = false;
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (dollarTag !== null) {
|
||||
if (sql.startsWith(dollarTag, i)) {
|
||||
i += dollarTag.length;
|
||||
dollarTag = null;
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (inSingle) {
|
||||
if (ch === "'" && next === "'") {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === '\\' && next !== undefined) {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === "'") inSingle = false;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (inDouble) {
|
||||
if (ch === '"' && next === '"') {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') inDouble = false;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (inBacktick) {
|
||||
if (ch === '`' && next === '`') {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === '`') inBacktick = false;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '-' && next === '-') {
|
||||
inLineComment = true;
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === '/' && next === '*') {
|
||||
inBlockComment = true;
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === "'") {
|
||||
inSingle = true;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
inDouble = true;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === '`') {
|
||||
inBacktick = true;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === '$') {
|
||||
const match = /^\$[a-zA-Z0-9_]*\$/u.exec(sql.slice(i));
|
||||
if (match) {
|
||||
dollarTag = match[0];
|
||||
i += dollarTag.length;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (ch === ';') {
|
||||
const raw = sql.slice(start, i);
|
||||
if (raw.trim().length > 0) {
|
||||
statements.push({ start, end: i + 1, text: raw.trim() });
|
||||
}
|
||||
start = i + 1;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
const tail = sql.slice(start);
|
||||
if (tail.trim().length > 0) {
|
||||
statements.push({ start, end: sql.length, text: tail.trim() });
|
||||
}
|
||||
|
||||
if (statements.length === 0) return sql.trim();
|
||||
|
||||
for (const stmt of statements) {
|
||||
if (clampedCursor >= stmt.start && clampedCursor <= stmt.end) {
|
||||
return stmt.text;
|
||||
}
|
||||
}
|
||||
// If cursor sits in trailing whitespace after a semicolon, return the preceding statement.
|
||||
let chosen = statements[0];
|
||||
for (const stmt of statements) {
|
||||
if (stmt.start <= clampedCursor) chosen = stmt;
|
||||
}
|
||||
return chosen.text;
|
||||
}
|
||||
|
||||
/** Extract simple `FROM/JOIN [schema.]table [AS] alias` bindings for dot-completion. */
|
||||
export function extractSqlTableAliases(sql: string): Map<string, string> {
|
||||
const aliases = new Map<string, string>();
|
||||
const pattern = /\b(?:from|join|update|into)\s+(?:["`]?([a-zA-Z_][\w$]*)["`]?\.)?["`]?([a-zA-Z_][\w$]*)["`]?(?:\s+(?:as\s+)?["`]?([a-zA-Z_][\w$]*)["`]?)?/giu;
|
||||
const reserved = new Set([
|
||||
'where', 'on', 'set', 'values', 'inner', 'left', 'right', 'full', 'outer',
|
||||
'cross', 'join', 'group', 'order', 'having', 'limit', 'offset', 'union',
|
||||
'select', 'from', 'as', 'using', 'returning',
|
||||
]);
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = pattern.exec(sql)) !== null) {
|
||||
const tableName = match[2];
|
||||
const alias = match[3];
|
||||
if (!tableName) continue;
|
||||
aliases.set(tableName.toLowerCase(), tableName);
|
||||
if (alias && !reserved.has(alias.toLowerCase())) {
|
||||
aliases.set(alias.toLowerCase(), tableName);
|
||||
}
|
||||
}
|
||||
return aliases;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
export type PluginWidgetEventCallback = (
|
||||
widgetEvent: string,
|
||||
detail?: Record<string, unknown>,
|
||||
) => void;
|
||||
|
||||
export interface PluginCodeEditorCompletionColumn {
|
||||
name: string;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
export interface PluginCodeEditorCompletionTable {
|
||||
name: string;
|
||||
schema?: string;
|
||||
columns?: PluginCodeEditorCompletionColumn[];
|
||||
}
|
||||
|
||||
export interface PluginCodeEditorCompletionFunction {
|
||||
name: string;
|
||||
detail?: string;
|
||||
insertText?: string;
|
||||
}
|
||||
|
||||
export interface PluginCodeEditorCompletionSchema {
|
||||
tables?: PluginCodeEditorCompletionTable[];
|
||||
functions?: PluginCodeEditorCompletionFunction[];
|
||||
keywords?: string[];
|
||||
}
|
||||
|
||||
export interface PluginCodeEditorDiagnostic {
|
||||
line: number;
|
||||
column: number;
|
||||
endLine?: number;
|
||||
endColumn?: number;
|
||||
message: string;
|
||||
severity?: 'error' | 'warning' | 'info' | 'hint';
|
||||
}
|
||||
|
||||
export interface PluginCodeEditorWidgetProps {
|
||||
value?: string;
|
||||
language?: 'sql' | 'pgsql' | 'mysql' | 'json' | 'plaintext';
|
||||
readOnly?: boolean;
|
||||
placeholder?: string;
|
||||
lineNumbers?: 'on' | 'off' | 'relative';
|
||||
minimap?: boolean;
|
||||
wordWrap?: 'on' | 'off' | 'wordWrapColumn' | 'bounded';
|
||||
completionSchema?: PluginCodeEditorCompletionSchema;
|
||||
diagnostics?: PluginCodeEditorDiagnostic[];
|
||||
height?: number | string;
|
||||
}
|
||||
|
||||
export interface PluginDataGridColumn {
|
||||
name: string;
|
||||
type?: string;
|
||||
primaryKey?: boolean;
|
||||
nullable?: boolean;
|
||||
width?: number;
|
||||
sortable?: boolean;
|
||||
}
|
||||
|
||||
export interface PluginDataGridSort {
|
||||
column: string;
|
||||
direction: 'asc' | 'desc';
|
||||
}
|
||||
|
||||
export type PluginDataGridRow = Record<string, unknown> | unknown[];
|
||||
|
||||
export interface PluginDataGridWidgetProps {
|
||||
columns?: PluginDataGridColumn[];
|
||||
rows?: PluginDataGridRow[];
|
||||
rowKeyField?: string;
|
||||
dirtyCells?: Record<string, unknown>;
|
||||
deletedRowIndices?: number[];
|
||||
insertedRows?: PluginDataGridRow[];
|
||||
selectedRowIndices?: number[];
|
||||
sort?: PluginDataGridSort | null;
|
||||
editable?: boolean;
|
||||
loading?: boolean;
|
||||
emptyMessage?: string;
|
||||
}
|
||||
|
||||
export interface PluginSplitPaneWidgetProps {
|
||||
direction?: 'horizontal' | 'vertical';
|
||||
initialSize?: number;
|
||||
minSize?: number;
|
||||
maxSize?: number;
|
||||
collapsible?: boolean;
|
||||
collapsed?: boolean;
|
||||
}
|
||||
|
||||
export interface PluginErColumn {
|
||||
name: string;
|
||||
type: string;
|
||||
isPk?: boolean;
|
||||
isFk?: boolean;
|
||||
nullable?: boolean;
|
||||
}
|
||||
|
||||
export interface PluginErTable {
|
||||
name: string;
|
||||
schema?: string;
|
||||
columns: PluginErColumn[];
|
||||
x?: number;
|
||||
y?: number;
|
||||
}
|
||||
|
||||
export interface PluginErRelation {
|
||||
fromTable: string;
|
||||
fromColumn: string;
|
||||
toTable: string;
|
||||
toColumn: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface PluginErCanvasWidgetProps {
|
||||
tables?: PluginErTable[];
|
||||
relations?: PluginErRelation[];
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { renderToStaticMarkup } from "react-dom/server";
|
||||
|
||||
import { I18nProvider } from "../../application/i18n/I18nProvider.tsx";
|
||||
import type { Host } from "../../types.ts";
|
||||
import { TerminalConnectionDialog } from "./TerminalConnectionDialog.tsx";
|
||||
import { TerminalConnectionDialog, resolveChainProgressAddressLine } from "./TerminalConnectionDialog.tsx";
|
||||
|
||||
const host: Host = {
|
||||
id: "host-1",
|
||||
@@ -193,6 +193,68 @@ test("keeps connection log padding inside the scrollable content", () => {
|
||||
assert.match(markup, /class="[^"]*p-2\.5[^"]*pb-4[^"]*pr-4/);
|
||||
});
|
||||
|
||||
test("chain progress shows the current jump hop's address, not the target's", () => {
|
||||
const markup = renderDialog({
|
||||
host: { ...host, label: "Prod DB", hostname: "10.0.0.5" },
|
||||
chainProgress: {
|
||||
currentHop: 2,
|
||||
totalHops: 3,
|
||||
currentHostLabel: "Bastion B",
|
||||
currentHostAddress: "b.example.com:2201",
|
||||
},
|
||||
});
|
||||
|
||||
assert.match(markup, /Chain 2 of 3: <\/span><span>Bastion B<\/span>/);
|
||||
assert.match(markup, /SSH b\.example\.com:2201/);
|
||||
assert.equal(markup.includes("10.0.0.5"), false);
|
||||
});
|
||||
|
||||
test("chain progress shows the target's label and address on the final hop", () => {
|
||||
const markup = renderDialog({
|
||||
host: { ...host, label: "Prod DB", hostname: "10.0.0.5" },
|
||||
chainProgress: {
|
||||
currentHop: 3,
|
||||
totalHops: 3,
|
||||
currentHostLabel: "Prod DB",
|
||||
currentHostAddress: "10.0.0.5:22",
|
||||
},
|
||||
});
|
||||
|
||||
assert.match(markup, /Chain 3 of 3: <\/span><span>Prod DB<\/span>/);
|
||||
assert.match(markup, /SSH 10\.0\.0\.5:22/);
|
||||
});
|
||||
|
||||
test("chain progress address line keeps the target's protocol on the final hop", () => {
|
||||
const t = (key: string) => ({
|
||||
"terminal.connection.protocol.ssh": "SSH",
|
||||
"terminal.connection.protocol.et": "ET",
|
||||
}[key] ?? key);
|
||||
const etInfo = { i18nKey: "terminal.connection.protocol.et", showPort: true, port: 2022 };
|
||||
const target = { hostname: "10.0.0.5" };
|
||||
|
||||
// Jump hop: always SSH with the hop's own address.
|
||||
assert.equal(
|
||||
resolveChainProgressAddressLine(
|
||||
{ currentHop: 1, totalHops: 2, currentHostAddress: "bastion.example.com:22" },
|
||||
target, etInfo, t,
|
||||
),
|
||||
"SSH bastion.example.com:22",
|
||||
);
|
||||
// Final hop: the target's protocol and port (ET 2022, not the SSH port).
|
||||
assert.equal(
|
||||
resolveChainProgressAddressLine(
|
||||
{ currentHop: 2, totalHops: 2, currentHostAddress: "10.0.0.5:22" },
|
||||
target, etInfo, t,
|
||||
),
|
||||
"ET 10.0.0.5:2022",
|
||||
);
|
||||
// Older progress events without an address fall back to the target.
|
||||
assert.equal(
|
||||
resolveChainProgressAddressLine({ currentHop: 1, totalHops: 2 }, target, etInfo, t),
|
||||
"ET 10.0.0.5:2022",
|
||||
);
|
||||
});
|
||||
|
||||
test("shows the ET server port (not the SSH port) for an ET host with a custom etPort", () => {
|
||||
const markup = renderDialog({
|
||||
host: { ...host, etEnabled: true, port: 22, etPort: 9022 },
|
||||
|
||||
@@ -28,8 +28,29 @@ export interface ChainProgress {
|
||||
currentHop: number;
|
||||
totalHops: number;
|
||||
currentHostLabel: string;
|
||||
/** host:port of the hop being connected; falls back to the target's address. */
|
||||
currentHostAddress?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Address line under the "Chain X of Y" heading. Jump hops are always SSH, so
|
||||
* they show the hop's own address; the final hop keeps the target's
|
||||
* protocol-aware line (Mosh/ET/Telnet ports differ from the SSH port).
|
||||
*/
|
||||
export const resolveChainProgressAddressLine = (
|
||||
chainProgress: Pick<ChainProgress, 'currentHop' | 'totalHops' | 'currentHostAddress'>,
|
||||
host: Pick<Host, 'hostname'>,
|
||||
protocolInfo: { i18nKey: string; showPort: boolean; port: number },
|
||||
t: (key: string) => string,
|
||||
): string => {
|
||||
const isJumpHop = chainProgress.currentHop < chainProgress.totalHops;
|
||||
if (isJumpHop && chainProgress.currentHostAddress) {
|
||||
return `${t('terminal.connection.protocol.ssh')} ${chainProgress.currentHostAddress}`;
|
||||
}
|
||||
const address = protocolInfo.showPort ? formatHostPort(host.hostname, protocolInfo.port) : host.hostname;
|
||||
return `${t(protocolInfo.i18nKey)} ${address}`;
|
||||
};
|
||||
|
||||
export interface TerminalConnectionDialogProps {
|
||||
host: Host;
|
||||
status: 'connecting' | 'connected' | 'disconnected';
|
||||
@@ -304,7 +325,7 @@ export const TerminalConnectionDialog: React.FC<TerminalConnectionDialogProps> =
|
||||
className="text-[10px] font-mono truncate"
|
||||
style={{ color: 'color-mix(in srgb, var(--terminal-ui-fg, var(--foreground)) 58%, transparent)' }}
|
||||
>
|
||||
{t(protocolInfo.i18nKey)} {protocolInfo.showPort ? formatHostPort(host.hostname, protocolInfo.port) : host.hostname}
|
||||
{resolveChainProgressAddressLine(chainProgress, host, protocolInfo, t)}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
|
||||
@@ -41,6 +41,7 @@ import { resolveBridgeSshAgentAuth, resolveHostAuth } from "../../../domain/sshA
|
||||
import { connectionTotpFields } from "../../../domain/totpConfig";
|
||||
import { requiresFidoSshAgentAuth } from "../../../domain/fidoSsh";
|
||||
import {
|
||||
formatHostPort,
|
||||
hostRestrictsExtraSshChannels,
|
||||
resolveHostKeepalive,
|
||||
resolveTelnetPassword,
|
||||
@@ -642,12 +643,15 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
totalHops,
|
||||
currentHostLabel:
|
||||
jumpHosts[0]?.label || jumpHosts[0]?.hostname || ctx.host.hostname,
|
||||
currentHostAddress: jumpHosts[0]?.hostname
|
||||
? formatHostPort(jumpHosts[0].hostname, jumpHosts[0].port || 22)
|
||||
: undefined,
|
||||
connectionPhase: 'connecting',
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
const unsub = ctx.terminalBackend.onChainProgress((sid, hop, total, label, status, error) => {
|
||||
const unsub = ctx.terminalBackend.onChainProgress((sid, hop, total, label, status, error, address) => {
|
||||
// P1: Only process events for this session
|
||||
if (sid !== ctx.sessionId) return;
|
||||
// Disconnect/reconnect can leave two SSH starts sharing this UI
|
||||
@@ -660,6 +664,7 @@ export const createTerminalSessionStarters = (ctx: TerminalSessionStartersContex
|
||||
currentHop: hop,
|
||||
totalHops: total,
|
||||
currentHostLabel: label,
|
||||
currentHostAddress: address,
|
||||
connectionPhase: status,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ export type TerminalBackendApi = {
|
||||
error?: string;
|
||||
}>;
|
||||
onChainProgress: (
|
||||
cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string) => void,
|
||||
cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string, address?: string) => void,
|
||||
) => (() => void) | undefined;
|
||||
onConnectionReuseFallback?: (
|
||||
cb: (sessionId: string, sourceSessionId?: string) => void,
|
||||
@@ -126,6 +126,8 @@ type ChainProgressState = {
|
||||
currentHop: number;
|
||||
totalHops: number;
|
||||
currentHostLabel: string;
|
||||
/** host:port of the hop being connected; absent from older progress events. */
|
||||
currentHostAddress?: string;
|
||||
connectionPhase: string;
|
||||
} | null;
|
||||
|
||||
|
||||
@@ -1,11 +1,45 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
normalizeGroupTargetPath,
|
||||
resolveHostGroupForSave,
|
||||
remapSnippetTargetGroupPaths,
|
||||
removeSnippetTargetGroupPaths,
|
||||
} from './hostGroupPathMutations.ts';
|
||||
import type { Snippet } from './models';
|
||||
|
||||
const dirtyPaths = ['prod / web', 'prod//web', 'prod\\web', ' prod / web ', '/ prod / / web //'];
|
||||
|
||||
test('Host Details normalizes new and changed group paths with the shared rules', () => {
|
||||
for (const value of dirtyPaths) {
|
||||
assert.equal(normalizeGroupTargetPath(value), 'prod/web');
|
||||
assert.equal(resolveHostGroupForSave(value), 'prod/web', 'new host');
|
||||
assert.equal(resolveHostGroupForSave(value, ''), 'prod/web', 'previously ungrouped host');
|
||||
assert.equal(resolveHostGroupForSave(value, 'staging'), 'prod/web', 'changed group');
|
||||
}
|
||||
});
|
||||
|
||||
test('Host Details preserves unchanged stored paths on unrelated edits', () => {
|
||||
for (const storedGroup of [...dirtyPaths, '', ' ']) {
|
||||
const value = storedGroup.trim() || storedGroup || '';
|
||||
assert.equal(resolveHostGroupForSave(value, storedGroup), storedGroup);
|
||||
assert.equal(resolveHostGroupForSave(storedGroup, storedGroup), storedGroup);
|
||||
}
|
||||
});
|
||||
|
||||
test('Host Details normalizes an explicitly changed group equivalent after trimming', () => {
|
||||
for (const storedGroup of [' prod/web ', ' prod / web ']) {
|
||||
assert.equal(resolveHostGroupForSave(storedGroup.trim(), storedGroup, true), 'prod/web');
|
||||
}
|
||||
});
|
||||
|
||||
test('Host Details allows changed paths to normalize to ungrouped', () => {
|
||||
for (const value of ['', ' / / \\ ']) {
|
||||
assert.equal(resolveHostGroupForSave(value, 'prod / web'), '');
|
||||
assert.equal(resolveHostGroupForSave(value), '');
|
||||
}
|
||||
});
|
||||
|
||||
const snippets: Snippet[] = [{
|
||||
id: 'script-a',
|
||||
label: 'A',
|
||||
|
||||
@@ -9,6 +9,16 @@ export function normalizeGroupTargetPath(value: string): string {
|
||||
.join('/');
|
||||
}
|
||||
|
||||
// Undefined means a new host; existing ungrouped hosts use ''. Preserve legacy
|
||||
// paths on unrelated edits so their exact-path connection defaults do not change.
|
||||
// Compare the raw field before save-time trimming to determine groupChanged.
|
||||
export function resolveHostGroupForSave(value: string, originalGroup?: string, groupChanged = false): string {
|
||||
if (!groupChanged && originalGroup !== undefined && (value === originalGroup || value === originalGroup.trim())) {
|
||||
return originalGroup;
|
||||
}
|
||||
return normalizeGroupTargetPath(value);
|
||||
}
|
||||
|
||||
export function normalizeGroupTargetPaths(values: Iterable<string>): string[] {
|
||||
return Array.from(new Set(
|
||||
[...values].map(normalizeGroupTargetPath).filter(Boolean),
|
||||
|
||||
@@ -8,11 +8,17 @@ const ELEMENTS = new Set(["form", "img", "div", "span", "p", "h1", "h2", "h3", "
|
||||
const VOID_ELEMENTS = new Set(["br", "hr", "img", "input"]);
|
||||
const ATTRIBUTES = new Set(["lang", "dir", "anchor", "src", "alt", "width", "height", "class", "id", "title", "role", "style", "name", "placeholder", "value", "checked", "disabled", "readonly", "required", "multiple", "selected", "type", "for", "tabindex", "min", "max", "step", "minlength", "maxlength", "rows", "cols", "colspan", "rowspan", "scope", "open", "autocomplete"]);
|
||||
const INPUT_TYPES = new Set(["text", "search", "email", "url", "tel", "number", "password", "checkbox", "radio", "range", "date", "time", "datetime-local", "color", "button"]);
|
||||
const ALLOWED_WIDGETS = new Set(["code-editor", "data-grid", "split-pane", "er-canvas"]);
|
||||
const FORBIDDEN_JSON_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
||||
const NAME = /^[a-zA-Z0-9_-]{1,80}$/u;
|
||||
const MAX_NODES = 1024;
|
||||
const MAX_DEPTH = 24;
|
||||
const MAX_VALUE = 8192;
|
||||
const MAX_RECORDS = 2048;
|
||||
const MAX_NODES = 4096;
|
||||
const MAX_DEPTH = 32;
|
||||
const MAX_VALUE = 131072;
|
||||
const MAX_WIDGET_PROPS_VALUE = 768 * 1024;
|
||||
const MAX_TEXT_SIZE = 1024 * 1024;
|
||||
const MAX_RECORDS = 4096;
|
||||
const MAX_BATCH_BYTES = 1024 * 1024;
|
||||
const MAX_WIDGET_PROPS_DEPTH = 12;
|
||||
function validateId(value, root = false) {
|
||||
if (typeof value !== "string" || (root && value === "~" ? false : !NAME.test(value))) throw new TypeError("Invalid view node ID");
|
||||
}
|
||||
@@ -20,10 +26,39 @@ function record(value) {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
&& (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
||||
}
|
||||
function validateSafeJsonValue(value, depth = 0) {
|
||||
if (depth > MAX_WIDGET_PROPS_DEPTH) throw new TypeError("Widget props exceed depth limit");
|
||||
if (value === null || typeof value === "boolean" || typeof value === "string") return;
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isFinite(value)) throw new TypeError("Invalid numeric value in widget props");
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) validateSafeJsonValue(item, depth + 1);
|
||||
return;
|
||||
}
|
||||
if (typeof value === "object") {
|
||||
for (const [k, v] of Object.entries(value)) {
|
||||
if (FORBIDDEN_JSON_KEYS.has(k)) throw new TypeError("Forbidden key in widget props");
|
||||
validateSafeJsonValue(v, depth + 1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
throw new TypeError("Invalid value in widget props");
|
||||
}
|
||||
function validateWidgetProps(raw) {
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(raw); } catch { throw new TypeError("Invalid plugin widget props JSON"); }
|
||||
if (!record(parsed)) throw new TypeError("Plugin widget props must be a JSON object");
|
||||
validateSafeJsonValue(parsed, 0);
|
||||
}
|
||||
function validateAttribute(element, name, value) {
|
||||
if (typeof name !== "string" || !/^[a-z][a-z0-9-]{0,79}$/u.test(name) || (!ATTRIBUTES.has(name) && !/^aria-[a-z0-9-]+$/u.test(name) && !/^data-[a-z0-9-]+$/u.test(name))) throw new TypeError("Forbidden view attribute");
|
||||
if (value === null) return;
|
||||
if (typeof value !== "string" || value.length > MAX_VALUE || value.includes("\0")) throw new TypeError("Invalid view attribute value");
|
||||
const maxLen = name === "data-plugin-widget-props" ? MAX_WIDGET_PROPS_VALUE : MAX_VALUE;
|
||||
if (typeof value !== "string" || value.length > maxLen || value.includes("\0")) throw new TypeError("Invalid view attribute value");
|
||||
if (name === "data-plugin-widget" && !ALLOWED_WIDGETS.has(value)) throw new TypeError("Forbidden plugin widget type");
|
||||
if (name === "data-plugin-widget-props") validateWidgetProps(value);
|
||||
if (name === "type" && element === "input" && !INPUT_TYPES.has(value.toLowerCase())) throw new TypeError("Forbidden input type");
|
||||
if (name === "type" && element === "button" && !["button", "reset", "submit"].includes(value.toLowerCase())) throw new TypeError("Forbidden button type");
|
||||
if (name === "src" && (!/^asset:[a-zA-Z0-9_-][a-zA-Z0-9_./-]{0,255}$/.test(value) || value.slice(6).split("/").some((part) => !part || part === "." || part === ".."))) throw new TypeError("Only package images are permitted");
|
||||
@@ -38,7 +73,7 @@ function validatePluginRemoteTree(root) {
|
||||
validateId(node.id); if (ids.has(node.id)) throw new TypeError("Duplicate view node"); ids.add(node.id);
|
||||
if (node.type === 3 || node.type === 8) {
|
||||
if (Object.keys(node).some((key) => !["id", "type", "data"].includes(key)) || typeof node.data !== "string" || node.data.length > MAX_VALUE) throw new TypeError("Invalid view text");
|
||||
textSize += node.data.length; if (textSize > 128 * 1024) throw new TypeError("View text exceeds limits"); return;
|
||||
textSize += node.data.length; if (textSize > MAX_TEXT_SIZE) throw new TypeError("View text exceeds limits"); return;
|
||||
}
|
||||
if (node.type !== 1 || typeof node.element !== "string" || !ELEMENTS.has(node.element)
|
||||
|| !Array.isArray(node.children) || !record(node.attributes)
|
||||
@@ -50,7 +85,7 @@ function validatePluginRemoteTree(root) {
|
||||
for (const [name, value] of attributes) {
|
||||
validateAttribute(node.element, name, value);
|
||||
textSize += name.length + (value?.length ?? 0);
|
||||
if (textSize > 128 * 1024) throw new TypeError("View data exceeds limits");
|
||||
if (textSize > MAX_TEXT_SIZE) throw new TypeError("View data exceeds limits");
|
||||
}
|
||||
for (const child of node.children) visit(child, depth + 1);
|
||||
};
|
||||
@@ -62,7 +97,7 @@ function validatePluginMutationBatch(batch) {
|
||||
if (!Array.isArray(batch) || batch.length > MAX_RECORDS) throw new TypeError("Invalid view mutations");
|
||||
let size;
|
||||
try { size = new TextEncoder().encode(JSON.stringify(batch)).byteLength; } catch { throw new TypeError("Invalid view mutations"); }
|
||||
if (size > 256 * 1024) throw new TypeError("View mutations exceed limits");
|
||||
if (size > MAX_BATCH_BYTES) throw new TypeError("View mutations exceed limits");
|
||||
for (const item of batch) {
|
||||
if (!Array.isArray(item) || ![0, 1, 2, 3].includes(item[0])) throw new TypeError("Invalid view mutation");
|
||||
validateId(item[1], true);
|
||||
@@ -79,4 +114,17 @@ function validatePluginMutationBatch(batch) {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
module.exports = { validatePluginRemoteTree, validatePluginMutationBatch, validateAttribute, ELEMENTS };
|
||||
module.exports = {
|
||||
validatePluginRemoteTree,
|
||||
validatePluginMutationBatch,
|
||||
validateAttribute,
|
||||
ELEMENTS,
|
||||
ALLOWED_WIDGETS,
|
||||
MAX_NODES,
|
||||
MAX_DEPTH,
|
||||
MAX_VALUE,
|
||||
MAX_WIDGET_PROPS_VALUE,
|
||||
MAX_TEXT_SIZE,
|
||||
MAX_RECORDS,
|
||||
MAX_BATCH_BYTES,
|
||||
};
|
||||
@@ -28,11 +28,24 @@ test("untrusted content cannot introduce executable elements, URLs or dangerous
|
||||
});
|
||||
|
||||
test("remote trees and mutation batches are bounded", () => {
|
||||
assert.throws(() => validatePluginRemoteTree({ children: Array.from({ length: 1025 }, (_, i) => text(`${i}`, "x")) }));
|
||||
let node = text("25", "x"); for (let i = 24; i >= 0; i--) node = element(`${i}`, "div", {}, [node]);
|
||||
assert.throws(() => validatePluginRemoteTree({ children: Array.from({ length: 4097 }, (_, i) => text(`${i}`, "x")) }));
|
||||
let node = text("33", "x"); for (let i = 32; i >= 0; i--) node = element(`${i}`, "div", {}, [node]);
|
||||
assert.throws(() => validatePluginRemoteTree({ children: [node] }));
|
||||
assert.throws(() => validatePluginMutationBatch(Array.from({ length: 2049 }, () => [2, "1", "x"])));
|
||||
assert.throws(() => validatePluginMutationBatch([[2, "1", "x".repeat(8193)]]));
|
||||
assert.throws(() => validatePluginMutationBatch(Array.from({ length: 4097 }, () => [2, "1", "x"])));
|
||||
assert.throws(() => validatePluginMutationBatch([[2, "1", "x".repeat(131073)]]));
|
||||
assert.equal(validatePluginMutationBatch([[2, "1", "x".repeat(131072)]]), true);
|
||||
});
|
||||
|
||||
test("declarative plugin widget markers and JSON props are strictly validated", () => {
|
||||
const validWidget = element("w1", "div", {
|
||||
"data-plugin-widget": "code-editor",
|
||||
"data-plugin-widget-props": JSON.stringify({ value: "SELECT 1;", language: "sql" }),
|
||||
});
|
||||
assert.equal(validatePluginRemoteTree({ children: [validWidget] }), true);
|
||||
assert.throws(() => validatePluginRemoteTree({ children: [element("w2", "div", { "data-plugin-widget": "iframe-hack" })] }), /widget/);
|
||||
assert.throws(() => validatePluginRemoteTree({ children: [element("w3", "div", { "data-plugin-widget": "data-grid", "data-plugin-widget-props": "{bad json" })] }), /JSON/);
|
||||
assert.throws(() => validatePluginRemoteTree({ children: [element("w4", "div", { "data-plugin-widget": "data-grid", "data-plugin-widget-props": "[]" })] }), /JSON object/);
|
||||
assert.throws(() => validatePluginRemoteTree({ children: [element("w5", "div", { "data-plugin-widget": "data-grid", "data-plugin-widget-props": "{\"__proto__\":{\"polluted\":true}}" })] }), /Forbidden key/);
|
||||
});
|
||||
|
||||
test("void children are rejected in snapshots and mutation insertions", () => {
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
// Plugin styles are untrusted: they are never inserted before this check.
|
||||
const cssTree = require("css-tree");
|
||||
const MAX_CSS_LENGTH = 64 * 1024;
|
||||
const MAX_AST_NODES = 20_000;
|
||||
const MAX_CSS_LENGTH = 128 * 1024;
|
||||
const MAX_AST_NODES = 40_000;
|
||||
const ALLOWED_AT_RULES = new Set(["media", "supports", "container", "keyframes", "-webkit-keyframes", "layer"]);
|
||||
const ALLOWED_FUNCTIONS = new Set([
|
||||
"var", "calc", "min", "max", "clamp", "abs", "sign", "round", "mod", "rem", "hypot", "pow", "sqrt", "log", "exp", "sin", "cos", "tan", "asin", "acos", "atan", "atan2",
|
||||
@@ -14,7 +14,18 @@ const ALLOWED_FUNCTIONS = new Set([
|
||||
"cubic-bezier", "steps", "linear", "minmax", "repeat", "fit-content", "env", "counter", "counters", "symbols",
|
||||
]);
|
||||
const DENIED_PROPERTIES = new Set(["behavior", "-moz-binding", "-webkit-app-region", "app-region"]);
|
||||
const HOST_TOKENS = new Set(["--background", "--foreground", "--muted", "--muted-foreground", "--border", "--primary", "--primary-foreground"]);
|
||||
const HOST_TOKENS = new Set([
|
||||
"--background", "--foreground",
|
||||
"--card", "--card-foreground",
|
||||
"--popover", "--popover-foreground",
|
||||
"--primary", "--primary-foreground",
|
||||
"--secondary", "--secondary-foreground",
|
||||
"--muted", "--muted-foreground",
|
||||
"--accent", "--accent-foreground",
|
||||
"--destructive", "--destructive-foreground",
|
||||
"--border", "--input", "--ring",
|
||||
"--radius", "--font-sans", "--font-mono",
|
||||
]);
|
||||
const decode = (name) => cssTree.ident.decode(name).toLowerCase();
|
||||
|
||||
/** Returns canonical CSS only if every construct is safe for a clipped shadow root. */
|
||||
|
||||
@@ -4,7 +4,11 @@ const assert = require("node:assert/strict");
|
||||
const { validatePluginStylesheet } = require("./pluginViewStylePolicy.cjs");
|
||||
|
||||
test("plugin styling supports ordinary layouts, animation and scoped theme tokens", () => {
|
||||
const css = `.layout { display: grid; grid-template-columns: 1fr 2fr; gap: 12px; --plugin-accent: #fa0; color: hsl(var(--foreground)); }
|
||||
const css = `.layout { display: grid; grid-template-columns: 1fr 2fr; gap: 12px; --plugin-accent: #fa0; color: hsl(var(--foreground)); background: hsl(var(--card)); border-radius: var(--radius); font-family: var(--font-mono); }
|
||||
.badge { background: hsl(var(--secondary)); color: hsl(var(--secondary-foreground)); border: 1px solid hsl(var(--input)); outline-color: hsl(var(--ring)); }
|
||||
.danger { background: hsl(var(--destructive)); color: hsl(var(--destructive-foreground)); }
|
||||
.menu { background: hsl(var(--popover)); color: hsl(var(--popover-foreground)); font-family: var(--font-sans); }
|
||||
.active { background: hsl(var(--accent)); color: hsl(var(--accent-foreground)); }
|
||||
@media (max-width: 400px) { .layout { display:flex; flex-direction:column; } }
|
||||
@keyframes spin { from { transform:rotate(0deg) } to { transform:rotate(360deg) } }
|
||||
.action:hover { animation:spin 1s; color:var(--plugin-accent); }`;
|
||||
@@ -22,5 +26,5 @@ test("plugin CSS rejects network loads, escapes and access outside the surface",
|
||||
'.x{--foreground:red}', '.x{content:attr(data-secret)}', '.x{color:red;}\0',
|
||||
];
|
||||
for (const attack of attacks) assert.throws(() => validatePluginStylesheet(attack), undefined, attack);
|
||||
assert.throws(() => validatePluginStylesheet('x'.repeat(65537)));
|
||||
assert.throws(() => validatePluginStylesheet('x'.repeat(131073)));
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
buildMergedWorkspaceTitle,
|
||||
buildMergedWorkspaceTitleFromSessions,
|
||||
getSessionConnectionLabel,
|
||||
isGenericLoopbackHostname,
|
||||
resolveCodingCliProviderIconUpdate,
|
||||
resolveSessionTabTitle,
|
||||
resolveWorkspaceTabLabel,
|
||||
@@ -129,6 +130,136 @@ test('resolveSessionTabTitle prefers the live prompt host over a generic shell t
|
||||
);
|
||||
});
|
||||
|
||||
test('isGenericLoopbackHostname matches only generic localhost and loopback names', () => {
|
||||
for (const generic of [
|
||||
'localhost',
|
||||
'localhost.localdomain',
|
||||
'localhost.local',
|
||||
'127.0.0.1',
|
||||
'::1',
|
||||
'LocalHost',
|
||||
' LOCALHOST.LOCALDOMAIN. ',
|
||||
'localhost.',
|
||||
]) {
|
||||
assert.equal(isGenericLoopbackHostname(generic), true, generic);
|
||||
}
|
||||
for (const specific of ['', ' ', '.', 'localhost..', 'ubuntu', '10.1.64.1', '192.168.100.222']) {
|
||||
assert.equal(isGenericLoopbackHostname(specific), false, specific);
|
||||
}
|
||||
});
|
||||
|
||||
test('resolveSessionTabTitle ignores generic localhost prompt hosts in default and agent modes', () => {
|
||||
for (const promptHostname of [
|
||||
'localhost',
|
||||
'localhost.localdomain',
|
||||
'localhost.local',
|
||||
'127.0.0.1',
|
||||
'::1',
|
||||
'LocalHost',
|
||||
'localhost.',
|
||||
]) {
|
||||
assert.equal(
|
||||
resolveSessionTabTitle({
|
||||
hostLabel: '192.168.100.222',
|
||||
promptHostname,
|
||||
}),
|
||||
'192.168.100.222',
|
||||
);
|
||||
assert.equal(
|
||||
resolveSessionTabTitle(
|
||||
{
|
||||
hostLabel: '192.168.100.222',
|
||||
promptHostname,
|
||||
dynamicTitle: 'root@localhost:~',
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
'192.168.100.222',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('resolveSessionTabTitle keeps distinct SSH hostLabels when both remotes report localhost', () => {
|
||||
const sessionA = { hostLabel: '192.168.100.222', promptHostname: 'localhost' };
|
||||
const sessionB = { hostLabel: '192.168.100.220', promptHostname: 'localhost' };
|
||||
assert.equal(resolveSessionTabTitle(sessionA), '192.168.100.222');
|
||||
assert.equal(resolveSessionTabTitle(sessionB), '192.168.100.220');
|
||||
});
|
||||
|
||||
test('resolveSessionTabTitle keeps customName ahead of a generic prompt host', () => {
|
||||
assert.equal(
|
||||
resolveSessionTabTitle({
|
||||
customName: 'LAN Node 1',
|
||||
hostLabel: '192.168.100.222',
|
||||
promptHostname: 'localhost',
|
||||
}),
|
||||
'LAN Node 1',
|
||||
);
|
||||
});
|
||||
|
||||
test('getSessionConnectionLabel skips generic promptHostname and keeps non-generic ones', () => {
|
||||
assert.equal(
|
||||
getSessionConnectionLabel({
|
||||
hostLabel: '192.168.100.222',
|
||||
promptHostname: 'localhost',
|
||||
}),
|
||||
'192.168.100.222',
|
||||
);
|
||||
assert.equal(
|
||||
getSessionConnectionLabel({
|
||||
hostLabel: '192.168.100.222',
|
||||
promptHostname: 'localhost.localdomain',
|
||||
}),
|
||||
'192.168.100.222',
|
||||
);
|
||||
assert.equal(
|
||||
getSessionConnectionLabel({
|
||||
customName: 'Node 222',
|
||||
hostLabel: '192.168.100.222',
|
||||
promptHostname: 'localhost',
|
||||
}),
|
||||
'Node 222',
|
||||
);
|
||||
assert.equal(
|
||||
getSessionConnectionLabel({
|
||||
hostLabel: '192.168.100.222',
|
||||
promptHostname: 'ubuntu',
|
||||
}),
|
||||
'ubuntu',
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveSessionTabTitle keeps non-generic prompt host overrides across default, agent, and all modes', () => {
|
||||
assert.equal(
|
||||
resolveSessionTabTitle({
|
||||
hostLabel: '192.168.100.222',
|
||||
promptHostname: 'ubuntu',
|
||||
}),
|
||||
'ubuntu',
|
||||
);
|
||||
assert.equal(
|
||||
resolveSessionTabTitle(
|
||||
{
|
||||
hostLabel: '192.168.100.222',
|
||||
promptHostname: 'ubuntu',
|
||||
},
|
||||
'agent',
|
||||
),
|
||||
'ubuntu',
|
||||
);
|
||||
assert.equal(
|
||||
resolveSessionTabTitle(
|
||||
{
|
||||
hostLabel: '192.168.100.222',
|
||||
promptHostname: 'ubuntu',
|
||||
dynamicTitle: 'root@ubuntu:~',
|
||||
},
|
||||
'all',
|
||||
),
|
||||
'ubuntu',
|
||||
);
|
||||
});
|
||||
|
||||
test('coding CLI icon updates stop without clearing the current icon when dynamic titles are off', () => {
|
||||
assert.equal(shouldUpdateCodingCliTabIcon('off'), false);
|
||||
assert.equal(shouldUpdateCodingCliTabIcon('agent'), true);
|
||||
|
||||
@@ -3,11 +3,28 @@ import type { CodingCliProviderId } from './codingCliProviders';
|
||||
import { normalizeCodingCliTitle } from './codingCliTitleParse';
|
||||
import type { DynamicTabTitleMode } from './models/terminal';
|
||||
|
||||
const GENERIC_LOOPBACK_HOSTNAMES = new Set([
|
||||
'localhost',
|
||||
'localhost.localdomain',
|
||||
'localhost.local',
|
||||
'127.0.0.1',
|
||||
'::1',
|
||||
]);
|
||||
|
||||
export const isGenericLoopbackHostname = (value: string): boolean => {
|
||||
const trimmed = value.trim();
|
||||
const normalized = (trimmed.endsWith('.') ? trimmed.slice(0, -1) : trimmed).toLowerCase();
|
||||
return GENERIC_LOOPBACK_HOSTNAMES.has(normalized);
|
||||
};
|
||||
|
||||
/** Connection label: user rename, live prompt host, then configured host label. */
|
||||
export const getSessionConnectionLabel = (
|
||||
session: Pick<TerminalSession, 'customName' | 'hostLabel' | 'promptHostname'>,
|
||||
): string => {
|
||||
return session.customName || session.promptHostname || session.hostLabel || '';
|
||||
const promptHostname = session.promptHostname?.trim();
|
||||
const effectivePromptHostname =
|
||||
promptHostname && !isGenericLoopbackHostname(promptHostname) ? promptHostname : '';
|
||||
return session.customName || effectivePromptHostname || session.hostLabel || '';
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -150,7 +167,7 @@ export const resolveSessionTabTitle = (
|
||||
if (agentTitle) return normalizeCodingCliTitle(agentTitle) || agentTitle;
|
||||
}
|
||||
const promptHostname = session.promptHostname?.trim();
|
||||
if (promptHostname) {
|
||||
if (promptHostname && !isGenericLoopbackHostname(promptHostname)) {
|
||||
return promptHostname;
|
||||
}
|
||||
if (dynamicTabTitleMode === 'off') {
|
||||
|
||||
@@ -169,22 +169,29 @@ function isDefaultCmdPromptLine(line) {
|
||||
return CMD_PROMPT_PATTERN.test(String(line || "").replace(/\s+$/, ""));
|
||||
}
|
||||
|
||||
function stripLeadingDecorativeToken(line) {
|
||||
// Optional short decorative token, stripped only for recognition (#4354).
|
||||
return line.replace(/^\s*[^\s\w\p{L}\p{N}@:#$\\\/>\[\]().]{1,4}\s+/u, "");
|
||||
}
|
||||
|
||||
function isDefaultPosixPromptLine(line) {
|
||||
const normalized = String(line || "").replace(/\s+$/, "");
|
||||
// Optional virtualenv / conda / BT-panel style env name prefix: "(name) "
|
||||
// before the shell prompt. Recognition only; callers still return the full
|
||||
// prompt line so suffix matching sees the visible prefix (#3947).
|
||||
const withoutEnvPrefix = normalized.replace(/^\([^()\n\r]+\)\s+/, "");
|
||||
return (
|
||||
POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
BRACKET_TIME_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
PAREN_POSIX_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
ALPINE_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
MACOS_ROOT_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
ZSH_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
POWERLEVEL10K_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
POWERLINE_PROMPT_PATTERN.test(withoutEnvPrefix) ||
|
||||
OH_MY_ZSH_ROBBYRUSSELL_PROMPT_PATTERN.test(withoutEnvPrefix)
|
||||
return [withoutEnvPrefix, stripLeadingDecorativeToken(withoutEnvPrefix)].some(
|
||||
(prompt) => (
|
||||
POSIX_PROMPT_PATTERN.test(prompt) ||
|
||||
BRACKET_TIME_POSIX_PROMPT_PATTERN.test(prompt) ||
|
||||
PAREN_POSIX_PROMPT_PATTERN.test(prompt) ||
|
||||
ALPINE_PROMPT_PATTERN.test(prompt) ||
|
||||
MACOS_ROOT_PROMPT_PATTERN.test(prompt) ||
|
||||
ZSH_PROMPT_PATTERN.test(prompt) ||
|
||||
POWERLEVEL10K_PROMPT_PATTERN.test(prompt) ||
|
||||
POWERLINE_PROMPT_PATTERN.test(prompt) ||
|
||||
OH_MY_ZSH_ROBBYRUSSELL_PROMPT_PATTERN.test(prompt)
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -454,6 +454,42 @@ test("Powerline recognition preserves existing idle prompt recognition", () => {
|
||||
assert.equal(extractTrailingIdlePrompt(twoLinePrompt), twoLinePrompt);
|
||||
});
|
||||
|
||||
test("isDefaultPosixPromptLine matches short decorative prefixes and keeps the full prompt", () => {
|
||||
for (const prompt of [
|
||||
"root@testhost:~# ",
|
||||
" root@testhost \uE0B0 ~ \uE0B0 ",
|
||||
"\u26A1 root@testhost:~# ",
|
||||
"\u26A1 root@testhost:~#",
|
||||
" \u26A1 root@testhost:~# ",
|
||||
"\u26A1\uFE0F root@testhost:~# ",
|
||||
"\u26A1\uFE0E root@testhost:~# ",
|
||||
" \u26A1 root@testhost \uE0B0 ~ \uE0B0 ",
|
||||
"(venv) \u26A1 root@testhost:~# ",
|
||||
"\u26A1\u26A1\u26A1\u26A1 root@testhost:~# ",
|
||||
"\u{1F680}\u{1F680}\u{1F680}\u{1F680} root@testhost:~# ",
|
||||
]) {
|
||||
assert.equal(isDefaultPosixPromptLine(prompt), true, prompt);
|
||||
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${prompt}`), prompt, prompt);
|
||||
}
|
||||
});
|
||||
|
||||
test("decorative prefix recognition rejects pending input and non-decorative prefixes", () => {
|
||||
for (const line of [
|
||||
"\u26A1 root@testhost:~# echo hi",
|
||||
" \u26A1 root@testhost \uE0B0 ~ \uE0B0 ls",
|
||||
"OK root@testhost:~# ",
|
||||
"yes root@testhost:~# ",
|
||||
"git:(main) root@testhost:~# ",
|
||||
"\u26A1\u26A1\u26A1\u26A1\u26A1 root@testhost:~# ",
|
||||
"\u{1F680}\u{1F680}\u{1F680}\u{1F680}\u{1F680} root@testhost:~# ",
|
||||
...["\u00E9", "\u4E2D", "\u0661", "_", "@", ":", "#", "$", "\\", "/", ">", "[", "]", "(", ")", "."]
|
||||
.map(prefix => `${prefix} root@testhost:~# `),
|
||||
]) {
|
||||
assert.equal(isDefaultPosixPromptLine(line), false, line);
|
||||
assert.equal(extractTrailingIdlePrompt(`welcome\r\n${line}`), "", line);
|
||||
}
|
||||
});
|
||||
|
||||
test("trackSessionIdlePrompt and getFreshIdlePrompt accept a Powerlevel10k ❯ prompt", () => {
|
||||
const session = {};
|
||||
trackSessionIdlePrompt(session, "Last login...\r\n~ ❯ ");
|
||||
|
||||
@@ -1562,6 +1562,50 @@ test("jump-host auth failure does not emit exit before encrypted-key retry succe
|
||||
);
|
||||
});
|
||||
|
||||
test("chain progress names every hop by its label and reports each hop's address", async (t) => {
|
||||
const { bridge } = loadBridgeWithAuthRetryMocks(t, {
|
||||
connectEvents: ["ready", "ready", "ready"],
|
||||
encryptedKeys: [],
|
||||
});
|
||||
const ipcMain = makeIpcMain();
|
||||
bridge.init({ sessions: new Map(), electronModule: {} });
|
||||
bridge.registerHandlers(ipcMain);
|
||||
const start = ipcMain.handlers.get("netcatty:start");
|
||||
const sender = makeSender();
|
||||
|
||||
const result = await start(
|
||||
{ sender },
|
||||
{
|
||||
sessionId: "chain-label-session",
|
||||
hostname: "10.0.0.5",
|
||||
hostLabel: "Prod DB",
|
||||
username: "alice",
|
||||
port: 22,
|
||||
knownHosts: [],
|
||||
jumpHosts: [
|
||||
{ hostname: "a.example.com", username: "alice", port: 22, label: "Bastion A" },
|
||||
{ hostname: "b.example.com", username: "alice", port: 2201 },
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
assert.deepEqual(result, { sessionId: "chain-label-session" });
|
||||
const progress = sender.sent
|
||||
.filter((message) => message.channel === "netcatty:chain:progress")
|
||||
.map((message) => message.payload);
|
||||
const hopSummary = (hop) => [
|
||||
...new Set(progress.filter((p) => p.hop === hop).map((p) => `${p.label} @ ${p.address}`)),
|
||||
];
|
||||
|
||||
assert.ok(progress.every((p) => p.total === 3));
|
||||
assert.deepEqual(hopSummary(1), ["Bastion A @ a.example.com:22"]);
|
||||
// An unlabeled jump host keeps its host:port label.
|
||||
assert.deepEqual(hopSummary(2), ["b.example.com:2201 @ b.example.com:2201"]);
|
||||
// The final target is named by its label, not its raw IP.
|
||||
assert.deepEqual(hopSummary(3), ["Prod DB @ 10.0.0.5:22"]);
|
||||
assert.ok(progress.some((p) => p.hop === 3 && p.status === "connected"));
|
||||
});
|
||||
|
||||
test("jump-host auth failure is attributed to the failing jump host", async (t) => {
|
||||
const { bridge } = loadBridgeWithAuthRetryMocks(t, {
|
||||
connectEvents: ["auth-error"],
|
||||
|
||||
@@ -64,6 +64,10 @@ const {
|
||||
} = require("./sshAlgorithms.cjs");
|
||||
const { enableSshNoDelay, enableTcpNoDelay } = require("./tcpNoDelay.cjs");
|
||||
const { createSshPingLatencyProbe } = require("./sshBridge/sshPingLatency.cjs");
|
||||
const {
|
||||
formatChainHopAddress,
|
||||
resolveChainHopAddress,
|
||||
} = require("./sshBridge/chainProgress.cjs");
|
||||
const {
|
||||
configureTerminalSessionDataEmitter,
|
||||
} = require("./emitTerminalSessionData.cjs");
|
||||
@@ -376,7 +380,8 @@ async function connectThroughChain(event, options, jumpHosts, targetHost, target
|
||||
|
||||
const sendProgress = (hop, total, label, status, error) => {
|
||||
if (!sender.isDestroyed()) {
|
||||
sender.send("netcatty:chain:progress", { sessionId, hop, total, label, status, error });
|
||||
const address = resolveChainHopAddress(jumpHosts, targetHost, targetPort, hop);
|
||||
sender.send("netcatty:chain:progress", { sessionId, hop, total, label, status, error, address });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -388,7 +393,7 @@ async function connectThroughChain(event, options, jumpHosts, targetHost, target
|
||||
const jump = jumpHosts[i];
|
||||
const isFirst = i === 0;
|
||||
const isLast = i === jumpHosts.length - 1;
|
||||
const hopLabel = jump.label || (jump.hostname.includes(':') && !jump.hostname.startsWith('[') ? `[${jump.hostname}]:${jump.port || 22}` : `${jump.hostname}:${jump.port || 22}`);
|
||||
const hopLabel = jump.label || formatChainHopAddress(jump.hostname, jump.port);
|
||||
|
||||
sendProgress(i + 1, totalHops + 1, hopLabel, 'connecting');
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
|
||||
/**
|
||||
* Helpers for `netcatty:chain:progress` events sent while connecting through
|
||||
* jump hosts. Each event names the hop being connected (`label`) and its
|
||||
* network address (`address`), so the connection dialog can show
|
||||
* "Chain 2 of 3: Prod DB" with the matching "SSH 10.0.0.5:22" below it.
|
||||
*/
|
||||
|
||||
/** Format `host:port`, bracketing bare IPv6 literals (`[::1]:22`). */
|
||||
function formatChainHopAddress(hostname, port) {
|
||||
const host = String(hostname || "");
|
||||
const display = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
return `${display}:${port || 22}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Address of the 1-based `hop` in a chain of `jumpHosts` followed by the
|
||||
* final target. Hops past the jump hosts are the target.
|
||||
*/
|
||||
function resolveChainHopAddress(jumpHosts, targetHostname, targetPort, hop) {
|
||||
const jumps = Array.isArray(jumpHosts) ? jumpHosts : [];
|
||||
const jump = hop >= 1 && hop <= jumps.length ? jumps[hop - 1] : null;
|
||||
if (jump) return formatChainHopAddress(jump.hostname, jump.port);
|
||||
return formatChainHopAddress(targetHostname, targetPort);
|
||||
}
|
||||
|
||||
/**
|
||||
* Label for the final target in chain progress. Jump hops already show their
|
||||
* vault label; the target should too, instead of its raw address. Direct
|
||||
* (single-hop) connections keep the address, which the dialog does not use
|
||||
* as a chain heading.
|
||||
*/
|
||||
function resolveChainTargetLabel(options, hasJumpHosts) {
|
||||
const hostname = options?.hostname || "";
|
||||
if (!hasJumpHosts) return hostname;
|
||||
return options?.hostLabel || options?.label || hostname;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
formatChainHopAddress,
|
||||
resolveChainHopAddress,
|
||||
resolveChainTargetLabel,
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
const {
|
||||
formatChainHopAddress,
|
||||
resolveChainHopAddress,
|
||||
resolveChainTargetLabel,
|
||||
} = require("./chainProgress.cjs");
|
||||
|
||||
test("formatChainHopAddress formats host:port and brackets bare IPv6", () => {
|
||||
assert.equal(formatChainHopAddress("10.0.0.5", 22), "10.0.0.5:22");
|
||||
assert.equal(formatChainHopAddress("bastion.example.com", 2222), "bastion.example.com:2222");
|
||||
assert.equal(formatChainHopAddress("10.0.0.5"), "10.0.0.5:22");
|
||||
assert.equal(formatChainHopAddress("fd00::5", 22), "[fd00::5]:22");
|
||||
assert.equal(formatChainHopAddress("[fd00::5]", 22), "[fd00::5]:22");
|
||||
});
|
||||
|
||||
test("resolveChainHopAddress maps each hop of a long chain to its own address", () => {
|
||||
const jumps = [
|
||||
{ hostname: "a.example.com", port: 22 },
|
||||
{ hostname: "b.example.com", port: 2201 },
|
||||
{ hostname: "fd00::c" },
|
||||
];
|
||||
assert.equal(resolveChainHopAddress(jumps, "10.0.0.5", 22, 1), "a.example.com:22");
|
||||
assert.equal(resolveChainHopAddress(jumps, "10.0.0.5", 22, 2), "b.example.com:2201");
|
||||
assert.equal(resolveChainHopAddress(jumps, "10.0.0.5", 22, 3), "[fd00::c]:22");
|
||||
// The hop after the last jump host is the target.
|
||||
assert.equal(resolveChainHopAddress(jumps, "10.0.0.5", 22, 4), "10.0.0.5:22");
|
||||
// A direct connection only has the target.
|
||||
assert.equal(resolveChainHopAddress(undefined, "10.0.0.5", 2222, 1), "10.0.0.5:2222");
|
||||
});
|
||||
|
||||
test("resolveChainTargetLabel names a chained target by its label, not its address", () => {
|
||||
assert.equal(
|
||||
resolveChainTargetLabel({ hostname: "10.0.0.5", hostLabel: "Prod DB" }, true),
|
||||
"Prod DB",
|
||||
);
|
||||
assert.equal(resolveChainTargetLabel({ hostname: "10.0.0.5", label: "Prod DB" }, true), "Prod DB");
|
||||
// Unlabeled target falls back to its address.
|
||||
assert.equal(resolveChainTargetLabel({ hostname: "10.0.0.5", hostLabel: "" }, true), "10.0.0.5");
|
||||
// Direct connections keep the address (unchanged behavior).
|
||||
assert.equal(
|
||||
resolveChainTargetLabel({ hostname: "10.0.0.5", hostLabel: "Prod DB" }, false),
|
||||
"10.0.0.5",
|
||||
);
|
||||
});
|
||||
@@ -31,6 +31,10 @@ const {
|
||||
buildRemoteShellExitPayload,
|
||||
normalizeRemoteExitSignal,
|
||||
} = require("./remoteShellExit.cjs");
|
||||
const {
|
||||
resolveChainHopAddress,
|
||||
resolveChainTargetLabel,
|
||||
} = require("./chainProgress.cjs");
|
||||
const { looksLikeSkOpenSshMaterial } = require("../sshAuthHelper.cjs");
|
||||
|
||||
const SSH_TCP_CONNECT_TIMEOUT_MS = 20000;
|
||||
@@ -1521,7 +1525,13 @@ function createStartSessionApi(ctx) {
|
||||
|
||||
const sendProgress = (hop, total, label, status, error) => {
|
||||
if (!sender.isDestroyed()) {
|
||||
sender.send("netcatty:chain:progress", { sessionId, hop, total, label, status, error });
|
||||
const address = resolveChainHopAddress(
|
||||
options.jumpHosts,
|
||||
options.hostname,
|
||||
options.port,
|
||||
hop,
|
||||
);
|
||||
sender.send("netcatty:chain:progress", { sessionId, hop, total, label, status, error, address });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1557,6 +1567,9 @@ function createStartSessionApi(ctx) {
|
||||
const hasJumpHosts = jumpHosts.length > 0;
|
||||
const hasProxy = !!options.proxy;
|
||||
const totalHops = jumpHosts.length + 1; // +1 for final target
|
||||
// Name the final hop by its vault label (like the jump hops) instead of
|
||||
// its raw address; the address is sent separately per hop.
|
||||
const targetProgressLabel = resolveChainTargetLabel(options, hasJumpHosts);
|
||||
|
||||
// Build base connection options for final target
|
||||
const keepalivePolicy = resolveConnectionKeepalivePolicy(options);
|
||||
@@ -1708,10 +1721,10 @@ function createStartSessionApi(ctx) {
|
||||
bootEpoch: options.bootEpoch,
|
||||
logPrefix: "[SSH]",
|
||||
onPassphrasePromptShown: () => sendProgress(
|
||||
totalHops, totalHops, options.hostname, "auth-attempt", "waiting for user input...",
|
||||
totalHops, totalHops, targetProgressLabel, "auth-attempt", "waiting for user input...",
|
||||
),
|
||||
onPassphrasePromptResolved: () => sendProgress(
|
||||
totalHops, totalHops, options.hostname, "auth-attempt", "user responded",
|
||||
totalHops, totalHops, targetProgressLabel, "auth-attempt", "user responded",
|
||||
),
|
||||
onLoaded: (loaded) => {
|
||||
log("Loaded identity file", { keyPath: loaded.keyPath, encrypted: !!loaded.passphrase });
|
||||
@@ -1737,10 +1750,10 @@ function createStartSessionApi(ctx) {
|
||||
bootEpoch: options.bootEpoch,
|
||||
logPrefix: "[SSH]",
|
||||
onPassphrasePromptShown: () => sendProgress(
|
||||
totalHops, totalHops, options.hostname, "auth-attempt", "waiting for user input...",
|
||||
totalHops, totalHops, targetProgressLabel, "auth-attempt", "waiting for user input...",
|
||||
),
|
||||
onPassphrasePromptResolved: () => sendProgress(
|
||||
totalHops, totalHops, options.hostname, "auth-attempt", "user responded",
|
||||
totalHops, totalHops, targetProgressLabel, "auth-attempt", "user responded",
|
||||
),
|
||||
})
|
||||
: null;
|
||||
@@ -2057,7 +2070,7 @@ function createStartSessionApi(ctx) {
|
||||
|
||||
// Log rejection of previous method
|
||||
if (lastTriedMethod && !partialSuccess) {
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', `${lastTriedMethod} rejected`);
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', `${lastTriedMethod} rejected`);
|
||||
if (
|
||||
lastTriedMethod === "password" &&
|
||||
passwordAttemptSawKeyboardInteractive &&
|
||||
@@ -2081,7 +2094,7 @@ function createStartSessionApi(ctx) {
|
||||
if (methodsLeft === null && !attemptedMethodIds.has("none")) {
|
||||
attemptedMethodIds.add("none");
|
||||
lastTriedMethod = "none";
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', 'none (no credentials)');
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'none (no credentials)');
|
||||
return callback("none");
|
||||
}
|
||||
|
||||
@@ -2218,7 +2231,7 @@ function createStartSessionApi(ctx) {
|
||||
// Only log safe identifier, not the full agent object which may contain private keys
|
||||
const agentType = typeof method.agent === "string" ? "path" : "NetcattyAgent";
|
||||
log("Trying agent auth", { id: method.id, agentType });
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', 'SSH agent');
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'SSH agent');
|
||||
return method.agent === connectOpts.agent
|
||||
? callback("agent")
|
||||
: callback({
|
||||
@@ -2235,7 +2248,7 @@ function createStartSessionApi(ctx) {
|
||||
: method.id === "publickey-user"
|
||||
? "configured key"
|
||||
: method.id;
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', keyLabel);
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', keyLabel);
|
||||
return callback({
|
||||
type: "publickey",
|
||||
username: connectOpts.username,
|
||||
@@ -2244,7 +2257,7 @@ function createStartSessionApi(ctx) {
|
||||
});
|
||||
} else if (method.type === "password") {
|
||||
log("Trying password auth", { id: method.id });
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', 'password');
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'password');
|
||||
passwordAttemptSawKeyboardInteractive = availableMethods.includes("keyboard-interactive");
|
||||
return callback({
|
||||
type: "password",
|
||||
@@ -2253,7 +2266,7 @@ function createStartSessionApi(ctx) {
|
||||
});
|
||||
} else if (method.type === "keyboard-interactive") {
|
||||
log("Trying keyboard-interactive auth", { id: method.id });
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', 'keyboard-interactive');
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'keyboard-interactive');
|
||||
// Return string instead of object - ssh2 requires a prompt function
|
||||
// for keyboard-interactive objects. Returning the string lets ssh2
|
||||
// use its default handling and trigger the keyboard-interactive event.
|
||||
@@ -2262,7 +2275,7 @@ function createStartSessionApi(ctx) {
|
||||
}
|
||||
|
||||
log("All auth methods exhausted");
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'auth-attempt', 'all methods exhausted');
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'all methods exhausted');
|
||||
return callback(false);
|
||||
};
|
||||
|
||||
@@ -2313,7 +2326,7 @@ function createStartSessionApi(ctx) {
|
||||
delete connectOpts.host;
|
||||
delete connectOpts.port;
|
||||
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'connecting');
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'connecting');
|
||||
} else if (hasProxy) {
|
||||
sendProgress(1, 1, options.hostname, 'connecting');
|
||||
connectionSocket = await createProxySocket(
|
||||
@@ -2391,7 +2404,7 @@ function createStartSessionApi(ctx) {
|
||||
elapsedMs: Date.now() - connectionStartedAt,
|
||||
authReadyTimeoutMs,
|
||||
});
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'tcp-connected');
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'tcp-connected');
|
||||
enableSshNoDelay(conn);
|
||||
});
|
||||
});
|
||||
@@ -2405,7 +2418,7 @@ function createStartSessionApi(ctx) {
|
||||
hostname: options.hostname,
|
||||
elapsedMs: Date.now() - connectionStartedAt,
|
||||
});
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'authenticating');
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'authenticating');
|
||||
});
|
||||
|
||||
conn.on("banner", (message) => {
|
||||
@@ -2436,7 +2449,7 @@ function createStartSessionApi(ctx) {
|
||||
}
|
||||
}
|
||||
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'authenticated');
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'authenticated');
|
||||
|
||||
if (testMode) {
|
||||
// Headless connection test: authentication succeeded. Report the
|
||||
@@ -2462,7 +2475,7 @@ function createStartSessionApi(ctx) {
|
||||
return;
|
||||
}
|
||||
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'shell');
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'shell');
|
||||
|
||||
let establishedOwnerSession = null;
|
||||
const sendTerminalMessage = (data) => {
|
||||
@@ -2525,12 +2538,12 @@ function createStartSessionApi(ctx) {
|
||||
if (options.x11Forwarding && /x11/i.test(err.message || "")) {
|
||||
sendTerminalMessage("\r\n[X11] Could not enable X11 forwarding. Make sure X11 forwarding is allowed on the server and xauth is installed.\r\n");
|
||||
}
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'error', `Failed to open shell: ${err.message}`);
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'error', `Failed to open shell: ${err.message}`);
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'connected');
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'connected');
|
||||
|
||||
// Create the shared reference-counted descriptor for this
|
||||
// connection now that the owning channel is open, then wire the
|
||||
@@ -2667,7 +2680,7 @@ function createStartSessionApi(ctx) {
|
||||
}
|
||||
|
||||
const visibleError = userVisibleSshErrorMessage(err, options);
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'error', visibleError);
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'error', visibleError);
|
||||
const suppressPreShellAuthExit = Boolean(options._suppressPreShellAuthExit && isAuthError);
|
||||
if (suppressPreShellAuthExit) {
|
||||
log("suppressing pre-shell auth exit for wrapper-managed retry", {
|
||||
@@ -2712,7 +2725,7 @@ function createStartSessionApi(ctx) {
|
||||
authReadyTimeoutMs,
|
||||
});
|
||||
const contents = event.sender;
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'error', err.message);
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'error', err.message);
|
||||
safeSendSessionExit({ safeSend, electronModule, sessions }, contents, sessionId, { sessionId, exitCode: 1, error: err.message, reason: "timeout" });
|
||||
sessionLogStreamManager.stopStream(sessionId, ownerLogStreamToken);
|
||||
sessions.get(sessionId)?.zmodemSentry?.cancel();
|
||||
@@ -2743,7 +2756,7 @@ function createStartSessionApi(ctx) {
|
||||
transportError: ownsCurrentSession ? currentSession?._transportError : undefined,
|
||||
});
|
||||
if (!settled) {
|
||||
sendProgress(totalHops, totalHops, options.hostname, 'error', `Connection to ${options.hostname} closed unexpectedly`);
|
||||
sendProgress(totalHops, totalHops, targetProgressLabel, 'error', `Connection to ${options.hostname} closed unexpectedly`);
|
||||
}
|
||||
// This handler owns teardown for the *owner* session only. ssh2
|
||||
// fires conn "close" before the owner's stream "close" on a
|
||||
@@ -2844,14 +2857,14 @@ function createStartSessionApi(ctx) {
|
||||
getAuthBanner: () => authBanner,
|
||||
shouldSkipAutoFill: () => shouldSkipKiPasswordAutoFill(authPhase),
|
||||
onAutoFill: (kind) => sendProgress(
|
||||
totalHops, totalHops, options.hostname, 'auth-attempt',
|
||||
totalHops, totalHops, targetProgressLabel, 'auth-attempt',
|
||||
kind === 'totp' ? 'using authenticator code' : 'using saved password',
|
||||
),
|
||||
onPromptShown: () => sendProgress(
|
||||
totalHops, totalHops, options.hostname, 'auth-attempt', 'waiting for user input...',
|
||||
totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'waiting for user input...',
|
||||
),
|
||||
onUserResponded: () => sendProgress(
|
||||
totalHops, totalHops, options.hostname, 'auth-attempt', 'user responded',
|
||||
totalHops, totalHops, targetProgressLabel, 'auth-attempt', 'user responded',
|
||||
),
|
||||
}));
|
||||
|
||||
|
||||
@@ -10,10 +10,25 @@ const { PluginRpcError, RPC_ERRORS, raceWithAbort } = require("./rpcRouter.cjs")
|
||||
|
||||
const HOST_LIMITS = Object.freeze(require("./generated/plugin-contract.schema.json").$defs.HostByteStreamLimits.const);
|
||||
const LIMITS = Object.freeze(require("./generated/plugin-contract.schema.json").$defs.ByteStreamLimits.const);
|
||||
const { canonicalizeStreamEndpoint, isLocalControlAddress } = require("./byteStreamEndpoint.cjs");
|
||||
const {
|
||||
canonicalizeStreamEndpoint,
|
||||
getNetcattyInternalControlPorts,
|
||||
isLocalControlAddress,
|
||||
isLoopbackAddress,
|
||||
isUnconditionallyBlockedAddress,
|
||||
} = require("./byteStreamEndpoint.cjs");
|
||||
|
||||
function failure(code, message) { return new PluginRpcError(RPC_ERRORS[code], message); }
|
||||
|
||||
function formatCertDistinguishedName(value) {
|
||||
if (!value || typeof value !== "object") return "";
|
||||
return Object.entries(value)
|
||||
.filter(([, v]) => typeof v === "string" || Array.isArray(v))
|
||||
.map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(",") : v}`)
|
||||
.join(", ")
|
||||
.slice(0, 512);
|
||||
}
|
||||
|
||||
class PluginByteStreamBroker {
|
||||
constructor(options) {
|
||||
this.permissionEngine = options.permissionEngine;
|
||||
@@ -22,10 +37,17 @@ class PluginByteStreamBroker {
|
||||
this.lookup = options.lookup ?? dns.lookup;
|
||||
this.connectSocket = options.connectSocket ?? ((params) => net.createConnection(params));
|
||||
this.connectTls = options.connectTls ?? ((params) => tls.connect(params));
|
||||
// Only a host test harness can opt a specific loopback endpoint in. The
|
||||
// production default excludes all loopback/link-local control surfaces.
|
||||
// Only a host test harness can opt a specific loopback endpoint in without
|
||||
// interactive user confirmation. Production always blocks internal ports.
|
||||
this.testLocalEndpoints = new Set(options.testLocalEndpoints ?? []);
|
||||
this.isControlEndpoint = options.isControlEndpoint ?? (() => false);
|
||||
this.isInternalControlPort = options.isInternalControlPort ?? ((address, port) => (
|
||||
(isLoopbackAddress(address) || this.isControlEndpoint(address, port))
|
||||
&& getNetcattyInternalControlPorts().has(port)
|
||||
));
|
||||
this.confirmTlsCert = options.confirmTlsCert ?? null;
|
||||
this.isTrustedTlsCert = options.isTrustedTlsCert ?? (() => false);
|
||||
this.rememberTlsCert = options.rememberTlsCert ?? (() => {});
|
||||
this.connections = new Map();
|
||||
this.closeListeners = new Set();
|
||||
this.closed = false;
|
||||
@@ -91,7 +113,62 @@ class PluginByteStreamBroker {
|
||||
context.assertCommit?.();
|
||||
}
|
||||
|
||||
async connect(endpoint, context, hostTransport) {
|
||||
#attachSocketLifecycle(state, socket) {
|
||||
const onError = () => this.finish(state, failure("unavailable", "Byte stream transport failed"));
|
||||
const onClose = () => {
|
||||
if (!state.eof) this.finish(state, failure("unavailable", "Byte stream transport closed"));
|
||||
};
|
||||
const onEnd = () => { state.eof = true; };
|
||||
state.socketListeners = { socket, onError, onClose, onEnd };
|
||||
socket.on("error", onError);
|
||||
socket.on("close", onClose);
|
||||
socket.on("end", onEnd);
|
||||
}
|
||||
|
||||
#detachSocketLifecycle(state) {
|
||||
const prev = state.socketListeners;
|
||||
if (!prev) return;
|
||||
prev.socket.off("error", prev.onError);
|
||||
prev.socket.off("close", prev.onClose);
|
||||
prev.socket.off("end", prev.onEnd);
|
||||
state.socketListeners = null;
|
||||
}
|
||||
|
||||
async #verifyUntrustedTlsSocket(socket, state, context, servername) {
|
||||
const cert = typeof socket.getPeerCertificate === "function" ? socket.getPeerCertificate(false) : null;
|
||||
const fingerprint256 = typeof cert?.fingerprint256 === "string" ? cert.fingerprint256 : "";
|
||||
if (!fingerprint256) {
|
||||
throw failure("permissionDenied", "TLS server did not present a verifiable certificate");
|
||||
}
|
||||
if (this.isTrustedTlsCert(state.pluginId, state.endpoint, fingerprint256)) {
|
||||
return;
|
||||
}
|
||||
if (typeof this.confirmTlsCert !== "function") {
|
||||
throw failure("permissionDenied", "Untrusted TLS certificate requires explicit user confirmation");
|
||||
}
|
||||
const certInfo = Object.freeze({
|
||||
endpoint: state.endpoint,
|
||||
...(servername ? { servername } : {}),
|
||||
fingerprint256,
|
||||
subject: formatCertDistinguishedName(cert.subject),
|
||||
issuer: formatCertDistinguishedName(cert.issuer),
|
||||
validTo: typeof cert.valid_to === "string" ? cert.valid_to.slice(0, 128) : "",
|
||||
reason: String(socket.authorizationError || "UNTRUSTED_CERT").slice(0, 256),
|
||||
});
|
||||
const decision = await raceWithAbort(
|
||||
Promise.resolve(this.confirmTlsCert(certInfo, state, context)),
|
||||
state.controller.signal,
|
||||
);
|
||||
await this.active(state, context);
|
||||
if (!decision?.approved) {
|
||||
throw failure("permissionDenied", "TLS certificate was rejected by user");
|
||||
}
|
||||
if (decision.remember === true) {
|
||||
this.rememberTlsCert(state.pluginId, state.endpoint, fingerprint256);
|
||||
}
|
||||
}
|
||||
|
||||
async connect(endpoint, context, hostTransport, connectOptions = {}) {
|
||||
let target;
|
||||
try { target = canonicalizeStreamEndpoint(endpoint); }
|
||||
catch { throw failure("invalidArgument", "Byte stream endpoint is invalid"); }
|
||||
@@ -99,17 +176,28 @@ class PluginByteStreamBroker {
|
||||
if (!context.runtimeId || !context.pluginId || typeof context.assertActive !== "function") {
|
||||
throw failure("unauthenticated", "Byte streams require a host runtime identity");
|
||||
}
|
||||
const activeLimits = hostTransport ? HOST_LIMITS : LIMITS;
|
||||
const count = [...this.connections.values()].filter((state) => state.runtimeId === context.runtimeId).length;
|
||||
if (count >= LIMITS.connectionsPerRuntime || this.connections.size >= LIMITS.connectionsTotal) {
|
||||
if (count >= activeLimits.connectionsPerRuntime || this.connections.size >= activeLimits.connectionsTotal) {
|
||||
throw failure("resourceExhausted", "Byte stream connection limit exceeded");
|
||||
}
|
||||
const {
|
||||
localApproved = false,
|
||||
skipPermissionAuthorize = false,
|
||||
allowSelfSigned = false,
|
||||
caPem,
|
||||
servername,
|
||||
} = connectOptions;
|
||||
const state = {
|
||||
...target, permission: hostTransport ? "network.hostStream" : "network.stream",
|
||||
limits: hostTransport ? HOST_LIMITS : LIMITS,
|
||||
limits: activeLimits,
|
||||
id: randomUUID(), pluginId: context.pluginId, runtimeId: context.runtimeId,
|
||||
controller: new AbortController(), bytesRead: 0, bytesWritten: 0,
|
||||
sourceOwner: context.sourceOwner, sourceId: context.sourceId,
|
||||
closed: false, reading: false, writing: false, socket: null,
|
||||
socketListeners: null,
|
||||
isTls: target.transport === "tls",
|
||||
upgrading: false, upgradeDone: null, suspendRead: null,
|
||||
};
|
||||
this.connections.set(state.id, state);
|
||||
const onAbort = () => this.finish(state, failure("cancelled", "Byte stream connection cancelled"));
|
||||
@@ -117,16 +205,19 @@ class PluginByteStreamBroker {
|
||||
try {
|
||||
await this.active(state, context);
|
||||
this.assertCommit(state, context);
|
||||
if (!hostTransport) await raceWithAbort(Promise.resolve(this.permissionEngine.authorize({ ...context, signal: state.controller.signal }, {
|
||||
permission: "network.stream", resources: [target.endpoint],
|
||||
reason: `Open byte stream to ${target.endpoint}`,
|
||||
operationId: `network.stream:${target.endpoint}`,
|
||||
validateBeforeGrant: () => this.assertCommit(state, context),
|
||||
})), state.controller.signal);
|
||||
if (!hostTransport && !skipPermissionAuthorize) {
|
||||
await raceWithAbort(Promise.resolve(this.permissionEngine.authorize({ ...context, signal: state.controller.signal }, {
|
||||
permission: "network.stream", resources: [target.endpoint],
|
||||
reason: `Open byte stream to ${target.endpoint}`,
|
||||
operationId: `network.stream:${target.endpoint}`,
|
||||
validateBeforeGrant: () => this.assertCommit(state, context),
|
||||
})), state.controller.signal);
|
||||
}
|
||||
await this.active(state, context);
|
||||
state.connectTimer = setTimeout(() => this.finish(state,
|
||||
failure("deadlineExceeded", "Byte stream connect timeout")), state.limits.connectMs);
|
||||
let socket;
|
||||
const effectiveServername = servername ?? (net.isIP(target.host) ? undefined : target.host);
|
||||
if (hostTransport) {
|
||||
socket = await raceWithAbort(hostTransport.open(state.controller.signal), state.controller.signal);
|
||||
} else {
|
||||
@@ -143,12 +234,18 @@ class PluginByteStreamBroker {
|
||||
if (![4, 6].includes(peer.family) || net.isIP(peer.address) !== peer.family) {
|
||||
throw failure("unavailable", "Byte stream resolver returned an invalid address");
|
||||
}
|
||||
const local = isLocalControlAddress(peer.address);
|
||||
const allowedTestPeer = this.testLocalEndpoints.has(target.endpoint)
|
||||
&& !this.isControlEndpoint(peer.address, target.port);
|
||||
if ((local && !allowedTestPeer) || (!local && this.isControlEndpoint(peer.address, target.port))) {
|
||||
// Always block link-local/metadata/multicast and Netcatty's own internal ports.
|
||||
if (isUnconditionallyBlockedAddress(peer.address) || this.isInternalControlPort(peer.address, target.port)) {
|
||||
throw failure("permissionDenied", "Byte streams cannot reach local or application control endpoints");
|
||||
}
|
||||
if (!localApproved) {
|
||||
const local = isLocalControlAddress(peer.address);
|
||||
const allowedTestPeer = this.testLocalEndpoints.has(target.endpoint)
|
||||
&& !this.isControlEndpoint(peer.address, target.port);
|
||||
if ((local && !allowedTestPeer) || (!local && this.isControlEndpoint(peer.address, target.port))) {
|
||||
throw failure("permissionDenied", "Byte streams cannot reach local or application control endpoints");
|
||||
}
|
||||
}
|
||||
}
|
||||
const peer = addresses[0];
|
||||
const params = {
|
||||
@@ -157,9 +254,10 @@ class PluginByteStreamBroker {
|
||||
};
|
||||
if (target.transport === "tls") {
|
||||
Object.assign(params, {
|
||||
rejectUnauthorized: true, minVersion: "TLSv1.2",
|
||||
...(net.isIP(target.host) ? {} : { servername: target.host }),
|
||||
checkServerIdentity: (_name, certificate) => tls.checkServerIdentity(target.host, certificate),
|
||||
rejectUnauthorized: !allowSelfSigned, minVersion: "TLSv1.2",
|
||||
...(effectiveServername ? { servername: effectiveServername } : {}),
|
||||
...(caPem ? { ca: caPem } : {}),
|
||||
checkServerIdentity: (_name, certificate) => tls.checkServerIdentity(effectiveServername ?? target.host, certificate),
|
||||
});
|
||||
}
|
||||
this.assertCommit(state, context);
|
||||
@@ -167,20 +265,17 @@ class PluginByteStreamBroker {
|
||||
}
|
||||
state.socket = socket;
|
||||
if (state.closed) { socket.destroy(); throw state.error ?? failure("cancelled", "Byte stream connection cancelled"); }
|
||||
socket.on("error", () => this.finish(state, failure("unavailable", "Byte stream transport failed")));
|
||||
// Preserve one EOF observation for a delayed consumer. This reservation
|
||||
// still counts toward quotas and expires on the existing idle/life timer.
|
||||
socket.on("close", () => {
|
||||
if (!state.eof) this.finish(state, failure("unavailable", "Byte stream transport closed"));
|
||||
});
|
||||
socket.on("end", () => { state.eof = true; });
|
||||
this.#attachSocketLifecycle(state, socket);
|
||||
socket.pause();
|
||||
if (!hostTransport) await raceWithAbort(new Promise((resolve) => socket.once(
|
||||
target.transport === "tls" ? "secureConnect" : "connect", resolve,
|
||||
)), state.controller.signal);
|
||||
await this.active(state, context);
|
||||
if (target.transport === "tls" && !socket.authorized) {
|
||||
throw failure("permissionDenied", "Byte stream TLS validation failed");
|
||||
if (!allowSelfSigned) {
|
||||
throw failure("permissionDenied", "Byte stream TLS validation failed");
|
||||
}
|
||||
await this.#verifyUntrustedTlsSocket(socket, state, context, effectiveServername);
|
||||
}
|
||||
clearTimeout(state.connectTimer);
|
||||
state.lifetimeTimer = setTimeout(() => this.finish(state,
|
||||
@@ -198,6 +293,121 @@ class PluginByteStreamBroker {
|
||||
}
|
||||
}
|
||||
|
||||
async upgradeTls(id, options, context) {
|
||||
const state = this.get(id, context);
|
||||
if (state.isTls) throw failure("failedPrecondition", "Byte stream is already encrypted with TLS");
|
||||
if (state.upgrading) throw failure("failedPrecondition", "Byte stream TLS upgrade is already in progress");
|
||||
if (state.writing) throw failure("failedPrecondition", "Cannot upgrade TLS while a write is pending");
|
||||
const allowSelfSigned = options?.allowSelfSigned === true;
|
||||
const caPem = options?.caPem;
|
||||
const effectiveServername = options?.servername ?? (net.isIP(state.host) ? undefined : state.host);
|
||||
state.upgrading = true;
|
||||
let releaseUpgrade;
|
||||
state.upgradeDone = new Promise((resolve) => { releaseUpgrade = resolve; });
|
||||
const onAbort = () => this.finish(state, failure("cancelled", "Byte stream TLS upgrade cancelled"));
|
||||
context.signal?.addEventListener("abort", onAbort, { once: true });
|
||||
let upgradeTimer;
|
||||
try {
|
||||
await this.active(state, context);
|
||||
// Pause any active read() waiting on the plaintext socket without closing it.
|
||||
if (state.suspendRead) {
|
||||
state.suspendRead();
|
||||
state.suspendRead = null;
|
||||
}
|
||||
const rawSocket = state.socket;
|
||||
if (!rawSocket || rawSocket.destroyed) {
|
||||
throw failure("unavailable", "Byte stream socket is closed");
|
||||
}
|
||||
this.#detachSocketLifecycle(state);
|
||||
const ignoreRawError = () => {};
|
||||
rawSocket.on("error", ignoreRawError);
|
||||
rawSocket.pause();
|
||||
|
||||
const tlsParams = {
|
||||
socket: rawSocket,
|
||||
minVersion: "TLSv1.2",
|
||||
rejectUnauthorized: !allowSelfSigned,
|
||||
highWaterMark: LIMITS.bufferBytes,
|
||||
...(effectiveServername ? { servername: effectiveServername } : {}),
|
||||
...(caPem ? { ca: caPem } : {}),
|
||||
...(effectiveServername
|
||||
? { checkServerIdentity: (_name, certificate) => tls.checkServerIdentity(effectiveServername, certificate) }
|
||||
: {}),
|
||||
};
|
||||
this.assertCommit(state, context);
|
||||
const tlsSocket = this.connectTls(tlsParams);
|
||||
tlsSocket.pause();
|
||||
upgradeTimer = setTimeout(() => {
|
||||
tlsSocket.destroy();
|
||||
this.finish(state, failure("deadlineExceeded", "Byte stream TLS upgrade timeout"));
|
||||
}, state.limits.connectMs);
|
||||
upgradeTimer.unref?.();
|
||||
|
||||
await raceWithAbort(new Promise((resolve, reject) => {
|
||||
const cleanup = () => {
|
||||
tlsSocket.off("secureConnect", onSecure);
|
||||
tlsSocket.off("error", onError);
|
||||
tlsSocket.off("close", onClose);
|
||||
};
|
||||
const onSecure = () => { cleanup(); resolve(); };
|
||||
const onError = (err) => { cleanup(); reject(err); };
|
||||
const onClose = () => { cleanup(); reject(failure("unavailable", "Byte stream closed during TLS upgrade")); };
|
||||
tlsSocket.once("secureConnect", onSecure);
|
||||
tlsSocket.once("error", onError);
|
||||
tlsSocket.once("close", onClose);
|
||||
}), state.controller.signal);
|
||||
|
||||
clearTimeout(upgradeTimer);
|
||||
upgradeTimer = null;
|
||||
await this.active(state, context);
|
||||
|
||||
if (!tlsSocket.authorized) {
|
||||
if (!allowSelfSigned) {
|
||||
tlsSocket.destroy();
|
||||
throw failure("permissionDenied", "Byte stream TLS validation failed");
|
||||
}
|
||||
try {
|
||||
await this.#verifyUntrustedTlsSocket(tlsSocket, state, context, effectiveServername);
|
||||
} catch (err) {
|
||||
tlsSocket.destroy();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
rawSocket.off("error", ignoreRawError);
|
||||
state.socket = tlsSocket;
|
||||
state.isTls = true;
|
||||
this.#attachSocketLifecycle(state, tlsSocket);
|
||||
this.touch(state);
|
||||
this.assertCommit(state, context);
|
||||
this.record(state, "upgradeTls");
|
||||
|
||||
const cert = typeof tlsSocket.getPeerCertificate === "function" ? tlsSocket.getPeerCertificate(false) : null;
|
||||
const protocol = typeof tlsSocket.getProtocol === "function" ? tlsSocket.getProtocol() : undefined;
|
||||
const fingerprint256 = typeof cert?.fingerprint256 === "string" ? cert.fingerprint256 : undefined;
|
||||
const subject = cert?.subject ? formatCertDistinguishedName(cert.subject) : undefined;
|
||||
return Object.freeze({
|
||||
upgraded: true,
|
||||
authorized: Boolean(tlsSocket.authorized),
|
||||
...(protocol ? { protocol } : {}),
|
||||
...(fingerprint256 ? { fingerprint256 } : {}),
|
||||
...(subject ? { subject } : {}),
|
||||
});
|
||||
} catch (error) {
|
||||
clearTimeout(upgradeTimer);
|
||||
const rpcError = error instanceof PluginRpcError
|
||||
? error
|
||||
: failure("unavailable", "Byte stream TLS upgrade failed");
|
||||
this.finish(state, rpcError);
|
||||
throw rpcError;
|
||||
} finally {
|
||||
context.signal?.removeEventListener("abort", onAbort);
|
||||
state.upgrading = false;
|
||||
state.upgradeDone = null;
|
||||
releaseUpgrade();
|
||||
}
|
||||
}
|
||||
|
||||
get(id, context) {
|
||||
const state = this.connections.get(id);
|
||||
if (!state || state.pluginId !== context.pluginId || state.runtimeId !== context.runtimeId
|
||||
@@ -226,24 +436,32 @@ class PluginByteStreamBroker {
|
||||
await this.active(state, context);
|
||||
while (true) {
|
||||
this.assertCommit(state, context);
|
||||
const available = state.socket.readableLength;
|
||||
const bytes = state.socket.read(Math.min(available || LIMITS.chunkBytes, LIMITS.chunkBytes));
|
||||
if (state.upgrading && state.upgradeDone) {
|
||||
await raceWithAbort(state.upgradeDone, state.controller.signal);
|
||||
await this.active(state, context);
|
||||
continue;
|
||||
}
|
||||
const socket = state.socket;
|
||||
const available = socket.readableLength;
|
||||
const bytes = socket.read(Math.min(available || LIMITS.chunkBytes, LIMITS.chunkBytes));
|
||||
if (bytes !== null) {
|
||||
this.charge(state, "bytesRead", bytes.byteLength);
|
||||
await this.active(state, context);
|
||||
this.assertCommit(state, context);
|
||||
return new Uint8Array(bytes);
|
||||
}
|
||||
if (state.eof || state.socket.readableEnded) { this.finish(state); return null; }
|
||||
if (state.eof || socket.readableEnded) { this.finish(state); return null; }
|
||||
await raceWithAbort(new Promise((resolve) => {
|
||||
const readable = () => {
|
||||
state.socket.off("end", readable);
|
||||
state.socket.off("readable", readable);
|
||||
if (state.suspendRead === readable) state.suspendRead = null;
|
||||
socket.off("end", readable);
|
||||
socket.off("readable", readable);
|
||||
state.controller.signal.removeEventListener("abort", readable);
|
||||
resolve();
|
||||
};
|
||||
state.socket.once("readable", readable);
|
||||
state.socket.once("end", readable);
|
||||
state.suspendRead = readable;
|
||||
socket.once("readable", readable);
|
||||
socket.once("end", readable);
|
||||
// Remove listeners even when cancellation wins the race.
|
||||
state.controller.signal.addEventListener("abort", readable, { once: true });
|
||||
}), state.controller.signal);
|
||||
@@ -253,6 +471,7 @@ class PluginByteStreamBroker {
|
||||
this.finish(state, error);
|
||||
throw error;
|
||||
} finally {
|
||||
state.suspendRead = null;
|
||||
context.signal?.removeEventListener("abort", onAbort);
|
||||
state.reading = false;
|
||||
}
|
||||
@@ -260,6 +479,7 @@ class PluginByteStreamBroker {
|
||||
|
||||
async write(id, bytes, context) {
|
||||
const state = this.get(id, context);
|
||||
if (state.upgrading) throw failure("failedPrecondition", "Cannot write while TLS upgrade is in progress");
|
||||
if (!(bytes instanceof Uint8Array) || bytes.byteLength < 1 || bytes.byteLength > LIMITS.chunkBytes) {
|
||||
throw failure("invalidArgument", "Byte stream chunk size is invalid");
|
||||
}
|
||||
@@ -302,4 +522,4 @@ class PluginByteStreamBroker {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { LIMITS, PluginByteStreamBroker, canonicalizeStreamEndpoint, isLocalControlAddress };
|
||||
module.exports = { LIMITS, HOST_LIMITS, PluginByteStreamBroker, canonicalizeStreamEndpoint, isLocalControlAddress };
|
||||
@@ -328,3 +328,129 @@ test("real TLS validates trust and the original hostname against a pinned IP", a
|
||||
const wrong = broker(t, wrongEndpoint, { lookup, connectTls: (options) => tls.connect({ ...options, ca: cert }) }).instance;
|
||||
await assert.rejects(wrong.connect(wrongEndpoint, context()), { code: RPC_ERRORS.unavailable });
|
||||
});
|
||||
|
||||
test("dynamic local opt-in allows loopback when approved but unconditionally blocks Netcatty internal control ports and metadata IPs", async (t) => {
|
||||
const peer = await server(t, (socket) => socket.on("data", (bytes) => socket.write(bytes)));
|
||||
const port = peer.address().port;
|
||||
const endpoint = `tcp://127.0.0.1:${port}`;
|
||||
const { instance } = broker(t, null, {
|
||||
isInternalControlPort: (_address, targetPort) => targetPort === port,
|
||||
});
|
||||
// Even with localApproved: true, Netcatty's own internal control port is unconditionally blocked.
|
||||
await assert.rejects(
|
||||
instance.connect(endpoint, context(), undefined, { localApproved: true, skipPermissionAuthorize: true }),
|
||||
{ code: RPC_ERRORS.permissionDenied },
|
||||
);
|
||||
// Link-local cloud metadata IP is unconditionally blocked even with localApproved: true.
|
||||
await assert.rejects(
|
||||
instance.connect("tcp://169.254.169.254:80", context(), undefined, { localApproved: true, skipPermissionAuthorize: true }),
|
||||
{ code: RPC_ERRORS.permissionDenied },
|
||||
);
|
||||
// Approved loopback to a non-control DB port succeeds cleanly.
|
||||
const allowed = broker(t, null, {
|
||||
isInternalControlPort: () => false,
|
||||
}).instance;
|
||||
const ctx = context();
|
||||
const handle = await allowed.connect(endpoint, ctx, undefined, { localApproved: true, skipPermissionAuthorize: true });
|
||||
await allowed.write(handle.handleId, Uint8Array.from([1, 2, 3]), ctx);
|
||||
assert.deepEqual(await allowed.read(handle.handleId, ctx), Uint8Array.from([1, 2, 3]));
|
||||
allowed.close(handle.handleId, ctx);
|
||||
});
|
||||
|
||||
test("in-band STARTTLS upgradeTls upgrades a plaintext TCP stream with CA validation, pending-read resume, and explicit self-signed cert approval", async (t) => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-starttls-test-"));
|
||||
t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
const keyPath = path.join(directory, "test.key");
|
||||
const certPath = path.join(directory, "test.crt");
|
||||
execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", keyPath,
|
||||
"-out", certPath, "-days", "1", "-subj", "/CN=db.local.test", "-addext", "subjectAltName=DNS:db.local.test"],
|
||||
{ stdio: "ignore" });
|
||||
const key = fs.readFileSync(keyPath);
|
||||
const cert = fs.readFileSync(certPath);
|
||||
|
||||
// Simulate PostgreSQL SSLRequest -> 'S' -> STARTTLS upgrade -> encrypted echo.
|
||||
const peer = await server(t, (rawSocket) => {
|
||||
rawSocket.once("data", (chunk) => {
|
||||
if (chunk.toString() === "SSLREQ") {
|
||||
rawSocket.write("S");
|
||||
const tlsSocket = new tls.TLSSocket(rawSocket, { isServer: true, key, cert });
|
||||
tlsSocket.on("error", () => {});
|
||||
tlsSocket.on("data", (data) => tlsSocket.write(Buffer.concat([Buffer.from("TLS:"), data])));
|
||||
}
|
||||
});
|
||||
});
|
||||
const endpoint = `tcp://127.0.0.1:${peer.address().port}`;
|
||||
|
||||
// 1) Trusted CA upgrade with a pending read() already active on the plaintext socket.
|
||||
{
|
||||
const { instance } = broker(t, endpoint);
|
||||
const ctx = context();
|
||||
const { handleId } = await instance.connect(endpoint, ctx);
|
||||
await instance.write(handleId, Buffer.from("SSLREQ"), ctx);
|
||||
assert.equal(Buffer.from(await instance.read(handleId, ctx)).toString(), "S");
|
||||
// Start a pending read (mirrors byteStreamService.pump()) BEFORE calling upgradeTls.
|
||||
const pendingRead = instance.read(handleId, ctx);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
const upgraded = await instance.upgradeTls(handleId, { servername: "db.local.test", caPem: cert.toString("utf8") }, ctx);
|
||||
assert.equal(upgraded.upgraded, true);
|
||||
assert.equal(upgraded.authorized, true);
|
||||
assert.ok(upgraded.fingerprint256);
|
||||
await instance.write(handleId, Buffer.from("SELECT 1"), ctx);
|
||||
assert.equal(Buffer.from(await pendingRead).toString(), "TLS:SELECT 1");
|
||||
instance.close(handleId, ctx);
|
||||
}
|
||||
|
||||
// 2) Self-signed cert fails closed without allowSelfSigned, prompts user with allowSelfSigned, and honors remembered fingerprint.
|
||||
{
|
||||
const trustedFingerprints = new Set();
|
||||
const prompts = [];
|
||||
const { instance } = broker(t, endpoint, {
|
||||
isTrustedTlsCert: (_pluginId, _ep, fp) => trustedFingerprints.has(fp),
|
||||
rememberTlsCert: (_pluginId, _ep, fp) => trustedFingerprints.add(fp),
|
||||
confirmTlsCert: async (info) => {
|
||||
prompts.push(info);
|
||||
return { approved: prompts.length > 1, remember: true };
|
||||
},
|
||||
});
|
||||
const ctx = context();
|
||||
// First attempt: user rejects self-signed cert -> fails closed.
|
||||
const first = await instance.connect(endpoint, ctx);
|
||||
await instance.write(first.handleId, Buffer.from("SSLREQ"), ctx);
|
||||
assert.equal(Buffer.from(await instance.read(first.handleId, ctx)).toString(), "S");
|
||||
await assert.rejects(
|
||||
instance.upgradeTls(first.handleId, { servername: "db.local.test", allowSelfSigned: true }, ctx),
|
||||
{ code: RPC_ERRORS.permissionDenied },
|
||||
);
|
||||
assert.equal(prompts.length, 1);
|
||||
assert.ok(prompts[0].fingerprint256.length > 20);
|
||||
assert.match(prompts[0].subject, /CN=db\.local\.test/);
|
||||
|
||||
// Second attempt: user approves with remember: true.
|
||||
const second = await instance.connect(endpoint, ctx);
|
||||
await instance.write(second.handleId, Buffer.from("SSLREQ"), ctx);
|
||||
assert.equal(Buffer.from(await instance.read(second.handleId, ctx)).toString(), "S");
|
||||
const res2 = await instance.upgradeTls(second.handleId, { servername: "db.local.test", allowSelfSigned: true }, ctx);
|
||||
assert.equal(res2.upgraded, true);
|
||||
assert.equal(res2.authorized, false);
|
||||
assert.equal(prompts.length, 2);
|
||||
await instance.write(second.handleId, Buffer.from("PING"), ctx);
|
||||
assert.equal(Buffer.from(await instance.read(second.handleId, ctx)).toString(), "TLS:PING");
|
||||
instance.close(second.handleId, ctx);
|
||||
|
||||
// Third attempt: remembered fingerprint skips prompt automatically.
|
||||
const third = await instance.connect(endpoint, ctx);
|
||||
await instance.write(third.handleId, Buffer.from("SSLREQ"), ctx);
|
||||
assert.equal(Buffer.from(await instance.read(third.handleId, ctx)).toString(), "S");
|
||||
const res3 = await instance.upgradeTls(third.handleId, { servername: "db.local.test", allowSelfSigned: true }, ctx);
|
||||
assert.equal(res3.upgraded, true);
|
||||
assert.equal(prompts.length, 2);
|
||||
instance.close(third.handleId, ctx);
|
||||
}
|
||||
});
|
||||
|
||||
test("DB-friendly stream budgets expose expanded concurrency, idle, lifetime, and byte caps", () => {
|
||||
assert.equal(LIMITS.connectionsPerRuntime, 24);
|
||||
assert.equal(LIMITS.idleMs, 1_800_000);
|
||||
assert.equal(LIMITS.lifetimeMs, 28_800_000);
|
||||
assert.equal(LIMITS.connectionBytes, 536_870_912);
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const fs = require("node:fs");
|
||||
const net = require("node:net");
|
||||
|
||||
function failure(_code, message) { return new TypeError(message); }
|
||||
@@ -42,18 +43,79 @@ function normalizeStreamAddress(address) {
|
||||
return [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join(".");
|
||||
}
|
||||
|
||||
function isLocalControlAddress(address) {
|
||||
address = normalizeStreamAddress(address);
|
||||
if (net.isIP(address) === 4) {
|
||||
const [a, b] = address.split(".").map(Number);
|
||||
return a === 0 || a === 127 || a >= 224 || (a === 169 && b === 254);
|
||||
function isLoopbackAddress(address) {
|
||||
const normalized = normalizeStreamAddress(address);
|
||||
if (net.isIP(normalized) === 4) {
|
||||
return normalized.startsWith("127.");
|
||||
}
|
||||
if (net.isIP(address) !== 6) return true;
|
||||
const canonical = address;
|
||||
// Also exclude compatible/tunnel addresses that can obscure a local IPv4 peer.
|
||||
return canonical.startsWith("::") || canonical.startsWith("ff")
|
||||
|| /^fe[89ab]/u.test(canonical) || canonical.startsWith("2002:")
|
||||
|| canonical.startsWith("2001:0:");
|
||||
return normalized === "::1";
|
||||
}
|
||||
|
||||
module.exports = { canonicalizeStreamEndpoint, isLocalControlAddress, normalizeStreamAddress };
|
||||
function isUnconditionallyBlockedAddress(address) {
|
||||
const normalized = normalizeStreamAddress(address);
|
||||
if (net.isIP(normalized) === 4) {
|
||||
const [a, b] = normalized.split(".").map(Number);
|
||||
return a === 0 || a >= 224 || (a === 169 && b === 254);
|
||||
}
|
||||
if (net.isIP(normalized) !== 6) return true;
|
||||
if (normalized === "::1") return false;
|
||||
return normalized.startsWith("::") || normalized.startsWith("ff")
|
||||
|| /^fe[89ab]/u.test(normalized) || normalized.startsWith("2002:")
|
||||
|| normalized.startsWith("2001:0:");
|
||||
}
|
||||
|
||||
function isLocalControlAddress(address) {
|
||||
return isLoopbackAddress(address) || isUnconditionallyBlockedAddress(address);
|
||||
}
|
||||
|
||||
function getNetcattyInternalControlPorts() {
|
||||
const ports = new Set();
|
||||
const discoveryFile = process.env.NETCATTY_TOOL_CLI_DISCOVERY_FILE;
|
||||
if (typeof discoveryFile === "string" && discoveryFile.length > 0) {
|
||||
try {
|
||||
const parsed = JSON.parse(fs.readFileSync(discoveryFile, "utf8"));
|
||||
if (Number.isInteger(parsed?.port) && parsed.port > 0 && parsed.port <= 65535) {
|
||||
ports.add(parsed.port);
|
||||
}
|
||||
} catch { /* discovery file may not exist */ }
|
||||
}
|
||||
const viteUrl = process.env.VITE_DEV_SERVER_URL;
|
||||
if (typeof viteUrl === "string" && viteUrl.length > 0) {
|
||||
try {
|
||||
const parsed = new URL(viteUrl);
|
||||
const port = Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80));
|
||||
if (Number.isInteger(port) && port > 0 && port <= 65535) ports.add(port);
|
||||
} catch { /* ignore invalid dev server URL */ }
|
||||
}
|
||||
for (const arg of [...(process.argv ?? []), ...(process.execArgv ?? [])]) {
|
||||
const match = /^--(?:remote-debugging-port|inspect|inspect-brk)=(?:[^:]*:)?(\d{1,5})$/u.exec(String(arg));
|
||||
if (match) {
|
||||
const port = Number(match[1]);
|
||||
if (port > 0 && port <= 65535) ports.add(port);
|
||||
}
|
||||
}
|
||||
// In the live Electron main process, every active TCP net.Server belongs to
|
||||
// Netcatty's own internal bridges (MCP/CLI RPC, external MCP HTTP, OAuth, etc.).
|
||||
if (process.versions?.electron && typeof process._getActiveHandles === "function") {
|
||||
try {
|
||||
for (const handle of process._getActiveHandles()) {
|
||||
if (handle instanceof net.Server && handle.listening) {
|
||||
const addr = handle.address();
|
||||
if (addr && typeof addr === "object" && Number.isInteger(addr.port) && addr.port > 0) {
|
||||
ports.add(addr.port);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch { /* ignore handle inspection errors */ }
|
||||
}
|
||||
return ports;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
canonicalizeStreamEndpoint,
|
||||
getNetcattyInternalControlPorts,
|
||||
isLocalControlAddress,
|
||||
isLoopbackAddress,
|
||||
isUnconditionallyBlockedAddress,
|
||||
normalizeStreamAddress,
|
||||
};
|
||||
@@ -2,7 +2,11 @@
|
||||
|
||||
const { randomUUID } = require("node:crypto");
|
||||
const os = require("node:os");
|
||||
const { normalizeStreamAddress } = require("./byteStreamEndpoint.cjs");
|
||||
const {
|
||||
canonicalizeStreamEndpoint,
|
||||
isLocalControlAddress,
|
||||
normalizeStreamAddress,
|
||||
} = require("./byteStreamEndpoint.cjs");
|
||||
const { PluginByteStreamBroker, LIMITS } = require("./byteStreamBroker.cjs");
|
||||
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
|
||||
const { createDefinitionValidator } = require("./contractValidator.cjs");
|
||||
@@ -17,22 +21,63 @@ function validator(name) {
|
||||
};
|
||||
}
|
||||
|
||||
function manifestStreamDeclaration(manifest, canonicalEndpoint) {
|
||||
const declarations = [
|
||||
...(manifest?.permissions?.required ?? []),
|
||||
...(manifest?.permissions?.optional ?? []),
|
||||
];
|
||||
let declared = false;
|
||||
let staticMatch = false;
|
||||
for (const item of declarations) {
|
||||
if (item === "network.stream") {
|
||||
declared = true;
|
||||
} else if (item && typeof item === "object" && item.permission === "network.stream") {
|
||||
declared = true;
|
||||
if (Array.isArray(item.resources)) {
|
||||
for (const resource of item.resources) {
|
||||
try {
|
||||
if (canonicalizeStreamEndpoint(resource).endpoint === canonicalEndpoint) {
|
||||
staticMatch = true;
|
||||
}
|
||||
} catch { /* ignore invalid entry */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { declared, staticMatch };
|
||||
}
|
||||
|
||||
function isOwnMachineAddress(address) {
|
||||
const normalized = normalizeStreamAddress(address);
|
||||
return normalized !== null && Object.values(os.networkInterfaces()).flat()
|
||||
.some((item) => item?.address && normalizeStreamAddress(item.address) === normalized);
|
||||
}
|
||||
|
||||
class PluginByteStreamService {
|
||||
constructor(options) {
|
||||
this.database = options.database;
|
||||
this.permissionEngine = options.permissionEngine;
|
||||
this.runtimeSupervisor = options.runtimeSupervisor;
|
||||
this.interactionService = options.interactionService ?? null;
|
||||
this.records = new Map();
|
||||
this.closedHandles = new Map();
|
||||
this.memoryEndpoints = new Map();
|
||||
this.memoryTrustedCerts = new Map();
|
||||
this.closed = false;
|
||||
this.broker = new PluginByteStreamBroker({
|
||||
permissionEngine: options.permissionEngine,
|
||||
quotaManager: options.quotaManager,
|
||||
// The public host service never forwards transport fixture overrides.
|
||||
isControlEndpoint: (address) => {
|
||||
const normalized = normalizeStreamAddress(address);
|
||||
return normalized !== null && Object.values(os.networkInterfaces()).flat()
|
||||
.some((item) => item?.address && normalizeStreamAddress(item.address) === normalized);
|
||||
},
|
||||
isControlEndpoint: (address) => isOwnMachineAddress(address),
|
||||
isTrustedTlsCert: (pluginId, endpoint, fingerprint256) => (
|
||||
this.isTrustedTlsCert(pluginId, endpoint, fingerprint256)
|
||||
),
|
||||
rememberTlsCert: (pluginId, endpoint, fingerprint256) => (
|
||||
this.rememberTrustedTlsCert(pluginId, endpoint, fingerprint256)
|
||||
),
|
||||
confirmTlsCert: async (certInfo, _state, context) => (
|
||||
this.#confirmTlsCert(certInfo, context)
|
||||
),
|
||||
audit: (pluginId, operation, fields, state) => {
|
||||
if (this.sourceMatches(state)) this.database.recordSecurityAudit(pluginId, operation, fields);
|
||||
},
|
||||
@@ -40,6 +85,163 @@ class PluginByteStreamService {
|
||||
this.brokerClose = this.broker.onDidClose((state, reason) => {
|
||||
if (reason) this.closeRecord(this.records.get(state.id), reason);
|
||||
});
|
||||
this.revocation = this.permissionEngine?.onDidRevoke?.((event) => {
|
||||
if (event.permission === undefined || event.permission === "network.stream") {
|
||||
if (event.resource) {
|
||||
this.revokeDynamicEndpoint(event.pluginId, event.resource);
|
||||
} else {
|
||||
this.clearRememberedEndpoints(event.pluginId);
|
||||
}
|
||||
}
|
||||
}) ?? { dispose() {} };
|
||||
}
|
||||
|
||||
#ownerKey(pluginId) {
|
||||
return typeof this.database?.privateOwner === "function"
|
||||
? this.database.privateOwner(pluginId)
|
||||
: pluginId;
|
||||
}
|
||||
|
||||
#readPref(key, fallback) {
|
||||
if (this.database?.db) {
|
||||
try {
|
||||
const row = this.database.db.prepare("SELECT value_json FROM plugin_host_preferences WHERE key = ?").get(key);
|
||||
if (row?.value_json) return JSON.parse(row.value_json);
|
||||
} catch { /* fall through */ }
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
#writePref(key, value) {
|
||||
if (this.database?.db) {
|
||||
try {
|
||||
this.database.db.prepare(
|
||||
"INSERT INTO plugin_host_preferences(key,value_json,updated_at) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET value_json=excluded.value_json,updated_at=excluded.updated_at",
|
||||
).run(key, JSON.stringify(value), Date.now());
|
||||
} catch { /* ignore when mock db */ }
|
||||
}
|
||||
}
|
||||
|
||||
#deletePref(key) {
|
||||
if (this.database?.db) {
|
||||
try {
|
||||
this.database.db.prepare("DELETE FROM plugin_host_preferences WHERE key = ?").run(key);
|
||||
} catch { /* ignore when mock db */ }
|
||||
}
|
||||
}
|
||||
|
||||
#endpointPrefKey(pluginId) {
|
||||
return `permission:${this.#ownerKey(pluginId)}:stream-endpoints`;
|
||||
}
|
||||
|
||||
#tlsCertPrefKey(pluginId) {
|
||||
return `permission:${this.#ownerKey(pluginId)}:stream-tls-certs`;
|
||||
}
|
||||
|
||||
listDynamicEndpoints(pluginId) {
|
||||
const key = this.#endpointPrefKey(pluginId);
|
||||
const list = this.#readPref(key, this.memoryEndpoints.get(key) ?? []);
|
||||
return Array.isArray(list) ? list : [];
|
||||
}
|
||||
|
||||
isDynamicEndpointRemembered(pluginId, endpoint) {
|
||||
return this.listDynamicEndpoints(pluginId).includes(endpoint);
|
||||
}
|
||||
|
||||
rememberDynamicEndpoint(pluginId, endpoint) {
|
||||
const key = this.#endpointPrefKey(pluginId);
|
||||
const current = new Set(this.listDynamicEndpoints(pluginId));
|
||||
current.add(endpoint);
|
||||
const next = [...current].slice(-256);
|
||||
this.memoryEndpoints.set(key, next);
|
||||
this.#writePref(key, next);
|
||||
}
|
||||
|
||||
revokeDynamicEndpoint(pluginId, endpoint) {
|
||||
const key = this.#endpointPrefKey(pluginId);
|
||||
const next = this.listDynamicEndpoints(pluginId).filter((item) => item !== endpoint);
|
||||
this.memoryEndpoints.set(key, next);
|
||||
if (next.length === 0) this.#deletePref(key);
|
||||
else this.#writePref(key, next);
|
||||
// Also revoke remembered certs for that endpoint.
|
||||
const certKey = this.#tlsCertPrefKey(pluginId);
|
||||
const certs = { ...this.#readPref(certKey, this.memoryTrustedCerts.get(certKey) ?? {}) };
|
||||
if (endpoint in certs) {
|
||||
delete certs[endpoint];
|
||||
this.memoryTrustedCerts.set(certKey, certs);
|
||||
if (Object.keys(certs).length === 0) this.#deletePref(certKey);
|
||||
else this.#writePref(certKey, certs);
|
||||
}
|
||||
}
|
||||
|
||||
clearRememberedEndpoints(pluginId) {
|
||||
const key = this.#endpointPrefKey(pluginId);
|
||||
const certKey = this.#tlsCertPrefKey(pluginId);
|
||||
this.memoryEndpoints.delete(key);
|
||||
this.memoryTrustedCerts.delete(certKey);
|
||||
this.#deletePref(key);
|
||||
this.#deletePref(certKey);
|
||||
}
|
||||
|
||||
isTrustedTlsCert(pluginId, endpoint, fingerprint256) {
|
||||
const certKey = this.#tlsCertPrefKey(pluginId);
|
||||
const certs = this.#readPref(certKey, this.memoryTrustedCerts.get(certKey) ?? {});
|
||||
return Array.isArray(certs?.[endpoint]) && certs[endpoint].includes(fingerprint256);
|
||||
}
|
||||
|
||||
rememberTrustedTlsCert(pluginId, endpoint, fingerprint256) {
|
||||
const certKey = this.#tlsCertPrefKey(pluginId);
|
||||
const certs = { ...this.#readPref(certKey, this.memoryTrustedCerts.get(certKey) ?? {}) };
|
||||
const existing = new Set(Array.isArray(certs[endpoint]) ? certs[endpoint] : []);
|
||||
existing.add(fingerprint256);
|
||||
certs[endpoint] = [...existing].slice(-16);
|
||||
this.memoryTrustedCerts.set(certKey, certs);
|
||||
this.#writePref(certKey, certs);
|
||||
}
|
||||
|
||||
async #confirmDynamicEndpoint(target, context) {
|
||||
const isLocal = target.host === "localhost"
|
||||
|| isLocalControlAddress(target.host)
|
||||
|| isOwnMachineAddress(target.host);
|
||||
if (this.interactionService?.owner) {
|
||||
const result = await this.interactionService.request({
|
||||
kind: "network.stream.confirm",
|
||||
endpoint: target.endpoint,
|
||||
host: target.host,
|
||||
port: target.port,
|
||||
transport: target.transport,
|
||||
isLocal,
|
||||
}, context);
|
||||
if (result?.cancelled || !result?.approved) {
|
||||
throw new PluginRpcError(RPC_ERRORS.cancelled, "Byte stream connection cancelled");
|
||||
}
|
||||
if (result.remember === true) {
|
||||
this.rememberDynamicEndpoint(context.pluginId, target.endpoint);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Non-interactive / headless test fallback: defer to permissionEngine hook.
|
||||
await this.permissionEngine.authorize({ ...context, signal: context.signal }, {
|
||||
permission: "network.stream",
|
||||
resources: [target.endpoint],
|
||||
reason: `Open byte stream to ${target.endpoint}`,
|
||||
operationId: `network.stream:${target.endpoint}`,
|
||||
validateBeforeGrant: () => context.assertCommit?.(),
|
||||
});
|
||||
}
|
||||
|
||||
async #confirmTlsCert(certInfo, context) {
|
||||
if (this.interactionService?.owner) {
|
||||
const result = await this.interactionService.request({
|
||||
kind: "network.stream.tlsConfirm",
|
||||
...certInfo,
|
||||
}, context);
|
||||
if (result?.cancelled || !result?.approved) {
|
||||
return { approved: false };
|
||||
}
|
||||
return { approved: true, remember: result.remember === true };
|
||||
}
|
||||
return { approved: false };
|
||||
}
|
||||
|
||||
sourceMatches(identity) {
|
||||
@@ -73,13 +275,46 @@ class PluginByteStreamService {
|
||||
|
||||
register(registry) {
|
||||
// These routes own authorization: connect authenticates before the broker
|
||||
// obtains its exact endpoint grant; attach/close prove handle ownership.
|
||||
// obtains its exact endpoint grant; attach/close/upgradeTls prove handle ownership.
|
||||
// The registry public flag skips only the generic permission middleware.
|
||||
// Runtime authentication and quota middleware still apply to every call.
|
||||
registry.registerRequest("network.stream.connect", async ({ endpoint }, caller) => {
|
||||
registry.registerRequest("network.stream.connect", async (params, caller) => {
|
||||
const context = await this.authenticate(caller);
|
||||
return this.connect(endpoint, context);
|
||||
let target;
|
||||
try { target = canonicalizeStreamEndpoint(params.endpoint); }
|
||||
catch { throw new PluginRpcError(RPC_ERRORS.invalidArgument, "Byte stream endpoint is invalid"); }
|
||||
const { declared, staticMatch } = manifestStreamDeclaration(context.manifest, target.endpoint);
|
||||
const isDynamic = !staticMatch || params.allowLocal === true;
|
||||
const connectOptions = {
|
||||
allowSelfSigned: params.allowSelfSigned === true,
|
||||
...(params.caPem === undefined ? {} : { caPem: params.caPem }),
|
||||
...(params.servername === undefined ? {} : { servername: params.servername }),
|
||||
};
|
||||
if (isDynamic && declared) {
|
||||
const mode = this.permissionEngine.getMode?.(context, "network.stream") ?? "allow";
|
||||
if (mode === "deny") {
|
||||
throw new PluginRpcError(RPC_ERRORS.permissionDenied, "Plugin permission is disabled: network.stream");
|
||||
}
|
||||
if (!this.isDynamicEndpointRemembered(context.pluginId, target.endpoint)) {
|
||||
await this.#confirmDynamicEndpoint(target, context);
|
||||
}
|
||||
await context.assertActive();
|
||||
connectOptions.localApproved = true;
|
||||
connectOptions.skipPermissionAuthorize = true;
|
||||
}
|
||||
return this.connect(target.endpoint, context, undefined, connectOptions);
|
||||
}, { validateParams: validator("ByteStreamConnectRequest"), metadata: { capability: "network.stream", mutating: true, public: true } });
|
||||
|
||||
registry.registerRequest("network.stream.upgradeTls", async ({ handleId, servername, allowSelfSigned, caPem }, caller) => {
|
||||
const context = await this.authenticate(caller);
|
||||
const record = this.get(handleId, context);
|
||||
return this.broker.upgradeTls(handleId, {
|
||||
...(servername === undefined ? {} : { servername }),
|
||||
allowSelfSigned: allowSelfSigned === true,
|
||||
...(caPem === undefined ? {} : { caPem }),
|
||||
}, record.context);
|
||||
}, { validateParams: validator("ByteStreamUpgradeTlsRequest"), metadata: { capability: "network.stream", mutating: true, public: true } });
|
||||
|
||||
registry.registerRequest("network.stream.attach", async ({ handleId }, caller) => {
|
||||
const context = await this.authenticate(caller);
|
||||
const record = this.get(handleId, context);
|
||||
@@ -130,8 +365,8 @@ class PluginByteStreamService {
|
||||
});
|
||||
}
|
||||
|
||||
async connect(endpoint, context, hostTransport) {
|
||||
const handle = await this.broker.connect(endpoint, context, hostTransport);
|
||||
async connect(endpoint, context, hostTransport, connectOptions) {
|
||||
const handle = await this.broker.connect(endpoint, context, hostTransport, connectOptions);
|
||||
try {
|
||||
context.assertCommit();
|
||||
this.broker.get(handle.handleId, context);
|
||||
@@ -208,6 +443,7 @@ class PluginByteStreamService {
|
||||
for (const record of this.records.values()) this.closeRecord(record);
|
||||
this.broker.shutdown();
|
||||
this.brokerClose.dispose();
|
||||
this.revocation.dispose();
|
||||
this.streamRegistration?.dispose();
|
||||
this.closedHandles.clear();
|
||||
}
|
||||
|
||||
@@ -9,11 +9,11 @@ const PLUGIN_UTILITY_TERMINATION_GRACE_MS = 500;
|
||||
const PLUGIN_UTILITY_FORCE_EXIT_TIMEOUT_MS = 1_000;
|
||||
const PLUGIN_RPC_DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const PLUGIN_RPC_MAX_PENDING = 256;
|
||||
const PLUGIN_RPC_MAX_JSON_BYTES = 1024 * 1024;
|
||||
const PLUGIN_RPC_MAX_JSON_BYTES = 8 * 1024 * 1024;
|
||||
// Broker payloads live inside the control-plane JSON envelope. Reserve enough
|
||||
// room for worst-case JSON string escaping (six wire bytes per raw byte),
|
||||
// headers, paths, correlation fields, and future compatible metadata.
|
||||
const PLUGIN_RPC_MAX_RAW_BYTES = Math.floor(PLUGIN_RPC_MAX_JSON_BYTES / 8);
|
||||
const PLUGIN_RPC_MAX_RAW_BYTES = 128 * 1024;
|
||||
const PLUGIN_STREAM_MAX_FRAME_JSON_BYTES = 24 * 1024 * 1024;
|
||||
const PLUGIN_CRASH_WINDOW_MS = 5 * 60_000;
|
||||
const PLUGIN_CRASH_QUARANTINE_THRESHOLD = 3;
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
const { randomUUID } = require("node:crypto");
|
||||
|
||||
const DEFAULT_RASTER_TIMEOUT_MS = 5_000;
|
||||
const DEFAULT_POOLED_RASTER_TIMEOUT_MS = 15_000;
|
||||
const DEFAULT_POOLED_IDLE_MS = 15_000;
|
||||
const RASTER_BLANK_HTML_URL = "data:text/html;charset=utf-8,%3Cmeta%20http-equiv%3D%22Content-Security-Policy%22%20content%3D%22default-src%20'none'%3B%20img-src%20data%3A%3B%22%3E";
|
||||
|
||||
function withTimeout(promise, timeoutMs, message) {
|
||||
let timer;
|
||||
@@ -82,7 +85,7 @@ function createIsolatedContributionIconRasterizer(options) {
|
||||
(_details, callback) => callback({ cancel: true }),
|
||||
);
|
||||
await withTimeout(
|
||||
Promise.resolve(win.loadURL("data:text/html;charset=utf-8,%3Cmeta%20http-equiv%3D%22Content-Security-Policy%22%20content%3D%22default-src%20'none'%3B%20img-src%20data%3A%3B%22%3E")),
|
||||
Promise.resolve(win.loadURL(RASTER_BLANK_HTML_URL)),
|
||||
timeoutMs,
|
||||
"Plugin contribution icon rasterizer did not load in time",
|
||||
);
|
||||
@@ -108,8 +111,147 @@ function createIsolatedContributionIconRasterizer(options) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reuses a single sandboxed, network-denied BrowserWindow across burst decodes
|
||||
* (e.g. plugin view icon grids) and destroys it automatically after idleMs, on
|
||||
* any error/timeout, or on dispose(). Preserves the exact same sandbox, CSP,
|
||||
* spellcheck:false, and network-deny guarantees as per-call windows while
|
||||
* eliminating repeated OS window creation overhead.
|
||||
*/
|
||||
function createPooledContributionIconRasterizer(options) {
|
||||
const BrowserWindow = options?.BrowserWindow;
|
||||
const randomUUIDFn = options?.randomUUID ?? randomUUID;
|
||||
const timeoutMs = options?.timeoutMs ?? DEFAULT_POOLED_RASTER_TIMEOUT_MS;
|
||||
const idleMs = options?.idleMs ?? DEFAULT_POOLED_IDLE_MS;
|
||||
|
||||
let activeWindow = null;
|
||||
let windowReadyPromise = null;
|
||||
let inFlight = 0;
|
||||
let idleTimer = null;
|
||||
let generation = 0;
|
||||
|
||||
const clearIdleTimer = () => {
|
||||
if (idleTimer !== null) {
|
||||
clearTimeout(idleTimer);
|
||||
idleTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
const destroyCurrent = (expectedGen) => {
|
||||
if (expectedGen !== undefined && expectedGen !== generation) return;
|
||||
clearIdleTimer();
|
||||
const win = activeWindow;
|
||||
activeWindow = null;
|
||||
windowReadyPromise = null;
|
||||
generation += 1;
|
||||
if (win) {
|
||||
try { win.destroy(); } catch {}
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleIdleDestroy = (expectedGen) => {
|
||||
clearIdleTimer();
|
||||
if (inFlight > 0 || !activeWindow || idleMs <= 0) return;
|
||||
idleTimer = setTimeout(() => {
|
||||
idleTimer = null;
|
||||
if (inFlight === 0 && generation === expectedGen) destroyCurrent(expectedGen);
|
||||
}, idleMs);
|
||||
idleTimer.unref?.();
|
||||
};
|
||||
|
||||
const acquireWindow = async () => {
|
||||
if (typeof BrowserWindow !== "function") {
|
||||
throw new Error("Isolated plugin contribution icon rasterizer is unavailable");
|
||||
}
|
||||
clearIdleTimer();
|
||||
if (activeWindow && windowReadyPromise && !activeWindow.isDestroyed?.()) {
|
||||
const currentGen = generation;
|
||||
await windowReadyPromise;
|
||||
if (activeWindow && generation === currentGen && !activeWindow.isDestroyed?.()) {
|
||||
return { win: activeWindow, gen: currentGen };
|
||||
}
|
||||
}
|
||||
destroyCurrent();
|
||||
const currentGen = generation;
|
||||
const partition = `plugin-icon-raster-${randomUUIDFn()}`;
|
||||
const win = new BrowserWindow({
|
||||
show: false,
|
||||
width: 64,
|
||||
height: 64,
|
||||
webPreferences: {
|
||||
partition,
|
||||
sandbox: true,
|
||||
spellcheck: false,
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
webSecurity: true,
|
||||
allowRunningInsecureContent: false,
|
||||
backgroundThrottling: false,
|
||||
},
|
||||
});
|
||||
activeWindow = win;
|
||||
const ready = (async () => {
|
||||
win.removeMenu?.();
|
||||
win.webContents?.session?.webRequest?.onBeforeRequest?.(
|
||||
{ urls: ["http://*/*", "https://*/*", "file://*/*", "ftp://*/*"] },
|
||||
(_details, callback) => callback({ cancel: true }),
|
||||
);
|
||||
await withTimeout(
|
||||
Promise.resolve(win.loadURL(RASTER_BLANK_HTML_URL)),
|
||||
timeoutMs,
|
||||
"Plugin contribution icon rasterizer did not load in time",
|
||||
);
|
||||
})();
|
||||
windowReadyPromise = ready;
|
||||
try {
|
||||
await ready;
|
||||
return { win, gen: currentGen };
|
||||
} catch (error) {
|
||||
destroyCurrent(currentGen);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const rasterize = async ({ body, mimeType, width, height, maxEdge }) => {
|
||||
inFlight += 1;
|
||||
let gen;
|
||||
try {
|
||||
const acquired = await acquireWindow();
|
||||
gen = acquired.gen;
|
||||
const result = await withTimeout(
|
||||
Promise.resolve(acquired.win.webContents.executeJavaScript(browserRasterizeExpression({
|
||||
source: body.toString("base64"),
|
||||
mimeType,
|
||||
width,
|
||||
height,
|
||||
maxEdge,
|
||||
}), true)),
|
||||
timeoutMs,
|
||||
"Plugin contribution icon rasterization timed out",
|
||||
);
|
||||
const prefix = "data:image/png;base64,";
|
||||
if (typeof result !== "string" || !result.startsWith(prefix)) {
|
||||
throw new Error("Plugin contribution icon rasterizer returned an invalid result");
|
||||
}
|
||||
return Buffer.from(result.slice(prefix.length), "base64");
|
||||
} catch (error) {
|
||||
destroyCurrent(gen);
|
||||
throw error;
|
||||
} finally {
|
||||
inFlight = Math.max(0, inFlight - 1);
|
||||
if (inFlight === 0 && activeWindow) scheduleIdleDestroy(generation);
|
||||
}
|
||||
};
|
||||
|
||||
rasterize.dispose = () => destroyCurrent();
|
||||
return rasterize;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_RASTER_TIMEOUT_MS,
|
||||
DEFAULT_POOLED_RASTER_TIMEOUT_MS,
|
||||
DEFAULT_POOLED_IDLE_MS,
|
||||
browserRasterizeExpression,
|
||||
createIsolatedContributionIconRasterizer,
|
||||
createPooledContributionIconRasterizer,
|
||||
};
|
||||
@@ -6,6 +6,7 @@ const test = require("node:test");
|
||||
const {
|
||||
browserRasterizeExpression,
|
||||
createIsolatedContributionIconRasterizer,
|
||||
createPooledContributionIconRasterizer,
|
||||
} = require("./contributionIconRasterizer.cjs");
|
||||
|
||||
test("viewBox-only SVG icons receive an explicit isolated raster viewport", () => {
|
||||
@@ -96,3 +97,52 @@ test("timed-out contribution icon rasterizers always destroy their isolated wind
|
||||
}), /timed out/);
|
||||
assert.equal(destroyed, true);
|
||||
});
|
||||
|
||||
test("pooled contribution icon rasterizer reuses one sandboxed window across bursts, destroys on error and dispose", async () => {
|
||||
let created = 0;
|
||||
let destroyed = 0;
|
||||
let failNext = false;
|
||||
class BrowserWindowStub {
|
||||
constructor(options) {
|
||||
created += 1;
|
||||
assert.equal(options.webPreferences.sandbox, true);
|
||||
assert.equal(options.webPreferences.spellcheck, false);
|
||||
assert.equal(options.webPreferences.nodeIntegration, false);
|
||||
this._destroyed = false;
|
||||
this.webContents = {
|
||||
session: { webRequest: { onBeforeRequest() {} } },
|
||||
async executeJavaScript() {
|
||||
if (failNext) {
|
||||
failNext = false;
|
||||
throw new Error("transient decode failure");
|
||||
}
|
||||
return `data:image/png;base64,${Buffer.from("pooled-png").toString("base64")}`;
|
||||
},
|
||||
};
|
||||
}
|
||||
async loadURL() {}
|
||||
removeMenu() {}
|
||||
isDestroyed() { return this._destroyed; }
|
||||
destroy() { this._destroyed = true; destroyed += 1; }
|
||||
}
|
||||
const rasterize = createPooledContributionIconRasterizer({
|
||||
BrowserWindow: BrowserWindowStub,
|
||||
idleMs: 10_000,
|
||||
});
|
||||
const payload = { body: Buffer.from("img"), mimeType: "image/png", width: 16, height: 16, maxEdge: 64 };
|
||||
const [a, b, c] = await Promise.all([rasterize(payload), rasterize(payload), rasterize(payload)]);
|
||||
assert.deepEqual(a, Buffer.from("pooled-png"));
|
||||
assert.deepEqual(b, Buffer.from("pooled-png"));
|
||||
assert.deepEqual(c, Buffer.from("pooled-png"));
|
||||
assert.equal(created, 1);
|
||||
assert.equal(destroyed, 0);
|
||||
|
||||
failNext = true;
|
||||
await assert.rejects(rasterize(payload), /transient decode failure/);
|
||||
assert.equal(destroyed, 1);
|
||||
|
||||
assert.deepEqual(await rasterize(payload), Buffer.from("pooled-png"));
|
||||
assert.equal(created, 2);
|
||||
rasterize.dispose();
|
||||
assert.equal(destroyed, 2);
|
||||
});
|
||||
@@ -56,7 +56,7 @@
|
||||
"RpcLimits": {
|
||||
"description": "Host-enforced byte limit for one JSON-RPC control message. Larger payloads must use a stream.",
|
||||
"const": {
|
||||
"maxJsonBytes": 1048576
|
||||
"maxJsonBytes": 8388608
|
||||
}
|
||||
},
|
||||
"SafeUnsignedInteger": {
|
||||
@@ -576,9 +576,41 @@
|
||||
},
|
||||
"kind": {
|
||||
"const": "network.stream.connectViaHost"
|
||||
},
|
||||
"durable": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": [
|
||||
"kind",
|
||||
"hostBindingToken",
|
||||
"endpoint"
|
||||
],
|
||||
"properties": {
|
||||
"kind": {
|
||||
"const": "network.stream.connectViaHost"
|
||||
},
|
||||
"hostBindingToken": {
|
||||
"type": "string",
|
||||
"minLength": 16,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[A-Za-z0-9._-]+$"
|
||||
},
|
||||
"endpoint": {
|
||||
"$ref": "#/$defs/ByteStreamEndpoint"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/HostByteStreamConfirmRequest"
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/HostByteStreamTlsConfirmRequest"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -820,12 +852,14 @@
|
||||
"HostInteractionLimits": {
|
||||
"const": {
|
||||
"textBytes": 4096,
|
||||
"requestBytes": 65536,
|
||||
"clipboardBytes": 4194304,
|
||||
"requestBytes": 4259840,
|
||||
"items": 100,
|
||||
"pendingPerRuntime": 1,
|
||||
"pendingTotal": 8,
|
||||
"requestsPerMinute": 10,
|
||||
"timeoutMs": 60000
|
||||
"requestsPerMinute": 60,
|
||||
"timeoutMs": 60000,
|
||||
"fileMaxBytes": 67108864
|
||||
}
|
||||
},
|
||||
"HostInteractionFeature": {
|
||||
@@ -957,7 +991,7 @@
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"maxLength": 4096,
|
||||
"maxLength": 4194304,
|
||||
"pattern": "^[^\\u0000]*$"
|
||||
}
|
||||
},
|
||||
@@ -1013,7 +1047,7 @@
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 4096,
|
||||
"maxLength": 4194304,
|
||||
"pattern": "^[^\\u0000]*$"
|
||||
},
|
||||
{
|
||||
@@ -1035,6 +1069,25 @@
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/ByteStreamConnectionDescriptor"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": [
|
||||
"cancelled",
|
||||
"approved"
|
||||
],
|
||||
"properties": {
|
||||
"cancelled": {
|
||||
"const": false
|
||||
},
|
||||
"approved": {
|
||||
"const": true
|
||||
},
|
||||
"remember": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -1086,6 +1139,9 @@
|
||||
},
|
||||
"scriptsRun": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"remember": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -1202,6 +1258,14 @@
|
||||
"$ref": "#/$defs/VaultHostEditFields"
|
||||
}
|
||||
]
|
||||
},
|
||||
"durableHostId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 128
|
||||
},
|
||||
"autoCommit": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -1556,14 +1620,14 @@
|
||||
},
|
||||
"ByteStreamLimits": {
|
||||
"const": {
|
||||
"connectionsPerRuntime": 4,
|
||||
"connectionsTotal": 64,
|
||||
"connectionsPerRuntime": 24,
|
||||
"connectionsTotal": 128,
|
||||
"chunkBytes": 65536,
|
||||
"bufferBytes": 65536,
|
||||
"connectionBytes": 8388608,
|
||||
"connectionBytes": 536870912,
|
||||
"connectMs": 10000,
|
||||
"idleMs": 30000,
|
||||
"lifetimeMs": 120000
|
||||
"idleMs": 1800000,
|
||||
"lifetimeMs": 28800000
|
||||
}
|
||||
},
|
||||
"ByteStreamEndpoint": {
|
||||
@@ -1581,6 +1645,23 @@
|
||||
"properties": {
|
||||
"endpoint": {
|
||||
"$ref": "#/$defs/ByteStreamEndpoint"
|
||||
},
|
||||
"allowLocal": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"allowSelfSigned": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"caPem": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 65536
|
||||
},
|
||||
"servername": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 253,
|
||||
"pattern": "^[A-Za-z0-9.-]+$"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -1623,6 +1704,12 @@
|
||||
},
|
||||
"windowBytes": {
|
||||
"const": 65536
|
||||
},
|
||||
"hostBindingToken": {
|
||||
"type": "string",
|
||||
"minLength": 16,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[A-Za-z0-9._-]+$"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -1964,10 +2051,7 @@
|
||||
"PermissionDeclaration": {
|
||||
"oneOf": [
|
||||
{
|
||||
"$ref": "#/$defs/PluginPermission",
|
||||
"not": {
|
||||
"const": "network.stream"
|
||||
}
|
||||
"$ref": "#/$defs/PluginPermission"
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/PermissionResourceDeclaration"
|
||||
@@ -2591,14 +2675,14 @@
|
||||
},
|
||||
"mutations": {
|
||||
"type": "array",
|
||||
"maxItems": 2048,
|
||||
"maxItems": 4096,
|
||||
"items": {
|
||||
"$ref": "#/$defs/JsonValue"
|
||||
}
|
||||
},
|
||||
"css": {
|
||||
"type": "string",
|
||||
"maxLength": 65536
|
||||
"maxLength": 131072
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -2653,12 +2737,16 @@
|
||||
"compositionend",
|
||||
"dismiss",
|
||||
"submit",
|
||||
"reset"
|
||||
"reset",
|
||||
"dblclick",
|
||||
"contextmenu",
|
||||
"scroll",
|
||||
"widget"
|
||||
]
|
||||
},
|
||||
"value": {
|
||||
"type": "string",
|
||||
"maxLength": 8192
|
||||
"maxLength": 131072
|
||||
},
|
||||
"checked": {
|
||||
"type": "boolean"
|
||||
@@ -2695,6 +2783,47 @@
|
||||
"type": "string",
|
||||
"maxLength": 8192
|
||||
}
|
||||
},
|
||||
"x": {
|
||||
"type": "number"
|
||||
},
|
||||
"y": {
|
||||
"type": "number"
|
||||
},
|
||||
"scrollTop": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"scrollLeft": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"clientHeight": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"clientWidth": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"selectionStart": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 131072
|
||||
},
|
||||
"selectionEnd": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 131072
|
||||
},
|
||||
"widgetEvent": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 64,
|
||||
"pattern": "^[a-zA-Z][a-zA-Z0-9_-]{0,63}$"
|
||||
},
|
||||
"detail": {
|
||||
"$ref": "#/$defs/JsonValue"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -8664,35 +8793,387 @@
|
||||
},
|
||||
"HostByteStreamLimits": {
|
||||
"const": {
|
||||
"connectionsPerRuntime": 4,
|
||||
"connectionsTotal": 64,
|
||||
"connectionsPerRuntime": 24,
|
||||
"connectionsTotal": 128,
|
||||
"chunkBytes": 65536,
|
||||
"bufferBytes": 65536,
|
||||
"connectionBytes": 67108864,
|
||||
"connectionBytes": 536870912,
|
||||
"connectMs": 120000,
|
||||
"idleMs": 300000,
|
||||
"lifetimeMs": 1800000
|
||||
"idleMs": 1800000,
|
||||
"lifetimeMs": 28800000
|
||||
}
|
||||
},
|
||||
"HostByteStreamConnectRequest": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"required": [
|
||||
"target",
|
||||
"expectedRevision",
|
||||
"endpoint"
|
||||
],
|
||||
"properties": {
|
||||
"target": {
|
||||
"$ref": "#/$defs/VaultHostRef"
|
||||
},
|
||||
"expectedRevision": {
|
||||
"type": "string",
|
||||
"maxLength": 128,
|
||||
"pattern": "^[^\\u0000-\\u001f\\u007f]*$",
|
||||
"minLength": 1
|
||||
},
|
||||
"endpoint": {
|
||||
"$ref": "#/$defs/ByteStreamEndpoint"
|
||||
},
|
||||
"durable": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": [
|
||||
"hostBindingToken",
|
||||
"endpoint"
|
||||
],
|
||||
"properties": {
|
||||
"hostBindingToken": {
|
||||
"type": "string",
|
||||
"minLength": 16,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[A-Za-z0-9._-]+$"
|
||||
},
|
||||
"endpoint": {
|
||||
"$ref": "#/$defs/ByteStreamEndpoint"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"ByteStreamUpgradeTlsRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"target",
|
||||
"expectedRevision",
|
||||
"endpoint"
|
||||
"handleId"
|
||||
],
|
||||
"properties": {
|
||||
"target": {
|
||||
"$ref": "#/$defs/VaultHostRef"
|
||||
},
|
||||
"expectedRevision": {
|
||||
"handleId": {
|
||||
"type": "string",
|
||||
"maxLength": 128,
|
||||
"pattern": "^[^\\u0000-\\u001f\\u007f]*$",
|
||||
"minLength": 1
|
||||
"format": "uuid"
|
||||
},
|
||||
"servername": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 253,
|
||||
"pattern": "^[A-Za-z0-9.-]+$"
|
||||
},
|
||||
"allowSelfSigned": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"caPem": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 65536
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ByteStreamUpgradeTlsResult": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"upgraded",
|
||||
"authorized"
|
||||
],
|
||||
"properties": {
|
||||
"upgraded": {
|
||||
"const": true
|
||||
},
|
||||
"authorized": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"protocol": {
|
||||
"type": "string",
|
||||
"maxLength": 64
|
||||
},
|
||||
"fingerprint256": {
|
||||
"type": "string",
|
||||
"maxLength": 128
|
||||
},
|
||||
"subject": {
|
||||
"type": "string",
|
||||
"maxLength": 512
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"VaultHostBindingRevokeParams": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"hostBindingToken"
|
||||
],
|
||||
"properties": {
|
||||
"hostBindingToken": {
|
||||
"type": "string",
|
||||
"minLength": 16,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[A-Za-z0-9._-]+$"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostByteStreamConfirmRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"kind",
|
||||
"endpoint",
|
||||
"host",
|
||||
"port",
|
||||
"transport",
|
||||
"isLocal"
|
||||
],
|
||||
"properties": {
|
||||
"kind": {
|
||||
"const": "network.stream.confirm"
|
||||
},
|
||||
"endpoint": {
|
||||
"$ref": "#/$defs/ByteStreamEndpoint"
|
||||
},
|
||||
"host": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 253
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 65535
|
||||
},
|
||||
"transport": {
|
||||
"enum": [
|
||||
"tcp",
|
||||
"tls"
|
||||
]
|
||||
},
|
||||
"isLocal": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostByteStreamTlsConfirmRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"kind",
|
||||
"endpoint",
|
||||
"fingerprint256",
|
||||
"subject",
|
||||
"issuer",
|
||||
"validTo",
|
||||
"reason"
|
||||
],
|
||||
"properties": {
|
||||
"kind": {
|
||||
"const": "network.stream.tlsConfirm"
|
||||
},
|
||||
"endpoint": {
|
||||
"$ref": "#/$defs/ByteStreamEndpoint"
|
||||
},
|
||||
"servername": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 253
|
||||
},
|
||||
"fingerprint256": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 128
|
||||
},
|
||||
"subject": {
|
||||
"type": "string",
|
||||
"maxLength": 512
|
||||
},
|
||||
"issuer": {
|
||||
"type": "string",
|
||||
"maxLength": 512
|
||||
},
|
||||
"validTo": {
|
||||
"type": "string",
|
||||
"maxLength": 128
|
||||
},
|
||||
"reason": {
|
||||
"type": "string",
|
||||
"maxLength": 256
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostFileDialogFilter": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"name",
|
||||
"extensions"
|
||||
],
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 64,
|
||||
"pattern": "^[^\\u0000-\\u001f\\u007f]*$"
|
||||
},
|
||||
"extensions": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 32,
|
||||
"items": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 32,
|
||||
"pattern": "^(\\*|[A-Za-z0-9][A-Za-z0-9._-]{0,31})$"
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostOpenFileRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 128,
|
||||
"pattern": "^[^\\u0000-\\u001f\\u007f]*$"
|
||||
},
|
||||
"filters": {
|
||||
"type": "array",
|
||||
"maxItems": 32,
|
||||
"items": {
|
||||
"$ref": "#/$defs/HostFileDialogFilter"
|
||||
}
|
||||
},
|
||||
"readAs": {
|
||||
"enum": [
|
||||
"bytes",
|
||||
"utf8"
|
||||
]
|
||||
},
|
||||
"maxBytes": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 67108864
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostSaveFileRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 128,
|
||||
"pattern": "^[^\\u0000-\\u001f\\u007f]*$"
|
||||
},
|
||||
"defaultName": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[^\\u0000-\\u001f\\u007f/\\\\]+$"
|
||||
},
|
||||
"filters": {
|
||||
"type": "array",
|
||||
"maxItems": 32,
|
||||
"items": {
|
||||
"$ref": "#/$defs/HostFileDialogFilter"
|
||||
}
|
||||
},
|
||||
"data": {
|
||||
"type": "string",
|
||||
"maxLength": 5592408
|
||||
},
|
||||
"encoding": {
|
||||
"enum": [
|
||||
"base64",
|
||||
"utf8"
|
||||
]
|
||||
},
|
||||
"deferredWrite": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostFileHandleReadRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"handleId"
|
||||
],
|
||||
"properties": {
|
||||
"handleId": {
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
},
|
||||
"offset": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 67108864
|
||||
},
|
||||
"length": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 4194304
|
||||
},
|
||||
"encoding": {
|
||||
"enum": [
|
||||
"base64",
|
||||
"utf8"
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostFileHandleWriteRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"handleId",
|
||||
"data"
|
||||
],
|
||||
"properties": {
|
||||
"handleId": {
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
},
|
||||
"data": {
|
||||
"type": "string",
|
||||
"maxLength": 5592408
|
||||
},
|
||||
"encoding": {
|
||||
"enum": [
|
||||
"base64",
|
||||
"utf8"
|
||||
]
|
||||
},
|
||||
"mode": {
|
||||
"enum": [
|
||||
"replace",
|
||||
"append"
|
||||
]
|
||||
},
|
||||
"commit": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostFileHandleCloseRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"handleId"
|
||||
],
|
||||
"properties": {
|
||||
"handleId": {
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
"use strict";
|
||||
|
||||
const { isPluginDevelopmentEnabled } = require("./constants.cjs");
|
||||
|
||||
function startPluginHost(options) {
|
||||
// The plugin platform is not shipping in this release. Keep its data
|
||||
// untouched and allow existing developer workflows to opt in as before.
|
||||
if (!isPluginDevelopmentEnabled(options.env)) return null;
|
||||
// TODO(revert): temporarily enabled by default for database plugin development
|
||||
if (options.env?.NETCATTY_PLUGIN_DEV === "0") return null;
|
||||
|
||||
const reportFailure = (message, error) => {
|
||||
try { options.logger?.error?.(message, error); } catch {}
|
||||
|
||||
@@ -5,10 +5,10 @@ const test = require("node:test");
|
||||
|
||||
const { startPluginHost } = require("./hostBootstrap.cjs");
|
||||
|
||||
test("default startup leaves the plugin host and stored plugin data untouched", () => {
|
||||
test("explicitly disabling NETCATTY_PLUGIN_DEV leaves the plugin host and stored plugin data untouched", () => {
|
||||
const effects = [];
|
||||
assert.equal(startPluginHost({
|
||||
env: {},
|
||||
env: { NETCATTY_PLUGIN_DEV: "0" },
|
||||
createService() { effects.push("create"); },
|
||||
registerShutdown() { effects.push("register"); },
|
||||
logger: { error() { effects.push("error"); } },
|
||||
@@ -16,6 +16,24 @@ test("default startup leaves the plugin host and stored plugin data untouched",
|
||||
assert.deepEqual(effects, []);
|
||||
});
|
||||
|
||||
test("default startup enables the plugin host during database plugin development", async () => {
|
||||
let initialized = 0;
|
||||
const service = {
|
||||
manager: {
|
||||
async initialize() { initialized += 1; },
|
||||
async shutdown() {},
|
||||
},
|
||||
};
|
||||
assert.equal(startPluginHost({
|
||||
env: {},
|
||||
createService: () => service,
|
||||
registerShutdown() {},
|
||||
logger: { error() {} },
|
||||
}), service);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
assert.equal(initialized, 1);
|
||||
});
|
||||
|
||||
test("synchronous plugin host construction failure leaves Netcatty available", () => {
|
||||
const errors = [];
|
||||
let registered = 0;
|
||||
|
||||
@@ -102,3 +102,53 @@ test("window closure during opening aborts the operation and rejects a late conn
|
||||
assert.equal(f.opens[0].context.signal.aborted, true);
|
||||
assert.equal(f.vault.streams.size, 0);
|
||||
});
|
||||
|
||||
test("durable SSH tunnel binding survives selection expiry and blur, enforces exact endpoint, and can be revoked", async (t) => {
|
||||
const f = await fixture(t);
|
||||
const pending = f.call("network.stream.connectViaHost", { ...f.params, durable: true });
|
||||
await f.tick();
|
||||
await f.respond("submit", { remember: true });
|
||||
await f.respond("commit", {}, { hostId: "host-one" });
|
||||
const first = await pending;
|
||||
assert.equal(typeof first.hostBindingToken, "string");
|
||||
assert.ok(first.hostBindingToken.startsWith("hb_"));
|
||||
|
||||
// Expire ephemeral selection and clear selections (simulating blur/restart).
|
||||
f.expire();
|
||||
f.vault.clearSelections();
|
||||
|
||||
// Mismatched endpoint with the same durable token must be rejected.
|
||||
await assert.rejects(
|
||||
f.call("network.stream.connectViaHost", { hostBindingToken: first.hostBindingToken, endpoint: "tcp://127.0.0.1:5432" }),
|
||||
/binding/u,
|
||||
);
|
||||
// Forged token must be rejected.
|
||||
await assert.rejects(
|
||||
f.call("network.stream.connectViaHost", { hostBindingToken: "hb_forged_token_000000000000000000", endpoint: f.params.endpoint }),
|
||||
/binding/u,
|
||||
);
|
||||
|
||||
// Reconnect with durable token skips request phase and emits autoCommit prompt bound to host-one.
|
||||
const reconnect = f.call("network.stream.connectViaHost", {
|
||||
hostBindingToken: first.hostBindingToken,
|
||||
endpoint: f.params.endpoint,
|
||||
});
|
||||
await f.tick();
|
||||
const prompt = f.prompts.at(-1);
|
||||
assert.equal(prompt.phase, "commit");
|
||||
assert.equal(prompt.autoCommit, true);
|
||||
assert.equal(prompt.durableHostId, "host-one");
|
||||
await f.respond("commit", {}, { hostId: "host-one" });
|
||||
const second = await reconnect;
|
||||
assert.equal(second.endpoint, f.params.endpoint);
|
||||
assert.equal(second.hostBindingToken, first.hostBindingToken);
|
||||
assert.equal(f.opens.length, 2);
|
||||
|
||||
// Revoke durable binding -> subsequent reconnect fails closed.
|
||||
const revoked = await f.call("vault.revokeHostBinding", { hostBindingToken: first.hostBindingToken });
|
||||
assert.deepEqual(revoked, { revoked: true });
|
||||
await assert.rejects(
|
||||
f.call("network.stream.connectViaHost", { hostBindingToken: first.hostBindingToken, endpoint: f.params.endpoint }),
|
||||
/binding/u,
|
||||
);
|
||||
});
|
||||
@@ -107,13 +107,16 @@ class HostDrawnViewHost {
|
||||
const { plugin } = this.contributions.assertViewActivationCurrent(instance.activation, { context: instance.context });
|
||||
instance.resources ??= new Map();
|
||||
if (instance.resources.has(resource)) return instance.resources.get(resource);
|
||||
if (instance.resources.size >= 32) throw new Error("Plugin image limit exceeded");
|
||||
if (instance.resources.size >= 128) throw new Error("Plugin image limit exceeded");
|
||||
const pending = this.resources.image(plugin, resource).then((result) => {
|
||||
if (this.isLocked() || this.instances.get(id) !== instance) throw new Error("Plugin view closed");
|
||||
this.contributions.assertViewActivationCurrent(instance.activation, { context: instance.context });
|
||||
instance.resourceBytes = (instance.resourceBytes ?? 0) + result.url.length;
|
||||
if (instance.resourceBytes > 8 * 1024 * 1024) throw new Error("Plugin image budget exceeded");
|
||||
if (instance.resourceBytes > 24 * 1024 * 1024) throw new Error("Plugin image budget exceeded");
|
||||
return result;
|
||||
}).catch((error) => {
|
||||
if (instance.resources?.get(resource) === pending) instance.resources.delete(resource);
|
||||
throw error;
|
||||
});
|
||||
instance.resources.set(resource, pending);
|
||||
return pending;
|
||||
@@ -121,6 +124,12 @@ class HostDrawnViewHost {
|
||||
async event(id, event, sender) {
|
||||
const instance = this.owned(id, sender);
|
||||
if (this.isLocked() || !validateEvent(event)) throw new TypeError("Invalid plugin view event");
|
||||
if (event.detail !== undefined) {
|
||||
let detailBytes = 0;
|
||||
try { detailBytes = Buffer.byteLength(JSON.stringify(event.detail), "utf8"); }
|
||||
catch { throw new TypeError("Invalid plugin view event detail"); }
|
||||
if (detailBytes > 256 * 1024) throw new TypeError("Plugin view event detail exceeds limits");
|
||||
}
|
||||
this.contributions.assertViewActivationCurrent(instance.activation, { context: instance.context });
|
||||
await this.contributions.runtimeSupervisor.notify(instance.pluginId, "plugin.view.message", { viewId: instance.viewId,
|
||||
message: { kind: "host-ui.event", instanceId: id, event } }, { expectedIdentity: instance.identity });
|
||||
@@ -144,6 +153,7 @@ class HostDrawnViewHost {
|
||||
this.closed = true; for (const opening of this.opening.values()) opening.cancelled = true;
|
||||
await Promise.all([...this.instances.keys()].map((id) => this.close(id, undefined, "shutdown")));
|
||||
this.messageSubscription?.dispose(); this.changeSubscription?.dispose(); this.unsubscribeLock?.();
|
||||
this.resources?.dispose?.();
|
||||
}
|
||||
}
|
||||
module.exports = { HostDrawnViewHost };
|
||||
@@ -61,6 +61,7 @@ test("package resources require the same window and survive no close or revocati
|
||||
await assert.rejects(pending, /closed/); await assert.rejects(duplicate, /closed/);
|
||||
await f.host.shutdown();
|
||||
});
|
||||
|
||||
test("disable and owner navigation invalidate every retained view", async () => {
|
||||
for (const reason of ['plugin-disabled', 'runtime-stopped', 'runtime-error', 'runtime-quarantined']) {
|
||||
const f = fixture(); await open(f); f.change({ reason, pluginId: 'com.test.plugin' });
|
||||
@@ -69,10 +70,42 @@ test("disable and owner navigation invalidate every retained view", async () =>
|
||||
const f = fixture(); await open(f); f.sender.emit('did-start-navigation', { isMainFrame: true, isSameDocument: false });
|
||||
assert.equal(f.host.instances.size, 0); await f.host.shutdown();
|
||||
});
|
||||
|
||||
test("updates are rate limited and resource caches are bounded", async () => {
|
||||
const f = fixture({ image: async () => ({ url: 'data:image/png;base64,AAAA' }) }); await open(f);
|
||||
for (let i = 0; i < 32; i++) await f.host.resource('instance-1', `image-${i}.png`, f.sender);
|
||||
for (let i = 0; i < 128; i++) await f.host.resource('instance-1', `image-${i}.png`, f.sender);
|
||||
await assert.rejects(f.host.resource('instance-1', 'extra.png', f.sender), /limit/);
|
||||
for (let i = 1; i <= 121; i++) f.message({ ...update(i), mutations: [] });
|
||||
assert.equal(f.host.instances.size, 0); await f.host.shutdown();
|
||||
});
|
||||
|
||||
test("extended surface and widget events validate schema and bound detail payload size", async () => {
|
||||
const f = fixture(); await open(f);
|
||||
await f.host.event("instance-1", { nodeId: "1", type: "contextmenu", x: 42, y: 84 }, f.sender);
|
||||
await f.host.event("instance-1", { nodeId: "1", type: "dblclick", x: 10, y: 20 }, f.sender);
|
||||
await f.host.event("instance-1", { nodeId: "1", type: "scroll", scrollTop: 100, scrollLeft: 0, clientHeight: 400, clientWidth: 600 }, f.sender);
|
||||
await f.host.event("instance-1", { nodeId: "1", type: "widget", widgetEvent: "execute", detail: { value: "SELECT 1;", currentStatement: "SELECT 1" } }, f.sender);
|
||||
assert.equal(f.notifications.at(-1)[2].message.event.widgetEvent, "execute");
|
||||
await assert.rejects(
|
||||
f.host.event("instance-1", { nodeId: "1", type: "widget", widgetEvent: "change", detail: { value: "x".repeat(260 * 1024) } }, f.sender),
|
||||
/exceeds limits/,
|
||||
);
|
||||
await f.host.shutdown();
|
||||
});
|
||||
|
||||
test("transient resource decode failures are evicted so retries can succeed", async () => {
|
||||
let calls = 0;
|
||||
const f = fixture({
|
||||
image: async () => {
|
||||
calls += 1;
|
||||
if (calls === 1) throw new Error("temporary decode failure");
|
||||
return { url: "data:image/png;base64,AAAA" };
|
||||
},
|
||||
});
|
||||
await open(f);
|
||||
await assert.rejects(f.host.resource("instance-1", "icon.png", f.sender), /temporary decode failure/);
|
||||
const recovered = await f.host.resource("instance-1", "icon.png", f.sender);
|
||||
assert.equal(recovered.url, "data:image/png;base64,AAAA");
|
||||
assert.equal(calls, 2);
|
||||
await f.host.shutdown();
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
"use strict";
|
||||
|
||||
const { createHmac, randomBytes, randomUUID, timingSafeEqual } = require("node:crypto");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { createDefinitionValidator } = require("./contractValidator.cjs");
|
||||
const { TerminalSelectionAuthority } = require("./terminalSelectionAuthority.cjs");
|
||||
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
|
||||
@@ -11,11 +13,28 @@ const validateRequest = createDefinitionValidator("HostInteractionRequest");
|
||||
const validateResponse = createDefinitionValidator("HostInteractionResponse");
|
||||
const validateResult = createDefinitionValidator("HostInteractionResult");
|
||||
const validateSingleLineInput = createDefinitionValidator("HostSingleLineInputText");
|
||||
const validateOpenFile = createDefinitionValidator("HostOpenFileRequest");
|
||||
const validateSaveFile = createDefinitionValidator("HostSaveFileRequest");
|
||||
const validateReadFileHandle = createDefinitionValidator("HostFileHandleReadRequest");
|
||||
const validateWriteFileHandle = createDefinitionValidator("HostFileHandleWriteRequest");
|
||||
const validateCloseFileHandle = createDefinitionValidator("HostFileHandleCloseRequest");
|
||||
const PROMPT_CHANNEL = "netcatty:plugins:host-interaction";
|
||||
|
||||
const INLINE_FILE_BYTES = 2 * 1024 * 1024;
|
||||
const MAX_FILE_HANDLES_PER_RUNTIME = 16;
|
||||
const MAX_FILE_HANDLES_TOTAL = 64;
|
||||
|
||||
function tryLoadElectronDialog() {
|
||||
try {
|
||||
return require("electron")?.dialog ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function fail(code, message) { return new PluginRpcError(RPC_ERRORS[code], message); }
|
||||
function assertTextBytes(text) {
|
||||
if (typeof text !== "string" || Buffer.byteLength(text, "utf8") > LIMITS.textBytes || text.includes("\0")) {
|
||||
function assertTextBytes(text, limit = LIMITS.textBytes) {
|
||||
if (typeof text !== "string" || Buffer.byteLength(text, "utf8") > limit || text.includes("\0")) {
|
||||
throw fail("resourceExhausted", "Host interaction text exceeds its limit");
|
||||
}
|
||||
return text;
|
||||
@@ -25,8 +44,8 @@ function assertInteractionRequest(params) {
|
||||
if (Buffer.byteLength(JSON.stringify(params)) > LIMITS.requestBytes) {
|
||||
throw fail("resourceExhausted", "Host interaction request exceeds its limit");
|
||||
}
|
||||
if (params.kind === "input") assertTextBytes(params.initialValue ?? "");
|
||||
if (params.kind === "clipboard.write") assertTextBytes(params.text);
|
||||
if (params.kind === "input") assertTextBytes(params.initialValue ?? "", LIMITS.textBytes);
|
||||
if (params.kind === "clipboard.write") assertTextBytes(params.text, LIMITS.clipboardBytes);
|
||||
if (params.kind === "terminal.input.propose" && Buffer.byteLength(params.text, "utf8") > LIMITS.textBytes) throw fail("resourceExhausted", "Terminal input draft exceeds its limit");
|
||||
if (params.kind === "quickPick" && new Set(params.items.map((item) => item.id)).size !== params.items.length) {
|
||||
throw fail("invalidArgument", "Host interaction choice IDs must be unique");
|
||||
@@ -39,6 +58,17 @@ function interactionAuthorization(params, terminalTarget) {
|
||||
return { permission: params.kind, resources: [terminalTarget.resource],
|
||||
reason: params.kind === "terminal.selection.read" ? "Preview and explicitly share the selected terminal text" : "Open an editable host draft without sending terminal input", operationId: params.kind, allowedScopes: ["once"], deferDecision: true };
|
||||
}
|
||||
if (params.kind === "network.stream.confirm" || params.kind === "network.stream.tlsConfirm") {
|
||||
return {
|
||||
permission: "network.stream",
|
||||
resources: [params.endpoint],
|
||||
reason: params.kind === "network.stream.tlsConfirm"
|
||||
? "Review an untrusted TLS certificate before continuing"
|
||||
: `Confirm byte stream connection to ${params.endpoint}`,
|
||||
operationId: `ui:${params.kind}`,
|
||||
deferDecision: true,
|
||||
};
|
||||
}
|
||||
const permission = params.kind === "clipboard.read" ? "clipboard.read"
|
||||
: params.kind === "clipboard.write" ? "clipboard.write" : "ui.interact";
|
||||
return {
|
||||
@@ -57,12 +87,14 @@ class PluginHostInteractionService {
|
||||
this.permissionEngine = options.permissionEngine;
|
||||
this.quotaManager = options.quotaManager;
|
||||
this.clipboard = options.clipboard;
|
||||
this.dialog = options.dialog ?? tryLoadElectronDialog();
|
||||
this.getWindow = options.getWindow ?? (() => null);
|
||||
this.isLocked = options.isLocked ?? (() => true);
|
||||
this.clock = options.clock ?? Date.now;
|
||||
this.timeoutMs = Math.min(options.timeoutMs ?? LIMITS.timeoutMs, LIMITS.timeoutMs);
|
||||
this.key = randomBytes(32);
|
||||
this.pending = new Map();
|
||||
this.fileHandles = new Map();
|
||||
this.terminalSelection = new TerminalSelectionAuthority({database: this.database, getWindow: this.getWindow, getManager: options.getTerminalWorkerManager, clock: this.clock});
|
||||
this.terminalInvalidation = this.terminalSelection.onDidInvalidate(() => {
|
||||
for (const entry of [...this.pending.values()]) if (entry.terminalTarget && !this.#terminalCurrent(entry)) {
|
||||
@@ -91,6 +123,59 @@ class PluginHostInteractionService {
|
||||
}
|
||||
|
||||
registerRpcCapabilities(registry) {
|
||||
const fileAuth = (operation) => ({
|
||||
permission: "ui.interact",
|
||||
resources: ["*"],
|
||||
reason: operation === "open"
|
||||
? "Open a user-selected file via native file dialog"
|
||||
: operation === "save"
|
||||
? "Save a file via native save dialog"
|
||||
: "Access a user-selected file handle",
|
||||
operationId: `ui:file:${operation}`,
|
||||
deferDecision: true,
|
||||
});
|
||||
registry.registerRequest("ui.openFile", (params, context) => this.openFile(params, context), {
|
||||
metadata: { capability: "ui", mutating: false },
|
||||
validateParams: (params) => {
|
||||
const normalized = params === undefined || params === null ? {} : params;
|
||||
if (!validateOpenFile(normalized)) throw fail("invalidArgument", "Open file parameters are invalid");
|
||||
return Object.freeze(structuredClone(normalized));
|
||||
},
|
||||
authorization: () => fileAuth("open"),
|
||||
});
|
||||
registry.registerRequest("ui.saveFile", (params, context) => this.saveFile(params, context), {
|
||||
metadata: { capability: "ui", mutating: true },
|
||||
validateParams: (params) => {
|
||||
const normalized = params === undefined || params === null ? {} : params;
|
||||
if (!validateSaveFile(normalized)) throw fail("invalidArgument", "Save file parameters are invalid");
|
||||
return Object.freeze(structuredClone(normalized));
|
||||
},
|
||||
authorization: () => fileAuth("save"),
|
||||
});
|
||||
registry.registerRequest("ui.readFileHandle", (params, context) => this.readFileHandle(params, context), {
|
||||
metadata: { capability: "ui", mutating: false },
|
||||
validateParams: (params) => {
|
||||
if (!validateReadFileHandle(params)) throw fail("invalidArgument", "File handle read parameters are invalid");
|
||||
return Object.freeze(structuredClone(params));
|
||||
},
|
||||
authorization: () => fileAuth("readHandle"),
|
||||
});
|
||||
registry.registerRequest("ui.writeFileHandle", (params, context) => this.writeFileHandle(params, context), {
|
||||
metadata: { capability: "ui", mutating: true },
|
||||
validateParams: (params) => {
|
||||
if (!validateWriteFileHandle(params)) throw fail("invalidArgument", "File handle write parameters are invalid");
|
||||
return Object.freeze(structuredClone(params));
|
||||
},
|
||||
authorization: () => fileAuth("writeHandle"),
|
||||
});
|
||||
registry.registerRequest("ui.closeFileHandle", (params, context) => this.closeFileHandle(params, context), {
|
||||
metadata: { capability: "ui", mutating: true },
|
||||
validateParams: (params) => {
|
||||
if (!validateCloseFileHandle(params)) throw fail("invalidArgument", "File handle close parameters are invalid");
|
||||
return Object.freeze(structuredClone(params));
|
||||
},
|
||||
authorization: () => fileAuth("closeHandle"),
|
||||
});
|
||||
registry.registerRequest("ui.interact", (params, context) => this.request(params, context), {
|
||||
metadata: { capability: "ui", mutating: true },
|
||||
validateParams: assertInteractionRequest,
|
||||
@@ -101,6 +186,260 @@ class PluginHostInteractionService {
|
||||
});
|
||||
}
|
||||
|
||||
#assertFileDialogPermission(context) {
|
||||
const mode = this.permissionEngine.getMode?.(context, "ui.interact") ?? "allow";
|
||||
if (mode === "deny") throw fail("permissionDenied", "Plugin permission is disabled");
|
||||
}
|
||||
|
||||
#allocateFileHandle(context, filePath) {
|
||||
const runtimeCount = [...this.fileHandles.values()].filter((h) => h.runtimeId === context.runtimeId).length;
|
||||
if (runtimeCount >= MAX_FILE_HANDLES_PER_RUNTIME || this.fileHandles.size >= MAX_FILE_HANDLES_TOTAL) {
|
||||
throw fail("resourceExhausted", "Too many open file handles");
|
||||
}
|
||||
const id = randomUUID();
|
||||
const handle = {
|
||||
id,
|
||||
pluginId: context.pluginId,
|
||||
runtimeId: context.runtimeId,
|
||||
sourceOwner: context.sourceOwner,
|
||||
filePath,
|
||||
name: path.basename(filePath),
|
||||
stagingPath: null,
|
||||
stagingBytes: 0,
|
||||
createdAt: this.clock(),
|
||||
};
|
||||
this.fileHandles.set(id, handle);
|
||||
return handle;
|
||||
}
|
||||
|
||||
#getFileHandle(handleId, context) {
|
||||
const handle = this.fileHandles.get(handleId);
|
||||
if (!handle || handle.pluginId !== context.pluginId || handle.runtimeId !== context.runtimeId
|
||||
|| handle.sourceOwner !== context.sourceOwner) {
|
||||
throw fail("permissionDenied", "File handle is invalid or closed");
|
||||
}
|
||||
return handle;
|
||||
}
|
||||
|
||||
async #disposeFileHandle(handle) {
|
||||
if (!handle) return;
|
||||
this.fileHandles.delete(handle.id);
|
||||
if (handle.stagingPath) {
|
||||
const temp = handle.stagingPath;
|
||||
handle.stagingPath = null;
|
||||
handle.stagingBytes = 0;
|
||||
await fs.unlink(temp).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
async openFile(params, context) {
|
||||
await context.assertActive();
|
||||
this.#assertFileDialogPermission(context);
|
||||
if (this.closed || this.isLocked()) {
|
||||
throw fail("unavailable", "Host file dialogs require an unlocked window");
|
||||
}
|
||||
if (typeof this.dialog?.showOpenDialog !== "function") {
|
||||
throw fail("unavailable", "Native file dialog is unavailable");
|
||||
}
|
||||
const window = this.getWindow();
|
||||
const dialogOptions = {
|
||||
title: params.title ?? "Open File",
|
||||
properties: ["openFile"],
|
||||
...(params.filters?.length ? { filters: params.filters } : {}),
|
||||
};
|
||||
const picked = window && !window.isDestroyed?.()
|
||||
? await this.dialog.showOpenDialog(window, dialogOptions)
|
||||
: await this.dialog.showOpenDialog(dialogOptions);
|
||||
await context.assertActive();
|
||||
if (this.closed || this.isLocked()) {
|
||||
throw fail("cancelled", "Host locked during file selection");
|
||||
}
|
||||
if (!picked || picked.canceled || !Array.isArray(picked.filePaths) || picked.filePaths.length === 0) {
|
||||
return { cancelled: true };
|
||||
}
|
||||
const filePath = picked.filePaths[0];
|
||||
const stat = await fs.stat(filePath);
|
||||
if (!stat.isFile()) {
|
||||
throw fail("invalidArgument", "Selected path is not a regular file");
|
||||
}
|
||||
const maxBytes = Math.min(params.maxBytes ?? LIMITS.fileMaxBytes, LIMITS.fileMaxBytes);
|
||||
if (stat.size > maxBytes) {
|
||||
throw fail("resourceExhausted", `Selected file exceeds the ${maxBytes} byte limit`);
|
||||
}
|
||||
const handle = this.#allocateFileHandle(context, filePath);
|
||||
this.database?.recordSecurityAudit?.(context.pluginId, "ui.file.open", { size: stat.size });
|
||||
const encoding = params.readAs === "utf8" ? "utf8" : "base64";
|
||||
if (stat.size <= INLINE_FILE_BYTES) {
|
||||
const raw = await fs.readFile(filePath);
|
||||
await context.assertActive();
|
||||
this.quotaManager?.chargeBytes?.(context.runtimeId, "ui", raw.byteLength);
|
||||
return {
|
||||
cancelled: false,
|
||||
name: handle.name,
|
||||
size: raw.byteLength,
|
||||
handleId: handle.id,
|
||||
streamed: false,
|
||||
encoding,
|
||||
data: encoding === "utf8" ? raw.toString("utf8") : raw.toString("base64"),
|
||||
};
|
||||
}
|
||||
return {
|
||||
cancelled: false,
|
||||
name: handle.name,
|
||||
size: stat.size,
|
||||
handleId: handle.id,
|
||||
streamed: true,
|
||||
encoding,
|
||||
};
|
||||
}
|
||||
|
||||
async saveFile(params, context) {
|
||||
await context.assertActive();
|
||||
this.#assertFileDialogPermission(context);
|
||||
if (this.closed || this.isLocked()) {
|
||||
throw fail("unavailable", "Host file dialogs require an unlocked window");
|
||||
}
|
||||
if (typeof this.dialog?.showSaveDialog !== "function") {
|
||||
throw fail("unavailable", "Native save dialog is unavailable");
|
||||
}
|
||||
const window = this.getWindow();
|
||||
const dialogOptions = {
|
||||
title: params.title ?? "Save File",
|
||||
...(params.defaultName ? { defaultPath: params.defaultName } : {}),
|
||||
...(params.filters?.length ? { filters: params.filters } : {}),
|
||||
};
|
||||
const picked = window && !window.isDestroyed?.()
|
||||
? await this.dialog.showSaveDialog(window, dialogOptions)
|
||||
: await this.dialog.showSaveDialog(dialogOptions);
|
||||
await context.assertActive();
|
||||
if (this.closed || this.isLocked()) {
|
||||
throw fail("cancelled", "Host locked during save dialog");
|
||||
}
|
||||
if (!picked || picked.canceled || typeof picked.filePath !== "string" || picked.filePath.length === 0) {
|
||||
return { cancelled: true };
|
||||
}
|
||||
const handle = this.#allocateFileHandle(context, picked.filePath);
|
||||
if (params.deferredWrite === true || params.data === undefined) {
|
||||
this.database?.recordSecurityAudit?.(context.pluginId, "ui.file.save", { deferred: true });
|
||||
return { cancelled: false, name: handle.name, size: 0, handleId: handle.id };
|
||||
}
|
||||
const buf = Buffer.from(params.data, params.encoding === "base64" ? "base64" : "utf8");
|
||||
if (buf.byteLength > LIMITS.fileMaxBytes) {
|
||||
await this.#disposeFileHandle(handle);
|
||||
throw fail("resourceExhausted", "File payload exceeds the maximum size limit");
|
||||
}
|
||||
this.quotaManager?.chargeBytes?.(context.runtimeId, "ui", buf.byteLength);
|
||||
const tempPath = `${handle.filePath}.netcatty-tmp-${randomUUID()}`;
|
||||
try {
|
||||
await fs.writeFile(tempPath, buf);
|
||||
await context.assertActive();
|
||||
await fs.rename(tempPath, handle.filePath);
|
||||
} catch (error) {
|
||||
await fs.unlink(tempPath).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
this.database?.recordSecurityAudit?.(context.pluginId, "ui.file.save", { size: buf.byteLength });
|
||||
return { cancelled: false, name: handle.name, size: buf.byteLength, handleId: handle.id };
|
||||
}
|
||||
|
||||
async readFileHandle(params, context) {
|
||||
await context.assertActive();
|
||||
this.#assertFileDialogPermission(context);
|
||||
if (this.closed || this.isLocked()) throw fail("unavailable", "Host is locked");
|
||||
const handle = this.#getFileHandle(params.handleId, context);
|
||||
const stat = await fs.stat(handle.filePath);
|
||||
if (!stat.isFile()) throw fail("unavailable", "File handle target is no longer a regular file");
|
||||
if (stat.size > LIMITS.fileMaxBytes) throw fail("resourceExhausted", "File exceeds the maximum size limit");
|
||||
const offset = params.offset ?? 0;
|
||||
const length = Math.min(params.length ?? INLINE_FILE_BYTES, 4 * 1024 * 1024);
|
||||
const remaining = Math.max(0, stat.size - offset);
|
||||
const toRead = Math.min(length, remaining);
|
||||
const encoding = params.encoding === "utf8" ? "utf8" : "base64";
|
||||
if (toRead === 0) {
|
||||
return { data: "", encoding, bytesRead: 0, totalSize: stat.size, eof: true };
|
||||
}
|
||||
const fd = await fs.open(handle.filePath, "r");
|
||||
try {
|
||||
const buffer = Buffer.allocUnsafe(toRead);
|
||||
const { bytesRead } = await fd.read(buffer, 0, toRead, offset);
|
||||
await context.assertActive();
|
||||
const slice = buffer.subarray(0, bytesRead);
|
||||
this.quotaManager?.chargeBytes?.(context.runtimeId, "ui", bytesRead);
|
||||
return {
|
||||
data: encoding === "utf8" ? slice.toString("utf8") : slice.toString("base64"),
|
||||
encoding,
|
||||
bytesRead,
|
||||
totalSize: stat.size,
|
||||
eof: offset + bytesRead >= stat.size,
|
||||
};
|
||||
} finally {
|
||||
await fd.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
async writeFileHandle(params, context) {
|
||||
await context.assertActive();
|
||||
this.#assertFileDialogPermission(context);
|
||||
if (this.closed || this.isLocked()) throw fail("unavailable", "Host is locked");
|
||||
const handle = this.#getFileHandle(params.handleId, context);
|
||||
const buf = Buffer.from(params.data, params.encoding === "base64" ? "base64" : "utf8");
|
||||
const mode = params.mode ?? "replace";
|
||||
const commit = params.commit !== false;
|
||||
if (mode === "replace") {
|
||||
if (handle.stagingPath) {
|
||||
await fs.unlink(handle.stagingPath).catch(() => {});
|
||||
handle.stagingPath = null;
|
||||
handle.stagingBytes = 0;
|
||||
}
|
||||
if (buf.byteLength > LIMITS.fileMaxBytes) {
|
||||
throw fail("resourceExhausted", "File write exceeds the maximum size limit");
|
||||
}
|
||||
handle.stagingPath = `${handle.filePath}.netcatty-tmp-${randomUUID()}`;
|
||||
handle.stagingBytes = buf.byteLength;
|
||||
this.quotaManager?.chargeBytes?.(context.runtimeId, "ui", buf.byteLength);
|
||||
await fs.writeFile(handle.stagingPath, buf);
|
||||
} else {
|
||||
if (!handle.stagingPath) {
|
||||
throw fail("failedPrecondition", "Append write requires an open replace transaction");
|
||||
}
|
||||
if (handle.stagingBytes + buf.byteLength > LIMITS.fileMaxBytes) {
|
||||
const temp = handle.stagingPath;
|
||||
handle.stagingPath = null;
|
||||
handle.stagingBytes = 0;
|
||||
await fs.unlink(temp).catch(() => {});
|
||||
throw fail("resourceExhausted", "File write exceeds the maximum size limit");
|
||||
}
|
||||
this.quotaManager?.chargeBytes?.(context.runtimeId, "ui", buf.byteLength);
|
||||
await fs.appendFile(handle.stagingPath, buf);
|
||||
handle.stagingBytes += buf.byteLength;
|
||||
}
|
||||
const totalSize = handle.stagingBytes;
|
||||
if (commit) {
|
||||
await context.assertActive();
|
||||
const temp = handle.stagingPath;
|
||||
handle.stagingPath = null;
|
||||
handle.stagingBytes = 0;
|
||||
try {
|
||||
await fs.rename(temp, handle.filePath);
|
||||
} catch (error) {
|
||||
await fs.unlink(temp).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
this.database?.recordSecurityAudit?.(context.pluginId, "ui.file.writeHandle", { size: totalSize });
|
||||
}
|
||||
return { bytesWritten: buf.byteLength, totalSize, committed: commit };
|
||||
}
|
||||
|
||||
async closeFileHandle(params, context) {
|
||||
await context.assertActive();
|
||||
const handle = this.fileHandles.get(params.handleId);
|
||||
if (handle && handle.pluginId === context.pluginId && handle.runtimeId === context.runtimeId
|
||||
&& handle.sourceOwner === context.sourceOwner) {
|
||||
await this.#disposeFileHandle(handle);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
admitRequest(params, context) {
|
||||
const sender = this.#admit(params, context);
|
||||
let guard = this.admissionGuards.get(context.runtimeId);
|
||||
@@ -240,10 +579,6 @@ class PluginHostInteractionService {
|
||||
this.admissions.delete(params);
|
||||
let sender;
|
||||
if (admission?.runtimeId === context.runtimeId) {
|
||||
// Electron may resolve showMessageBox before restoring parent focus.
|
||||
// Never focus it ourselves or defer an originally background request.
|
||||
// Owner replacement, lock, hide, revoke and runtime stop invalidate this
|
||||
// host-owned admission, including changes during the permission prompt.
|
||||
const deadline = Date.now() + this.focusRestoreMs;
|
||||
for (;;) {
|
||||
context.signal?.throwIfAborted();
|
||||
@@ -281,16 +616,19 @@ class PluginHostInteractionService {
|
||||
const entry = { context, params };
|
||||
this.#audit(entry, "completed");
|
||||
if (params.kind === "clipboard.write") { this.clipboard.writeText(params.text); return { cancelled: false, value: true }; }
|
||||
const text = assertTextBytes(this.clipboard.readText());
|
||||
const text = assertTextBytes(this.clipboard.readText(), LIMITS.clipboardBytes);
|
||||
this.quotaManager.chargeBytes(context.runtimeId, "clipboard", Buffer.byteLength(text));
|
||||
await context.assertActive();
|
||||
return { cancelled: false, value: text };
|
||||
}
|
||||
const now = this.clock();
|
||||
const initialPhase = this.vaultService?.isRequest(params)
|
||||
? (this.vaultService.initialPhase?.(params, context) ?? "request")
|
||||
: "request";
|
||||
return new Promise((resolve, reject) => {
|
||||
const entry = {
|
||||
id: randomUUID(), context, params, sender, resolve, reject, terminalTarget, permissionMode, controller: new AbortController(),
|
||||
expiresAt: now + this.timeoutMs, phase: "request", actionToken: null, terminalWatch: null,
|
||||
expiresAt: now + this.timeoutMs, phase: initialPhase, actionToken: null, terminalWatch: null,
|
||||
};
|
||||
entry.onAbort = () => this.#finish(entry, null, fail("cancelled", "Host interaction was cancelled"));
|
||||
entry.timer = setTimeout(() => this.#finish(entry, null, fail("deadlineExceeded", "Host interaction expired")), this.timeoutMs);
|
||||
@@ -301,7 +639,7 @@ class PluginHostInteractionService {
|
||||
if (context.signal?.aborted) { entry.onAbort(); return; }
|
||||
try {
|
||||
if (params.kind === "clipboard.read") {
|
||||
entry.previewText = assertTextBytes(this.clipboard.readText());
|
||||
entry.previewText = assertTextBytes(this.clipboard.readText(), LIMITS.clipboardBytes);
|
||||
this.quotaManager.chargeBytes(context.runtimeId, "clipboard", Buffer.byteLength(entry.previewText));
|
||||
entry.phase = "preview";
|
||||
}
|
||||
@@ -331,6 +669,15 @@ class PluginHostInteractionService {
|
||||
this.#audit(entry, "cancelled");
|
||||
return this.#finish(entry, { cancelled: true });
|
||||
}
|
||||
if (entry.params.kind === "network.stream.confirm" || entry.params.kind === "network.stream.tlsConfirm") {
|
||||
if (response.action !== "submit") throw fail("invalidArgument", "Stream confirmation requires a submit action");
|
||||
this.#audit(entry, entry.params.kind === "network.stream.tlsConfirm" ? "tls-cert-confirmed" : "stream-confirmed");
|
||||
return this.#finish(entry, {
|
||||
cancelled: false,
|
||||
approved: true,
|
||||
remember: response.remember === true,
|
||||
});
|
||||
}
|
||||
if (this.vaultService?.isRequest(entry.params)) {
|
||||
const outcome = await this.vaultService.respond(entry, response, nativeOptions);
|
||||
await entry.context.assertActive();
|
||||
@@ -352,7 +699,7 @@ class PluginHostInteractionService {
|
||||
}
|
||||
if (entry.params.kind === "terminal.selection.read" && entry.phase === "request") {
|
||||
if (response.action !== "preview") throw fail("invalidArgument", "Terminal sharing requires a preview action");
|
||||
const text = assertTextBytes(response.value);
|
||||
const text = assertTextBytes(response.value, LIMITS.textBytes);
|
||||
if (!text.length) throw fail("failedPrecondition", "Select terminal text before requesting a share");
|
||||
this.#audit(entry, "preview-confirmed");
|
||||
this.quotaManager.chargeBytes(entry.context.runtimeId, "terminal", Buffer.byteLength(text));
|
||||
@@ -369,7 +716,7 @@ class PluginHostInteractionService {
|
||||
let rawText;
|
||||
try { rawText = this.clipboard.readText(); }
|
||||
catch { throw fail("unavailable", "Host clipboard text is unavailable"); }
|
||||
const text = assertTextBytes(rawText);
|
||||
const text = assertTextBytes(rawText, LIMITS.clipboardBytes);
|
||||
this.quotaManager.chargeBytes(entry.context.runtimeId, "clipboard", Buffer.byteLength(text));
|
||||
entry.previewText = text;
|
||||
entry.phase = "preview";
|
||||
@@ -381,7 +728,7 @@ class PluginHostInteractionService {
|
||||
let value;
|
||||
if (entry.params.kind === "input") {
|
||||
if (!validateSingleLineInput(response.value)) throw fail("invalidArgument", "Host input must be a single line");
|
||||
value = assertTextBytes(response.value);
|
||||
value = assertTextBytes(response.value, LIMITS.textBytes);
|
||||
}
|
||||
else if (entry.params.kind === "quickPick") {
|
||||
if (!entry.params.items.some((item) => item.id === response.value)) throw fail("invalidArgument", "Host interaction choice is invalid");
|
||||
@@ -423,6 +770,9 @@ class PluginHostInteractionService {
|
||||
this.terminalSelection.releasePlugin(pluginId);
|
||||
this.admissionRevision++;
|
||||
this.vaultService?.releasePlugin(pluginId);
|
||||
for (const handle of [...this.fileHandles.values()]) {
|
||||
if (handle.pluginId === pluginId) void this.#disposeFileHandle(handle);
|
||||
}
|
||||
for (const entry of [...this.pending.values()]) {
|
||||
if (entry.context.pluginId === pluginId) this.#finish(entry, null, fail("cancelled", "Plugin access was revoked"));
|
||||
}
|
||||
@@ -432,6 +782,9 @@ class PluginHostInteractionService {
|
||||
this.cancelRuntimeRequests(runtimeId, "Plugin runtime stopped");
|
||||
this.rates.delete(runtimeId);
|
||||
this.vaultService?.releaseRuntime(runtimeId);
|
||||
for (const handle of [...this.fileHandles.values()]) {
|
||||
if (handle.runtimeId === runtimeId) void this.#disposeFileHandle(handle);
|
||||
}
|
||||
}
|
||||
cancelRuntimeRequests(runtimeId, reason = "Host command finished") {
|
||||
const guard = this.admissionGuards.get(runtimeId);
|
||||
@@ -454,6 +807,8 @@ class PluginHostInteractionService {
|
||||
this.closed = true;
|
||||
if (this.owner) this.releaseWindow(this.owner);
|
||||
this.cancelAll(); this.rates.clear(); this.admissionGuards.clear();
|
||||
for (const handle of [...this.fileHandles.values()]) void this.#disposeFileHandle(handle);
|
||||
this.fileHandles.clear();
|
||||
this.revocation.dispose(); this.unsubscribeLock?.();
|
||||
this.terminalInvalidation.dispose(); this.terminalSelection.shutdown();
|
||||
this.key.fill(0);
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const { EventEmitter } = require("node:events");
|
||||
const test = require("node:test");
|
||||
const { PluginHostInteractionService, assertInteractionRequest, interactionAuthorization, PROMPT_CHANNEL } = require("./hostInteractionService.cjs");
|
||||
const { PluginHostInteractionService, LIMITS, assertInteractionRequest, interactionAuthorization, PROMPT_CHANNEL } = require("./hostInteractionService.cjs");
|
||||
|
||||
function fixture(t, options = {}) {
|
||||
const messages = [], audit = [], writes = [], charges = [];
|
||||
@@ -210,7 +210,8 @@ test("quota, deadline, locked host, unknown fields, duplicate choices and text b
|
||||
await assert.rejects(f.service.request(assertInteractionRequest({ kind: "input", title: "Locked" }), f.context), /focused unlocked/);
|
||||
assert.throws(() => assertInteractionRequest({ kind: "clipboard.read", title: "Forged", userGesture: true }), /invalid/);
|
||||
assert.throws(() => assertInteractionRequest({ kind: "quickPick", title: "Duplicate", items: [{ id: "same", label: "A" }, { id: "same", label: "B" }] }), /unique/);
|
||||
assert.throws(() => assertInteractionRequest({ kind: "clipboard.write", title: "Too long", text: "文".repeat(1500) }), /limit/);
|
||||
assert.throws(() => assertInteractionRequest({ kind: "input", title: "Too long", initialValue: "文".repeat(1500) }), /limit/);
|
||||
assert.throws(() => assertInteractionRequest({ kind: "clipboard.write", title: "Too long", text: "a".repeat(LIMITS.clipboardBytes + 1) }), /invalid|limit/);
|
||||
assert.equal(interactionAuthorization({ kind: "clipboard.read" }).permission, "clipboard.read");
|
||||
assert.equal(interactionAuthorization({ kind: "clipboard.write" }).permission, "clipboard.write");
|
||||
assert.equal(interactionAuthorization({ kind: "input" }).permission, "ui.interact");
|
||||
@@ -234,7 +235,7 @@ test("manifest permission checks and interaction quota run before any host promp
|
||||
await assert.rejects(denied({ kind: "input", title: "Undeclared" }, { signal: f.context.signal }), /declare/);
|
||||
assert.equal(decisions, 0); assert.equal(f.messages.length, 0);
|
||||
const route = registry.createRoutes({ ...base, manifest: { ...base.manifest, permissions: { optional: ["ui.interact"] } } }).requestHandlers["ui.interact"];
|
||||
for (let count = 1; count < 10; count++) {
|
||||
for (let count = 1; count < LIMITS.requestsPerMinute; count++) {
|
||||
await assert.rejects(route({ kind: "input", title: "Denied" }, { signal: f.context.signal }), /disabled/);
|
||||
}
|
||||
const before = decisions;
|
||||
@@ -408,3 +409,104 @@ test("terminalSelection timer stays idle without terminal dialogs/handles and st
|
||||
service.terminalSelection.clearHandles();
|
||||
assert.equal(service.terminalSelection.timer, null, "timer disarms once handle is cleared");
|
||||
});
|
||||
|
||||
test("clipboard write supports up to 4 MiB and native file dialogs support open, save, chunked handles, and isolation", async (t) => {
|
||||
const fsPromises = require("node:fs/promises");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const dir = await fsPromises.mkdtemp(path.join(os.tmpdir(), "netcatty-file-dialog-test-"));
|
||||
t.after(() => fsPromises.rm(dir, { recursive: true, force: true }));
|
||||
const samplePath = path.join(dir, "demo.sqlite");
|
||||
const savePath = path.join(dir, "export.bin");
|
||||
const initialBytes = Buffer.from("SQLite format 3\0demo-payload");
|
||||
await fsPromises.writeFile(samplePath, initialBytes);
|
||||
|
||||
let nextOpen = { canceled: false, filePaths: [samplePath] };
|
||||
let nextSave = { canceled: false, filePath: savePath };
|
||||
const f = fixture(t, {
|
||||
dialog: {
|
||||
showOpenDialog: async () => nextOpen,
|
||||
showSaveDialog: async () => nextSave,
|
||||
},
|
||||
});
|
||||
|
||||
// 1) Large clipboard write (1 MiB) succeeds within the 4 MiB limit.
|
||||
const largeText = "SELECT 1;\n".repeat(100_000);
|
||||
const clipReq = await f.begin({ kind: "clipboard.write", title: "Copy SQL", text: largeText });
|
||||
await f.respond(clipReq.prompt, "submit");
|
||||
assert.deepEqual(await clipReq.promise, { cancelled: false, value: true });
|
||||
assert.equal(f.writes.at(-1).length, largeText.length);
|
||||
|
||||
// 2) ui.openFile returns basename, data, and opaque handleId without exposing full path.
|
||||
const opened = await f.service.openFile({ title: "Open DB", readAs: "bytes" }, f.context);
|
||||
assert.equal(opened.cancelled, false);
|
||||
assert.equal(opened.name, "demo.sqlite");
|
||||
assert.equal(opened.streamed, false);
|
||||
assert.equal(JSON.stringify(opened).includes(dir), false);
|
||||
assert.deepEqual(Buffer.from(opened.data, "base64"), initialBytes);
|
||||
|
||||
// 3) Re-save back to the exact picked handle without re-prompting (chunked atomic write).
|
||||
const part1 = Buffer.from("SQLite format 3\0updated-part-1-");
|
||||
const part2 = Buffer.from("updated-part-2");
|
||||
await f.service.writeFileHandle({ handleId: opened.handleId, data: part1.toString("base64"), encoding: "base64", mode: "replace", commit: false }, f.context);
|
||||
// Before commit, the original file is untouched!
|
||||
assert.deepEqual(await fsPromises.readFile(samplePath), initialBytes);
|
||||
const commitRes = await f.service.writeFileHandle({ handleId: opened.handleId, data: part2.toString("base64"), encoding: "base64", mode: "append", commit: true }, f.context);
|
||||
assert.equal(commitRes.committed, true);
|
||||
assert.deepEqual(await fsPromises.readFile(samplePath), Buffer.concat([part1, part2]));
|
||||
|
||||
// 4) Another runtime cannot access this handle.
|
||||
await assert.rejects(
|
||||
f.service.readFileHandle({ handleId: opened.handleId }, { ...f.context, runtimeId: "other-runtime" }),
|
||||
/invalid or closed/,
|
||||
);
|
||||
|
||||
// 5) ui.saveFile writes atomically and returns handleId.
|
||||
const saved = await f.service.saveFile({
|
||||
title: "Save Export",
|
||||
defaultName: "export.bin",
|
||||
data: Buffer.from("exported-csv").toString("base64"),
|
||||
encoding: "base64",
|
||||
}, f.context);
|
||||
assert.equal(saved.cancelled, false);
|
||||
assert.equal(saved.name, "export.bin");
|
||||
assert.equal(await fsPromises.readFile(savePath, "utf8"), "exported-csv");
|
||||
|
||||
// 6) Closing handle prevents further reads/writes.
|
||||
await f.service.closeFileHandle({ handleId: opened.handleId }, f.context);
|
||||
await assert.rejects(f.service.readFileHandle({ handleId: opened.handleId }, f.context), /invalid or closed/);
|
||||
|
||||
// 7) Cancelled file dialog returns { cancelled: true }.
|
||||
nextOpen = { canceled: true, filePaths: [] };
|
||||
assert.deepEqual(await f.service.openFile({}, f.context), { cancelled: true });
|
||||
});
|
||||
|
||||
test("stream endpoint and TLS certificate confirmation prompts return approval and remember choice", async (t) => {
|
||||
const f = fixture(t);
|
||||
const streamPromise = f.service.request({
|
||||
kind: "network.stream.confirm",
|
||||
endpoint: "tcp://127.0.0.1:5432",
|
||||
host: "127.0.0.1",
|
||||
port: 5432,
|
||||
transport: "tcp",
|
||||
isLocal: true,
|
||||
}, f.context);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
const streamPrompt = f.messages.filter((m) => !m.closed).at(-1);
|
||||
await f.service.respond(f.sender, { requestId: streamPrompt.requestId, actionToken: streamPrompt.actionToken, action: "submit", remember: true });
|
||||
assert.deepEqual(await streamPromise, { cancelled: false, approved: true, remember: true });
|
||||
|
||||
const tlsPromise = f.service.request({
|
||||
kind: "network.stream.tlsConfirm",
|
||||
endpoint: "tcp://127.0.0.1:5432",
|
||||
fingerprint256: "AA:BB:CC",
|
||||
subject: "CN=postgres",
|
||||
issuer: "CN=postgres",
|
||||
validTo: "2030-01-01",
|
||||
reason: "DEPTH_ZERO_SELF_SIGNED_CERT",
|
||||
}, f.context);
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
const tlsPrompt = f.messages.filter((m) => !m.closed).at(-1);
|
||||
await f.service.respond(f.sender, { requestId: tlsPrompt.requestId, actionToken: tlsPrompt.actionToken, action: "submit", remember: false });
|
||||
assert.deepEqual(await tlsPromise, { cancelled: false, approved: true, remember: false });
|
||||
});
|
||||
@@ -336,15 +336,31 @@ function createDefaultPluginHostRpcRegistry(options) {
|
||||
validateParams: (params) => options.assertStorageParams(params),
|
||||
});
|
||||
registry.registerRequest("storage.keys", async (params, context) => {
|
||||
return { keys: options.database.listKeys(context.pluginId) };
|
||||
const keys = options.database.listKeys(context.pluginId);
|
||||
const prefix = params?.prefix;
|
||||
return {
|
||||
keys: typeof prefix === "string" && prefix.length > 0
|
||||
? keys.filter((key) => key.startsWith(prefix))
|
||||
: keys,
|
||||
};
|
||||
}, {
|
||||
metadata: { capability: "storage", mutating: false, permission: "storage" },
|
||||
authorization: { permission: "storage", resources: ["*"], reason: "List plugin storage keys" },
|
||||
validateParams: (params) => {
|
||||
if (params && (typeof params !== "object" || Array.isArray(params) || Object.keys(params).length > 0)) {
|
||||
throw new TypeError("storage.keys does not accept parameters");
|
||||
if (params === undefined || params === null) return {};
|
||||
if (typeof params !== "object" || Array.isArray(params)) {
|
||||
throw new TypeError("storage.keys parameters must be an object");
|
||||
}
|
||||
return params;
|
||||
const keys = Object.keys(params);
|
||||
if (keys.some((key) => key !== "prefix")) {
|
||||
throw new TypeError("storage.keys only accepts an optional prefix parameter");
|
||||
}
|
||||
if (params.prefix !== undefined) {
|
||||
if (typeof params.prefix !== "string" || params.prefix.length > 256 || params.prefix.includes("\0")) {
|
||||
throw new TypeError("storage.keys prefix is invalid");
|
||||
}
|
||||
}
|
||||
return params.prefix === undefined ? {} : { prefix: params.prefix };
|
||||
},
|
||||
});
|
||||
registry.registerNotification("log.write", async (params, context) => {
|
||||
|
||||
@@ -308,3 +308,30 @@ test("reserved lifecycle and transport methods cannot be claimed as host capabil
|
||||
}
|
||||
assert.equal(assertHostMethod("commands.execute"), "commands.execute");
|
||||
});
|
||||
|
||||
test("storage.keys supports optional prefix filtering and rejects unknown parameters", async () => {
|
||||
const { createDefaultPluginHostRpcRegistry } = require("./hostRpcRegistry.cjs");
|
||||
const registry = createDefaultPluginHostRpcRegistry({
|
||||
assertStorageParams: (params) => params,
|
||||
database: {
|
||||
listKeys: () => ["conn:1", "conn:2", "history:1", "draft:tab1"],
|
||||
getValue: () => undefined,
|
||||
setValue() {},
|
||||
deleteValue() {},
|
||||
},
|
||||
});
|
||||
const routes = registry.createRoutes(identity());
|
||||
const transport = { signal: AbortSignal.timeout(100) };
|
||||
assert.deepEqual(
|
||||
await routes.requestHandlers["storage.keys"]({}, transport),
|
||||
{ keys: ["conn:1", "conn:2", "history:1", "draft:tab1"] },
|
||||
);
|
||||
assert.deepEqual(
|
||||
await routes.requestHandlers["storage.keys"]({ prefix: "conn:" }, transport),
|
||||
{ keys: ["conn:1", "conn:2"] },
|
||||
);
|
||||
await assert.rejects(
|
||||
routes.requestHandlers["storage.keys"]({ unknown: true }, transport),
|
||||
/only accepts an optional prefix/,
|
||||
);
|
||||
});
|
||||
@@ -222,6 +222,7 @@ function createPluginHostService(options) {
|
||||
interactionService = new PluginHostInteractionService({
|
||||
database, permissionEngine, quotaManager,
|
||||
clipboard: options.electron.clipboard,
|
||||
dialog: options.electron.dialog,
|
||||
getWindow: options.getInteractionWindow,
|
||||
isLocked: options.isAppLocked,
|
||||
subscribeLock: options.subscribeAppLock,
|
||||
@@ -327,7 +328,7 @@ function createPluginHostService(options) {
|
||||
},
|
||||
utilityModuleMappings: options.utilityModuleMappings ?? createUtilityModuleMappings(moduleResources),
|
||||
});
|
||||
byteStreamService = new PluginByteStreamService({ database, permissionEngine, quotaManager, runtimeSupervisor });
|
||||
byteStreamService = new PluginByteStreamService({ database, permissionEngine, quotaManager, runtimeSupervisor, interactionService });
|
||||
byteStreamService.register(rpcRegistry);
|
||||
aiHostAdapter = options.pluginAIHostAdapter ?? new PluginAITrustedHostAdapter({
|
||||
getWindow: options.getInteractionWindow ?? (() => null),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use strict";
|
||||
|
||||
const { createHmac, randomBytes } = require("node:crypto");
|
||||
const { createHash, createHmac, randomBytes, timingSafeEqual } = require("node:crypto");
|
||||
const { canonicalizeStreamEndpoint } = require("./byteStreamEndpoint.cjs");
|
||||
const { createDefinitionValidator } = require("./contractValidator.cjs");
|
||||
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
|
||||
@@ -8,25 +8,43 @@ const fail = (code, message) => new PluginRpcError(RPC_ERRORS[code], message);
|
||||
const METHODS = ["vault.selectHosts", "vault.requestHostDraft", "vault.requestConnect", "network.stream.connectViaHost"];
|
||||
const MAX_SELECTED = 50;
|
||||
const MAX_REFERENCES = 500;
|
||||
const MAX_DURABLE_BINDINGS_PER_PLUGIN = 128;
|
||||
const TARGET_LIFETIME_MS = 5 * 60_000;
|
||||
|
||||
function hashToken(token) {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
function timingSafeHexEqual(a, b) {
|
||||
if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false;
|
||||
return timingSafeEqual(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
|
||||
}
|
||||
|
||||
/** Typed host selection only. Selection references identify a reviewed target;
|
||||
* the interaction service owns separate operation-specific commit authority. */
|
||||
class PluginHostVaultService {
|
||||
constructor({ sourceBinding, interactionService, openStream, clock = Date.now }) {
|
||||
constructor({ sourceBinding, interactionService, openStream, database, clock = Date.now }) {
|
||||
this.sourceBinding = sourceBinding;
|
||||
this.openStream = openStream;
|
||||
this.interactionService = interactionService;
|
||||
this.database = database ?? interactionService?.database ?? null;
|
||||
this.clock = clock;
|
||||
this.key = randomBytes(32);
|
||||
this.targets = new Map();
|
||||
this.memoryDurableBindings = new Map();
|
||||
this.streams = new Set();
|
||||
this.admissions = new WeakMap();
|
||||
this.validators = Object.fromEntries([
|
||||
"VaultSelectHostsParams", "VaultHostDraftParams", "VaultHostConnectParams",
|
||||
"HostByteStreamConnectRequest", "VaultHostSelectedResources", "VaultHostCreateFields", "VaultHostEditFields",
|
||||
"HostByteStreamConnectRequest", "VaultHostBindingRevokeParams",
|
||||
"VaultHostSelectedResources", "VaultHostCreateFields", "VaultHostEditFields",
|
||||
].map((name) => [name, createDefinitionValidator(name)]));
|
||||
interactionService.vaultService = this;
|
||||
this.revocation = interactionService.permissionEngine?.onDidRevoke?.((event) => {
|
||||
if (event.permission === undefined || event.permission === "network.hostStream") {
|
||||
this.clearDurableBindings(event.pluginId);
|
||||
}
|
||||
}) ?? { dispose() {} };
|
||||
}
|
||||
|
||||
isRequest(params) { return METHODS.includes(params?.kind); }
|
||||
@@ -37,6 +55,90 @@ class PluginHostVaultService {
|
||||
return structuredClone(value);
|
||||
}
|
||||
|
||||
#ownerKey(pluginId) {
|
||||
return typeof this.database?.privateOwner === "function"
|
||||
? this.database.privateOwner(pluginId)
|
||||
: pluginId;
|
||||
}
|
||||
|
||||
#bindingsPrefKey(pluginId) {
|
||||
return `permission:${this.#ownerKey(pluginId)}:vault-host-bindings`;
|
||||
}
|
||||
|
||||
#readBindings(pluginId) {
|
||||
const key = this.#bindingsPrefKey(pluginId);
|
||||
if (this.database?.db) {
|
||||
try {
|
||||
const row = this.database.db.prepare("SELECT value_json FROM plugin_host_preferences WHERE key = ?").get(key);
|
||||
if (row?.value_json) {
|
||||
const parsed = JSON.parse(row.value_json);
|
||||
if (Array.isArray(parsed)) return parsed;
|
||||
}
|
||||
} catch { /* fall through */ }
|
||||
}
|
||||
return this.memoryDurableBindings.get(key) ?? [];
|
||||
}
|
||||
|
||||
#writeBindings(pluginId, bindings) {
|
||||
const key = this.#bindingsPrefKey(pluginId);
|
||||
const trimmed = bindings.slice(-MAX_DURABLE_BINDINGS_PER_PLUGIN);
|
||||
this.memoryDurableBindings.set(key, trimmed);
|
||||
if (this.database?.db) {
|
||||
try {
|
||||
if (trimmed.length === 0) {
|
||||
this.database.db.prepare("DELETE FROM plugin_host_preferences WHERE key = ?").run(key);
|
||||
} else {
|
||||
this.database.db.prepare(
|
||||
"INSERT INTO plugin_host_preferences(key,value_json,updated_at) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET value_json=excluded.value_json,updated_at=excluded.updated_at",
|
||||
).run(key, JSON.stringify(trimmed), this.clock());
|
||||
}
|
||||
} catch { /* ignore when mock db */ }
|
||||
}
|
||||
}
|
||||
|
||||
#issueDurableBinding(pluginId, hostId, endpoint) {
|
||||
const token = `hb_${randomBytes(24).toString("base64url")}`;
|
||||
const tokenHash = hashToken(token);
|
||||
const current = this.#readBindings(pluginId);
|
||||
// Replace any existing binding for the same (hostId, endpoint) so list stays tidy.
|
||||
const next = current.filter((item) => !(item.hostId === hostId && item.endpoint === endpoint));
|
||||
next.push({ tokenHash, hostId, endpoint, createdAt: this.clock() });
|
||||
this.#writeBindings(pluginId, next);
|
||||
return token;
|
||||
}
|
||||
|
||||
#resolveDurableBinding(pluginId, token, endpoint) {
|
||||
if (typeof token !== "string" || token.length < 16) {
|
||||
throw fail("permissionDenied", "SSH tunnel binding token is invalid");
|
||||
}
|
||||
const candidateHash = hashToken(token);
|
||||
const bindings = this.#readBindings(pluginId);
|
||||
const match = bindings.find((item) => timingSafeHexEqual(item.tokenHash, candidateHash));
|
||||
if (!match || match.endpoint !== endpoint) {
|
||||
throw fail("permissionDenied", "SSH tunnel binding is invalid, expired, or was revoked");
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
revokeDurableBinding(pluginId, token) {
|
||||
const candidateHash = hashToken(token);
|
||||
const current = this.#readBindings(pluginId);
|
||||
const next = current.filter((item) => !timingSafeHexEqual(item.tokenHash, candidateHash));
|
||||
if (next.length === current.length) return false;
|
||||
this.#writeBindings(pluginId, next);
|
||||
return true;
|
||||
}
|
||||
|
||||
clearDurableBindings(pluginId) {
|
||||
const key = this.#bindingsPrefKey(pluginId);
|
||||
this.memoryDurableBindings.delete(key);
|
||||
if (this.database?.db) {
|
||||
try {
|
||||
this.database.db.prepare("DELETE FROM plugin_host_preferences WHERE key = ?").run(key);
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
registerRpcCapabilities(registry) {
|
||||
const definitions = ["VaultSelectHostsParams", "VaultHostDraftParams", "VaultHostConnectParams", "HostByteStreamConnectRequest"];
|
||||
for (const [index, method] of METHODS.entries()) {
|
||||
@@ -56,6 +158,7 @@ class PluginHostVaultService {
|
||||
}
|
||||
const binding = await this.sourceBinding.resolve(context);
|
||||
if (params.target) this.#resolveTarget(params.target, params.expectedRevision, binding);
|
||||
if (params.hostBindingToken) this.#resolveDurableBinding(context.pluginId, params.hostBindingToken, params.endpoint);
|
||||
this.interactionService.admitRequest(params, context);
|
||||
this.admissions.set(params, binding);
|
||||
return {
|
||||
@@ -67,6 +170,29 @@ class PluginHostVaultService {
|
||||
},
|
||||
});
|
||||
}
|
||||
registry.registerRequest("vault.revokeHostBinding", async (params, context) => {
|
||||
await context.assertActive();
|
||||
await this.sourceBinding.resolve(context);
|
||||
const revoked = this.revokeDurableBinding(context.pluginId, params.hostBindingToken);
|
||||
return { revoked };
|
||||
}, {
|
||||
metadata: { capability: "vault", mutating: true },
|
||||
validateParams: (params) => this.#validate("VaultHostBindingRevokeParams", params),
|
||||
authorization: {
|
||||
permission: "network.hostStream",
|
||||
resources: ["*"],
|
||||
reason: "Revoke a saved SSH tunnel binding",
|
||||
operationId: "vault.revokeHostBinding",
|
||||
deferDecision: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
initialPhase(params) {
|
||||
if (params.kind === "network.stream.connectViaHost" && params.hostBindingToken) {
|
||||
return "commit";
|
||||
}
|
||||
return "request";
|
||||
}
|
||||
|
||||
async request(params, originalContext) {
|
||||
@@ -81,6 +207,7 @@ class PluginHostVaultService {
|
||||
await originalContext.assertActive();
|
||||
if (await this.sourceBinding.resolve(originalContext) !== binding) throw fail("permissionDenied", "Host action source changed");
|
||||
if (params.target) this.#resolveTarget(params.target, params.expectedRevision, binding);
|
||||
if (params.hostBindingToken) this.#resolveDurableBinding(originalContext.pluginId, params.hostBindingToken, params.endpoint);
|
||||
};
|
||||
await assertActive();
|
||||
return this.interactionService.request(params, Object.freeze({ ...originalContext, assertActive, assertStreamActive, vaultBinding: binding }));
|
||||
@@ -114,6 +241,14 @@ class PluginHostVaultService {
|
||||
}
|
||||
|
||||
describePrompt(entry) {
|
||||
if (entry.params.kind === "network.stream.connectViaHost" && entry.params.hostBindingToken) {
|
||||
const saved = this.#resolveDurableBinding(entry.context.pluginId, entry.params.hostBindingToken, entry.params.endpoint);
|
||||
return {
|
||||
vaultTarget: { resourceId: saved.hostId, revision: "durable" },
|
||||
durableHostId: saved.hostId,
|
||||
autoCommit: true,
|
||||
};
|
||||
}
|
||||
if (!entry.params.target) return {};
|
||||
const target = this.#resolveTarget(entry.params.target, entry.params.expectedRevision, entry.context.vaultBinding);
|
||||
return { vaultTarget: { resourceId: target.resourceId, revision: target.revision } };
|
||||
@@ -143,18 +278,32 @@ class PluginHostVaultService {
|
||||
const draft = this.#validate(entry.params.target ? "VaultHostEditFields" : "VaultHostCreateFields", response.draft);
|
||||
return { phase: "commit", reviewedDraft: draft };
|
||||
}
|
||||
if (entry.params.kind === "network.stream.connectViaHost") return { phase: "commit" };
|
||||
if (entry.params.kind === "network.stream.connectViaHost") {
|
||||
entry.rememberBinding = response.remember === true;
|
||||
return { phase: "commit" };
|
||||
}
|
||||
if (typeof response.scriptsRun !== "boolean") throw fail("invalidArgument", "Connection script disclosure is required");
|
||||
return { phase: "commit" };
|
||||
}
|
||||
if (entry.params.kind === "network.stream.connectViaHost" && entry.phase === "commit" && response.action === "commit") {
|
||||
const target = this.#resolveTarget(entry.params.target, entry.params.expectedRevision, entry.context.vaultBinding);
|
||||
if (!this.openStream || !nativeOptions || nativeOptions.hostId !== target.resourceId) throw fail("permissionDenied", "Reviewed server connection is unavailable");
|
||||
const isDurableReconnect = Boolean(entry.params.hostBindingToken);
|
||||
const expectedHostId = isDurableReconnect
|
||||
? this.#resolveDurableBinding(entry.context.pluginId, entry.params.hostBindingToken, entry.params.endpoint).hostId
|
||||
: this.#resolveTarget(entry.params.target, entry.params.expectedRevision, entry.context.vaultBinding).resourceId;
|
||||
if (!this.openStream || !nativeOptions || nativeOptions.hostId !== expectedHostId) {
|
||||
throw fail("permissionDenied", "Reviewed server connection is unavailable");
|
||||
}
|
||||
const assertActive = async () => {
|
||||
entry.controller.signal.throwIfAborted();
|
||||
if (entry.streamDelivered) await entry.context.assertStreamActive();
|
||||
else await entry.context.assertActive();
|
||||
if (!entry.streamDelivered) this.#resolveTarget(entry.params.target, entry.params.expectedRevision, entry.context.vaultBinding);
|
||||
if (!entry.streamDelivered) {
|
||||
if (isDurableReconnect) {
|
||||
this.#resolveDurableBinding(entry.context.pluginId, entry.params.hostBindingToken, entry.params.endpoint);
|
||||
} else {
|
||||
this.#resolveTarget(entry.params.target, entry.params.expectedRevision, entry.context.vaultBinding);
|
||||
}
|
||||
}
|
||||
};
|
||||
const lease = { controller: entry.controller, runtimeId: entry.context.runtimeId, pluginId: entry.context.pluginId };
|
||||
this.streams.add(lease);
|
||||
@@ -162,7 +311,15 @@ class PluginHostVaultService {
|
||||
const handle = await this.openStream(entry.params.endpoint, { ...entry.context, signal: entry.controller.signal, assertActive }, entry.sender, nativeOptions);
|
||||
handle.onClose?.(() => { this.streams.delete(lease); });
|
||||
entry.disposeResult = () => { this.streams.delete(lease); handle.close(); };
|
||||
return { result: handle.descriptor };
|
||||
let hostBindingToken = isDurableReconnect ? entry.params.hostBindingToken : undefined;
|
||||
if (!isDurableReconnect && entry.rememberBinding === true) {
|
||||
hostBindingToken = this.#issueDurableBinding(entry.context.pluginId, expectedHostId, entry.params.endpoint);
|
||||
}
|
||||
return {
|
||||
result: hostBindingToken
|
||||
? { ...handle.descriptor, hostBindingToken }
|
||||
: handle.descriptor,
|
||||
};
|
||||
}
|
||||
if (entry.phase === "commit" && response.action === "commit") return { phase: "executing" };
|
||||
if (entry.phase === "executing" && response.action === "complete") {
|
||||
@@ -185,7 +342,7 @@ class PluginHostVaultService {
|
||||
// revoked old runtime must never rebind itself to a replacement source.
|
||||
}
|
||||
clearSelections() { this.targets.clear(); for (const lease of this.streams) lease.controller.abort(); }
|
||||
shutdown() { this.clearSelections(); this.sourceBinding.shutdown(); this.key.fill(0); }
|
||||
shutdown() { this.clearSelections(); this.revocation.dispose(); this.sourceBinding.shutdown(); this.key.fill(0); }
|
||||
}
|
||||
|
||||
module.exports = { PluginHostVaultService, METHODS, MAX_SELECTED, TARGET_LIFETIME_MS };
|
||||
@@ -115,7 +115,7 @@ function normalizePermissionDeclarations(manifest) {
|
||||
: [...new Set((value.resources ?? []).map((resource) => (
|
||||
canonicalizePermissionResource(permission, resource)
|
||||
)))].sort();
|
||||
if ((required && RESOURCE_SCOPED_PERMISSIONS.has(permission)) || permission === "network.stream") {
|
||||
if (required && RESOURCE_SCOPED_PERMISSIONS.has(permission)) {
|
||||
if (resources.length === 0) {
|
||||
throw new TypeError(`Required permission ${permission} must declare resources`);
|
||||
}
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
|
||||
|
||||
const DEFAULT_QUOTAS = Object.freeze({
|
||||
messageBurst: 512,
|
||||
messagesPerSecond: 256,
|
||||
concurrentCapabilities: 32,
|
||||
capabilityBurst: 120,
|
||||
capabilitiesPerMinute: 600,
|
||||
messageBurst: 1024,
|
||||
messagesPerSecond: 512,
|
||||
concurrentCapabilities: 64,
|
||||
capabilityBurst: 240,
|
||||
capabilitiesPerMinute: 2400,
|
||||
logWritesPerMinute: 240,
|
||||
bytesPerMinute: 32 * 1024 * 1024,
|
||||
bytesPerMinute: 128 * 1024 * 1024,
|
||||
streamBytesPerMinute: 512 * 1024 * 1024,
|
||||
memoryBytes: 256 * 1024 * 1024,
|
||||
cpuPercent: 80,
|
||||
sustainedCpuSamples: 3,
|
||||
@@ -44,7 +45,12 @@ class TokenBucket {
|
||||
class PluginQuotaManager {
|
||||
constructor(options = {}) {
|
||||
this.clock = options.clock ?? (() => Date.now());
|
||||
this.quotas = Object.freeze({ ...DEFAULT_QUOTAS, ...(options.quotas ?? {}) });
|
||||
this.quotas = Object.freeze({
|
||||
...DEFAULT_QUOTAS,
|
||||
...(options.quotas ?? {}),
|
||||
streamBytesPerMinute: options.quotas?.streamBytesPerMinute
|
||||
?? (options.quotas?.bytesPerMinute ?? DEFAULT_QUOTAS.streamBytesPerMinute),
|
||||
});
|
||||
this.getProcessMetrics = options.getProcessMetrics ?? null;
|
||||
this.onViolation = options.onViolation ?? (() => {});
|
||||
this.setInterval = options.setInterval ?? setInterval;
|
||||
@@ -124,7 +130,10 @@ class PluginQuotaManager {
|
||||
this.byteWindows.set(key, window);
|
||||
}
|
||||
window.bytes += byteLength;
|
||||
if (window.bytes > this.quotas.bytesPerMinute) {
|
||||
const limit = category === "network.stream"
|
||||
? this.quotas.streamBytesPerMinute
|
||||
: this.quotas.bytesPerMinute;
|
||||
if (window.bytes > limit) {
|
||||
throw quotaError(`Plugin ${category} byte quota exceeded`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,12 @@ export async function connectByteStream({ client, streams, subscriptions, enable
|
||||
await close().catch(() => {});
|
||||
throw new PluginError("cancelled", "Byte stream connection cancelled");
|
||||
};
|
||||
const upgradeTls = (options = {}) => client.request("network.stream.upgradeTls", {
|
||||
handleId: descriptor.handleId,
|
||||
...(options?.servername === undefined ? {} : { servername: options.servername }),
|
||||
...(options?.allowSelfSigned === undefined ? {} : { allowSelfSigned: options.allowSelfSigned }),
|
||||
...(options?.caPem === undefined ? {} : { caPem: options.caPem }),
|
||||
}, { cancellationToken, deadlineMs: 60_000 });
|
||||
try {
|
||||
await checkCancelled();
|
||||
readablePromise = streams.acceptReadable(descriptor.outputStreamId);
|
||||
@@ -37,6 +43,7 @@ export async function connectByteStream({ client, streams, subscriptions, enable
|
||||
await checkCancelled();
|
||||
connection = Object.freeze({
|
||||
endpoint: descriptor.endpoint,
|
||||
...(descriptor.hostBindingToken ? { hostBindingToken: descriptor.hostBindingToken } : {}),
|
||||
readable: Object.freeze({
|
||||
id: readable.id, read: () => readable.read(), cancel, dispose: cancel,
|
||||
}),
|
||||
@@ -44,6 +51,7 @@ export async function connectByteStream({ client, streams, subscriptions, enable
|
||||
id: writable.id, write: (bytes) => writable.write(bytes), end: () => writable.end(),
|
||||
fail: cancel, cancel, dispose: cancel,
|
||||
}),
|
||||
upgradeTls,
|
||||
close, dispose: cancel,
|
||||
});
|
||||
cancellation = cancellationToken?.onCancellationRequested(cancel);
|
||||
|
||||
@@ -347,6 +347,50 @@ function createEmitter() {
|
||||
};
|
||||
}
|
||||
|
||||
const FILE_CHUNK_BYTES = 2 * 1024 * 1024;
|
||||
const FILE_DIALOG_DEADLINE_MS = 300_000;
|
||||
|
||||
function bytesToBase64(bytes) {
|
||||
if (typeof Buffer === "function") return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
|
||||
let binary = "";
|
||||
const step = 0x8000;
|
||||
for (let offset = 0; offset < bytes.byteLength; offset += step) {
|
||||
binary += String.fromCharCode(...bytes.subarray(offset, offset + step));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
function base64ToBytes(encoded) {
|
||||
if (typeof Buffer === "function") {
|
||||
const buf = Buffer.from(encoded, "base64");
|
||||
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
}
|
||||
const binary = atob(encoded);
|
||||
const out = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
||||
return out;
|
||||
}
|
||||
|
||||
function concatUint8Arrays(chunks, totalBytes) {
|
||||
const out = new Uint8Array(totalBytes);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
out.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function toBytes(data, encoding) {
|
||||
if (data instanceof Uint8Array) return data;
|
||||
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
||||
if (typeof data === "string") {
|
||||
if (encoding === "base64") return base64ToBytes(data);
|
||||
return new TextEncoder().encode(data);
|
||||
}
|
||||
throw new PluginError("invalid_argument", "File data must be a Uint8Array, ArrayBuffer, or string");
|
||||
}
|
||||
|
||||
function createPluginContext(config, client, runtimeApi) {
|
||||
const subscriptions = new DisposableStore();
|
||||
const storage = {
|
||||
@@ -356,11 +400,18 @@ function createPluginContext(config, client, runtimeApi) {
|
||||
.then(() => undefined),
|
||||
delete: (key) => client.request("storage.delete", { key: assertStorageKey(key) })
|
||||
.then(() => undefined),
|
||||
keys: () => client.request("storage.keys", {}).then((result) => result?.keys ?? []),
|
||||
keys: (options) => client.request(
|
||||
"storage.keys",
|
||||
options?.prefix !== undefined ? { prefix: options.prefix } : {},
|
||||
).then((result) => result?.keys ?? []),
|
||||
};
|
||||
const readOwnSecret = (key) => client.request("secrets.getPlaintext", { key: assertStorageKey(key) })
|
||||
.then((result) => result?.found ? result.value : undefined);
|
||||
const secrets = {
|
||||
get: (key) => client.request("secrets.get", { key: assertStorageKey(key) })
|
||||
.then((result) => result?.found ? result.secret : undefined),
|
||||
getPlaintext: readOwnSecret,
|
||||
readOwn: readOwnSecret,
|
||||
set: (key, value) => client.request("secrets.set", {
|
||||
key: assertStorageKey(key),
|
||||
value,
|
||||
@@ -378,13 +429,113 @@ function createPluginContext(config, client, runtimeApi) {
|
||||
};
|
||||
const interact = (params) => client.request("ui.interact", params, { deadlineMs: PLUGIN_HOST_INTERACTION_LIMITS.timeoutMs })
|
||||
.then((result) => result.cancelled ? undefined : result.value);
|
||||
const readFileHandleAll = async (handleId, options = {}) => {
|
||||
const chunks = [];
|
||||
let offset = 0;
|
||||
let total = 0;
|
||||
while (true) {
|
||||
const page = await client.request("ui.readFileHandle", {
|
||||
handleId,
|
||||
offset,
|
||||
length: FILE_CHUNK_BYTES,
|
||||
encoding: "base64",
|
||||
}, { deadlineMs: 60_000 });
|
||||
const bytes = page.bytesRead > 0 ? base64ToBytes(page.data) : new Uint8Array(0);
|
||||
if (bytes.byteLength > 0) {
|
||||
chunks.push(bytes);
|
||||
offset += bytes.byteLength;
|
||||
total += bytes.byteLength;
|
||||
}
|
||||
if (page.eof || page.bytesRead === 0) break;
|
||||
}
|
||||
const merged = concatUint8Arrays(chunks, total);
|
||||
return options?.readAs === "utf8" ? new TextDecoder().decode(merged) : merged;
|
||||
};
|
||||
const writeFileHandleAll = async (handleId, data, options = {}) => {
|
||||
const bytes = toBytes(data, options?.encoding);
|
||||
if (bytes.byteLength === 0) {
|
||||
return client.request("ui.writeFileHandle", {
|
||||
handleId, data: "", encoding: "base64", mode: "replace", commit: true,
|
||||
}, { deadlineMs: 60_000 });
|
||||
}
|
||||
let lastResult;
|
||||
for (let offset = 0; offset < bytes.byteLength; offset += FILE_CHUNK_BYTES) {
|
||||
const end = Math.min(offset + FILE_CHUNK_BYTES, bytes.byteLength);
|
||||
const slice = bytes.subarray(offset, end);
|
||||
lastResult = await client.request("ui.writeFileHandle", {
|
||||
handleId,
|
||||
data: bytesToBase64(slice),
|
||||
encoding: "base64",
|
||||
mode: offset === 0 ? "replace" : "append",
|
||||
commit: end >= bytes.byteLength,
|
||||
}, { deadlineMs: 60_000 });
|
||||
}
|
||||
return { bytesWritten: bytes.byteLength, totalSize: lastResult?.totalSize ?? bytes.byteLength };
|
||||
};
|
||||
const ui = {
|
||||
quickPick: (title, items) => interact({ kind: "quickPick", title, items }),
|
||||
input: (title, initialValue) => interact({ kind: "input", title, ...(initialValue === undefined ? {} : { initialValue }) }),
|
||||
openFile: async (options = {}) => {
|
||||
const result = await client.request("ui.openFile", {
|
||||
...(options?.title === undefined ? {} : { title: options.title }),
|
||||
...(options?.filters === undefined ? {} : { filters: options.filters }),
|
||||
...(options?.readAs === undefined ? {} : { readAs: options.readAs }),
|
||||
...(options?.maxBytes === undefined ? {} : { maxBytes: options.maxBytes }),
|
||||
}, { deadlineMs: FILE_DIALOG_DEADLINE_MS });
|
||||
if (result?.cancelled) return { cancelled: true };
|
||||
let data;
|
||||
if (result.streamed) {
|
||||
data = await readFileHandleAll(result.handleId, { readAs: options?.readAs });
|
||||
} else if (options?.readAs === "utf8") {
|
||||
data = result.encoding === "utf8" ? result.data : new TextDecoder().decode(base64ToBytes(result.data ?? ""));
|
||||
} else {
|
||||
data = result.encoding === "base64" ? base64ToBytes(result.data ?? "") : new TextEncoder().encode(result.data ?? "");
|
||||
}
|
||||
return {
|
||||
cancelled: false,
|
||||
name: result.name,
|
||||
size: result.size,
|
||||
handleId: result.handleId,
|
||||
data,
|
||||
};
|
||||
},
|
||||
saveFile: async (options = {}) => {
|
||||
const bytes = options?.data === undefined ? new Uint8Array(0) : toBytes(options.data, options.encoding);
|
||||
const baseReq = {
|
||||
...(options?.title === undefined ? {} : { title: options.title }),
|
||||
...(options?.defaultName === undefined ? {} : { defaultName: options.defaultName }),
|
||||
...(options?.filters === undefined ? {} : { filters: options.filters }),
|
||||
};
|
||||
if (bytes.byteLength <= FILE_CHUNK_BYTES) {
|
||||
return client.request("ui.saveFile", {
|
||||
...baseReq,
|
||||
data: bytesToBase64(bytes),
|
||||
encoding: "base64",
|
||||
}, { deadlineMs: FILE_DIALOG_DEADLINE_MS });
|
||||
}
|
||||
const opened = await client.request("ui.saveFile", {
|
||||
...baseReq,
|
||||
deferredWrite: true,
|
||||
}, { deadlineMs: FILE_DIALOG_DEADLINE_MS });
|
||||
if (opened?.cancelled) return { cancelled: true };
|
||||
const written = await writeFileHandleAll(opened.handleId, bytes);
|
||||
return {
|
||||
cancelled: false,
|
||||
name: opened.name,
|
||||
size: written.totalSize,
|
||||
handleId: opened.handleId,
|
||||
};
|
||||
},
|
||||
readFileHandle: readFileHandleAll,
|
||||
writeFileHandle: writeFileHandleAll,
|
||||
closeFileHandle: (handleId) => client.request("ui.closeFileHandle", { handleId }).then(() => undefined),
|
||||
};
|
||||
const vault = {
|
||||
...Object.fromEntries(["selectHosts", "requestHostDraft", "requestConnect"].map((method) => [
|
||||
method, (params) => client.request(`vault.${method}`, params, { deadlineMs: PLUGIN_HOST_INTERACTION_LIMITS.timeoutMs }),
|
||||
])),
|
||||
revokeHostBinding: (hostBindingToken) => client.request("vault.revokeHostBinding", { hostBindingToken }),
|
||||
};
|
||||
const vault = Object.fromEntries(["selectHosts", "requestHostDraft", "requestConnect"].map((method) => [
|
||||
method, (params) => client.request(`vault.${method}`, params, { deadlineMs: PLUGIN_HOST_INTERACTION_LIMITS.timeoutMs }),
|
||||
]));
|
||||
const clipboard = {
|
||||
readText: (title) => interact({ kind: "clipboard.read", title }),
|
||||
writeText: (text, title) => interact({ kind: "clipboard.write", title, text }).then((value) => value === true),
|
||||
|
||||
@@ -343,6 +343,22 @@ class PluginSecretStore {
|
||||
throw new PluginRpcError(RPC_ERRORS.dataLoss, "Plugin secret could not be decrypted");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypts a secret stored by this plugin itself in its own safeStorage-encrypted
|
||||
* namespace. Never accesses Netcatty Vault credentials or another plugin's secrets.
|
||||
*/
|
||||
getPlaintext(pluginId, key) {
|
||||
this.#assertAvailable();
|
||||
assertSecretKey(key);
|
||||
const record = this.database.getSecretByKey(pluginId, key);
|
||||
if (!record) return undefined;
|
||||
try {
|
||||
return this.safeStorage.decryptString(record.ciphertext);
|
||||
} catch {
|
||||
throw new PluginRpcError(RPC_ERRORS.dataLoss, "Plugin secret could not be decrypted");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -571,3 +571,18 @@ test("live provider backfill does not resurrect explicit unbind tombstones", (co
|
||||
assert.equal(store.resolveSyncProviderPlugin("com.example.sync"), undefined);
|
||||
database.close();
|
||||
});
|
||||
|
||||
test("getPlaintext reads only the calling plugin's own encrypted secrets and never leaks across plugins", (context) => {
|
||||
const database = createDatabase(context);
|
||||
const store = new PluginSecretStore({
|
||||
database,
|
||||
safeStorage: fakeSafeStorage(),
|
||||
});
|
||||
store.set("com.example.db", "conn:pg:password", "pg-secret-123");
|
||||
assert.equal(store.getPlaintext("com.example.db", "conn:pg:password"), "pg-secret-123");
|
||||
assert.equal(store.getPlaintext("com.example.db", "conn:missing"), undefined);
|
||||
assert.equal(store.getPlaintext("com.example.other", "conn:pg:password"), undefined);
|
||||
store.delete("com.example.db", "conn:pg:password");
|
||||
assert.equal(store.getPlaintext("com.example.db", "conn:pg:password"), undefined);
|
||||
database.close();
|
||||
});
|
||||
@@ -39,6 +39,15 @@ function registerSecurePluginCapabilities(registry, options) {
|
||||
validateParams: (params) => assertSecretParams(params),
|
||||
authorization: (params) => secretAuthorization(params, "Read"),
|
||||
});
|
||||
registry.registerRequest("secrets.getPlaintext", async ({ key }, context) => {
|
||||
await context.assertActive();
|
||||
const value = options.secretStore.getPlaintext(context.pluginId, key);
|
||||
return value === undefined ? { found: false } : { found: true, value };
|
||||
}, {
|
||||
metadata: { capability: "secrets", mutating: false, permission: "secrets" },
|
||||
validateParams: (params) => assertSecretParams(params),
|
||||
authorization: (params) => secretAuthorization(params, "Read"),
|
||||
});
|
||||
registry.registerRequest("secrets.set", async ({ key, value }, context) => {
|
||||
await context.assertActive();
|
||||
return { secret: options.secretStore.set(context.pluginId, key, value) };
|
||||
|
||||
@@ -334,3 +334,29 @@ test("networkBroker.validate preserves credentialLease for registry dispatch", (
|
||||
assert.equal(validated.authorization.scheme, "Basic");
|
||||
assert.equal(validated.authorization.username, "alice");
|
||||
});
|
||||
|
||||
test("secrets.getPlaintext reads only the calling plugin's own encrypted secrets and checks runtime liveness", async () => {
|
||||
const store = new Map([["com.example.db\0conn:pg", "s3cr3t-pg-pass"]]);
|
||||
const requests = createRegistrations({
|
||||
getPlaintext(pluginId, key) {
|
||||
return store.get(`${pluginId}\0${key}`);
|
||||
},
|
||||
getReference() { return null; },
|
||||
set() { return { kind: "secret", id: "0".repeat(32), key: "k" }; },
|
||||
delete() {},
|
||||
});
|
||||
const ownCtx = { pluginId: "com.example.db", async assertActive() {} };
|
||||
const otherCtx = { pluginId: "com.example.other", async assertActive() {} };
|
||||
assert.deepEqual(
|
||||
await requests.get("secrets.getPlaintext")({ key: "conn:pg" }, ownCtx),
|
||||
{ found: true, value: "s3cr3t-pg-pass" },
|
||||
);
|
||||
assert.deepEqual(
|
||||
await requests.get("secrets.getPlaintext")({ key: "conn:pg" }, otherCtx),
|
||||
{ found: false },
|
||||
);
|
||||
await assert.rejects(
|
||||
requests.get("secrets.getPlaintext")({ key: "conn:pg" }, { pluginId: "com.example.db", async assertActive() { throw new Error("inactive"); } }),
|
||||
/inactive/,
|
||||
);
|
||||
});
|
||||
@@ -2,23 +2,87 @@
|
||||
const path = require("node:path");
|
||||
const { readContainedFile } = require("./pluginProtocol.cjs");
|
||||
const { inspectContributionIconSource, createBoundedIconRasterizer } = require("./contributionIconService.cjs");
|
||||
const { createIsolatedContributionIconRasterizer } = require("./contributionIconRasterizer.cjs");
|
||||
const { createPooledContributionIconRasterizer } = require("./contributionIconRasterizer.cjs");
|
||||
|
||||
const MAX_VIEW_RESOURCE_CACHE_ENTRIES = 256;
|
||||
const MAX_VIEW_RESOURCE_CACHE_BYTES = 24 * 1024 * 1024;
|
||||
|
||||
function buildCacheKey(plugin, resource) {
|
||||
if (!plugin || typeof plugin.id !== "string" || typeof plugin.activeVersion !== "string") return null;
|
||||
return JSON.stringify([plugin.id, plugin.activeVersion, plugin.archiveSha256 ?? "", resource]);
|
||||
}
|
||||
|
||||
class PluginViewResources {
|
||||
constructor({ electron, packageStore }) {
|
||||
this.packageStore = packageStore;
|
||||
this.rasterize = createBoundedIconRasterizer(createIsolatedContributionIconRasterizer(electron), { maxConcurrent: 2, maxQueued: 16 });
|
||||
this.pooledRasterizer = createPooledContributionIconRasterizer(electron);
|
||||
this.rasterize = createBoundedIconRasterizer(this.pooledRasterizer, { maxConcurrent: 8, maxQueued: 256 });
|
||||
this.cache = new Map();
|
||||
this.cacheBytes = 0;
|
||||
this.pending = new Map();
|
||||
}
|
||||
|
||||
#getCached(key) {
|
||||
if (!key || !this.cache.has(key)) return undefined;
|
||||
const value = this.cache.get(key);
|
||||
this.cache.delete(key);
|
||||
this.cache.set(key, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
#setCached(key, value) {
|
||||
if (!key) return;
|
||||
const size = value.url.length;
|
||||
if (size > MAX_VIEW_RESOURCE_CACHE_BYTES) return;
|
||||
if (this.cache.has(key)) {
|
||||
this.cacheBytes -= this.cache.get(key).url.length;
|
||||
this.cache.delete(key);
|
||||
}
|
||||
while (this.cache.size >= MAX_VIEW_RESOURCE_CACHE_ENTRIES || this.cacheBytes + size > MAX_VIEW_RESOURCE_CACHE_BYTES) {
|
||||
const oldestKey = this.cache.keys().next().value;
|
||||
if (oldestKey === undefined) break;
|
||||
this.cacheBytes -= this.cache.get(oldestKey).url.length;
|
||||
this.cache.delete(oldestKey);
|
||||
}
|
||||
this.cache.set(key, value);
|
||||
this.cacheBytes += size;
|
||||
}
|
||||
|
||||
async image(plugin, resource) {
|
||||
if (typeof resource !== 'string' || resource.length > 256 || !/^[a-zA-Z0-9_-][a-zA-Z0-9_./-]*$/.test(resource)
|
||||
|| resource.split('/').some((part) => !part || part === '.' || part === '..')) throw new TypeError('Invalid plugin image path');
|
||||
const root = await this.packageStore.preparePackageRoot(plugin);
|
||||
const file = await readContainedFile(root, resource.split('/'), 512 * 1024);
|
||||
if (path.extname(resource).toLowerCase() === '.svg' && /<!DOCTYPE|<\?xml-stylesheet|\b(?:href|src)\s*=|@import|url\s*\(/i.test(file.body.toString('utf8'))) throw new Error('Plugin SVG references are unavailable');
|
||||
const inspected = inspectContributionIconSource(file.body, path.extname(resource).toLowerCase());
|
||||
const png = await this.rasterize({ body: file.body, ...inspected, maxEdge: 2048 });
|
||||
if (png.length > 4 * 1024 * 1024) throw new Error('Plugin image exceeds size limit');
|
||||
inspectContributionIconSource(png, '.png', 2048);
|
||||
return { url: `data:image/png;base64,${png.toString('base64')}` };
|
||||
const cacheKey = buildCacheKey(plugin, resource);
|
||||
const cached = this.#getCached(cacheKey);
|
||||
if (cached) return cached;
|
||||
if (cacheKey && this.pending.has(cacheKey)) return this.pending.get(cacheKey);
|
||||
|
||||
const task = (async () => {
|
||||
const root = await this.packageStore.preparePackageRoot(plugin);
|
||||
const file = await readContainedFile(root, resource.split('/'), 512 * 1024);
|
||||
if (path.extname(resource).toLowerCase() === '.svg' && /<!DOCTYPE|<\?xml-stylesheet|\b(?:href|src)\s*=|@import|url\s*\(/i.test(file.body.toString('utf8'))) throw new Error('Plugin SVG references are unavailable');
|
||||
const inspected = inspectContributionIconSource(file.body, path.extname(resource).toLowerCase());
|
||||
const png = await this.rasterize({ body: file.body, ...inspected, maxEdge: 2048 });
|
||||
if (png.length > 4 * 1024 * 1024) throw new Error('Plugin image exceeds size limit');
|
||||
inspectContributionIconSource(png, '.png', 2048);
|
||||
const result = { url: `data:image/png;base64,${png.toString('base64')}` };
|
||||
this.#setCached(cacheKey, result);
|
||||
return result;
|
||||
})();
|
||||
|
||||
if (cacheKey) {
|
||||
this.pending.set(cacheKey, task);
|
||||
task.finally(() => {
|
||||
if (this.pending.get(cacheKey) === task) this.pending.delete(cacheKey);
|
||||
}).catch(() => {});
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this.pooledRasterizer?.dispose?.();
|
||||
this.cache.clear();
|
||||
this.cacheBytes = 0;
|
||||
this.pending.clear();
|
||||
}
|
||||
}
|
||||
module.exports = { PluginViewResources };
|
||||
@@ -21,3 +21,31 @@ test('view images reject traversal, symlink escapes, external SVGs and oversize
|
||||
}
|
||||
assert.equal(decoded, 0);
|
||||
});
|
||||
|
||||
test('view images cache decoded results by plugin version/hash and never cache transient failures', async (t) => {
|
||||
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'netcatty-view-image-cache-'));
|
||||
t.after(() => fs.rm(directory, { recursive: true, force: true }));
|
||||
const root = path.join(directory, 'package'); await fs.mkdir(root);
|
||||
// Minimal valid 1x1 PNG header/bytes
|
||||
const pngHeader = Buffer.from([
|
||||
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
||||
0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
|
||||
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
|
||||
0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89,
|
||||
]);
|
||||
await fs.writeFile(path.join(root, 'icon.png'), pngHeader);
|
||||
const resources = new PluginViewResources({ electron: {}, packageStore: { preparePackageRoot: async () => root } });
|
||||
let attempts = 0;
|
||||
resources.rasterize = async () => {
|
||||
attempts += 1;
|
||||
if (attempts === 1) throw new Error('transient timeout');
|
||||
return pngHeader;
|
||||
};
|
||||
const plugin = { id: 'com.test.db', activeVersion: '0.2.0', archiveSha256: 'abc123' };
|
||||
await assert.rejects(resources.image(plugin, 'icon.png'), /transient timeout/);
|
||||
const first = await resources.image(plugin, 'icon.png');
|
||||
const second = await resources.image(plugin, 'icon.png');
|
||||
assert.equal(first.url, second.url);
|
||||
assert.equal(attempts, 2);
|
||||
resources.dispose();
|
||||
});
|
||||
@@ -493,11 +493,11 @@ ipcRenderer.on("netcatty:exit", (_event, payload) => {
|
||||
|
||||
// Chain progress events (for jump host connections)
|
||||
ipcRenderer.on("netcatty:chain:progress", (_event, payload) => {
|
||||
const { sessionId, hop, total, label, status, error } = payload;
|
||||
const { sessionId, hop, total, label, status, error, address } = payload;
|
||||
// Notify all registered chain progress listeners
|
||||
chainProgressListeners.forEach((cb) => {
|
||||
try {
|
||||
cb(sessionId, hop, total, label, status, error);
|
||||
cb(sessionId, hop, total, label, status, error, address);
|
||||
} catch (err) {
|
||||
console.error("Chain progress callback failed", err);
|
||||
}
|
||||
|
||||
+3
-3
@@ -1,14 +1,14 @@
|
||||
{
|
||||
version = "1.1.90";
|
||||
version = "1.1.91";
|
||||
|
||||
sources = {
|
||||
x86_64-linux = {
|
||||
appImageArch = "x86_64";
|
||||
hash = "sha256-oa/T3Zey0FHsH+SOt4C1H4CT6aZRJta+x4x/11EAOJE=";
|
||||
hash = "sha256-+JUalTjinzIH2sIovwtwhEP6IaaYPZDgfPoj0rVDOsM=";
|
||||
};
|
||||
aarch64-linux = {
|
||||
appImageArch = "arm64";
|
||||
hash = "sha256-r5hr3+gpIGrv9XJ7PQkHCdhOd2COkhELMHlnr3xIG7A=";
|
||||
hash = "sha256-kDwH7pLgaPoC/4AqoQhlZDo8/dbEL9Il2H+mPlUgu64=";
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -12,7 +12,8 @@ test("byte stream packages require negotiated features and exact resources in op
|
||||
for (const resources of [["*"], ["tcp://*:3306"], ["tcp://host:3306/"], ["udp://host:3306"], ["https://host"]]) {
|
||||
assert.equal(validateManifestValue({ ...manifest, permissions: { required: ["commands", "views"], optional: [{ permission: "network.stream", resources }] } }).valid, false);
|
||||
}
|
||||
assert.equal(validateManifestValue({ ...manifest, permissions: { required: ["commands", "views"], optional: ["network.stream"] } }).valid, false);
|
||||
assert.equal(validateManifestValue({ ...manifest, permissions: { required: ["commands", "views"], optional: ["network.stream"] } }).valid, true);
|
||||
assert.equal(validateManifestValue({ ...manifest, permissions: { required: ["commands", "views", "network.stream"] } }).valid, false);
|
||||
assert.equal(checkPluginCompatibility(manifest, { netcattyVersion: "1.0.0", features: [] }).compatible, false);
|
||||
assert.equal(checkPluginCompatibility(manifest, { netcattyVersion: "1.0.0", features: ["network.byte-streams"] }).compatible, true);
|
||||
});
|
||||
@@ -56,7 +56,7 @@
|
||||
"RpcLimits": {
|
||||
"description": "Host-enforced byte limit for one JSON-RPC control message. Larger payloads must use a stream.",
|
||||
"const": {
|
||||
"maxJsonBytes": 1048576
|
||||
"maxJsonBytes": 8388608
|
||||
}
|
||||
},
|
||||
"SafeUnsignedInteger": {
|
||||
@@ -576,9 +576,41 @@
|
||||
},
|
||||
"kind": {
|
||||
"const": "network.stream.connectViaHost"
|
||||
},
|
||||
"durable": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": [
|
||||
"kind",
|
||||
"hostBindingToken",
|
||||
"endpoint"
|
||||
],
|
||||
"properties": {
|
||||
"kind": {
|
||||
"const": "network.stream.connectViaHost"
|
||||
},
|
||||
"hostBindingToken": {
|
||||
"type": "string",
|
||||
"minLength": 16,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[A-Za-z0-9._-]+$"
|
||||
},
|
||||
"endpoint": {
|
||||
"$ref": "#/$defs/ByteStreamEndpoint"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/HostByteStreamConfirmRequest"
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/HostByteStreamTlsConfirmRequest"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -820,12 +852,14 @@
|
||||
"HostInteractionLimits": {
|
||||
"const": {
|
||||
"textBytes": 4096,
|
||||
"requestBytes": 65536,
|
||||
"clipboardBytes": 4194304,
|
||||
"requestBytes": 4259840,
|
||||
"items": 100,
|
||||
"pendingPerRuntime": 1,
|
||||
"pendingTotal": 8,
|
||||
"requestsPerMinute": 10,
|
||||
"timeoutMs": 60000
|
||||
"requestsPerMinute": 60,
|
||||
"timeoutMs": 60000,
|
||||
"fileMaxBytes": 67108864
|
||||
}
|
||||
},
|
||||
"HostInteractionFeature": {
|
||||
@@ -957,7 +991,7 @@
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"maxLength": 4096,
|
||||
"maxLength": 4194304,
|
||||
"pattern": "^[^\\u0000]*$"
|
||||
}
|
||||
},
|
||||
@@ -1013,7 +1047,7 @@
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 4096,
|
||||
"maxLength": 4194304,
|
||||
"pattern": "^[^\\u0000]*$"
|
||||
},
|
||||
{
|
||||
@@ -1035,6 +1069,25 @@
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/ByteStreamConnectionDescriptor"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": [
|
||||
"cancelled",
|
||||
"approved"
|
||||
],
|
||||
"properties": {
|
||||
"cancelled": {
|
||||
"const": false
|
||||
},
|
||||
"approved": {
|
||||
"const": true
|
||||
},
|
||||
"remember": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -1086,6 +1139,9 @@
|
||||
},
|
||||
"scriptsRun": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"remember": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -1202,6 +1258,14 @@
|
||||
"$ref": "#/$defs/VaultHostEditFields"
|
||||
}
|
||||
]
|
||||
},
|
||||
"durableHostId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 128
|
||||
},
|
||||
"autoCommit": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -1556,14 +1620,14 @@
|
||||
},
|
||||
"ByteStreamLimits": {
|
||||
"const": {
|
||||
"connectionsPerRuntime": 4,
|
||||
"connectionsTotal": 64,
|
||||
"connectionsPerRuntime": 24,
|
||||
"connectionsTotal": 128,
|
||||
"chunkBytes": 65536,
|
||||
"bufferBytes": 65536,
|
||||
"connectionBytes": 8388608,
|
||||
"connectionBytes": 536870912,
|
||||
"connectMs": 10000,
|
||||
"idleMs": 30000,
|
||||
"lifetimeMs": 120000
|
||||
"idleMs": 1800000,
|
||||
"lifetimeMs": 28800000
|
||||
}
|
||||
},
|
||||
"ByteStreamEndpoint": {
|
||||
@@ -1581,6 +1645,23 @@
|
||||
"properties": {
|
||||
"endpoint": {
|
||||
"$ref": "#/$defs/ByteStreamEndpoint"
|
||||
},
|
||||
"allowLocal": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"allowSelfSigned": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"caPem": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 65536
|
||||
},
|
||||
"servername": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 253,
|
||||
"pattern": "^[A-Za-z0-9.-]+$"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -1623,6 +1704,12 @@
|
||||
},
|
||||
"windowBytes": {
|
||||
"const": 65536
|
||||
},
|
||||
"hostBindingToken": {
|
||||
"type": "string",
|
||||
"minLength": 16,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[A-Za-z0-9._-]+$"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -1964,10 +2051,7 @@
|
||||
"PermissionDeclaration": {
|
||||
"oneOf": [
|
||||
{
|
||||
"$ref": "#/$defs/PluginPermission",
|
||||
"not": {
|
||||
"const": "network.stream"
|
||||
}
|
||||
"$ref": "#/$defs/PluginPermission"
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/PermissionResourceDeclaration"
|
||||
@@ -2591,14 +2675,14 @@
|
||||
},
|
||||
"mutations": {
|
||||
"type": "array",
|
||||
"maxItems": 2048,
|
||||
"maxItems": 4096,
|
||||
"items": {
|
||||
"$ref": "#/$defs/JsonValue"
|
||||
}
|
||||
},
|
||||
"css": {
|
||||
"type": "string",
|
||||
"maxLength": 65536
|
||||
"maxLength": 131072
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -2653,12 +2737,16 @@
|
||||
"compositionend",
|
||||
"dismiss",
|
||||
"submit",
|
||||
"reset"
|
||||
"reset",
|
||||
"dblclick",
|
||||
"contextmenu",
|
||||
"scroll",
|
||||
"widget"
|
||||
]
|
||||
},
|
||||
"value": {
|
||||
"type": "string",
|
||||
"maxLength": 8192
|
||||
"maxLength": 131072
|
||||
},
|
||||
"checked": {
|
||||
"type": "boolean"
|
||||
@@ -2695,6 +2783,47 @@
|
||||
"type": "string",
|
||||
"maxLength": 8192
|
||||
}
|
||||
},
|
||||
"x": {
|
||||
"type": "number"
|
||||
},
|
||||
"y": {
|
||||
"type": "number"
|
||||
},
|
||||
"scrollTop": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"scrollLeft": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"clientHeight": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"clientWidth": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"selectionStart": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 131072
|
||||
},
|
||||
"selectionEnd": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 131072
|
||||
},
|
||||
"widgetEvent": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 64,
|
||||
"pattern": "^[a-zA-Z][a-zA-Z0-9_-]{0,63}$"
|
||||
},
|
||||
"detail": {
|
||||
"$ref": "#/$defs/JsonValue"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
@@ -8664,35 +8793,387 @@
|
||||
},
|
||||
"HostByteStreamLimits": {
|
||||
"const": {
|
||||
"connectionsPerRuntime": 4,
|
||||
"connectionsTotal": 64,
|
||||
"connectionsPerRuntime": 24,
|
||||
"connectionsTotal": 128,
|
||||
"chunkBytes": 65536,
|
||||
"bufferBytes": 65536,
|
||||
"connectionBytes": 67108864,
|
||||
"connectionBytes": 536870912,
|
||||
"connectMs": 120000,
|
||||
"idleMs": 300000,
|
||||
"lifetimeMs": 1800000
|
||||
"idleMs": 1800000,
|
||||
"lifetimeMs": 28800000
|
||||
}
|
||||
},
|
||||
"HostByteStreamConnectRequest": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"required": [
|
||||
"target",
|
||||
"expectedRevision",
|
||||
"endpoint"
|
||||
],
|
||||
"properties": {
|
||||
"target": {
|
||||
"$ref": "#/$defs/VaultHostRef"
|
||||
},
|
||||
"expectedRevision": {
|
||||
"type": "string",
|
||||
"maxLength": 128,
|
||||
"pattern": "^[^\\u0000-\\u001f\\u007f]*$",
|
||||
"minLength": 1
|
||||
},
|
||||
"endpoint": {
|
||||
"$ref": "#/$defs/ByteStreamEndpoint"
|
||||
},
|
||||
"durable": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"required": [
|
||||
"hostBindingToken",
|
||||
"endpoint"
|
||||
],
|
||||
"properties": {
|
||||
"hostBindingToken": {
|
||||
"type": "string",
|
||||
"minLength": 16,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[A-Za-z0-9._-]+$"
|
||||
},
|
||||
"endpoint": {
|
||||
"$ref": "#/$defs/ByteStreamEndpoint"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
]
|
||||
},
|
||||
"ByteStreamUpgradeTlsRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"target",
|
||||
"expectedRevision",
|
||||
"endpoint"
|
||||
"handleId"
|
||||
],
|
||||
"properties": {
|
||||
"target": {
|
||||
"$ref": "#/$defs/VaultHostRef"
|
||||
},
|
||||
"expectedRevision": {
|
||||
"handleId": {
|
||||
"type": "string",
|
||||
"maxLength": 128,
|
||||
"pattern": "^[^\\u0000-\\u001f\\u007f]*$",
|
||||
"minLength": 1
|
||||
"format": "uuid"
|
||||
},
|
||||
"servername": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 253,
|
||||
"pattern": "^[A-Za-z0-9.-]+$"
|
||||
},
|
||||
"allowSelfSigned": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"caPem": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 65536
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"ByteStreamUpgradeTlsResult": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"upgraded",
|
||||
"authorized"
|
||||
],
|
||||
"properties": {
|
||||
"upgraded": {
|
||||
"const": true
|
||||
},
|
||||
"authorized": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"protocol": {
|
||||
"type": "string",
|
||||
"maxLength": 64
|
||||
},
|
||||
"fingerprint256": {
|
||||
"type": "string",
|
||||
"maxLength": 128
|
||||
},
|
||||
"subject": {
|
||||
"type": "string",
|
||||
"maxLength": 512
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"VaultHostBindingRevokeParams": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"hostBindingToken"
|
||||
],
|
||||
"properties": {
|
||||
"hostBindingToken": {
|
||||
"type": "string",
|
||||
"minLength": 16,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[A-Za-z0-9._-]+$"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostByteStreamConfirmRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"kind",
|
||||
"endpoint",
|
||||
"host",
|
||||
"port",
|
||||
"transport",
|
||||
"isLocal"
|
||||
],
|
||||
"properties": {
|
||||
"kind": {
|
||||
"const": "network.stream.confirm"
|
||||
},
|
||||
"endpoint": {
|
||||
"$ref": "#/$defs/ByteStreamEndpoint"
|
||||
},
|
||||
"host": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 253
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 65535
|
||||
},
|
||||
"transport": {
|
||||
"enum": [
|
||||
"tcp",
|
||||
"tls"
|
||||
]
|
||||
},
|
||||
"isLocal": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostByteStreamTlsConfirmRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"kind",
|
||||
"endpoint",
|
||||
"fingerprint256",
|
||||
"subject",
|
||||
"issuer",
|
||||
"validTo",
|
||||
"reason"
|
||||
],
|
||||
"properties": {
|
||||
"kind": {
|
||||
"const": "network.stream.tlsConfirm"
|
||||
},
|
||||
"endpoint": {
|
||||
"$ref": "#/$defs/ByteStreamEndpoint"
|
||||
},
|
||||
"servername": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 253
|
||||
},
|
||||
"fingerprint256": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 128
|
||||
},
|
||||
"subject": {
|
||||
"type": "string",
|
||||
"maxLength": 512
|
||||
},
|
||||
"issuer": {
|
||||
"type": "string",
|
||||
"maxLength": 512
|
||||
},
|
||||
"validTo": {
|
||||
"type": "string",
|
||||
"maxLength": 128
|
||||
},
|
||||
"reason": {
|
||||
"type": "string",
|
||||
"maxLength": 256
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostFileDialogFilter": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"name",
|
||||
"extensions"
|
||||
],
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 64,
|
||||
"pattern": "^[^\\u0000-\\u001f\\u007f]*$"
|
||||
},
|
||||
"extensions": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"maxItems": 32,
|
||||
"items": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 32,
|
||||
"pattern": "^(\\*|[A-Za-z0-9][A-Za-z0-9._-]{0,31})$"
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostOpenFileRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 128,
|
||||
"pattern": "^[^\\u0000-\\u001f\\u007f]*$"
|
||||
},
|
||||
"filters": {
|
||||
"type": "array",
|
||||
"maxItems": 32,
|
||||
"items": {
|
||||
"$ref": "#/$defs/HostFileDialogFilter"
|
||||
}
|
||||
},
|
||||
"readAs": {
|
||||
"enum": [
|
||||
"bytes",
|
||||
"utf8"
|
||||
]
|
||||
},
|
||||
"maxBytes": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 67108864
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostSaveFileRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 128,
|
||||
"pattern": "^[^\\u0000-\\u001f\\u007f]*$"
|
||||
},
|
||||
"defaultName": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 256,
|
||||
"pattern": "^[^\\u0000-\\u001f\\u007f/\\\\]+$"
|
||||
},
|
||||
"filters": {
|
||||
"type": "array",
|
||||
"maxItems": 32,
|
||||
"items": {
|
||||
"$ref": "#/$defs/HostFileDialogFilter"
|
||||
}
|
||||
},
|
||||
"data": {
|
||||
"type": "string",
|
||||
"maxLength": 5592408
|
||||
},
|
||||
"encoding": {
|
||||
"enum": [
|
||||
"base64",
|
||||
"utf8"
|
||||
]
|
||||
},
|
||||
"deferredWrite": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostFileHandleReadRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"handleId"
|
||||
],
|
||||
"properties": {
|
||||
"handleId": {
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
},
|
||||
"offset": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 67108864
|
||||
},
|
||||
"length": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 4194304
|
||||
},
|
||||
"encoding": {
|
||||
"enum": [
|
||||
"base64",
|
||||
"utf8"
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostFileHandleWriteRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"handleId",
|
||||
"data"
|
||||
],
|
||||
"properties": {
|
||||
"handleId": {
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
},
|
||||
"data": {
|
||||
"type": "string",
|
||||
"maxLength": 5592408
|
||||
},
|
||||
"encoding": {
|
||||
"enum": [
|
||||
"base64",
|
||||
"utf8"
|
||||
]
|
||||
},
|
||||
"mode": {
|
||||
"enum": [
|
||||
"replace",
|
||||
"append"
|
||||
]
|
||||
},
|
||||
"commit": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
},
|
||||
"HostFileHandleCloseRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"handleId"
|
||||
],
|
||||
"properties": {
|
||||
"handleId": {
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
|
||||
@@ -366,7 +366,7 @@ test("required resource-scoped permissions declare activation-time bounds", () =
|
||||
assert.equal(validate({
|
||||
...validManifest,
|
||||
permissions: { optional: [permission] },
|
||||
}), permission !== "network.stream", `${permission}: ${JSON.stringify(validate.errors)}`);
|
||||
}), true, `${permission}: ${JSON.stringify(validate.errors)}`);
|
||||
assert.equal(validate({
|
||||
...validManifest,
|
||||
permissions: { optional: [{ permission, resources: [resource] }] },
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
export const PLUGIN_JSON_MAX_DEPTH = 128 as const;
|
||||
export const PLUGIN_JSON_MAX_NODES = 100000 as const;
|
||||
export const PLUGIN_WIRE_MAX_SAFE_INTEGER = 9007199254740991 as const;
|
||||
export const PLUGIN_RPC_MAX_JSON_BYTES = 1048576 as const;
|
||||
export const PLUGIN_HOST_INTERACTION_LIMITS = {"textBytes":4096,"requestBytes":65536,"items":100,"pendingPerRuntime":1,"pendingTotal":8,"requestsPerMinute":10,"timeoutMs":60000} as const;
|
||||
export const PLUGIN_BYTE_STREAM_LIMITS = {"connectionsPerRuntime":4,"connectionsTotal":64,"chunkBytes":65536,"bufferBytes":65536,"connectionBytes":8388608,"connectMs":10000,"idleMs":30000,"lifetimeMs":120000} as const;
|
||||
export const PLUGIN_RPC_MAX_JSON_BYTES = 8388608 as const;
|
||||
export const PLUGIN_HOST_INTERACTION_LIMITS = {"textBytes":4096,"clipboardBytes":4194304,"requestBytes":4259840,"items":100,"pendingPerRuntime":1,"pendingTotal":8,"requestsPerMinute":60,"timeoutMs":60000,"fileMaxBytes":67108864} as const;
|
||||
export const PLUGIN_BYTE_STREAM_LIMITS = {"connectionsPerRuntime":24,"connectionsTotal":128,"chunkBytes":65536,"bufferBytes":65536,"connectionBytes":536870912,"connectMs":10000,"idleMs":1800000,"lifetimeMs":28800000} as const;
|
||||
export const PLUGIN_RPC_ERROR_CODES = [-32700,-32600,-32601,-32602,-32603,-32001,-32002,-32003,-32004,-32005,-32006,-32007,-32008,-32009,-32010,-32011,-32012,-32013,-32014,-32015,-32016] as const;
|
||||
export const PLUGIN_STREAM_MAX_ID_LENGTH = 128 as const;
|
||||
export const PLUGIN_STREAM_MAX_CHUNK_BYTES = 16777216 as const;
|
||||
|
||||
@@ -83,10 +83,15 @@ export type ByteStreamConnectionDescriptor = {
|
||||
inputStreamId: StreamId;
|
||||
outputStreamId: StreamId;
|
||||
windowBytes: 65536;
|
||||
hostBindingToken?: string;
|
||||
};
|
||||
|
||||
export type ByteStreamConnectRequest = {
|
||||
endpoint: ByteStreamEndpoint;
|
||||
allowLocal?: boolean;
|
||||
allowSelfSigned?: boolean;
|
||||
caPem?: string;
|
||||
servername?: string;
|
||||
};
|
||||
|
||||
export type ByteStreamEndpoint = string;
|
||||
@@ -97,7 +102,22 @@ export type ByteStreamHandleRequest = {
|
||||
handleId: string;
|
||||
};
|
||||
|
||||
export type ByteStreamLimits = {"connectionsPerRuntime":4,"connectionsTotal":64,"chunkBytes":65536,"bufferBytes":65536,"connectionBytes":8388608,"connectMs":10000,"idleMs":30000,"lifetimeMs":120000};
|
||||
export type ByteStreamLimits = {"connectionsPerRuntime":24,"connectionsTotal":128,"chunkBytes":65536,"bufferBytes":65536,"connectionBytes":536870912,"connectMs":10000,"idleMs":1800000,"lifetimeMs":28800000};
|
||||
|
||||
export type ByteStreamUpgradeTlsRequest = {
|
||||
handleId: string;
|
||||
servername?: string;
|
||||
allowSelfSigned?: boolean;
|
||||
caPem?: string;
|
||||
};
|
||||
|
||||
export type ByteStreamUpgradeTlsResult = {
|
||||
upgraded: true;
|
||||
authorized: boolean;
|
||||
protocol?: string;
|
||||
fingerprint256?: string;
|
||||
subject?: string;
|
||||
};
|
||||
|
||||
export type CommandContribution = {
|
||||
id: ContributionId;
|
||||
@@ -196,15 +216,39 @@ export type FeatureId = string;
|
||||
|
||||
export type FilesystemDirectoryEnumerationFeature = "filesystem.directory-enumeration";
|
||||
|
||||
export type HostByteStreamConnectRequest = {
|
||||
export type HostByteStreamConfirmRequest = {
|
||||
kind: "network.stream.confirm";
|
||||
endpoint: ByteStreamEndpoint;
|
||||
host: string;
|
||||
port: number;
|
||||
transport: "tcp" | "tls";
|
||||
isLocal: boolean;
|
||||
};
|
||||
|
||||
export type HostByteStreamConnectRequest = ({
|
||||
target: VaultHostRef;
|
||||
expectedRevision: string;
|
||||
endpoint: ByteStreamEndpoint;
|
||||
};
|
||||
durable?: boolean;
|
||||
}) | ({
|
||||
hostBindingToken: string;
|
||||
endpoint: ByteStreamEndpoint;
|
||||
});
|
||||
|
||||
export type HostByteStreamFeature = "network.host-byte-streams";
|
||||
|
||||
export type HostByteStreamLimits = {"connectionsPerRuntime":4,"connectionsTotal":64,"chunkBytes":65536,"bufferBytes":65536,"connectionBytes":67108864,"connectMs":120000,"idleMs":300000,"lifetimeMs":1800000};
|
||||
export type HostByteStreamLimits = {"connectionsPerRuntime":24,"connectionsTotal":128,"chunkBytes":65536,"bufferBytes":65536,"connectionBytes":536870912,"connectMs":120000,"idleMs":1800000,"lifetimeMs":28800000};
|
||||
|
||||
export type HostByteStreamTlsConfirmRequest = {
|
||||
kind: "network.stream.tlsConfirm";
|
||||
endpoint: ByteStreamEndpoint;
|
||||
servername?: string;
|
||||
fingerprint256: string;
|
||||
subject: string;
|
||||
issuer: string;
|
||||
validTo: string;
|
||||
reason: string;
|
||||
};
|
||||
|
||||
export type HostClipboardReadRequest = {
|
||||
kind: "clipboard.read";
|
||||
@@ -219,7 +263,7 @@ export type HostClipboardWriteRequest = {
|
||||
|
||||
export type HostDrawnViewEvent = {
|
||||
nodeId: string;
|
||||
type: "click" | "input" | "change" | "keydown" | "keyup" | "focusin" | "focusout" | "compositionstart" | "compositionupdate" | "compositionend" | "dismiss" | "submit" | "reset";
|
||||
type: "click" | "input" | "change" | "keydown" | "keyup" | "focusin" | "focusout" | "compositionstart" | "compositionupdate" | "compositionend" | "dismiss" | "submit" | "reset" | "dblclick" | "contextmenu" | "scroll" | "widget";
|
||||
value?: string;
|
||||
checked?: boolean;
|
||||
eventId?: number;
|
||||
@@ -230,6 +274,16 @@ export type HostDrawnViewEvent = {
|
||||
altKey?: boolean;
|
||||
shiftKey?: boolean;
|
||||
values?: Array<string>;
|
||||
x?: number;
|
||||
y?: number;
|
||||
scrollTop?: number;
|
||||
scrollLeft?: number;
|
||||
clientHeight?: number;
|
||||
clientWidth?: number;
|
||||
selectionStart?: number;
|
||||
selectionEnd?: number;
|
||||
widgetEvent?: string;
|
||||
detail?: JsonValue;
|
||||
};
|
||||
|
||||
export type HostDrawnViewMessage = ({
|
||||
@@ -261,6 +315,30 @@ export type HostDrawnViewOpenRequest = {
|
||||
|
||||
export type HostDrawnViewsFeature = "views.host-drawn";
|
||||
|
||||
export type HostFileDialogFilter = {
|
||||
name: string;
|
||||
extensions: Array<string>;
|
||||
};
|
||||
|
||||
export type HostFileHandleCloseRequest = {
|
||||
handleId: string;
|
||||
};
|
||||
|
||||
export type HostFileHandleReadRequest = {
|
||||
handleId: string;
|
||||
offset?: number;
|
||||
length?: number;
|
||||
encoding?: "base64" | "utf8";
|
||||
};
|
||||
|
||||
export type HostFileHandleWriteRequest = {
|
||||
handleId: string;
|
||||
data: string;
|
||||
encoding?: "base64" | "utf8";
|
||||
mode?: "replace" | "append";
|
||||
commit?: boolean;
|
||||
};
|
||||
|
||||
export type HostInputRequest = {
|
||||
kind: "input";
|
||||
title: string;
|
||||
@@ -276,7 +354,7 @@ export type HostInteractionEvent = (HostInteractionPrompt) | (HostInteractionClo
|
||||
|
||||
export type HostInteractionFeature = "host.interactions";
|
||||
|
||||
export type HostInteractionLimits = {"textBytes":4096,"requestBytes":65536,"items":100,"pendingPerRuntime":1,"pendingTotal":8,"requestsPerMinute":10,"timeoutMs":60000};
|
||||
export type HostInteractionLimits = {"textBytes":4096,"clipboardBytes":4194304,"requestBytes":4259840,"items":100,"pendingPerRuntime":1,"pendingTotal":8,"requestsPerMinute":60,"timeoutMs":60000,"fileMaxBytes":67108864};
|
||||
|
||||
export type HostInteractionPrompt = {
|
||||
permissionMode?: "allow" | "ask" | "deny";
|
||||
@@ -293,6 +371,8 @@ export type HostInteractionPrompt = {
|
||||
terminalLabel?: string;
|
||||
vaultTarget?: VaultHostLocalTarget;
|
||||
reviewedDraft?: (VaultHostCreateFields) | (VaultHostEditFields);
|
||||
durableHostId?: string;
|
||||
autoCommit?: boolean;
|
||||
};
|
||||
|
||||
export type HostInteractionReceipt = (boolean) | ({
|
||||
@@ -309,6 +389,7 @@ export type HostInteractionResponse = {
|
||||
resources?: VaultHostSelectedResources;
|
||||
draft?: (VaultHostCreateFields) | (VaultHostEditFields);
|
||||
scriptsRun?: boolean;
|
||||
remember?: boolean;
|
||||
};
|
||||
|
||||
export type HostInteractionResult = ({
|
||||
@@ -316,7 +397,18 @@ export type HostInteractionResult = ({
|
||||
}) | ({
|
||||
cancelled: false;
|
||||
value: (string) | (true) | (SharedTerminalSelection);
|
||||
}) | (VaultHostSelectedResult) | (VaultHostActionAccepted) | (ByteStreamConnectionDescriptor);
|
||||
}) | (VaultHostSelectedResult) | (VaultHostActionAccepted) | (ByteStreamConnectionDescriptor) | ({
|
||||
cancelled: false;
|
||||
approved: true;
|
||||
remember?: boolean;
|
||||
});
|
||||
|
||||
export type HostOpenFileRequest = {
|
||||
title?: string;
|
||||
filters?: Array<HostFileDialogFilter>;
|
||||
readAs?: "bytes" | "utf8";
|
||||
maxBytes?: number;
|
||||
};
|
||||
|
||||
export type HostQuickPickItem = {
|
||||
id: string;
|
||||
@@ -330,6 +422,15 @@ export type HostQuickPickRequest = {
|
||||
items: Array<HostQuickPickItem>;
|
||||
};
|
||||
|
||||
export type HostSaveFileRequest = {
|
||||
title?: string;
|
||||
defaultName?: string;
|
||||
filters?: Array<HostFileDialogFilter>;
|
||||
data?: string;
|
||||
encoding?: "base64" | "utf8";
|
||||
deferredWrite?: boolean;
|
||||
};
|
||||
|
||||
export type HostSingleLineInputText = string;
|
||||
|
||||
export type HostTerminalInputProposalRequest = {
|
||||
@@ -562,7 +663,7 @@ export type PermissionDecision = ({
|
||||
decision: "deny" | "cancel";
|
||||
});
|
||||
|
||||
export type PermissionDeclaration = Exclude<PluginPermission, "network.stream"> | PermissionResourceDeclaration;
|
||||
export type PermissionDeclaration = PluginPermission | PermissionResourceDeclaration;
|
||||
|
||||
export type PermissionGrantScope = "once" | "session" | "application" | "always";
|
||||
|
||||
@@ -1288,7 +1389,7 @@ export type RpcFailure = {
|
||||
|
||||
export type RpcId = (string) | (SafeUnsignedInteger);
|
||||
|
||||
export type RpcLimits = {"maxJsonBytes":1048576};
|
||||
export type RpcLimits = {"maxJsonBytes":8388608};
|
||||
|
||||
export type RpcMessage = (RpcRequest) | (RpcNotification) | (RpcSuccess) | (RpcFailure) | (RpcCancel) | (RpcProgressNotification) | (RuntimeInitializeRequest) | (TerminalInterceptorAttachmentRequest);
|
||||
|
||||
@@ -1760,12 +1861,21 @@ export type VaultHostActionRequest = ({
|
||||
expectedRevision: string;
|
||||
endpoint: ByteStreamEndpoint;
|
||||
kind: "network.stream.connectViaHost";
|
||||
});
|
||||
durable?: boolean;
|
||||
}) | ({
|
||||
kind: "network.stream.connectViaHost";
|
||||
hostBindingToken: string;
|
||||
endpoint: ByteStreamEndpoint;
|
||||
}) | (HostByteStreamConfirmRequest) | (HostByteStreamTlsConfirmRequest);
|
||||
|
||||
export type VaultHostActionResult = ({
|
||||
cancelled: true;
|
||||
}) | (VaultHostActionAccepted);
|
||||
|
||||
export type VaultHostBindingRevokeParams = {
|
||||
hostBindingToken: string;
|
||||
};
|
||||
|
||||
export type VaultHostConnectParams = {
|
||||
target: VaultHostRef;
|
||||
expectedRevision: string;
|
||||
|
||||
@@ -104,9 +104,12 @@ function subscribeControlPropertyMutations(container: HTMLElement, onMutation: (
|
||||
};
|
||||
}
|
||||
|
||||
const MAX_PLUGIN_CSS_LENGTH = 131072;
|
||||
const MAX_PLUGIN_EVENT_VALUE_LENGTH = 131072;
|
||||
|
||||
/** Build ordinary DOM in the isolated runtime; only validated data reaches the visible host. */
|
||||
export function registerHostDomView(views: PluginViews, viewId: string, mount: (container: HTMLElement, stateScope: string) => (() => void) | void, css = ''): Disposable {
|
||||
if (css.length > 65536) throw new TypeError('Plugin CSS exceeds the view limit');
|
||||
if (css.length > MAX_PLUGIN_CSS_LENGTH) throw new TypeError('Plugin CSS exceeds the view limit');
|
||||
type View = {
|
||||
container: HTMLDivElement;
|
||||
unmount: () => void;
|
||||
@@ -142,8 +145,51 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
|
||||
view.syncElementIndex();
|
||||
const element = view.elementsById.get(event.nodeId);
|
||||
if (!element || !(element instanceof HTMLElement)) return;
|
||||
if (event.type === 'dismiss') { element.dispatchEvent(new Event('netcatty-dismiss')); return; }
|
||||
if (event.type === 'click') {
|
||||
const eventType = event.type;
|
||||
if (eventType === 'dismiss') { element.dispatchEvent(new Event('netcatty-dismiss')); return; }
|
||||
if (eventType === 'widget') {
|
||||
element.dispatchEvent(new CustomEvent('netcatty-widget-event', {
|
||||
bubbles: false,
|
||||
detail: { widgetEvent: event.widgetEvent, detail: event.detail },
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (eventType === 'dblclick') {
|
||||
element.dispatchEvent(new MouseEvent('dblclick', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: event.x ?? 0,
|
||||
clientY: event.y ?? 0,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (eventType === 'contextmenu') {
|
||||
element.dispatchEvent(new MouseEvent('contextmenu', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
button: 2,
|
||||
clientX: event.x ?? 0,
|
||||
clientY: event.y ?? 0,
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (eventType === 'scroll') {
|
||||
try {
|
||||
if (typeof event.scrollTop === 'number') element.scrollTop = event.scrollTop;
|
||||
if (typeof event.scrollLeft === 'number') element.scrollLeft = event.scrollLeft;
|
||||
} catch {}
|
||||
element.dispatchEvent(new CustomEvent('scroll', {
|
||||
bubbles: false,
|
||||
detail: {
|
||||
scrollTop: event.scrollTop ?? 0,
|
||||
scrollLeft: event.scrollLeft ?? 0,
|
||||
clientHeight: event.clientHeight ?? 0,
|
||||
clientWidth: event.clientWidth ?? 0,
|
||||
},
|
||||
}));
|
||||
return;
|
||||
}
|
||||
if (eventType === 'click') {
|
||||
// The host already performed native checkbox/label behavior. Reproduce it
|
||||
// once for React's click-based change handler, without a second toggle.
|
||||
if (element instanceof HTMLInputElement && ['checkbox', 'radio'].includes(element.type) && event.checked !== undefined) {
|
||||
@@ -160,26 +206,34 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (event.type === 'reset' && element instanceof HTMLFormElement) { element.reset(); return; }
|
||||
if (event.type === 'submit') { const action = new Event(event.type, { bubbles: true, cancelable: true }); action.preventDefault(); element.dispatchEvent(action); return; }
|
||||
if (event.type === 'keydown' || event.type === 'keyup') {
|
||||
element.dispatchEvent(new KeyboardEvent(event.type, { key: event.key ?? '', ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey, bubbles: true, cancelable: true })); return;
|
||||
if (eventType === 'reset' && element instanceof HTMLFormElement) { element.reset(); return; }
|
||||
if (eventType === 'submit') { const action = new Event(eventType, { bubbles: true, cancelable: true }); action.preventDefault(); element.dispatchEvent(action); return; }
|
||||
if (eventType === 'keydown' || eventType === 'keyup') {
|
||||
if ((element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement)
|
||||
&& typeof event.selectionStart === 'number' && typeof event.selectionEnd === 'number') {
|
||||
try { element.setSelectionRange(event.selectionStart, event.selectionEnd); } catch {}
|
||||
}
|
||||
element.dispatchEvent(new KeyboardEvent(eventType, { key: event.key ?? '', ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey, bubbles: true, cancelable: true })); return;
|
||||
}
|
||||
if (event.type.startsWith('composition')) { element.dispatchEvent(new CompositionEvent(event.type, { data: event.data ?? '', bubbles: true })); return; }
|
||||
if (event.type === 'focusin' || event.type === 'focusout') { element.dispatchEvent(new FocusEvent(event.type, { bubbles: true })); return; }
|
||||
if (eventType.startsWith('composition')) { element.dispatchEvent(new CompositionEvent(eventType, { data: event.data ?? '', bubbles: true })); return; }
|
||||
if (eventType === 'focusin' || eventType === 'focusout') { element.dispatchEvent(new FocusEvent(eventType, { bubbles: true })); return; }
|
||||
if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) {
|
||||
if (element instanceof HTMLSelectElement && element.multiple && event.values) {
|
||||
for (const option of element.options) option.selected = event.values.includes(option.value);
|
||||
}
|
||||
if (!(element instanceof HTMLSelectElement && element.multiple) && event.value !== undefined && event.value.length <= 8192) {
|
||||
if (!(element instanceof HTMLSelectElement && element.multiple) && event.value !== undefined && event.value.length <= MAX_PLUGIN_EVENT_VALUE_LENGTH) {
|
||||
const prototype = element instanceof HTMLInputElement ? HTMLInputElement.prototype
|
||||
: element instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLSelectElement.prototype;
|
||||
Object.getOwnPropertyDescriptor(prototype, 'value')?.set?.call(element, event.value);
|
||||
}
|
||||
if ((element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement)
|
||||
&& typeof event.selectionStart === 'number' && typeof event.selectionEnd === 'number') {
|
||||
try { element.setSelectionRange(event.selectionStart, event.selectionEnd); } catch {}
|
||||
}
|
||||
if (element instanceof HTMLInputElement && typeof event.checked === 'boolean') {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'checked')?.set?.call(element, event.checked);
|
||||
}
|
||||
element.dispatchEvent(new Event(event.type, { bubbles: true, cancelable: true }));
|
||||
element.dispatchEvent(new Event(eventType, { bubbles: true, cancelable: true }));
|
||||
}
|
||||
};
|
||||
const subscription = views.onDidReceiveMessage(viewId, (message) => {
|
||||
|
||||
@@ -422,3 +422,107 @@ test('hostDom syncs valueAsNumber, valueAsDate, stepUp, stepDown, and setRangeTe
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('hostReact widgets and extended surface events round-trip cleanly through hostDom', async () => {
|
||||
const dom = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost', pretendToBeVisual: true });
|
||||
const saved = new Map<string, PropertyDescriptor | undefined>();
|
||||
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'HTMLInputElement', 'HTMLTextAreaElement', 'HTMLSelectElement', 'HTMLOptionElement', 'HTMLFormElement', 'Node', 'MutationObserver', 'Event', 'CustomEvent', 'MouseEvent']) {
|
||||
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value: key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window] });
|
||||
}
|
||||
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, writable: true, value: true });
|
||||
|
||||
const { default: React, act } = await import('react');
|
||||
const { remoteId } = await import('@remote-dom/core/elements');
|
||||
const {
|
||||
registerHostReactView,
|
||||
PluginPopover,
|
||||
PluginCodeEditor,
|
||||
PluginDataGrid,
|
||||
PluginSplitPane,
|
||||
PluginErCanvas,
|
||||
} = await import('./hostReact.js');
|
||||
|
||||
let receive: (value: JsonValue) => void = () => {};
|
||||
const messages: Array<Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>> = [];
|
||||
const views = {
|
||||
onDidReceiveMessage(_id: string, listener: (value: JsonValue) => void) { receive = listener; return { dispose() {} }; },
|
||||
postMessage(_id: string, value: JsonValue) { messages.push(value as unknown as Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>); },
|
||||
getState: async () => undefined,
|
||||
setState: async () => {},
|
||||
};
|
||||
|
||||
const received: Record<string, unknown> = {};
|
||||
function IdeView() {
|
||||
return (
|
||||
<div data-plugin-chrome="full-bleed">
|
||||
<button
|
||||
id="row-btn"
|
||||
onDoubleClick={(e) => { received.dblclick = { x: e.clientX, y: e.clientY }; }}
|
||||
onContextMenu={(e) => { received.contextmenu = { x: e.clientX, y: e.clientY }; }}
|
||||
>
|
||||
Row
|
||||
</button>
|
||||
<PluginPopover anchorX={40} anchorY={60} width={240} maxHeight={300} open onClose={() => { received.dismissed = true; }}>
|
||||
<span>Action</span>
|
||||
</PluginPopover>
|
||||
<PluginSplitPane direction="horizontal" initialSize={260} onResizeEnd={(d) => { received.resizeEnd = d; }}>
|
||||
<PluginCodeEditor value="SELECT 1;" language="sql" onExecute={(d) => { received.execute = d; }} />
|
||||
<PluginDataGrid
|
||||
columns={[{ name: 'id', primaryKey: true }]}
|
||||
rows={[{ id: 1 }]}
|
||||
editable
|
||||
onCellEdit={(d) => { received.cellEdit = d; }}
|
||||
/>
|
||||
</PluginSplitPane>
|
||||
<PluginErCanvas
|
||||
tables={[{ name: 'users', columns: [{ name: 'id', type: 'int', isPk: true }] }]}
|
||||
relations={[]}
|
||||
onTableClick={(d) => { received.tableClick = d; }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const registration = registerHostReactView(views, 'com.example.ide', () => <IdeView />);
|
||||
try {
|
||||
await act(async () => {
|
||||
receive({ kind: 'host-ui.open', instanceId: 'ide-1' });
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
});
|
||||
|
||||
const btn = document.getElementById('row-btn')!;
|
||||
const editorEl = document.querySelector('[data-plugin-widget="code-editor"]')!;
|
||||
const gridEl = document.querySelector('[data-plugin-widget="data-grid"]')!;
|
||||
const splitEl = document.querySelector('[data-plugin-widget="split-pane"]')!;
|
||||
const erEl = document.querySelector('[data-plugin-widget="er-canvas"]')!;
|
||||
const popoverEl = document.querySelector('[data-plugin-popover="true"]')!;
|
||||
|
||||
assert.equal(popoverEl.getAttribute('data-plugin-anchor-x'), '40');
|
||||
assert.equal(popoverEl.getAttribute('data-plugin-anchor-y'), '60');
|
||||
assert.equal(popoverEl.getAttribute('data-plugin-popover-width'), '240');
|
||||
assert.equal(popoverEl.getAttribute('data-plugin-popover-max-height'), '300');
|
||||
|
||||
await act(async () => {
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'dblclick', nodeId: remoteId(btn), x: 12, y: 34 } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'contextmenu', nodeId: remoteId(btn), x: 56, y: 78 } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(editorEl), widgetEvent: 'execute', detail: { value: 'SELECT 1;', selectedText: '', currentStatement: 'SELECT 1' } } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(gridEl), widgetEvent: 'cellEdit', detail: { rowIndex: 0, colName: 'id', value: '2', isNull: false } } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(splitEl), widgetEvent: 'resizeEnd', detail: { size: 320, collapsed: false } } });
|
||||
receive({ kind: 'host-ui.event', instanceId: 'ide-1', event: { type: 'widget', nodeId: remoteId(erEl), widgetEvent: 'tableClick', detail: { table: 'users' } } });
|
||||
});
|
||||
|
||||
assert.deepEqual(received.dblclick, { x: 12, y: 34 });
|
||||
assert.deepEqual(received.contextmenu, { x: 56, y: 78 });
|
||||
assert.deepEqual(received.execute, { value: 'SELECT 1;', selectedText: '', currentStatement: 'SELECT 1' });
|
||||
assert.deepEqual(received.cellEdit, { rowIndex: 0, colName: 'id', value: '2', isNull: false });
|
||||
assert.deepEqual(received.resizeEnd, { size: 320, collapsed: false });
|
||||
assert.deepEqual(received.tableClick, { table: 'users' });
|
||||
await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'ide-1' }); });
|
||||
} finally {
|
||||
await act(async () => { registration.dispose(); });
|
||||
for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
|
||||
Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
|
||||
dom.window.close();
|
||||
}
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { createElement, useEffect, useRef, type ReactNode } from 'react';
|
||||
import { createElement, useEffect, useMemo, useRef, type CSSProperties, type ReactNode } from 'react';
|
||||
import type { Disposable, PluginViews } from './index.js';
|
||||
import { registerHostDomView } from './hostDom.js';
|
||||
|
||||
@@ -10,13 +10,370 @@ export function registerHostReactView(views: PluginViews, viewId: string, render
|
||||
}, css);
|
||||
}
|
||||
|
||||
export interface PluginPopoverProps {
|
||||
anchor?: string;
|
||||
anchorX?: number;
|
||||
anchorY?: number;
|
||||
width?: number;
|
||||
maxHeight?: number;
|
||||
open: boolean;
|
||||
onClose(): void;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/** A host-positioned popup with freely authored content. */
|
||||
export function PluginPopover({ anchor, open, onClose, children }: { anchor: string; open: boolean; onClose(): void; children: ReactNode }) {
|
||||
export function PluginPopover({
|
||||
anchor,
|
||||
anchorX,
|
||||
anchorY,
|
||||
width,
|
||||
maxHeight,
|
||||
open,
|
||||
onClose,
|
||||
children,
|
||||
}: PluginPopoverProps) {
|
||||
const ref = useRef<HTMLElement>(null);
|
||||
useEffect(() => {
|
||||
const node = ref.current; if (!node) return;
|
||||
node.addEventListener('netcatty-dismiss', onClose);
|
||||
return () => node.removeEventListener('netcatty-dismiss', onClose);
|
||||
}, [onClose]);
|
||||
return createElement('div', { ref, 'data-plugin-popover': 'true', 'data-plugin-anchor': anchor, ...(open ? { open: true } : {}) }, children);
|
||||
return createElement(
|
||||
'div',
|
||||
{
|
||||
ref,
|
||||
'data-plugin-popover': 'true',
|
||||
...(anchor ? { 'data-plugin-anchor': anchor } : {}),
|
||||
...(anchorX !== undefined ? { 'data-plugin-anchor-x': String(anchorX) } : {}),
|
||||
...(anchorY !== undefined ? { 'data-plugin-anchor-y': String(anchorY) } : {}),
|
||||
...(width !== undefined ? { 'data-plugin-popover-width': String(width) } : {}),
|
||||
...(maxHeight !== undefined ? { 'data-plugin-popover-max-height': String(maxHeight) } : {}),
|
||||
...(open ? { open: true } : {}),
|
||||
},
|
||||
children,
|
||||
);
|
||||
}
|
||||
|
||||
type WidgetEventDetail = { widgetEvent?: string; detail?: Record<string, unknown> };
|
||||
|
||||
function useWidgetEventBridge(
|
||||
ref: React.RefObject<HTMLElement | null>,
|
||||
handler: (widgetEvent: string, detail: Record<string, unknown>) => void,
|
||||
) {
|
||||
const handlerRef = useRef(handler);
|
||||
handlerRef.current = handler;
|
||||
useEffect(() => {
|
||||
const node = ref.current;
|
||||
if (!node) return;
|
||||
const listener = (event: Event) => {
|
||||
const payload = (event as CustomEvent<WidgetEventDetail>).detail;
|
||||
if (!payload || typeof payload.widgetEvent !== 'string') return;
|
||||
handlerRef.current(payload.widgetEvent, payload.detail ?? {});
|
||||
};
|
||||
node.addEventListener('netcatty-widget-event', listener);
|
||||
return () => node.removeEventListener('netcatty-widget-event', listener);
|
||||
}, [ref]);
|
||||
}
|
||||
|
||||
export interface PluginCodeEditorCompletionColumn {
|
||||
name: string;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
export interface PluginCodeEditorCompletionTable {
|
||||
name: string;
|
||||
schema?: string;
|
||||
columns?: PluginCodeEditorCompletionColumn[];
|
||||
}
|
||||
|
||||
export interface PluginCodeEditorCompletionFunction {
|
||||
name: string;
|
||||
detail?: string;
|
||||
insertText?: string;
|
||||
}
|
||||
|
||||
export interface PluginCodeEditorCompletionSchema {
|
||||
tables?: PluginCodeEditorCompletionTable[];
|
||||
functions?: PluginCodeEditorCompletionFunction[];
|
||||
keywords?: string[];
|
||||
}
|
||||
|
||||
export interface PluginCodeEditorDiagnostic {
|
||||
line: number;
|
||||
column: number;
|
||||
endLine?: number;
|
||||
endColumn?: number;
|
||||
message: string;
|
||||
severity?: 'error' | 'warning' | 'info' | 'hint';
|
||||
}
|
||||
|
||||
export interface PluginCodeEditorProps {
|
||||
value: string;
|
||||
language?: 'sql' | 'pgsql' | 'mysql' | 'json' | 'plaintext';
|
||||
readOnly?: boolean;
|
||||
placeholder?: string;
|
||||
lineNumbers?: 'on' | 'off' | 'relative';
|
||||
minimap?: boolean;
|
||||
wordWrap?: 'on' | 'off' | 'wordWrapColumn' | 'bounded';
|
||||
completionSchema?: PluginCodeEditorCompletionSchema;
|
||||
diagnostics?: PluginCodeEditorDiagnostic[];
|
||||
height?: number | string;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
onChange?: (detail: { value: string }) => void;
|
||||
onSelection?: (detail: { selectionStart: number; selectionEnd: number; selectedText: string }) => void;
|
||||
onExecute?: (detail: { value: string; selectedText: string; currentStatement: string }) => void;
|
||||
onFormat?: (detail: { value: string }) => void;
|
||||
}
|
||||
|
||||
/** Host-rendered Monaco code editor with local zero-IPC schema completion. */
|
||||
export function PluginCodeEditor({
|
||||
value,
|
||||
language,
|
||||
readOnly,
|
||||
placeholder,
|
||||
lineNumbers,
|
||||
minimap,
|
||||
wordWrap,
|
||||
completionSchema,
|
||||
diagnostics,
|
||||
height,
|
||||
className,
|
||||
style,
|
||||
onChange,
|
||||
onSelection,
|
||||
onExecute,
|
||||
onFormat,
|
||||
}: PluginCodeEditorProps) {
|
||||
const ref = useRef<HTMLElement>(null);
|
||||
useWidgetEventBridge(ref, (eventName, detail) => {
|
||||
if (eventName === 'change') onChange?.(detail as { value: string });
|
||||
else if (eventName === 'selection') onSelection?.(detail as { selectionStart: number; selectionEnd: number; selectedText: string });
|
||||
else if (eventName === 'execute') onExecute?.(detail as { value: string; selectedText: string; currentStatement: string });
|
||||
else if (eventName === 'format') onFormat?.(detail as { value: string });
|
||||
});
|
||||
const serialized = useMemo(
|
||||
() => JSON.stringify({
|
||||
value,
|
||||
...(language !== undefined ? { language } : {}),
|
||||
...(readOnly !== undefined ? { readOnly } : {}),
|
||||
...(placeholder !== undefined ? { placeholder } : {}),
|
||||
...(lineNumbers !== undefined ? { lineNumbers } : {}),
|
||||
...(minimap !== undefined ? { minimap } : {}),
|
||||
...(wordWrap !== undefined ? { wordWrap } : {}),
|
||||
...(completionSchema !== undefined ? { completionSchema } : {}),
|
||||
...(diagnostics !== undefined ? { diagnostics } : {}),
|
||||
...(height !== undefined ? { height } : {}),
|
||||
}),
|
||||
[value, language, readOnly, placeholder, lineNumbers, minimap, wordWrap, completionSchema, diagnostics, height],
|
||||
);
|
||||
return createElement('div', {
|
||||
ref,
|
||||
className,
|
||||
style,
|
||||
'data-plugin-widget': 'code-editor',
|
||||
'data-plugin-widget-props': serialized,
|
||||
});
|
||||
}
|
||||
|
||||
export interface PluginDataGridColumn {
|
||||
name: string;
|
||||
type?: string;
|
||||
primaryKey?: boolean;
|
||||
nullable?: boolean;
|
||||
width?: number;
|
||||
sortable?: boolean;
|
||||
}
|
||||
|
||||
export interface PluginDataGridSort {
|
||||
column: string;
|
||||
direction: 'asc' | 'desc';
|
||||
}
|
||||
|
||||
export type PluginDataGridRow = Record<string, unknown> | unknown[];
|
||||
|
||||
export interface PluginDataGridProps {
|
||||
columns: PluginDataGridColumn[];
|
||||
rows: PluginDataGridRow[];
|
||||
rowKeyField?: string;
|
||||
dirtyCells?: Record<string, unknown>;
|
||||
deletedRowIndices?: number[];
|
||||
insertedRows?: PluginDataGridRow[];
|
||||
selectedRowIndices?: number[];
|
||||
sort?: PluginDataGridSort | null;
|
||||
editable?: boolean;
|
||||
loading?: boolean;
|
||||
emptyMessage?: string;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
onCellSelect?: (detail: { rowIndex: number; colName: string; value: unknown }) => void;
|
||||
onCellEdit?: (detail: { rowIndex: number; colName: string; value: unknown; isNull: boolean }) => void;
|
||||
onCellContextMenu?: (detail: { rowIndex: number; colName: string; x: number; y: number }) => void;
|
||||
onSortChange?: (detail: { column: string; direction: 'asc' | 'desc' }) => void;
|
||||
onRowSelect?: (detail: { selectedRowIndices: number[] }) => void;
|
||||
}
|
||||
|
||||
/** Host-rendered virtualized editable data grid powered by @tanstack/react-virtual. */
|
||||
export function PluginDataGrid({
|
||||
columns,
|
||||
rows,
|
||||
rowKeyField,
|
||||
dirtyCells,
|
||||
deletedRowIndices,
|
||||
insertedRows,
|
||||
selectedRowIndices,
|
||||
sort,
|
||||
editable,
|
||||
loading,
|
||||
emptyMessage,
|
||||
className,
|
||||
style,
|
||||
onCellSelect,
|
||||
onCellEdit,
|
||||
onCellContextMenu,
|
||||
onSortChange,
|
||||
onRowSelect,
|
||||
}: PluginDataGridProps) {
|
||||
const ref = useRef<HTMLElement>(null);
|
||||
useWidgetEventBridge(ref, (eventName, detail) => {
|
||||
if (eventName === 'cellSelect') onCellSelect?.(detail as { rowIndex: number; colName: string; value: unknown });
|
||||
else if (eventName === 'cellEdit') onCellEdit?.(detail as { rowIndex: number; colName: string; value: unknown; isNull: boolean });
|
||||
else if (eventName === 'cellContextMenu') onCellContextMenu?.(detail as { rowIndex: number; colName: string; x: number; y: number });
|
||||
else if (eventName === 'sortChange') onSortChange?.(detail as { column: string; direction: 'asc' | 'desc' });
|
||||
else if (eventName === 'rowSelect') onRowSelect?.(detail as { selectedRowIndices: number[] });
|
||||
});
|
||||
const serialized = useMemo(
|
||||
() => JSON.stringify({
|
||||
columns,
|
||||
rows,
|
||||
...(rowKeyField !== undefined ? { rowKeyField } : {}),
|
||||
...(dirtyCells !== undefined ? { dirtyCells } : {}),
|
||||
...(deletedRowIndices !== undefined ? { deletedRowIndices } : {}),
|
||||
...(insertedRows !== undefined ? { insertedRows } : {}),
|
||||
...(selectedRowIndices !== undefined ? { selectedRowIndices } : {}),
|
||||
...(sort !== undefined ? { sort } : {}),
|
||||
...(editable !== undefined ? { editable } : {}),
|
||||
...(loading !== undefined ? { loading } : {}),
|
||||
...(emptyMessage !== undefined ? { emptyMessage } : {}),
|
||||
}),
|
||||
[columns, rows, rowKeyField, dirtyCells, deletedRowIndices, insertedRows, selectedRowIndices, sort, editable, loading, emptyMessage],
|
||||
);
|
||||
return createElement('div', {
|
||||
ref,
|
||||
className,
|
||||
style,
|
||||
'data-plugin-widget': 'data-grid',
|
||||
'data-plugin-widget-props': serialized,
|
||||
});
|
||||
}
|
||||
|
||||
export interface PluginSplitPaneProps {
|
||||
direction?: 'horizontal' | 'vertical';
|
||||
initialSize?: number;
|
||||
minSize?: number;
|
||||
maxSize?: number;
|
||||
collapsible?: boolean;
|
||||
collapsed?: boolean;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
onResizeEnd?: (detail: { size: number; collapsed?: boolean }) => void;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/** Host-rendered 60fps resizable 2-child split pane container. */
|
||||
export function PluginSplitPane({
|
||||
direction = 'horizontal',
|
||||
initialSize,
|
||||
minSize,
|
||||
maxSize,
|
||||
collapsible,
|
||||
collapsed,
|
||||
className,
|
||||
style,
|
||||
onResizeEnd,
|
||||
children,
|
||||
}: PluginSplitPaneProps) {
|
||||
const ref = useRef<HTMLElement>(null);
|
||||
useWidgetEventBridge(ref, (eventName, detail) => {
|
||||
if (eventName === 'resizeEnd') onResizeEnd?.(detail as { size: number; collapsed?: boolean });
|
||||
});
|
||||
const serialized = useMemo(
|
||||
() => JSON.stringify({
|
||||
direction,
|
||||
...(initialSize !== undefined ? { initialSize } : {}),
|
||||
...(minSize !== undefined ? { minSize } : {}),
|
||||
...(maxSize !== undefined ? { maxSize } : {}),
|
||||
...(collapsible !== undefined ? { collapsible } : {}),
|
||||
...(collapsed !== undefined ? { collapsed } : {}),
|
||||
}),
|
||||
[direction, initialSize, minSize, maxSize, collapsible, collapsed],
|
||||
);
|
||||
return createElement(
|
||||
'div',
|
||||
{
|
||||
ref,
|
||||
className,
|
||||
style,
|
||||
'data-plugin-widget': 'split-pane',
|
||||
'data-plugin-widget-props': serialized,
|
||||
},
|
||||
children,
|
||||
);
|
||||
}
|
||||
|
||||
export interface PluginErColumn {
|
||||
name: string;
|
||||
type: string;
|
||||
isPk?: boolean;
|
||||
isFk?: boolean;
|
||||
nullable?: boolean;
|
||||
}
|
||||
|
||||
export interface PluginErTable {
|
||||
name: string;
|
||||
schema?: string;
|
||||
columns: PluginErColumn[];
|
||||
x?: number;
|
||||
y?: number;
|
||||
}
|
||||
|
||||
export interface PluginErRelation {
|
||||
fromTable: string;
|
||||
fromColumn: string;
|
||||
toTable: string;
|
||||
toColumn: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface PluginErCanvasProps {
|
||||
tables: PluginErTable[];
|
||||
relations: PluginErRelation[];
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
onTableClick?: (detail: { table: string; schema?: string }) => void;
|
||||
}
|
||||
|
||||
/** Host-rendered interactive pan/zoom SVG ER diagram canvas. */
|
||||
export function PluginErCanvas({
|
||||
tables,
|
||||
relations,
|
||||
className,
|
||||
style,
|
||||
onTableClick,
|
||||
}: PluginErCanvasProps) {
|
||||
const ref = useRef<HTMLElement>(null);
|
||||
useWidgetEventBridge(ref, (eventName, detail) => {
|
||||
if (eventName === 'tableClick') onTableClick?.(detail as { table: string; schema?: string });
|
||||
});
|
||||
const serialized = useMemo(
|
||||
() => JSON.stringify({ tables, relations }),
|
||||
[tables, relations],
|
||||
);
|
||||
return createElement('div', {
|
||||
ref,
|
||||
className,
|
||||
style,
|
||||
'data-plugin-widget': 'er-canvas',
|
||||
'data-plugin-widget-props': serialized,
|
||||
});
|
||||
}
|
||||
@@ -55,6 +55,12 @@ const testSecretStore: PluginSecretStore = {
|
||||
async get() {
|
||||
return testSecretRef;
|
||||
},
|
||||
async getPlaintext() {
|
||||
return "own-secret-value";
|
||||
},
|
||||
async readOwn() {
|
||||
return "own-secret-value";
|
||||
},
|
||||
async set() {
|
||||
return testSecretRef;
|
||||
},
|
||||
|
||||
@@ -72,11 +72,15 @@ export interface PluginKeyValueStore {
|
||||
get<T extends JsonValue>(key: string): Promise<T | undefined>;
|
||||
set(key: string, value: JsonValue): Promise<void>;
|
||||
delete(key: string): Promise<void>;
|
||||
keys(): Promise<readonly string[]>;
|
||||
keys(options?: Readonly<{ prefix?: string }>): Promise<readonly string[]>;
|
||||
}
|
||||
|
||||
export interface PluginSecretStore {
|
||||
get(key: string): Promise<SecretRef | undefined>;
|
||||
/** Reads plaintext of a secret previously stored by this plugin in its own encrypted namespace. */
|
||||
getPlaintext(key: string): Promise<string | undefined>;
|
||||
/** Alias for getPlaintext(key); strictly scoped to this plugin's own secrets, never Netcatty Vault credentials. */
|
||||
readOwn(key: string): Promise<string | undefined>;
|
||||
set(key: string, value: string): Promise<SecretRef>;
|
||||
delete(key: string): Promise<void>;
|
||||
}
|
||||
@@ -110,10 +114,68 @@ export interface PluginCommands {
|
||||
executeCommand<T extends JsonValue = JsonValue>(commandId: string, args?: JsonValue): Promise<T>;
|
||||
}
|
||||
|
||||
export interface PluginFileDialogFilter {
|
||||
readonly name: string;
|
||||
readonly extensions: readonly string[];
|
||||
}
|
||||
|
||||
export interface PluginOpenFileOptions {
|
||||
readonly title?: string;
|
||||
readonly filters?: readonly PluginFileDialogFilter[];
|
||||
readonly readAs?: "bytes" | "utf8";
|
||||
readonly maxBytes?: number;
|
||||
}
|
||||
|
||||
export type PluginOpenFileResult<TData extends Uint8Array | string = Uint8Array | string> =
|
||||
| Readonly<{ cancelled: true }>
|
||||
| Readonly<{
|
||||
cancelled: false;
|
||||
name: string;
|
||||
size: number;
|
||||
handleId: string;
|
||||
data: TData;
|
||||
}>;
|
||||
|
||||
export interface PluginSaveFileOptions {
|
||||
readonly title?: string;
|
||||
readonly defaultName?: string;
|
||||
readonly filters?: readonly PluginFileDialogFilter[];
|
||||
readonly data: Uint8Array | ArrayBuffer | string;
|
||||
readonly encoding?: "base64" | "utf8";
|
||||
}
|
||||
|
||||
export type PluginSaveFileResult =
|
||||
| Readonly<{ cancelled: true }>
|
||||
| Readonly<{
|
||||
cancelled: false;
|
||||
name: string;
|
||||
size: number;
|
||||
handleId: string;
|
||||
}>;
|
||||
|
||||
export interface PluginFileHandleWriteResult {
|
||||
readonly bytesWritten: number;
|
||||
readonly totalSize: number;
|
||||
}
|
||||
|
||||
export interface PluginHostUI {
|
||||
quickPick(title: string, items: readonly import("@netcatty/plugin-contract").HostQuickPickItem[]): Promise<string | undefined>;
|
||||
/** Single-line text. The host rejects CR/LF in initial values and submitted responses. */
|
||||
input(title: string, initialValue?: string): Promise<string | undefined>;
|
||||
/** Opens a native OS file picker and returns contents + a revocable per-runtime file handle. */
|
||||
openFile(options?: PluginOpenFileOptions & Readonly<{ readAs: "utf8" }>): Promise<PluginOpenFileResult<string>>;
|
||||
openFile(options?: PluginOpenFileOptions & Readonly<{ readAs?: "bytes" }>): Promise<PluginOpenFileResult<Uint8Array>>;
|
||||
openFile(options?: PluginOpenFileOptions): Promise<PluginOpenFileResult>;
|
||||
/** Opens a native OS save dialog and writes atomically, returning a revocable per-runtime file handle. */
|
||||
saveFile(options: PluginSaveFileOptions): Promise<PluginSaveFileResult>;
|
||||
/** Reads from a previously user-picked file handle without re-prompting. */
|
||||
readFileHandle(handleId: string, options: Readonly<{ readAs: "utf8" }>): Promise<string>;
|
||||
readFileHandle(handleId: string, options?: Readonly<{ readAs?: "bytes" }>): Promise<Uint8Array>;
|
||||
readFileHandle(handleId: string, options?: Readonly<{ readAs?: "bytes" | "utf8" }>): Promise<Uint8Array | string>;
|
||||
/** Atomically writes back to a previously user-picked file handle without re-prompting. */
|
||||
writeFileHandle(handleId: string, data: Uint8Array | ArrayBuffer | string, options?: Readonly<{ encoding?: "base64" | "utf8" }>): Promise<PluginFileHandleWriteResult>;
|
||||
/** Releases a user-picked file handle. */
|
||||
closeFileHandle(handleId: string): Promise<void>;
|
||||
}
|
||||
|
||||
/** Saved-host selection does not grant editing, connecting or session access.
|
||||
@@ -124,6 +186,8 @@ export interface PluginVault {
|
||||
/** Managed SSH-config drafts require the full Vault host editor. */
|
||||
requestHostDraft(params: import("@netcatty/plugin-contract").VaultHostDraftParams): Promise<import("@netcatty/plugin-contract").VaultHostActionResult>;
|
||||
requestConnect(params: import("@netcatty/plugin-contract").VaultHostConnectParams): Promise<import("@netcatty/plugin-contract").VaultHostActionResult>;
|
||||
/** Revokes a previously remembered durable SSH tunnel binding token. */
|
||||
revokeHostBinding(hostBindingToken: string): Promise<Readonly<{ revoked: boolean }>>;
|
||||
}
|
||||
|
||||
export interface PluginClipboard {
|
||||
@@ -701,10 +765,20 @@ export interface PluginAgentClient {
|
||||
closeChat(params: import("@netcatty/plugin-contract").PluginAgentChatRef): Promise<import("@netcatty/plugin-contract").PluginAIBooleanResult>;
|
||||
}
|
||||
|
||||
export interface PluginByteStreamUpgradeTlsOptions {
|
||||
readonly servername?: string;
|
||||
readonly allowSelfSigned?: boolean;
|
||||
readonly caPem?: string;
|
||||
}
|
||||
|
||||
export interface PluginByteConnection extends Disposable {
|
||||
readonly endpoint: string;
|
||||
/** Present when connectViaHost created or reused a durable SSH tunnel binding. */
|
||||
readonly hostBindingToken?: string;
|
||||
readonly readable: PluginReadableByteStream;
|
||||
readonly writable: PluginWritableByteStream;
|
||||
/** Performs an in-band STARTTLS upgrade on an open plaintext byte stream. */
|
||||
upgradeTls(options?: PluginByteStreamUpgradeTlsOptions): Promise<import("@netcatty/plugin-contract").ByteStreamUpgradeTlsResult>;
|
||||
/** Closes both directions. Repeated calls on this handle are harmless. */
|
||||
close(): Promise<void>;
|
||||
}
|
||||
@@ -985,7 +1059,7 @@ export function throwIfCancellationRequested(token: CancellationToken): void {
|
||||
}
|
||||
|
||||
export { PLUGIN_NETWORK_CREDENTIAL_LEASE_FEATURE } from "@netcatty/plugin-contract";
|
||||
export { PLUGIN_BYTE_STREAM_FEATURE, PLUGIN_BYTE_STREAM_LIMITS } from "@netcatty/plugin-contract";
|
||||
export { PLUGIN_BYTE_STREAM_FEATURE, PLUGIN_HOST_BYTE_STREAM_FEATURE, PLUGIN_BYTE_STREAM_LIMITS } from "@netcatty/plugin-contract";
|
||||
export { PLUGIN_AI_MODEL_INVOCATION_FEATURE, PLUGIN_SELECTED_CONTEXT_FEATURE } from "@netcatty/plugin-contract";
|
||||
|
||||
export { PLUGIN_HOST_INTERACTION_FEATURE } from "@netcatty/plugin-contract";
|
||||
|
||||
@@ -22,7 +22,7 @@ const electronBundlePath = path.join(
|
||||
);
|
||||
const checkOnly = process.argv.includes("--check");
|
||||
const typescriptTypeOverrides = new Map([
|
||||
["PermissionDeclaration", 'Exclude<PluginPermission, "network.stream"> | PermissionResourceDeclaration'],
|
||||
["PermissionDeclaration", "PluginPermission | PermissionResourceDeclaration"],
|
||||
[
|
||||
"ActivationEvent",
|
||||
'"onStartupFinished" | `onCommand:${ContributionId}` | `onView:${ContributionId}` | `onProvider:${ContributionId}`',
|
||||
|
||||
+3
-2
@@ -310,8 +310,9 @@ declare global {
|
||||
onLanguageChanged?(cb: (language: string) => void): () => void;
|
||||
|
||||
// Chain progress listener for jump host connections
|
||||
// Callback receives: (sessionId: string, currentHop: number, totalHops: number, hostLabel: string, status: string, error?: string)
|
||||
onChainProgress?(cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string) => void): () => void;
|
||||
// Callback receives: (sessionId: string, currentHop: number, totalHops: number, hostLabel: string, status: string, error?: string, address?: string)
|
||||
// `address` is the current hop's host:port, so the UI can show the hop being connected.
|
||||
onChainProgress?(cb: (sessionId: string, hop: number, total: number, label: string, status: string, error?: string, address?: string) => void): () => void;
|
||||
|
||||
// Fired when a requested SSH connection reuse cannot be honored and the
|
||||
// session falls back to a regular fresh connection.
|
||||
|
||||
Reference in new issue
Block a user