mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-28 20:50:46 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
529003ad6f | ||
|
|
9fcb16cec7 | ||
|
|
f213300c81 | ||
|
|
0ef7cb3d3c | ||
|
|
24e07bee97 |
No files matched your search
@@ -0,0 +1,220 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { Host, PortForwardingRule } from '../../domain/models';
|
||||
import { STORAGE_KEY_PORT_FORWARDING } from '../../infrastructure/config/storageKeys';
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import type { PortForwardingConnection } from '../../infrastructure/services/portForwardingService';
|
||||
import {
|
||||
handlePluginVaultDataRequest,
|
||||
type PluginPortForwardRuntimeDeps,
|
||||
type PluginVaultDataContext,
|
||||
} from './pluginVaultDataHandlers';
|
||||
|
||||
function installMemoryLocalStorage() {
|
||||
const store = new Map<string, string>();
|
||||
const previous = (globalThis as Record<string, unknown>).localStorage;
|
||||
const mockStorage = {
|
||||
get length() { return store.size; },
|
||||
clear() { store.clear(); },
|
||||
getItem(key: string) { return store.has(key) ? store.get(key)! : null; },
|
||||
key(index: number) { return Array.from(store.keys())[index] ?? null; },
|
||||
removeItem(key: string) { store.delete(key); },
|
||||
setItem(key: string, value: string) { store.set(key, String(value)); },
|
||||
};
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
value: mockStorage,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
});
|
||||
return () => {
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
value: previous,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
const sampleHost: Host = {
|
||||
id: 'host-1',
|
||||
label: 'Prod Bastion',
|
||||
hostname: '10.0.0.10',
|
||||
port: 22,
|
||||
username: 'ubuntu',
|
||||
os: 'linux',
|
||||
group: '',
|
||||
tags: [],
|
||||
protocol: 'ssh',
|
||||
};
|
||||
|
||||
const sampleRules: PortForwardingRule[] = [
|
||||
{
|
||||
id: 'rule-active',
|
||||
label: 'DB Tunnel',
|
||||
type: 'local',
|
||||
localPort: 15432,
|
||||
bindAddress: '127.0.0.1',
|
||||
remoteHost: '127.0.0.1',
|
||||
remotePort: 5432,
|
||||
hostId: 'host-1',
|
||||
status: 'inactive',
|
||||
createdAt: 1000,
|
||||
},
|
||||
{
|
||||
id: 'rule-err',
|
||||
label: 'Redis Tunnel',
|
||||
type: 'local',
|
||||
localPort: 16379,
|
||||
bindAddress: '127.0.0.1',
|
||||
remoteHost: '127.0.0.1',
|
||||
remotePort: 6379,
|
||||
hostId: 'host-1',
|
||||
status: 'inactive',
|
||||
createdAt: 2000,
|
||||
},
|
||||
];
|
||||
|
||||
function makeContext(portForwardRuntime: PluginPortForwardRuntimeDeps): PluginVaultDataContext {
|
||||
return {
|
||||
getVault: () => ({
|
||||
hosts: [sampleHost],
|
||||
keys: [],
|
||||
identities: [],
|
||||
knownHosts: [],
|
||||
groupConfigs: [],
|
||||
proxyProfiles: [],
|
||||
snippets: [],
|
||||
customGroups: [],
|
||||
updateHosts: () => {},
|
||||
updateSnippets: () => {},
|
||||
readCurrentHostActionState: () => ({
|
||||
hosts: [sampleHost],
|
||||
keys: [],
|
||||
identities: [],
|
||||
knownHosts: [],
|
||||
groupConfigs: [],
|
||||
proxyProfiles: [],
|
||||
snippets: [],
|
||||
customGroups: [],
|
||||
}),
|
||||
}) as never,
|
||||
resources: {} as never,
|
||||
portForwardRuntime,
|
||||
};
|
||||
}
|
||||
|
||||
test('portForward.list overlays live runtime status and error over persisted inactive rules', async () => {
|
||||
const restore = installMemoryLocalStorage();
|
||||
try {
|
||||
localStorageAdapter.write(STORAGE_KEY_PORT_FORWARDING, sampleRules);
|
||||
const activeConns = new Map<string, PortForwardingConnection>([
|
||||
['rule-active', { ruleId: 'rule-active', tunnelId: 't-1', status: 'active' }],
|
||||
]);
|
||||
const runtimeRules: PortForwardingRule[] = [
|
||||
{ ...sampleRules[0], status: 'active' },
|
||||
{ ...sampleRules[1], status: 'error', error: 'EADDRINUSE: port 16379 busy' },
|
||||
];
|
||||
const ctx = makeContext({
|
||||
getActiveConnection: (id) => activeConns.get(id),
|
||||
getRuntimeRules: () => runtimeRules,
|
||||
});
|
||||
|
||||
const result = await handlePluginVaultDataRequest('portForward.list', {}, ctx) as {
|
||||
rules: Array<{ id: string; status: string; error?: string }>;
|
||||
};
|
||||
const byId = new Map(result.rules.map((r) => [r.id, r]));
|
||||
assert.equal(byId.get('rule-active')?.status, 'active');
|
||||
assert.equal(byId.get('rule-active')?.error, undefined);
|
||||
assert.equal(byId.get('rule-err')?.status, 'error');
|
||||
assert.equal(byId.get('rule-err')?.error, 'EADDRINUSE: port 16379 busy');
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('portForward.start and portForward.stop return live runtime status instead of stripped storage inactive', async () => {
|
||||
const restore = installMemoryLocalStorage();
|
||||
try {
|
||||
localStorageAdapter.write(STORAGE_KEY_PORT_FORWARDING, [sampleRules[0]]);
|
||||
const activeConns = new Map<string, PortForwardingConnection>();
|
||||
const appliedStatuses: Array<{ ruleId: string; status: string; error?: string }> = [];
|
||||
let runtimeRules: PortForwardingRule[] = [{ ...sampleRules[0], status: 'inactive' }];
|
||||
|
||||
const ctx = makeContext({
|
||||
getActiveConnection: (id) => activeConns.get(id),
|
||||
getRuntimeRules: () => runtimeRules,
|
||||
applyRuntimeStatus: (ruleId, status, error) => {
|
||||
appliedStatuses.push({ ruleId, status, error });
|
||||
runtimeRules = runtimeRules.map((r) => (r.id === ruleId ? { ...r, status, error } : r));
|
||||
},
|
||||
startPortForward: async (rule, _host, _hosts, _keys, _ids, onStatusChange) => {
|
||||
onStatusChange?.('connecting');
|
||||
activeConns.set(rule.id, { ruleId: rule.id, tunnelId: 't-live', status: 'active' });
|
||||
onStatusChange?.('active');
|
||||
return { success: true };
|
||||
},
|
||||
stopAndCleanupRule: async (ruleId) => {
|
||||
activeConns.delete(ruleId);
|
||||
return { success: true };
|
||||
},
|
||||
});
|
||||
|
||||
const started = await handlePluginVaultDataRequest(
|
||||
'portForward.start',
|
||||
{ ruleId: 'rule-active' },
|
||||
ctx,
|
||||
) as { ok: boolean; rule: { id: string; status: string; error?: string } };
|
||||
assert.equal(started.ok, true);
|
||||
assert.equal(started.rule.status, 'active');
|
||||
assert.equal(started.rule.error, undefined);
|
||||
assert.ok(appliedStatuses.some((entry) => entry.ruleId === 'rule-active' && entry.status === 'active'));
|
||||
|
||||
// Subsequent list also reports active
|
||||
const listed = await handlePluginVaultDataRequest('portForward.list', {}, ctx) as {
|
||||
rules: Array<{ id: string; status: string }>;
|
||||
};
|
||||
assert.equal(listed.rules[0]?.status, 'active');
|
||||
|
||||
// Stop transitions cleanly back to inactive
|
||||
const stopped = await handlePluginVaultDataRequest(
|
||||
'portForward.stop',
|
||||
{ ruleId: 'rule-active' },
|
||||
ctx,
|
||||
) as { ok: boolean; rule: { id: string; status: string } };
|
||||
assert.equal(stopped.ok, true);
|
||||
assert.equal(stopped.rule.status, 'inactive');
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('portForward.start surfaces live error status and message when tunnel start fails', async () => {
|
||||
const restore = installMemoryLocalStorage();
|
||||
try {
|
||||
localStorageAdapter.write(STORAGE_KEY_PORT_FORWARDING, [sampleRules[1]]);
|
||||
let runtimeRules: PortForwardingRule[] = [{ ...sampleRules[1], status: 'inactive' }];
|
||||
const ctx = makeContext({
|
||||
getActiveConnection: () => undefined,
|
||||
getRuntimeRules: () => runtimeRules,
|
||||
applyRuntimeStatus: (ruleId, status, error) => {
|
||||
runtimeRules = runtimeRules.map((r) => (r.id === ruleId ? { ...r, status, error } : r));
|
||||
},
|
||||
startPortForward: async (_rule, _host, _hosts, _keys, _ids, onStatusChange) => {
|
||||
onStatusChange?.('error', 'Connection refused');
|
||||
return { success: false, error: 'Connection refused' };
|
||||
},
|
||||
});
|
||||
|
||||
const started = await handlePluginVaultDataRequest(
|
||||
'portForward.start',
|
||||
{ ruleId: 'rule-err' },
|
||||
ctx,
|
||||
) as { ok: boolean; rule: { id: string; status: string; error?: string }; error?: string };
|
||||
assert.equal(started.ok, false);
|
||||
assert.equal(started.rule.status, 'error');
|
||||
assert.equal(started.rule.error, 'Connection refused');
|
||||
assert.equal(started.error, 'Connection refused');
|
||||
} finally {
|
||||
restore();
|
||||
}
|
||||
});
|
||||
@@ -10,7 +10,11 @@ import { STORAGE_KEY_PORT_FORWARDING } from '../../infrastructure/config/storage
|
||||
import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter';
|
||||
import { netcattyBridge } from '../../infrastructure/services/netcattyBridge';
|
||||
import { preparePluginHostStream } from '../../infrastructure/services/pluginHostStreamService';
|
||||
import { startPortForward, stopAndCleanupRule } from '../../infrastructure/services/portForwardingService';
|
||||
import {
|
||||
getActiveConnection,
|
||||
startPortForward,
|
||||
stopAndCleanupRule,
|
||||
} from '../../infrastructure/services/portForwardingService';
|
||||
import { captureScreenSnapshot } from '../../infrastructure/scripts/screenSnapshotRegistry';
|
||||
import { activeTabStore } from './activeTabStore';
|
||||
import {
|
||||
@@ -19,12 +23,64 @@ import {
|
||||
type AppVaultRuntime,
|
||||
} from './appRuntimeBridge';
|
||||
import type { PluginHostActionResources } from './pluginHostActionResources';
|
||||
import {
|
||||
applyPortForwardingRuntimeStatus,
|
||||
getPortForwardingRuntimeRules,
|
||||
} from './usePortForwardingState';
|
||||
|
||||
export interface PluginPortForwardRuntimeDeps {
|
||||
startPortForward?: typeof startPortForward;
|
||||
stopAndCleanupRule?: typeof stopAndCleanupRule;
|
||||
getActiveConnection?: typeof getActiveConnection;
|
||||
getRuntimeRules?: typeof getPortForwardingRuntimeRules;
|
||||
applyRuntimeStatus?: typeof applyPortForwardingRuntimeStatus;
|
||||
}
|
||||
|
||||
export type PluginVaultDataContext = {
|
||||
getVault: () => AppVaultRuntime & ReturnType<AppVaultRuntime['readCurrentHostActionState']>;
|
||||
resources: PluginHostActionResources;
|
||||
portForwardRuntime?: PluginPortForwardRuntimeDeps;
|
||||
};
|
||||
|
||||
type PortForwardSummaryStatus = 'inactive' | 'connecting' | 'active' | 'error';
|
||||
|
||||
function normalizePortForwardSummaryStatus(
|
||||
status: PortForwardingRule['status'] | undefined,
|
||||
): PortForwardSummaryStatus {
|
||||
if (status === 'active' || status === 'connecting' || status === 'error' || status === 'inactive') {
|
||||
return status;
|
||||
}
|
||||
return 'inactive';
|
||||
}
|
||||
|
||||
function overlayPortForwardRuntimeStatus(
|
||||
rule: PortForwardingRule,
|
||||
runtime?: PluginPortForwardRuntimeDeps,
|
||||
): PortForwardingRule {
|
||||
const resolveConnection = runtime?.getActiveConnection ?? getActiveConnection;
|
||||
const liveConn = resolveConnection(rule.id);
|
||||
if (liveConn) {
|
||||
return {
|
||||
...rule,
|
||||
status: normalizePortForwardSummaryStatus(liveConn.status),
|
||||
error: liveConn.error,
|
||||
};
|
||||
}
|
||||
const runtimeRules = (runtime?.getRuntimeRules ?? getPortForwardingRuntimeRules)();
|
||||
const runtimeRule = runtimeRules.find((candidate) => candidate.id === rule.id);
|
||||
if (runtimeRule && (runtimeRule.status === 'active' || runtimeRule.status === 'connecting' || runtimeRule.status === 'error')) {
|
||||
return {
|
||||
...rule,
|
||||
status: runtimeRule.status,
|
||||
error: runtimeRule.error,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...rule,
|
||||
status: normalizePortForwardSummaryStatus(rule.status),
|
||||
};
|
||||
}
|
||||
|
||||
function readPortForwardRules(): PortForwardingRule[] {
|
||||
const raw = localStorageAdapter.read<PortForwardingRule[]>(STORAGE_KEY_PORT_FORWARDING);
|
||||
return migratePortForwardingRulesFromStorage(Array.isArray(raw) ? raw : []);
|
||||
@@ -164,7 +220,9 @@ export async function handlePluginVaultDataRequest(
|
||||
}
|
||||
|
||||
case 'portForward.list': {
|
||||
const rules = readPortForwardRules().slice(0, 500);
|
||||
const rules = readPortForwardRules()
|
||||
.slice(0, 500)
|
||||
.map((rule) => overlayPortForwardRuntimeStatus(rule, ctx.portForwardRuntime));
|
||||
return { rules: rules.map((rule) => summarizePortForwardRule(rule, vault.hosts)) };
|
||||
}
|
||||
|
||||
@@ -199,24 +257,42 @@ export async function handlePluginVaultDataRequest(
|
||||
const settings = getAppSettingsRuntime();
|
||||
const resolvedHost = effectiveHost(rawHost, vault);
|
||||
const resolvedHosts = vault.hosts.map((h) => effectiveHost(h, vault));
|
||||
const res = await startPortForward(
|
||||
const pfStart = ctx.portForwardRuntime?.startPortForward ?? startPortForward;
|
||||
const pfApplyStatus = ctx.portForwardRuntime?.applyRuntimeStatus ?? applyPortForwardingRuntimeStatus;
|
||||
const pfGetConnection = ctx.portForwardRuntime?.getActiveConnection ?? getActiveConnection;
|
||||
let observedStatus: PortForwardingRule['status'] | undefined;
|
||||
let observedError: string | undefined;
|
||||
const res = await pfStart(
|
||||
rule,
|
||||
resolvedHost,
|
||||
resolvedHosts,
|
||||
vault.keys,
|
||||
vault.identities,
|
||||
(status, error) => {
|
||||
const latest = readPortForwardRules();
|
||||
writePortForwardRules(latest.map((item) => (item.id === ruleId ? { ...item, status, error } : item)));
|
||||
observedStatus = status;
|
||||
observedError = error;
|
||||
pfApplyStatus(ruleId, status, error);
|
||||
},
|
||||
false,
|
||||
settings?.terminalSettings,
|
||||
vault.knownHosts,
|
||||
);
|
||||
const updated = readPortForwardRules().find((item) => item.id === ruleId) ?? rule;
|
||||
const liveConn = pfGetConnection(ruleId);
|
||||
const fallbackStatus: PortForwardSummaryStatus = res.success ? 'active' : 'error';
|
||||
const finalStatus = normalizePortForwardSummaryStatus(liveConn?.status ?? observedStatus ?? fallbackStatus);
|
||||
const finalError = finalStatus === 'active'
|
||||
? undefined
|
||||
: (liveConn?.error ?? observedError ?? (res.error ? String(res.error) : undefined));
|
||||
pfApplyStatus(ruleId, finalStatus, finalError);
|
||||
const latestRule = readPortForwardRules().find((item) => item.id === ruleId) ?? rule;
|
||||
const liveRule: PortForwardingRule = {
|
||||
...latestRule,
|
||||
status: finalStatus,
|
||||
error: finalError,
|
||||
};
|
||||
return {
|
||||
ok: Boolean(res.success),
|
||||
rule: summarizePortForwardRule(updated, vault.hosts),
|
||||
rule: summarizePortForwardRule(liveRule, vault.hosts),
|
||||
...(res.error ? { error: String(res.error).slice(0, 512) } : {}),
|
||||
};
|
||||
}
|
||||
@@ -226,11 +302,15 @@ export async function handlePluginVaultDataRequest(
|
||||
const rules = readPortForwardRules();
|
||||
const rule = rules.find((item) => item.id === ruleId);
|
||||
if (!rule) return { ok: false, error: 'Port forwarding rule not found' };
|
||||
await stopAndCleanupRule(ruleId);
|
||||
const pfStop = ctx.portForwardRuntime?.stopAndCleanupRule ?? stopAndCleanupRule;
|
||||
const pfApplyStatus = ctx.portForwardRuntime?.applyRuntimeStatus ?? applyPortForwardingRuntimeStatus;
|
||||
await pfStop(ruleId);
|
||||
pfApplyStatus(ruleId, 'inactive', undefined);
|
||||
const latestRules = readPortForwardRules();
|
||||
const nextRules = latestRules.map((item) => (item.id === ruleId ? { ...item, status: 'inactive' as const, error: undefined } : item));
|
||||
writePortForwardRules(nextRules);
|
||||
const updated = nextRules.find((item) => item.id === ruleId) ?? rule;
|
||||
const updated = overlayPortForwardRuntimeStatus(
|
||||
latestRules.find((item) => item.id === ruleId) ?? { ...rule, status: 'inactive', error: undefined },
|
||||
ctx.portForwardRuntime,
|
||||
);
|
||||
return { ok: true, rule: summarizePortForwardRule(updated, vault.hosts) };
|
||||
}
|
||||
|
||||
@@ -240,7 +320,8 @@ export async function handlePluginVaultDataRequest(
|
||||
if (!rules.some((item) => item.id === ruleId)) {
|
||||
return { ok: false, error: 'Port forwarding rule not found' };
|
||||
}
|
||||
await stopAndCleanupRule(ruleId).catch(() => {});
|
||||
const pfStop = ctx.portForwardRuntime?.stopAndCleanupRule ?? stopAndCleanupRule;
|
||||
await pfStop(ruleId).catch(() => {});
|
||||
const latestRules = readPortForwardRules();
|
||||
writePortForwardRules(latestRules.filter((item) => item.id !== ruleId));
|
||||
return { ok: true };
|
||||
|
||||
@@ -242,6 +242,9 @@ const persistPortForwardingConfig = (rules: PortForwardingRule[]) => {
|
||||
);
|
||||
};
|
||||
|
||||
/** Read-only snapshot of the in-memory runtime port-forwarding rules projection. */
|
||||
export const getPortForwardingRuntimeRules = (): readonly PortForwardingRule[] => globalRules;
|
||||
|
||||
/** Persist configuration only — never write runtime phases to storage. */
|
||||
const setGlobalRules = (newRules: PortForwardingRule[]) => {
|
||||
globalRules = normalizeVaultOrder(newRules);
|
||||
|
||||
@@ -40,7 +40,7 @@ export function VaultPageHeader({
|
||||
}
|
||||
|
||||
interface VaultHeaderSearchProps
|
||||
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "className"> {
|
||||
extends Omit<React.ComponentPropsWithRef<typeof Input>, "className"> {
|
||||
className?: string;
|
||||
inputClassName?: string;
|
||||
rightAdornment?: React.ReactNode;
|
||||
|
||||
@@ -738,6 +738,7 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
|
||||
}
|
||||
const keyListRef = React.useRef(keys);
|
||||
keyListRef.current = keys;
|
||||
const hostSearchInputRef = React.useRef<HTMLInputElement>(null);
|
||||
const newHostActionsRef = React.useRef<HTMLDivElement>(null);
|
||||
const sessionActionsRef = React.useRef<HTMLDivElement>(null);
|
||||
const { handlePluginPreviewCommit, getPluginPreviewAnalysis } =
|
||||
@@ -950,19 +951,34 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
|
||||
dataSection="vault-hosts-header"
|
||||
>
|
||||
<VaultHeaderSearch
|
||||
ref={hostSearchInputRef}
|
||||
placeholder={t("vault.hosts.search.placeholder")}
|
||||
className="flex-1"
|
||||
inputClassName={cn(
|
||||
search && "pr-12",
|
||||
isSearchQuickConnect &&
|
||||
"border-primary/50 ring-1 ring-primary/20",
|
||||
"pr-16 border-primary/50 ring-1 ring-primary/20",
|
||||
)}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
onKeyDown={handleSearchKeyDown}
|
||||
rightAdornment={
|
||||
isSearchQuickConnect ? (
|
||||
<Zap size={14} className="text-primary" />
|
||||
) : null
|
||||
search && (
|
||||
<div className="flex items-center gap-1">
|
||||
{isSearchQuickConnect && <Zap size={14} className="text-primary" />}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("common.clear")}
|
||||
className="grid size-6 cursor-pointer place-items-center rounded text-muted-foreground hover:bg-foreground/10 hover:text-foreground"
|
||||
onClick={() => {
|
||||
setSearch("");
|
||||
hostSearchInputRef.current?.focus();
|
||||
}}
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
|
||||
@@ -69,8 +69,19 @@ module.exports = {
|
||||
'dist/**/*',
|
||||
'electron/**/*',
|
||||
// The Windows Hello helper is shipped once through win.extraResources.
|
||||
// Exclude local per-arch build output from app.asar on every platform.
|
||||
// Exclude both its C++ source and local per-arch build output from app.asar.
|
||||
'!electron/bridges/windowsHelloHelper/build/**/*',
|
||||
'!electron/bridges/windowsHelloHelper/NetcattyWindowsHello.cpp',
|
||||
// Packaged builds always run `prebuild` -> `build:preload`, producing
|
||||
// `electron/preload.bundle.cjs` (preferred by preloadPath.cjs). Keep
|
||||
// the unbundled preload sources out of app.asar.
|
||||
'!electron/preload.cjs',
|
||||
'!electron/preload/**/*',
|
||||
// Build-time macOS entitlements plist, dev launcher, and internal docs
|
||||
// are not runtime app files.
|
||||
'!electron/entitlements.mac.plist',
|
||||
'!electron/launch.cjs',
|
||||
'!electron/plugins/distribution/README.md',
|
||||
// Test fixtures, test-only helpers, and dev/CI schema snapshots are not
|
||||
// runtime resources. Keep them out of production ASARs (including plugin
|
||||
// smoke fixtures so no example plugin can be mistaken for an installed package).
|
||||
@@ -178,6 +189,15 @@ module.exports = {
|
||||
// web-streams-polyfill is only a Node < 16.5 fallback inside fetch-blob;
|
||||
// Netcatty requires Node >= 22 / Electron 42 with native Web Streams.
|
||||
'!node_modules/web-streams-polyfill/**/*',
|
||||
// tar-stream and events-universal declare bare-* packages only for the
|
||||
// Holepunch/Bare runtime ("bare" import/export condition). Node/Electron
|
||||
// always resolves default Node.js built-ins and never loads bare-* or
|
||||
// their cross-platform iOS/Android/desktop .bare prebuilds.
|
||||
'!node_modules/bare-fs/**/*',
|
||||
'!node_modules/bare-url/**/*',
|
||||
'!node_modules/bare-path/**/*',
|
||||
'!node_modules/bare-events/**/*',
|
||||
'!node_modules/bare-stream/**/*',
|
||||
// Main process only CJS-requires css-tree (cjs/index.cjs) and mdn-data's
|
||||
// css/{at-rules,properties,syntaxes}.json; skip browser/ESM/l10n/schema copies.
|
||||
'!node_modules/css-tree/dist/**/*',
|
||||
@@ -229,6 +249,15 @@ module.exports = {
|
||||
// per-platform prebuilds); netcatty uses the user's copilot via cliPath,
|
||||
// so it is excluded entirely.
|
||||
'!**/@anthropic-ai/claude-agent-sdk-*/**/*',
|
||||
// claudeDriver.cjs only imports the default "@anthropic-ai/claude-agent-sdk"
|
||||
// entrypoint (sdk.mjs). Exclude unused sibling entrypoints and manifests
|
||||
// while keeping sdk.mjs, LICENSE.md, and README.md.
|
||||
'!node_modules/@anthropic-ai/claude-agent-sdk/assistant.mjs',
|
||||
'!node_modules/@anthropic-ai/claude-agent-sdk/bridge.mjs',
|
||||
'!node_modules/@anthropic-ai/claude-agent-sdk/browser-sdk.js',
|
||||
'!node_modules/@anthropic-ai/claude-agent-sdk/extractFromBunfs.js',
|
||||
'!node_modules/@anthropic-ai/claude-agent-sdk/manifest.json',
|
||||
'!node_modules/@anthropic-ai/claude-agent-sdk/manifest.zst.json',
|
||||
'!node_modules/@anthropic-ai/claude-code-*/**/*',
|
||||
'!node_modules/@openai/codex-{darwin,linux,linuxmusl,win32}-*/**/*',
|
||||
'!node_modules/@github/copilot-{darwin,linux,linuxmusl,win32}-*/**/*',
|
||||
@@ -246,8 +275,22 @@ module.exports = {
|
||||
'!node_modules/@cursor/sdk/dist/**/*.d.ts',
|
||||
'!node_modules/@cursor/sdk/dist/**/*.d.ts.map',
|
||||
// sqlite3 rebuilds a native module for Electron; its upstream source
|
||||
// tarball is build-time payload only.
|
||||
// tarball, C++ sources, and install-only prebuild-install/tar helpers
|
||||
// are not needed at runtime (sqlite3-binding.js only requires bindings).
|
||||
'!node_modules/sqlite3/deps/**/*',
|
||||
'!node_modules/sqlite3/src/**/*',
|
||||
'!node_modules/prebuild-install/**/*',
|
||||
'!node_modules/tar/**/*',
|
||||
// Native module C/C++ sources, build scripts, and node-pty's third_party
|
||||
// ConPTY staging copies are build-time only; runtime loads compiled
|
||||
// binaries from build/Release or prebuilds.
|
||||
'!node_modules/node-pty/third_party/**/*',
|
||||
'!node_modules/node-pty/deps/**/*',
|
||||
'!node_modules/node-pty/src/**/*',
|
||||
'!node_modules/node-pty/scripts/**/*',
|
||||
'!node_modules/node-pty/node-addon-api/**/*',
|
||||
'!node_modules/node-pty/typings/**/*',
|
||||
'!node_modules/@serialport/bindings-cpp/src/**/*',
|
||||
// Native compilation helpers are needed during install/rebuild only.
|
||||
// Match nested copies too; keep the actual native loaders and binaries.
|
||||
'!node_modules/**/node-gyp/**/*',
|
||||
|
||||
@@ -123,7 +123,17 @@ class PluginAISidebarService {
|
||||
}),
|
||||
registry.registerRequest("ai.openSidebar", (params, context) => this.openSidebar(params, context), {
|
||||
metadata: { capability: "plugin-ai-sidebar", mutating: false, permission: "ai.invoke" },
|
||||
authorization: auth("Open the Catty Agent contextual sidebar"),
|
||||
authorization: (params) => {
|
||||
const autoSend = Boolean(params?.autoSend);
|
||||
return {
|
||||
permission: "ai.invoke",
|
||||
resources: ["*"],
|
||||
reason: autoSend
|
||||
? "Automatically send a prompt to the Catty Agent sidebar"
|
||||
: "Open the Catty Agent contextual sidebar",
|
||||
...(autoSend ? {} : { deferDecision: true }),
|
||||
};
|
||||
},
|
||||
}),
|
||||
registry.registerRequest("ai.closeSidebar", (params, context) => this.closeSidebar(params, context), {
|
||||
metadata: { capability: "plugin-ai-sidebar", mutating: false, permission: "ai.invoke" },
|
||||
@@ -282,6 +292,7 @@ class PluginAISidebarService {
|
||||
throw invalidArgument("Plugin has no vault-page or terminal-sidebar view to attach the AI sidebar to");
|
||||
}
|
||||
const prompt = typeof normalizedParams.prompt === "string" ? normalizedParams.prompt.trim() : "";
|
||||
const autoSend = normalizedParams.autoSend === true && prompt.length > 0;
|
||||
if (prompt && CONTROL_CHAR_RE.test(prompt.replace(/[\r\n\t]/g, ""))) {
|
||||
throw invalidArgument("Plugin AI sidebar prompt contains invalid control characters");
|
||||
}
|
||||
@@ -290,7 +301,7 @@ class PluginAISidebarService {
|
||||
pluginId: context.pluginId,
|
||||
viewId,
|
||||
...(prompt ? { prompt } : {}),
|
||||
...(normalizedParams.autoSend === true && prompt ? { autoSend: true } : {}),
|
||||
...(autoSend ? { autoSend: true } : {}),
|
||||
timestamp: this.clock(),
|
||||
}));
|
||||
return null;
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
"use strict";
|
||||
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { PluginDatabase } = require("./database.cjs");
|
||||
const { PluginPermissionEngine } = require("./permissionEngine.cjs");
|
||||
const { PluginHostRpcRegistry } = require("./hostRpcRegistry.cjs");
|
||||
const { PluginAISidebarService, buildQualifiedToolName, MAX_TOOLS_PER_PLUGIN } = require("./pluginAiSidebarService.cjs");
|
||||
|
||||
const manifest = Object.freeze({
|
||||
@@ -177,3 +183,95 @@ test("PluginAISidebarService manages context, sidebar commands, lock, and runtim
|
||||
|
||||
service.shutdown();
|
||||
});
|
||||
|
||||
test("ai.openSidebar enforces active ai.invoke approval for autoSend: true while deferring decision for open/prefill", async (t) => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-ai-sidebar-auth-"));
|
||||
const database = new PluginDatabase(path.join(root, "plugins.db"));
|
||||
const authManifest = Object.freeze({
|
||||
...manifest,
|
||||
publisher: "example",
|
||||
permissions: { optional: ["ai.invoke"] },
|
||||
});
|
||||
database.installVersion({
|
||||
pluginId: authManifest.id,
|
||||
version: authManifest.version,
|
||||
manifest: authManifest,
|
||||
archiveSha256: "b".repeat(64),
|
||||
packageRelativePath: "test/pkg",
|
||||
});
|
||||
database.setEnabled(authManifest.id, true);
|
||||
|
||||
let approve = false;
|
||||
const decisionRequests = [];
|
||||
const engine = new PluginPermissionEngine({
|
||||
database,
|
||||
requestDecision: async (request) => {
|
||||
decisionRequests.push(request);
|
||||
return {
|
||||
requestId: request.requestId,
|
||||
decision: approve ? "allow" : "deny",
|
||||
...(approve ? { scope: "once" } : {}),
|
||||
};
|
||||
},
|
||||
});
|
||||
const registry = new PluginHostRpcRegistry();
|
||||
registry.use(engine.createMiddleware());
|
||||
const service = new PluginAISidebarService({ permissionEngine: engine });
|
||||
service.registerRpcCapabilities(registry);
|
||||
const commands = [];
|
||||
service.onDidEmitCommand((cmd) => commands.push(cmd));
|
||||
|
||||
t.after(() => {
|
||||
service.shutdown();
|
||||
engine.shutdown();
|
||||
database.close();
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
engine.setMode({ id: authManifest.id, manifest: authManifest }, "ai.invoke", "ask");
|
||||
const runtimeCtx = {
|
||||
pluginId: authManifest.id,
|
||||
pluginVersion: authManifest.version,
|
||||
runtimeId: "rt-auth",
|
||||
runtimeKind: "browser",
|
||||
manifest: authManifest,
|
||||
};
|
||||
const handlers = registry.createRoutes(runtimeCtx).requestHandlers;
|
||||
|
||||
// 1. Opening/prefilling without autoSend uses deferDecision: true (no Ask prompt)
|
||||
await handlers["ai.openSidebar"]({ prompt: "hello", autoSend: false }, {});
|
||||
assert.equal(decisionRequests.length, 0);
|
||||
assert.equal(commands.length, 1);
|
||||
assert.equal(commands[0].prompt, "hello");
|
||||
assert.equal(commands[0].autoSend, undefined);
|
||||
|
||||
// 2. autoSend: true does NOT defer decision: prompts on Ask and rejects when denied
|
||||
approve = false;
|
||||
await assert.rejects(
|
||||
handlers["ai.openSidebar"]({ prompt: "hello", autoSend: true }, {}),
|
||||
/denied/i,
|
||||
);
|
||||
assert.equal(decisionRequests.length, 1);
|
||||
assert.equal(decisionRequests[0].permission, "ai.invoke");
|
||||
assert.equal(commands.length, 1, "denied autoSend must not emit a sidebar command");
|
||||
|
||||
// 3. When user approves Ask prompt, autoSend: true proceeds
|
||||
approve = true;
|
||||
await handlers["ai.openSidebar"]({ prompt: "run query", autoSend: true }, {});
|
||||
assert.equal(decisionRequests.length, 2);
|
||||
assert.equal(commands.length, 2);
|
||||
assert.equal(commands[1].prompt, "run query");
|
||||
assert.equal(commands[1].autoSend, true);
|
||||
|
||||
// 4. Empty prompt with autoSend: true strips autoSend defensively
|
||||
await handlers["ai.openSidebar"]({ prompt: " ", autoSend: true }, {});
|
||||
assert.equal(commands.length, 3);
|
||||
assert.equal(commands[2].autoSend, undefined);
|
||||
|
||||
// 5. Explicit Deny blocks even non-autoSend openSidebar
|
||||
engine.setMode({ id: authManifest.id, manifest: authManifest }, "ai.invoke", "deny");
|
||||
await assert.rejects(
|
||||
handlers["ai.openSidebar"]({ prompt: "blocked", autoSend: false }, {}),
|
||||
/disabled|denied/i,
|
||||
);
|
||||
});
|
||||
@@ -10,6 +10,10 @@ export default [
|
||||
files: ["examples/plugins/starter-netcatty/panel.js"],
|
||||
languageOptions: { globals: globals.browser },
|
||||
},
|
||||
{
|
||||
files: ["plugins/*/scripts/**/*.{js,mjs,cjs}"],
|
||||
languageOptions: { globals: globals.node },
|
||||
},
|
||||
// The recommended preset has no file scope of its own, so scope it off all of
|
||||
// electron/ — that main-process tree is historically unlinted. The bridges
|
||||
// get a focused rule set in the dedicated block at the end of this config;
|
||||
|
||||
@@ -336,6 +336,8 @@ void electron.app
|
||||
console.error("MONITOR_ELECTRON_SMOKE_FAILED:", error);
|
||||
try {
|
||||
fs.rmSync(userData, { recursive: true, force: true });
|
||||
} catch {}
|
||||
} catch {
|
||||
// Best-effort temp dir cleanup on failure.
|
||||
}
|
||||
electron.app.exit(1);
|
||||
});
|
||||
@@ -318,6 +318,7 @@ export function computeAlertBadge(
|
||||
const count = Math.min(999, active.length);
|
||||
const criticalCount = active.filter((a) => a.severity === 'critical').length;
|
||||
const tone: 'warning' | 'danger' = criticalCount > 0 ? 'danger' : 'warning';
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const topMsg = (active[0]?.message ?? '').replace(/[\r\n\t\x00-\x1f\x7f]/g, ' ').trim();
|
||||
|
||||
const summary =
|
||||
|
||||
@@ -72,6 +72,11 @@ export function OverviewTab({
|
||||
return { min, avg, max };
|
||||
}, [points]);
|
||||
|
||||
const diskLayout = useMemo(
|
||||
() => buildMonitorDiskListLayout(stats, showSystemDisks, thresholds.diskWarning),
|
||||
[stats, showSystemDisks, thresholds.diskWarning],
|
||||
);
|
||||
|
||||
if (isProbe) {
|
||||
const probe = state?.probe;
|
||||
return (
|
||||
@@ -176,11 +181,6 @@ export function OverviewTab({
|
||||
? Math.min(100, (stats.fdUsed / stats.fdMax) * 100)
|
||||
: null;
|
||||
|
||||
const diskLayout = useMemo(
|
||||
() => buildMonitorDiskListLayout(stats, showSystemDisks, thresholds.diskWarning),
|
||||
[stats, showSystemDisks, thresholds.diskWarning],
|
||||
);
|
||||
|
||||
const hasCpuBreakdown = points.some((p) => p.cpuUser != null || p.cpuSystem != null);
|
||||
|
||||
return (
|
||||
|
||||
@@ -529,8 +529,31 @@ test("node_modules packaging exclusions prune unused payloads while preserving l
|
||||
"node_modules/foo/CHANGELOG.md",
|
||||
"node_modules/foo/HISTORY.md",
|
||||
"node_modules/@anthropic-ai/sdk/README.md",
|
||||
"node_modules/bare-url/prebuilds/ios-arm64/bare-url.bare",
|
||||
"node_modules/bare-fs/index.js",
|
||||
"node_modules/bare-path/index.js",
|
||||
"node_modules/bare-events/index.js",
|
||||
"node_modules/bare-stream/index.js",
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk/assistant.mjs",
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk/bridge.mjs",
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk/browser-sdk.js",
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk/extractFromBunfs.js",
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk/manifest.json",
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk/manifest.zst.json",
|
||||
"node_modules/node-pty/third_party/conpty/1.23.251008001/win10-x64/OpenConsole.exe",
|
||||
"node_modules/node-pty/deps/winpty/src/include/winpty.h",
|
||||
"node_modules/node-pty/src/unix/pty.cc",
|
||||
"node_modules/node-pty/scripts/post-install.js",
|
||||
"node_modules/node-pty/node-addon-api/napi.h",
|
||||
"node_modules/node-pty/typings/node-pty.d.ts",
|
||||
"node_modules/@serialport/bindings-cpp/src/serialport.cpp",
|
||||
"node_modules/sqlite3/src/database.cc",
|
||||
"node_modules/prebuild-install/index.js",
|
||||
"node_modules/tar/index.js",
|
||||
]) {
|
||||
assert.equal(nmMac(path.join(root, dropped), stat), false, `expected excluded: ${dropped}`);
|
||||
for (const [label, filter] of [["mac", nmMac], ["win", nmWin], ["linux", nmLinux]]) {
|
||||
assert.equal(filter(path.join(root, dropped), stat), false, `expected excluded (${label}): ${dropped}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const kept of [
|
||||
@@ -548,9 +571,20 @@ test("node_modules packaging exclusions prune unused payloads while preserving l
|
||||
"node_modules/foo/NOTICE.md",
|
||||
// @anthropic-ai/claude-agent-sdk declares "license": "SEE LICENSE IN README.md"
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk/README.md",
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk/LICENSE.md",
|
||||
"node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs",
|
||||
"node_modules/tar-stream/index.js",
|
||||
"node_modules/node-pty/lib/index.js",
|
||||
"node_modules/node-pty/build/Release/pty.node",
|
||||
"node_modules/node-pty/prebuilds/win32-x64/conpty/OpenConsole.exe",
|
||||
"node_modules/@serialport/bindings-cpp/dist/index.js",
|
||||
"node_modules/@serialport/bindings-cpp/build/Release/bindings.node",
|
||||
"node_modules/sqlite3/lib/sqlite3.js",
|
||||
"node_modules/sqlite3/build/Release/node_sqlite3.node",
|
||||
]) {
|
||||
assert.equal(nmMac(path.join(root, kept), stat), true, `expected preserved: ${kept}`);
|
||||
for (const [label, filter] of [["mac", nmMac], ["win", nmWin], ["linux", nmLinux]]) {
|
||||
assert.equal(filter(path.join(root, kept), stat), true, `expected preserved (${label}): ${kept}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Platform-scoped @vscode/windows-process-tree exclusion
|
||||
@@ -591,6 +625,12 @@ test("app file exclusions prune dev schemas, test helpers/fixtures, svg sources,
|
||||
"electron/bridges/cliDiscoveryTestIsolation.cjs",
|
||||
"electron/bridges/sshBridge/serverStatsTestHelpers.cjs",
|
||||
"electron/bridges/terminalBridge.moshConpty.integration.cjs",
|
||||
"electron/bridges/windowsHelloHelper/NetcattyWindowsHello.cpp",
|
||||
"electron/preload.cjs",
|
||||
"electron/preload/api.cjs",
|
||||
"electron/entitlements.mac.plist",
|
||||
"electron/launch.cjs",
|
||||
"electron/plugins/distribution/README.md",
|
||||
"dist/icon.svg",
|
||||
"dist/tray-iconTemplate.svg",
|
||||
]) {
|
||||
@@ -599,6 +639,7 @@ test("app file exclusions prune dev schemas, test helpers/fixtures, svg sources,
|
||||
|
||||
assert.equal(macFilter(path.join(root, "dist/index.html"), stat), true);
|
||||
assert.equal(macFilter(path.join(root, "electron/main.cjs"), stat), true);
|
||||
assert.equal(macFilter(path.join(root, "electron/preload.bundle.cjs"), stat), true);
|
||||
|
||||
const macosVariantIcon = path.join(root, "dist/icons/variants/macos/icon.png");
|
||||
assert.equal(macFilter(macosVariantIcon, stat), true);
|
||||
|
||||
Reference in new issue
Block a user