Compare commits

...
Author SHA1 Message Date
陈大猫 1cfa14b808 feat(database): enforce vendor variants and adapt native metadata boundaries 2026-11-07 19:46:06 +08:00
陈大猫 67c989c92d feat(database): add host-owned read-only PostgreSQL and MySQL TCP sessions 2026-11-07 17:50:35 +08:00
陈大猫 f907650299 feat(plugins): add app-wide modal presentation for host-drawn views 2026-11-07 16:56:53 +08:00
陈大猫 b4712f13ae feat(plugins): add trusted host icons and local modal focus 2026-11-07 16:09:06 +08:00
陈大猫 040936e7de Add explicit quiescent SQLite WAL session refresh 2026-11-07 15:23:50 +08:00
陈大猫 04b490734f Qualify fixed malformed SQLite fixture rejection 2026-11-07 14:02:56 +08:00
陈大猫 26f447be92 feat: qualify bounded SQLite writer pause and verified capture 2026-11-07 12:58:48 +08:00
陈大猫 8e46ea9ee9 feat: qualify fixture SQLite post-checkpoint admission and recovery rejection 2026-11-07 12:02:52 +08:00
陈大猫 2c1f5610b9 Qualify fixture WAL invalidation under concurrent writers 2026-11-07 11:06:57 +08:00
陈大猫 2a9cb96962 Add conservative fixture WAL snapshots with held sidecar identities 2026-11-07 10:08:37 +08:00
陈大猫 7e289cc072 fix: allow optional host AI feature declarations 2026-11-07 08:50:38 +08:00
陈大猫 d25f17e038 fix: bind fixture SQLite sessions to held file identities 2026-11-07 08:32:51 +08:00
陈大猫 a82a1baeff feat(plugins): add pinned SSH PostgreSQL fixture sessions 2026-11-07 08:12:12 +08:00
陈大猫 0d0635ebb4 feat: probe common database ports on saved hosts 2026-11-07 07:35:42 +08:00
陈大猫 2cf743c0d6 feat: add gated synthetic database tunnel probes 2026-11-07 07:02:45 +08:00
陈大猫 041bdb3ba1 Wait for native SQLite chooser parent focus before permission review 2026-11-07 04:27:52 +08:00
陈大猫 fd24e875be Add bounded readonly multi-table SQLite fixture schemas 2026-11-07 04:04:52 +08:00
陈大猫 258a9d9ac2 Persist fixture database connections with host-owned identity and secrets 2026-11-07 02:28:16 +08:00
陈大猫 74f9d96f60 Add restricted host-owned SQLite file chooser 2026-11-07 01:17:17 +08:00
陈大猫 9777255db8 Qualify Linux SQLite worker termination and target Cursor SDK staging 2026-11-07 00:31:56 +08:00
陈大猫 e1e25ded99 feat(plugins): add guarded experimental SQLite fixture service 2026-11-06 23:44:11 +08:00
88 changed files with 9976 additions and 52 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
type ModalRequest = { kind: 'open'; viewId: string; sourceId: string } | { kind: 'close'; viewId: string };
const listeners = new Set<(request: ModalRequest) => void>();
/** Called only after an owning main-process view session forwards validated navigation. */
export function publishPluginModalRequest(request: ModalRequest) { for (const listener of listeners) listener(request); }
export function subscribePluginModalRequests(listener: (request: ModalRequest) => void) { listeners.add(listener); return () => { listeners.delete(listener); }; }
+12 -1
View File
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import type { HostDrawnViewMessage, HostDrawnViewOpenRequest } from '@netcatty/plugin-contract';
type Update = Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }> & { viewId: string };
type Update = HostDrawnViewMessage & { viewId: string };
import { PluginViewSessions } from './pluginViewSession';
function fixture() {
let updates: (data: Update) => void = () => {}; let closed: (data: NetcattyPluginViewClosedEvent) => void = () => {};
@@ -39,3 +39,14 @@ test('idle instances are evicted while active instances are never silently repla
assert.throws(() => store.acquire('two', f.bridge, request), /Too many/); first.release();
const second = store.acquire('two', f.bridge, request); assert.notEqual(second, first); assert.equal(f.closes.length, 1); store.dispose();
});
test('only the active owning view instance can present or dismiss a modal', async () => {
const { subscribePluginModalRequests } = await import('./pluginModalRequests');
const requests: unknown[] = []; const stop = subscribePluginModalRequests(request => requests.push(request));
const f = fixture(); const store = new PluginViewSessions(); const view = store.acquire('one', f.bridge, request);
const message = { kind: 'host-ui.present' as const, instanceId: f.opened[0].instanceId, viewId: request.viewId, targetViewId: 'com.example.modal' };
f.update({ ...message, instanceId: 'wrong' }); assert.equal(requests.length, 0);
f.update(message); assert.deepEqual(requests[0], { kind: 'open', viewId: 'com.example.modal', sourceId: message.instanceId });
view.release(); f.update(message); assert.equal(requests.length, 1);
store.dispose(); f.update(message); assert.equal(requests.length, 1); stop();
});
+12 -2
View File
@@ -1,3 +1,4 @@
import { publishPluginModalRequest } from './pluginModalRequests';
import { createPluginRemoteTree } from './pluginRemoteTree';
import { validatePluginStylesheet } from '@/domain/pluginViewStylePolicy.cjs';
import type { HostDrawnViewEvent } from '@netcatty/plugin-contract';
@@ -27,7 +28,16 @@ export class PluginViewSessions {
};
if (!bridge.openHostDrawnPluginView || !bridge.onHostDrawnPluginViewUpdate || !bridge.onPluginViewClosed) throw new Error('Plugin views unavailable');
cleanup.push(bridge.onHostDrawnPluginViewUpdate((update) => {
if (disposed || update.kind !== 'host-ui.update' || update.instanceId !== id || update.viewId !== request.viewId) return;
if (disposed || update.instanceId !== id || update.viewId !== request.viewId) return;
if (update.kind === 'host-ui.present') {
if (users > 0) publishPluginModalRequest({ kind: 'open', viewId: update.targetViewId, sourceId: id });
return;
}
if (update.kind === 'host-ui.dismiss') {
if (users > 0) publishPluginModalRequest({ kind: 'close', viewId: request.viewId });
return;
}
if (update.kind !== 'host-ui.update') return;
try {
if (update.sequence !== sequence++) throw new Error('Invalid plugin update order');
publish({ tree: tree.apply(update.mutations), css: validatePluginStylesheet(update.css), loading: false, error: false, settled: (update.acknowledgedEvent ?? 0) >= eventId });
@@ -42,7 +52,7 @@ export class PluginViewSessions {
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 });
const result = await bridge.getPluginViewResource({ instanceId: id, path: path.startsWith('brand:') ? path.slice(6) : path, ...(path.startsWith('brand:') ? { kind: 'brand-icon' as const } : {}) });
if (disposed) throw new Error('Plugin view closed');
return result.url;
},
@@ -0,0 +1,51 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
test('scoped modal requests keep an existing plugin tab and reject duplicate presentation', async () => {
const dom = new JSDOM('<!doctype html><body><div id="root"></div></body>', { pretendToBeVisual: true, url: 'http://localhost' });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'CustomEvent']) {
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] });
}
for (const [key, value] of Object.entries({ IS_REACT_ACT_ENVIRONMENT: true, getComputedStyle: dom.window.getComputedStyle.bind(dom.window), requestAnimationFrame: dom.window.requestAnimationFrame.bind(dom.window), cancelAnimationFrame: dom.window.cancelAnimationFrame.bind(dom.window) })) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
Object.defineProperty(dom.window, 'matchMedia', { value: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }) });
const tabView = { id: 'com.test.plugin.tab', title: 'Tab', location: 'tab', visible: true };
const modalView = { id: 'com.test.plugin.modal', title: 'Modal', location: 'modal', visible: true };
const snapshot = { locale: 'en', plugins: [{ id: 'com.test.plugin', version: '1.0.0', displayName: 'Synthetic plugin', commands: [], keybindings: [], menus: [], settings: [], views: [tabView, modalView] }] };
Object.assign(dom.window, { netcatty: {
async getPluginRuntimeStatus() { return { available: true }; },
async getPluginContributions() { return snapshot; },
onPluginContributionsChanged() { return () => {}; },
async setPluginEnvironment() {},
} });
const { default: React, act } = await import('react'); const { createRoot } = await import('react-dom/client');
const { usePluginViewLifecycle } = await import('./usePluginViewLifecycle');
const { pluginViewTabStore } = await import('./pluginViewTabStore');
const { publishPluginModalRequest } = await import('./pluginModalRequests');
let model: ReturnType<typeof usePluginViewLifecycle> | undefined;
const context = {};
function Fixture() { model = usePluginViewLifecycle({ locale: 'en', theme: 'light', keybindingContext: context }); return <p>{model.activeView?.view.id}</p>; }
const root = createRoot(document.getElementById('root')!); const settle = () => new Promise(resolve => setTimeout(resolve, 40));
try {
const tab = pluginViewTabStore.open({ pluginId: snapshot.plugins[0].id, pluginName: 'Synthetic plugin', viewId: tabView.id, title: 'Tab' });
await act(async () => { root.render(<Fixture />); await settle(); }); await act(async () => { await settle(); });
assert.equal(model?.activeView?.view.id, tabView.id);
await act(async () => { publishPluginModalRequest({ kind: 'open', viewId: modalView.id, sourceId: 'one' }); await settle(); }); await act(async () => { await settle(); });
assert.equal(model?.activeView?.view.id, modalView.id);
await act(async () => { publishPluginModalRequest({ kind: 'open', viewId: 'com.test.plugin.other', sourceId: 'two' }); await settle(); });
assert.equal(model?.activeView?.view.id, modalView.id);
await act(async () => { await model?.close(); await settle(); }); await act(async () => { await settle(); });
assert.ok(pluginViewTabStore.getTab(tab.id), 'modal close must retain its underlying tab');
assert.equal(model?.activeView?.view.id, tabView.id);
await act(async () => { publishPluginModalRequest({ kind: 'open', viewId: modalView.id, sourceId: 'one' }); await settle(); }); await act(async () => { await settle(); });
await act(async () => { publishPluginModalRequest({ kind: 'close', viewId: 'com.test.plugin.other' }); await settle(); }); assert.equal(model?.activeView?.view.id, modalView.id);
await act(async () => { publishPluginModalRequest({ kind: 'close', viewId: modalView.id }); await settle(); }); await act(async () => { await settle(); });
assert.equal(model?.activeView?.view.id, tabView.id); assert.ok(pluginViewTabStore.getTab(tab.id));
await act(async () => { root.unmount(); }); pluginViewTabStore.close(tab.id);
} finally {
dom.window.close(); for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
}
});
+11 -1
View File
@@ -1,3 +1,4 @@
import { subscribePluginModalRequests } from './pluginModalRequests';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
@@ -49,6 +50,7 @@ export function usePluginViewLifecycle({
keybindingContext: Record<string, unknown>;
}) {
const [requested, setRequested] = useState<OpenPluginViewDetail | null>(null);
const requestedRef = useRef(requested); requestedRef.current = requested;
const activeTabId = useActiveTabId();
const pluginViewTabs = usePluginViewTabs();
const activePluginTab = pluginViewTabs.find((tab) => tab.id === activeTabId) ?? null;
@@ -109,6 +111,14 @@ export function usePluginViewLifecycle({
return () => window.removeEventListener('keydown', onKeyDown);
}, [executeCommand, keybindingContext, snapshot.plugins]);
useEffect(() => subscribePluginModalRequests((request) => {
if (request.kind === 'open') setRequested((current) => current ?? { viewId: request.viewId, context: { 'netcatty.surface': 'modal' } });
else if (requestedRef.current?.viewId === request.viewId) {
pluginViewSessions.closeView(request.viewId);
setRequested(null);
}
}), []);
useEffect(() => {
const listener = (event: Event) => setRequested((event as CustomEvent<OpenPluginViewDetail>).detail);
window.addEventListener(OPEN_PLUGIN_VIEW_EVENT, listener);
@@ -144,7 +154,7 @@ export function usePluginViewLifecycle({
const close = useCallback(async () => {
setRequested(null);
if (activeView) pluginViewSessions.closeView(activeView.view.id);
if (activePluginTab) pluginViewTabStore.close(activePluginTab.id);
if (activePluginTab && activeView?.view.location === 'tab') pluginViewTabStore.close(activePluginTab.id);
}, [activePluginTab, activeView]);
useEffect(() => {
@@ -1,3 +1,4 @@
import { PluginModalShell } from './PluginModalShell';
import { X } from 'lucide-react';
import { useI18n } from '../../application/i18n/I18nProvider';
@@ -41,16 +42,16 @@ export function PluginContributionHost({
if (!effectiveRequested || !activeView) return null;
const location = activeView.view.location;
const content = <PluginHostDrawnPage pluginId={activeView.plugin.id} viewId={activeView.view.id} version={activeView.plugin.version} slot={`view:${activeView.view.id}`} active context={viewQueryContext}
const content = <PluginHostDrawnPage showSettingsEntry={location !== 'modal'} pluginId={activeView.plugin.id} viewId={activeView.view.id} version={activeView.plugin.version} slot={`view:${activeView.view.id}`} active context={viewQueryContext}
subscribeHidden={subscribeNoop} unavailable={() => void close()} loadingLabel={t('plugins.vault.loading')} />;
if (location === 'modal') return <PluginModalShell title={activeView.view.title} pluginName={activeView.plugin.displayName} close={() => void close()}>{content}</PluginModalShell>;
const containerClass = location === 'aside'
? 'absolute inset-y-0 right-0 z-40 w-[420px] border-l border-border bg-background shadow-2xl'
: location === 'tab'
? 'absolute inset-0 z-40 flex p-2 pt-0'
: location === 'panel'
? 'absolute inset-x-0 bottom-0 z-40 h-[42%] border-t border-border bg-background shadow-2xl'
: location === 'modal'
? 'fixed left-1/2 top-1/2 z-40 h-[70vh] w-[min(800px,85vw)] -translate-x-1/2 -translate-y-1/2 rounded-xl border border-border bg-background shadow-2xl'
: 'absolute inset-0 z-40 bg-background';
if (location === 'tab') {
@@ -66,9 +67,7 @@ export function PluginContributionHost({
return (
<section
className={`${containerClass} flex flex-col`}
role={location === 'modal' ? 'dialog' : 'region'}
data-plugin-dialog={location === 'modal' ? 'true' : undefined}
aria-modal={location === 'modal' ? true : undefined}
role="region"
aria-label={activeView.view.title}
>
<header className="app-no-drag flex h-11 shrink-0 items-center justify-between border-b border-border px-3">
@@ -85,12 +84,11 @@ export function PluginContributionHost({
className="h-7 w-7"
onClick={() => void close()}
aria-label={t('common.close')}
autoFocus={location === 'modal'}
>
<X size={14} />
</Button>
</header>
<div className={location === 'modal' ? 'flex min-h-0 flex-1 p-3' : 'flex min-h-0 flex-1'}>
<div className="flex min-h-0 flex-1">
{content}
</div>
</section>
+3 -3
View File
@@ -2,14 +2,14 @@ import { useHostDrawnPluginView } from '../../application/state/useHostDrawnPlug
import { PluginSettingsEntry } from './PluginSettingsEntry';
import { PluginRemoteSurface } from './PluginRemoteSurface';
export function PluginHostDrawnPage(props: Parameters<typeof useHostDrawnPluginView>[0] & { loadingLabel: string; pluginId: string }) {
export function PluginHostDrawnPage(props: Parameters<typeof useHostDrawnPluginView>[0] & { loadingLabel: string; pluginId: string; showSettingsEntry?: boolean }) {
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]}>
<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="">
{props.showSettingsEntry !== false && <div className="absolute right-3 top-3 z-10" data-plugin-settings-entry="">
<PluginSettingsEntry key={`${props.pluginId}:${props.version}`} pluginId={props.pluginId} />
</div>
</div>}
</div>;
}
@@ -0,0 +1,15 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { pluginHostIcons, PluginHostIcon } from './PluginHostIcon';
import { HOST_ICON_NAMES } from '../../domain/pluginRemoteTreePolicy.cjs';
test('every policy icon maps to an original host Lucide and unknown names stay empty', () => {
assert.deepEqual(Object.keys(pluginHostIcons).sort(), [...HOST_ICON_NAMES].sort());
for (const name of HOST_ICON_NAMES) {
const markup = renderToStaticMarkup(<PluginHostIcon name={name} />);
assert.match(markup, /<svg/); assert.match(markup, /aria-hidden="true"/);
assert.doesNotMatch(markup, /(?:href|src)=/);
}
for (const name of ['__proto__', 'constructor', '../Database', '<svg>']) assert.equal(renderToStaticMarkup(<PluginHostIcon name={name} />), '');
});
+16
View File
@@ -0,0 +1,16 @@
import React from 'react';
import { Database, Plus, FileCode2, Play, Square, X, ChevronRight, ChevronDown, Table2, Eye, Search, RefreshCw, Sparkles, Unplug, Folder, KeyRound, Check, CircleAlert, LoaderCircle, ArrowRight, PanelLeft, Shield, Settings2, type LucideIcon } from 'lucide-react';
// These are the app's original statically imported icons. No plugin-supplied
// paths, markup, imports, event handlers or URLs ever enter this registry.
export const pluginHostIcons: Readonly<Record<string, LucideIcon>> = Object.freeze({
database: Database, plus: Plus, 'file-code': FileCode2, play: Play, square: Square,
x: X, 'chevron-right': ChevronRight, 'chevron-down': ChevronDown, table: Table2,
eye: Eye, search: Search, refresh: RefreshCw, sparkles: Sparkles, unplug: Unplug,
folder: Folder, key: KeyRound, check: Check, 'alert-circle': CircleAlert,
loader: LoaderCircle, 'arrow-right': ArrowRight, 'panel-left': PanelLeft, shield: Shield, settings: Settings2,
});
export function PluginHostIcon({ name }: { name: string }) {
const Icon = Object.hasOwn(pluginHostIcons, name) ? pluginHostIcons[name] : undefined;
return Icon ? <Icon size={16} strokeWidth={1.75} aria-hidden="true" focusable="false" style={{ pointerEvents: 'none', display: 'block' }} /> : null;
}
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
import { readFileSync } from 'node:fs';
test('modal is a single body portal, occludes native views and retains work on backdrop click', async () => {
const dom = new JSDOM('<!doctype html><body><div id="root"><button>Open</button><div id="native"></div></div></body>', { pretendToBeVisual: true });
const saved = new Map<string, PropertyDescriptor | undefined>();
for (const key of ['window', 'document', 'HTMLElement', 'Element', 'Node', 'MutationObserver', 'MouseEvent', 'Event']) {
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] });
}
for (const [key, value] of Object.entries({ IS_REACT_ACT_ENVIRONMENT: true, getComputedStyle: dom.window.getComputedStyle.bind(dom.window) })) {
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
}
const { default: React, act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { I18nProvider } = await import('../../application/i18n/I18nProvider');
const { PluginModalShell } = await import('./PluginModalShell');
const { isPluginViewOccluded } = await import('../../application/state/pluginViewOcclusion');
const root = createRoot(document.getElementById('root')!); let closed = 0;
try {
await act(async () => { root.render(<I18nProvider locale="en"><PluginModalShell title="New" pluginName="Synthetic plugin" close={() => { closed++; }}><button>Save</button></PluginModalShell></I18nProvider>); });
const portal = document.querySelector('[data-plugin-modal-portal]')!;
assert.equal(portal.parentElement, document.body); assert.equal(document.querySelectorAll('[role=dialog]').length, 1);
assert.equal(document.getElementById('root')!.inert, true);
const native = document.createElement('div'); document.body.append(native);
assert.equal(isPluginViewOccluded(native), true); native.remove();
document.querySelector('[data-plugin-modal-backdrop]')!.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
assert.equal(closed, 0, 'backdrop keeps unsaved content');
document.querySelector<HTMLButtonElement>('[aria-label="Close"]')!.click(); assert.equal(closed, 1);
await act(async () => { root.unmount(); }); assert.equal(document.querySelector('[role=dialog]'), null); assert.equal(document.getElementById('root')!.inert, false);
} finally {
dom.window.close(); for (const [key, value] of saved) { if (value) Object.defineProperty(globalThis, key, value); else Reflect.deleteProperty(globalThis, key); }
}
});
test('main and settings keep their contribution hosts in separate renderer routes', () => {
const entry = readFileSync(new URL('../../index.tsx', import.meta.url), 'utf8');
assert.match(entry, /if \(route === 'settings'\)[\s\S]*?<LazySettingsPage/);
const shell = readFileSync(new URL('../../application/app/AppPluginKeybindingHost.tsx', import.meta.url), 'utf8');
assert.equal((shell.match(/<PluginContributionHost/g) ?? []).length, 1);
const settings = readFileSync(new URL('../SettingsPage.tsx', import.meta.url), 'utf8');
assert.equal((settings.match(/<PluginContributionHost/g) ?? []).length, 1);
});
+25
View File
@@ -0,0 +1,25 @@
import { useLayoutEffect, useRef, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { X } from 'lucide-react';
import { bindPluginModalFocus } from './pluginModalFocus';
import { useI18n } from '../../application/i18n/I18nProvider';
/** Shell owns geometry, modality and dismissal; plugin content stays contained. */
export function PluginModalShell({ title, pluginName, close, children }: { title: string; pluginName: string; close(): void; children: ReactNode }) {
const { t } = useI18n();
const portal = useRef<HTMLDivElement>(null);
const dialog = useRef<HTMLElement>(null);
const closeRef = useRef(close); closeRef.current = close;
useLayoutEffect(() => bindPluginModalFocus(dialog.current!, portal.current!, () => closeRef.current()), []);
return createPortal(<div ref={portal} data-plugin-modal-portal>
<div data-plugin-modal-backdrop className="fixed inset-0 z-[10000] bg-black/40" />
<section ref={dialog} role="dialog" aria-modal="true" aria-label={title} data-plugin-dialog="true" tabIndex={-1}
className="fixed left-1/2 top-1/2 z-[10001] flex h-[min(600px,calc(100dvh-64px))] w-[min(820px,calc(100vw-64px))] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-xl border border-border bg-background text-foreground shadow-2xl">
<header className="app-no-drag flex h-14 shrink-0 items-center justify-between border-b border-border px-6">
<div className="flex min-w-0 items-baseline gap-3"><h2 className="truncate text-sm font-semibold">{title}</h2><span className="truncate text-xs text-muted-foreground">{pluginName}</span></div>
<button onClick={close} aria-label={t('common.close')} className="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring"><X size={16} /></button>
</header>
<div className="flex min-h-0 flex-1 overflow-hidden">{children}</div>
</section>
</div>, document.body);
}
@@ -18,7 +18,7 @@ test('plugin surface forwards its own input and contains malformed updates and r
const { PluginRemoteSurface } = await import('./PluginRemoteSurface');
const events: unknown[] = [];
const tree = { children: [{ id: '1', type: 1, element: 'div', attributes: { class: 'card', style: 'display:grid;gap:8px' }, children: [
{ id: '2', type: 1, element: 'button', attributes: { type: 'button', 'data-netcatty-remote-node': 'forged' }, children: [{ id: '3', type: 3, data: '<b>Hello</b>' }] },
{ id: '2', type: 1, element: 'button', attributes: { type: 'button', 'data-netcatty-remote-node': 'forged' }, children: [{ id: 'icon', type: 1, element: 'span', attributes: { 'data-plugin-icon': 'database' }, children: [] }, { id: '3', type: 3, data: '<b>Hello</b>' }] },
{ id: '4', type: 1, element: 'input', attributes: { type: 'text', value: '' }, children: [] },
] }] };
const root = createRoot(document.getElementById('root')!);
@@ -27,6 +27,9 @@ test('plugin surface forwards its own input and contains malformed updates and r
assert.ok(captured); assert.equal(document.querySelector('[data-plugin-remote-surface]')?.querySelector('button'), null);
assert.equal(captured!.querySelector('button')?.textContent, '<b>Hello</b>');
assert.equal(captured!.querySelector('button')?.getAttribute('data-netcatty-remote-node'), '2');
assert.equal(captured!.querySelector<HTMLElement>('[data-plugin-icon]')?.style.pointerEvents, 'none');
assert.equal(captured!.querySelector<HTMLElement>('[data-plugin-icon]')?.style.display, 'inline-flex');
assert.ok(captured!.querySelector('[data-plugin-icon] svg'));
await act(async () => { captured!.querySelector('button')!.click(); });
assert.deepEqual(events, [{ nodeId: '2', type: 'click' }]);
const input = captured!.querySelector('input')!; input.value = 'typed';
+7 -1
View File
@@ -1,5 +1,8 @@
import { registerPluginShadow } from './pluginModalFocus';
import React, { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { LazyLoadBoundary } from '../ui/lazy-load-boundary';
import { bindPluginDialogFocus } from './pluginDialogFocus';
import { PluginHostIcon } from './PluginHostIcon';
import { PluginViewPopover } from './PluginViewPopover';
import { createPortal } from 'react-dom';
import { validatePluginRemoteTree } from '@/domain/pluginRemoteTreePolicy.cjs';
@@ -19,7 +22,7 @@ function RemoteElement({ node, settled }: { node: RemoteNode; settled: boolean }
const attrs = node.type === 1 ? node.attributes : {};
const surface = useContext(SurfaceContext);
const loadImage = useContext(ResourceLoader);
const imagePath = node.type === 1 && node.element === 'img' ? attrs.src?.slice(6) : undefined;
const imagePath = node.type === 1 && node.element === 'img' ? (attrs.src?.startsWith('brand:') ? attrs.src : attrs.src?.slice(6)) : undefined;
const [imageUrl, setImageUrl] = useState<string | undefined>();
useEffect(() => {
let cancelled = false; setImageUrl(undefined);
@@ -62,6 +65,7 @@ function RemoteElement({ node, settled }: { node: RemoteNode; settled: boolean }
if (event.currentTarget instanceof event.currentTarget.ownerDocument.defaultView!.HTMLInputElement) setLocalChecked(event.currentTarget.checked);
};
}
if (node.element === 'span' && attrs['data-plugin-icon']) return <span {...props} ref={undefined} aria-hidden="true" style={{ display: 'inline-flex', flexShrink: 0, pointerEvents: 'none' }}><PluginHostIcon name={attrs['data-plugin-icon']} /></span>;
return React.createElement(node.element, props, ...(node.element === 'textarea' && remoteValue !== undefined ? [] : node.children).map((child) => <RemoteElement key={child.id} node={child} settled={settled} />));
}
@@ -89,7 +93,9 @@ function ValidatedPluginRemoteSurface({ tree, css, onEvent, settled }: { settled
const root = shadowRef.current ?? host.attachShadow({ mode: 'closed' });
shadowRef.current = root;
setShadow(root);
return registerPluginShadow(host, root);
}, []);
useEffect(() => shadow ? bindPluginDialogFocus(shadow) : undefined, [shadow]);
useEffect(() => {
if (!shadow) return;
const listener = (event: Event) => {
@@ -0,0 +1,24 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
import { bindPluginDialogFocus } from './pluginDialogFocus';
test('plugin modal focuses, traps Tab, and restores its local trigger', async () => {
const dom = new JSDOM('<div></div>', { pretendToBeVisual: true });
const shadow = dom.window.document.querySelector('div')!.attachShadow({ mode: 'closed' });
shadow.innerHTML = '<button id="trigger">Open</button>';
const trigger = shadow.querySelector<HTMLButtonElement>('#trigger')!; trigger.focus();
const dispose = bindPluginDialogFocus(shadow);
const dialog = dom.window.document.createElement('section');
dialog.setAttribute('role', 'dialog'); dialog.setAttribute('aria-modal', 'true');
dialog.innerHTML = '<button id="first">Start</button><button disabled>Disabled</button><input id="last">'; shadow.append(dialog);
await new Promise(resolve => dom.window.setTimeout(resolve, 0));
assert.equal(shadow.activeElement?.id, 'first');
const first = dialog.querySelector<HTMLButtonElement>('#first')!;
first.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Tab', shiftKey: true, bubbles: true, cancelable: true }));
assert.equal(shadow.activeElement?.id, 'last');
shadow.activeElement!.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true }));
assert.equal(shadow.activeElement?.id, 'first');
dialog.remove(); await new Promise(resolve => dom.window.setTimeout(resolve, 0));
assert.equal(shadow.activeElement, trigger);
dispose(); dom.window.close();
});
+27
View File
@@ -0,0 +1,27 @@
/** Local modality only: never reaches outside the plugin's closed shadow root. */
export function bindPluginDialogFocus(shadow: ShadowRoot): () => void {
const view = shadow.ownerDocument.defaultView;
if (!view) return () => {};
let current: HTMLElement | null = null;
let previous: Element | null = null;
const controls = (dialog: HTMLElement) => [...dialog.querySelectorAll<HTMLElement>('button,input,select,textarea,[tabindex]')]
.filter(el => !el.matches(':disabled,[hidden],[tabindex="-1"]') && !el.closest('[hidden],details:not([open])'));
const sync = () => {
const next = shadow.querySelector<HTMLElement>('[role="dialog"][aria-modal="true"]');
if (next === current) return;
if (next) { previous = shadow.activeElement; current = next; (controls(next)[0] ?? next).focus(); }
else { current = null; if (previous instanceof view.HTMLElement && previous.isConnected) previous.focus(); previous = null; }
};
const key = (event: Event) => {
if (!(event instanceof view.KeyboardEvent) || event.key !== 'Tab' || !current) return;
const items = controls(current); const first = items[0]; const last = items.at(-1);
if (!first || !last) { event.preventDefault(); return; }
if (!current.contains(shadow.activeElement) || (event.shiftKey && shadow.activeElement === first) || (!event.shiftKey && shadow.activeElement === last)) {
event.preventDefault(); (event.shiftKey ? last : first).focus();
}
};
const observer = new view.MutationObserver(sync);
observer.observe(shadow, { childList: true, subtree: true });
shadow.addEventListener('keydown', key, true); sync();
return () => { observer.disconnect(); shadow.removeEventListener('keydown', key, true); };
}
@@ -0,0 +1,37 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { JSDOM } from 'jsdom';
import { bindPluginModalFocus, registerPluginShadow } from './pluginModalFocus';
test('shell modality traps closed-shadow controls, Escape closes and restores trigger/inert state', () => {
const dom = new JSDOM('<body><main><button id="trigger">New</button></main><div id="portal"><section role="dialog" aria-modal="true"><button id="close">Close</button><div id="surface"></div></section></div></body>', { pretendToBeVisual: true });
const doc = dom.window.document;
const shadow = doc.getElementById('surface')!.attachShadow({ mode: 'closed' });
shadow.innerHTML = '<input><details><summary>Advanced</summary><input></details><button>Save</button>';
const unregister = registerPluginShadow(doc.getElementById('surface')!, shadow);
const trigger = doc.getElementById('trigger') as HTMLButtonElement; trigger.focus();
let closed = 0;
const cleanup = bindPluginModalFocus(doc.querySelector('section')!, doc.getElementById('portal')!, () => { closed++; });
assert.equal(doc.querySelector('main')!.inert, true);
assert.equal(doc.activeElement?.id, 'close');
shadow.querySelector('button')!.focus();
shadow.querySelector('button')!.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Tab', bubbles: true, composed: true, cancelable: true }));
assert.equal(doc.activeElement?.id, 'close');
doc.getElementById('close')!.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Tab', shiftKey: true, bubbles: true, cancelable: true }));
assert.equal(shadow.activeElement, shadow.querySelector('button'));
shadow.querySelector('input')!.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true, composed: true, cancelable: true }));
assert.equal(closed, 1);
const security = doc.createElement('section'); security.setAttribute('role', 'dialog'); security.setAttribute('data-host-security-surface', ''); security.innerHTML = '<button>Allow</button>'; doc.body.append(security);
return Promise.resolve().then(() => {
assert.equal(doc.getElementById('portal')!.inert, true, 'trusted approval suspends plugin input');
assert.equal(security.inert, false, 'approval must remain actionable');
security.dispatchEvent(new dom.window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }));
assert.equal(closed, 1, 'plugin Escape handler must yield to host approval');
security.remove();
return Promise.resolve();
}).then(() => {
assert.equal(doc.getElementById('portal')!.inert, false); assert.equal(doc.querySelector('main')!.inert, true);
cleanup(); assert.equal(doc.querySelector('main')!.inert, false); assert.equal(doc.activeElement, trigger);
unregister(); dom.window.close();
});
});
+61
View File
@@ -0,0 +1,61 @@
const roots = new WeakMap<Element, ShadowRoot>();
/** Host-owned registry; closed plugin shadows never become public DOM. */
export function registerPluginShadow(host: Element, shadow: ShadowRoot) {
roots.set(host, shadow);
return () => { roots.delete(host); };
}
function controls(root: ParentNode): HTMLElement[] {
const result: HTMLElement[] = [];
for (const node of root.querySelectorAll<HTMLElement>('*')) {
const details = node.closest('details:not([open])');
if (node.closest('[hidden],[inert]') || (details && !(node.tagName === 'SUMMARY' && node.parentElement === details)) || node.ownerDocument.defaultView!.getComputedStyle(node).display === 'none') continue;
if (node.matches('button,input,select,textarea,summary,[tabindex]') && !node.matches(':disabled,[tabindex="-1"],[aria-hidden="true"]')) result.push(node);
const shadow = roots.get(node); if (shadow) result.push(...controls(shadow));
}
return result;
}
function active(doc: Document): Element | null {
let node = doc.activeElement;
while (node && roots.get(node)?.activeElement) node = roots.get(node)!.activeElement;
return node;
}
export function bindPluginModalFocus(dialog: HTMLElement, portal: HTMLElement, close: () => void) {
const doc = dialog.ownerDocument;
const previous = active(doc);
const inert = new Map<HTMLElement, boolean>();
const hasPrioritySurface = () => [...doc.querySelectorAll<HTMLElement>('[role="dialog"], [role="alertdialog"], [data-app-lock-overlay]')]
.some(node => !portal.contains(node) && !node.hidden && node.getAttribute('data-state') !== 'closed'
&& doc.defaultView!.getComputedStyle(node).display !== 'none');
const disableBackground = () => {
const priority = hasPrioritySurface();
portal.inert = priority;
for (const sibling of doc.body.children) {
if (sibling === portal || !(sibling instanceof doc.defaultView!.HTMLElement)) continue;
if (!inert.has(sibling)) inert.set(sibling, sibling.inert === true);
// Host dialogs and lock overlays own input while present. Their own
// modality contains the app; plugins cannot create document-level peers.
sibling.inert = priority ? inert.get(sibling)! : true;
}
};
disableBackground();
const observer = new doc.defaultView!.MutationObserver(disableBackground);
observer.observe(doc.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['role', 'hidden', 'data-state', 'class', 'style'] });
if (!hasPrioritySurface()) (controls(dialog)[0] ?? dialog).focus();
const key = (event: KeyboardEvent) => {
if (hasPrioritySurface()) return;
if (event.key === 'Escape' && !event.isComposing) { event.preventDefault(); event.stopImmediatePropagation(); close(); }
if (event.key !== 'Tab') return;
const items = controls(dialog); const current = active(doc); const index = items.findIndex((node) => node === current);
if (!items.length) { event.preventDefault(); dialog.focus(); return; }
if (index < 0 || (event.shiftKey && index === 0) || (!event.shiftKey && index === items.length - 1)) {
event.preventDefault(); (event.shiftKey ? items.at(-1)! : items[0]).focus();
}
};
doc.addEventListener('keydown', key, true);
return () => {
observer.disconnect(); doc.removeEventListener('keydown', key, true);
portal.inert = false;
for (const [node, value] of inert) node.inert = value;
if (previous instanceof doc.defaultView!.HTMLElement && previous.isConnected) previous.focus();
};
}
+5 -2
View File
@@ -33,15 +33,18 @@ const DialogContent = React.forwardRef<
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & { hideCloseButton?: boolean; overlayClassName?: string }
>(({ className, children, hideCloseButton, overlayClassName, ...props }, ref) => {
const { t } = useI18n()
const abovePluginModal = Object.hasOwn(props, "data-host-security-surface")
|| (typeof document !== "undefined" && !!document.querySelector("[data-plugin-modal-portal]"))
return (
<DialogPortal>
<DialogOverlay className={overlayClassName} />
<DialogOverlay className={cn(overlayClassName, abovePluginModal && "z-[10010] bg-black/40")} />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
className,
abovePluginModal && "z-[10011]"
)}
style={{ boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.25), 0 12px 24px -8px rgba(0, 0, 0, 0.15)' }}
aria-describedby={undefined}
+11
View File
@@ -307,3 +307,14 @@ Native Electron launch on this executor aborts because `chrome-sandbox` is not
root-owned mode 4755. No sandbox bypass or native retry was attempted. Native
screenshots, video, and installed UI acceptance belong to the parent's working
cloud GUI machine on the integrated exact head. No native acceptance is claimed here.
## Optional AI enhancement (database gate D)
A plugin may declare `ai.model-invocation` in optional features together with
optional `ai.invoke`. The manifest validator accepts either required or optional
feature placement, but still rejects an AI permission without a feature declaration.
Compatibility negotiation enables optional AI only on supporting hosts; a required
AI feature still blocks incompatible hosts. Feature negotiation does not grant
permission or guarantee a configured model. Views must handle invocation failures
as unavailable and must never substitute a mock result for a provider response.
No AI RPC, credential boundary or permission policy changes accompany this rule.
@@ -0,0 +1,92 @@
# Existing host database port probe
## Scope and honest semantics
Extend Load permitted hosts and the existing Advanced host selector. Ordinary SSH
vault rows remain capability: metadata-only and tunnelAvailable: false. A negotiated
optional portProbe revision binds selection to the current sanitized metadata.
Selection makes no connection. Probe opens TCP sockets only; PROBE_OK means all five
TCP checks completed, not that any database authenticated or an SSH tunnel opened.
No credentials, payload bytes, SQL, or database session handles are involved.
Host-owned ports: 5432 PostgreSQL, 3306 MySQL / MariaDB, 1433 Microsoft SQL Server,
27017 MongoDB, 6379 Redis. Each completed socket check is open (TCP handshake),
closed (ECONNREFUSED), or timeout (local timeout / ETIMEDOUT). Other network/DNS
errors fail the operation as UNAVAILABLE rather than inventing closed results.
Probe is direct from the Netcatty host machine, not through SSH.
## Threat model
A plugin may forge destinations, ports, host IDs, revisions and cancellation IDs,
race vault changes or permission prompts, flood work, or replay another runtime's
operation. The schema rejects extra fields. Only hostId, revision, probeId enter
the probe request; the hostname comes exclusively from the sanitized authorized
vault row. No plugin-selected IP, DNS resolver, port list, SSH key or password.
The existing synthetic row may also be probed but its tunnel descriptor is not
required and does not make TCP results synthetic.
SSRF: this deliberately permits direct TCP connection to a saved host, including
private addresses, on exactly five ports. Vault metadata permission alone does not
silently initiate network activity: the explicit probe additionally requires
host permission database.query.read for database-host:common-ports. No arbitrary
network permission or payload transfer is introduced. Users who can edit trusted
vault metadata control the destination; DNS may change as with normal hostname
connections. This is not a general-purpose destination admission system.
TOCTOU: hash sanitized host metadata into an opaque revision, validate selection
after permission prompts, re-read before each socket and before returning results.
A changed/deleted selected row fails STALE_HOST, an initially unknown ID fails
UNKNOWN_HOST; no successful stale result is published. A change while an already
started TCP handshake is in flight cannot undo that handshake. Runtime/source
identity and revocation guards remain in force throughout.
Bound global and per-runtime operations, two concurrent socket checks per operation,
short per-port timers including DNS, whole-operation deadlines, bounded replay
records. Cancel is runtime/source scoped, idempotent, and remembers cancellation
that overtakes start. Abort destroys sockets, stops later checks, and suppresses
late authorization/results. Runtime release, revocation, lock, and shutdown abort.
## Contract and implementation
Schema authority: packages/plugin-contract/schema/plugin-contract.schema.json.
Feature database.host-port-probe.v1 is optional. Add DatabaseHostPortProbeCapability,
Request, CancelRequest, PortResult and Result. DatabaseHostMeta.portProbe is optional.
Methods probeHostDatabasePorts and cancelHostDatabasePorts pass through SDK,
runtimePeer and host routes to a host TCP service. Result has code, hostId, optional
hostname (only after authorization), synthetic:false, connected:false, ports.
Stable codes: PROBE_OK, UNKNOWN_HOST, STALE_HOST, CANCELLED, DEADLINE_EXCEEDED,
UNAVAILABLE. Protocol/feature/permission/budget violations retain RPC errors.
UI state lives in a separate hook and never changes SQLite session/test state.
Changing selection, reloading, closing/unmounting clears or cancels probe state.
English and zh-CN follow host locale. UI explains services, statuses, origin and
open-port versus authenticated-session/SSH-tunnel distinction.
## Qualification and non-goals
Real prepared fixture: 127.0.0.1:5432 open; 3306/1433/27017/6379 closed. Tests also
cover timeout, cancellation/deadline, stale/unknown hosts, forged fields, feature
and authorization gates, identity isolation, budgets, cleanup, and honest UI.
Existing SQLite and synthetic tunnel tests remain required. Package and React
HTML evidence are recorded; Electron smoke is attempted if practical.
Live SSH-to-PG is secondary and requires a distinct pinned-key host adapter and
host-API proof. Existing manual forward evidence is not host-API live proof.
No generic live database connection UI, production credentials, arbitrary SQLite
files, SQLCipher, AI, ER/history/import-export, or DBX parity changes. Official
DBX ports and upstream tree are untouched.
## Running focused verification
- `NETCATTY_TEST_PREPARED_DB_PROBE=1 node --test electron/plugins/databaseHostPortProbe.test.cjs` includes the already prepared loopback PostgreSQL fixture. Without the flag, this integration test is explicitly skipped; deterministic tests still run.
- `node --test electron/plugins/sqliteFixtureService.test.cjs electron/plugins/databaseTunnelTest.test.cjs electron/plugins/runtimePeer.test.cjs` covers routes, SQLite and synthetic regressions.
- `npm run test:plugin-contract` and `npm run check:plugin-contract` cover schema/SDK authority and drift.
- The plugin React lane accepts `NETCATTY_TEST_PREPARED_DB_PROBE=1` to render actual host RPC/TCP results, with permission decisions and vault rows injected for the fixture. This is not native vault/permission UI automation.
The full host experiment still requires `NETCATTY_EXPERIMENTAL_DATABASE=1` and an
available SQLite fixture runtime. Port probing does not require the synthetic
tunnel flag. User-facing host matches are limited to 20 with filtering so five
probe results fit the host remote-DOM budget over a populated workbench.
Live qualification remains BLOCKED at the plugin host API. A separate task
host-side diagnostic verified pinned SSH authentication and PostgreSQL SELECT 1
through a fixed forward using existing ssh2 plus fixture psql, including rejection
of a deliberately wrong pin. It is not a shipped live adapter or RPC. Required
follow-up: a separate live capability/result schema, host-owned credential and
session lifecycle, PostgreSQL driver/typed result path, and RPC-bound end-to-end
proof. The synthetic adapter and SYNTHETIC_OK semantics remain unchanged.
+62
View File
@@ -0,0 +1,62 @@
# Host-owned database TCP sessions
The existing `NETCATTY_EXPERIMENTAL_DATABASE=1` gate now advertises the optional
`database.tcp.v1` capability. It does not enable the optional SSH fixture.
`database.openTcp` is part of the public plugin contract and SDK. Requests and
responses are schema validated. Browser plugins remain offline; only the host
opens sockets after `database.query.read` approval for `database:tcp`.
The reviewed registry is `packages/plugin-contract/schema/database-drivers.json`.
Contract generation copies it into the packaged host, and `--check` checks drift.
It records the source mapping, fields, category, port, wire family and qualification.
SQL dialect similarity alone is insufficient: notably GBase requires its vendor
driver in DBX and remains catalog-only here. GoldenDB's DBX agent explicitly uses
`jdbc:mysql`; MariaDB/TiDB/OceanBase profiles use MySQL. PG-compatible profiles
remain best-effort aliases, with vendor-specific authentication unsupported.
PostgreSQL supports SCRAM-SHA-256 with server proof validation, MD5 and password
authentication. MySQL supports native password and caching SHA authentication;
full caching SHA password exchange requires verified TLS. Unknown authentication
methods fail closed. No authentication plugins, local-file requests, JDBC clients,
URLs, socket paths or dynamically loaded modules are accepted from plugins.
Non-loopback targets require TLS with system certificate verification. Cleartext
transport is restricted to literal `127.0.0.1` and `::1`. Custom trust stores,
client certificates, SSH forwarding and production compatibility qualification
are outside this implementation. The existing optional pinned SSH PG test is
unchanged and is not a general database session.
Network sessions are read-only and temporary. Passwords travel only in the open
request and are never written to metadata or returned; only owner-scoped handles
are returned. TCP sessions cannot be saved through the SQLite saved-connection
API. Runtime release, source changes, revocation, app lock, cancellation, deadline
and idle expiry close resources. Opens are limited to eight globally and two per
runtime, with bounded packet sizes and independent operation deadlines.
Existing `readSchema`, `query`, `cancel` and `close` dispatch by opaque session
ownership. Metadata covers the current schema/database, bounded to the public
contract. Queries use anonymous `?` bindings; PostgreSQL converts these to protocol
parameters, MySQL converts string values to UTF-8 hex literals. Multiple
statements, comments, dollar quoting and backslash escapes are rejected in this
small SQL surface. Queries run inside server read-only transactions. Write mode,
file export clauses and selected side-effect functions are rejected. Result bounds
are enforced before crossing the plugin boundary. Oversized or invalid results
fail closed. Use a database account with SELECT grants for an additional server
boundary; read-only transactions do not prohibit every possible server function.
SQLite workers, file identity/WAL guards, opaque secret storage, saved fixtures,
write review and insert-only AI drafts retain their existing boundaries.
Focused tests:
```sh
NETCATTY_TEST_DATABASE_FIXTURE=/absolute/disposable/connections.json \
node --test electron/plugins/databaseTcpService.test.cjs
```
The file contains `postgres` and/or `mysql` entries matching
`DatabaseTcpOpenRequest`. Do not log its contents. Without a fixture the actual
engine test emits an explicit skip. The T306 evidence contains local preparation,
cleanup, native Electron and fixture status scripts. PostgreSQL is qualified
against the prepared loopback server. MySQL has an implemented wire path but
remains unqualified until a real local MySQL/MariaDB fixture is available.
@@ -0,0 +1,107 @@
# Existing-host tunnel boundary: BLOCKED live path, synthetic scaffold
This work does not establish SSH or PostgreSQL connectivity. Docker is unavailable;
PostgreSQL server is not installed (client only), and package installation has not
been authorized. No production hosts, credentials, or keychains are consulted.
## Threat model and boundary
A compromised plugin can forge IDs, replay metadata, race cancellation and runtime
replacement, and supply hostile RPC fields. It must never choose an SSH endpoint,
forward destination, host key, credential bytes to redeem, or another source's
secret. Host metadata is not authority and selection is never connection success.
The host keeps the existing metadata-only capability and tunnelAvailable:false.
A parallel optional tunnelTest descriptor advertises only a recorded synthetic
adapter, with an opaque revision. Ordinary vault rows have no descriptor. A
separate, clearly labeled host-owned synthetic row is exposed only when both
NETCATTY_EXPERIMENTAL_DATABASE=1 and NETCATTY_DATABASE_TUNNEL_SYNTHETIC=1 are set,
and the plugin negotiates database.tunnel-test.synthetic.v1. It is an in-process
bridge fixture, not the disposable sshd and not a user vault host.
The sole allowed fixture is SSH 127.0.0.1:2222 / smoketest and forward destination
127.0.0.1:5432, with a synthetic pinned fingerprint. These are host constants;
the synthetic adapter opens no socket. No arbitrary destination or DNS resolution
is accepted. A future live adapter must pin a fixture's actual host-key digest,
reject unknown/mismatched keys before auth, and enforce the same target allowlist.
No trust-on-first-use or password retry loop is permitted.
## Flow and contracts
1. listHostsForDatabase returns metadata. No secret creation or session occurs.
2. An explicit database.testTunnel request contains only hostId, revision, testId.
The host registers a cancellable operation before permissions, validates the
current descriptor, and requests database read, vault.metadata and secrets
permission. Metadata revisions and active source/runtime identity are checked
again after prompts and adapter completion.
3. The host creates (once) a disposable random fixture credential in the existing
PluginSecretStore and retains only its opaque reference between requests.
Repeated tests resolve that same reference inside the host. This credential is
only for the recorded adapter; it is NOT the smoke sshd password or key.
safeStorage must be available; basic_text remains denied. No plaintext is sent
back in results, errors, events or evidence.
4. The narrow host adapter open({target, credential, signal}) returns a closeable
resource or a typed failure. The synthetic adapter can record success,
wrong-auth, unknown-host-key and host-key-mismatch, with cancellation delays.
Cleanup is attempted for every acquired resource in finally, including late completion after
abort. Runtime release, revocation, lock and shutdown abort pending operations.
5. The result is a terminal status snapshot: synthetic-passed / failed / cancelled,
a stable code, synthetic:true, connected:false, closed:true, optional opaque
secretRef. There is no live handle, SSH connected event, stream, or PG session.
An unexpected adapter cleanup failure returns UNAVAILABLE with closed:false;
it must not be presented as a successful or closed probe.
The UI shows testing then the terminal status and never promotes it to its
SQLite connection state. No event subscription is needed for this short probe.
6. database.cancelTunnelTest({testId}) is idempotent and runtime/source scoped.
Bounded tombstones prevent cancel-before-start races and test-ID replay.
Operation deadlines and a bounded pending budget prevent resource exhaustion.
Schema is the only wire authority. Add DatabaseTunnelTestFeature,
DatabaseTunnelTestCapability, DatabaseTunnelTestRequest,
DatabaseTunnelCancelRequest and DatabaseTunnelTestResult plus SDK/runtime methods.
DatabaseHostMeta gets only optional tunnelTest. Existing engine:"sqlite", saved
metadata, file policy, and tunnelAvailable:false remain unchanged. Negotiation
protects older clients from the additional field. Generated TypeScript and host
schema are regenerated, packaged SDK/contract/CLI are synced to plugin vendor.
Stable probe codes: SYNTHETIC_OK, AUTH_FAILED, UNKNOWN_HOST_KEY,
HOST_KEY_MISMATCH, UNKNOWN_HOST, STALE_HOST, CANCELLED, DEADLINE_EXCEEDED,
UNAVAILABLE. RPC malformed requests, feature absence, denied permissions,
identity mismatch, replay and budget limits retain existing invalidArgument,
unsupported, permissionDenied, failedPrecondition and resourceExhausted errors.
Permission failures inside the probe become UNAVAILABLE; the surrounding RPC
identity/authorization guards can still reject with their standard codes.
Raw adapter/SecretStore errors are never surfaced. Unexpected cleanup failure
returns UNAVAILABLE with closed:false; only closed:true is eligible for synthetic
success presentation. The shipped recorded adapter has idempotent, nonthrowing
cleanup. Secret reference ownership is
resolved using the authenticated plugin/source, not client-provided identity.
## Verification and non-goals
Tests must cover recorded success (explicitly not live), wrong auth without a
handle or diagnostic bytes, unknown host/key and mismatch, abort during auth,
cancel before dispatch, late resource return, idempotent cleanup, metadata-only
selection, same-reference reconnect, host revision changes, runtime/source
isolation, revocation and feature gates. UI tests cover disabled ordinary hosts,
synthetic labels, cancellation/stale completion, and English/zh-CN copy.
No openViaHost or live connected state is implemented until a real SSH+PG fixture
is proven. Future work adds a separate live capability and PG result types rather
than reinterpreting this synthetic result. Non-goals: production keychain reuse,
jump hosts, arbitrary remote PG, MySQL, SQLCipher, arbitrary SQLite admission,
TOCTOU file rewrites, live AI, ER/history/import-export and DBX parity.
Qi's next decision is approval for a disposable local PostgreSQL server package,
or provision of a pre-seeded local fixture image/tarball with server binaries and
task-owned disposable SSH credentials. Neither apt install nor docker pull is
performed. Native live success evidence is intentionally absent in BLOCKED mode.
## Follow-up: direct saved-host port probe
The environment limitations above describe the original synthetic-scaffold pass.
A later task prepared a disposable local PostgreSQL fixture and implemented
[direct common-port probing](database-host-port-probe.md) for ordinary saved hosts.
That TCP-only capability is separate from this recorded tunnel adapter. An open
port does not authenticate PostgreSQL or open SSH, and SYNTHETIC_OK remains purely
synthetic. The plugin host live SSH-to-PostgreSQL session API is still unavailable.
+22
View File
@@ -161,3 +161,25 @@ library or malicious plugin has been exhaustively verified.
context assignment in `TerminalLayerSidePanelSection.tsx`; the newly added
host-rendering modules have no reported errors. This does not turn the whole
project check into a passing check.
## Host visual primitives (local coordinated host/plugin build)
Views can read `--font-sans`, `--font-mono`, `--radius`, `--input`, `--ring`,
`--accent`, `--accent-foreground`, and `--destructive` in addition to the semantic
colors above. These variables cannot be assigned by plugin styles. This requires
a host build containing the corresponding stylesheet policy; older builds reject
unsupported variables rather than weakening stylesheet validation.
A decorative leaf `<span data-plugin-icon="database" aria-hidden="true" />`
requests an original, statically imported host Lucide icon. Names are explicitly
listed in `domain/pluginRemoteTreePolicy.cjs` and mapped in
`components/plugins/PluginHostIcon.tsx`, with a parity test. Unknown names,
non-span requests and icon children reject. No path, SVG, URL, arbitrary import,
module lookup or event callback is accepted. Icons are fixed at 16px and ignore
pointer events; put an accessible name on the surrounding button. User-supplied
SVG remains forbidden.
Within a surface, a `[role="dialog"][aria-modal="true"]` element moves keyboard
focus to its first control, contains Tab/Shift+Tab and restores the local trigger
when removed. The plugin owns its Escape handler. This does not create a trusted
host permission dialog, escape clipping, or move focus outside the closed root.
@@ -0,0 +1,53 @@
# Live SSH PostgreSQL fixture (experimental gate B)
`database.host-live-ssh-pg.fixture.v1` is optional and off by default. Enable both
`NETCATTY_EXPERIMENTAL_DATABASE=1` and
`NETCATTY_DATABASE_LIVE_SSH_PG_FIXTURE=1` to advertise it when the experimental
database runtime is available. The fixture row is host-owned; ordinary vault
hosts remain metadata-only with `tunnelAvailable:false`, even at the same address.
This development gate is intentionally tied to the prepared fixture at
`/workspace/agent-tools/database/existing-host-probe/fixture`. It installs nothing.
The host reads its mode-600 `ssh/id_ed25519` and `pg-connect.env` into
PluginSecretStore, and uses its `pg/pgsql/bin/psql` client. Secure OS storage is
required; `basic_text` is rejected. No secret value is exposed to the plugin.
Fixture references use a host-only source namespace, so plugin secrets RPC cannot
replace or resolve them. Encryption and source ownership continue to be enforced
by PluginSecretStore.
The host fixes SSH to `127.0.0.1:2222` / `smoketest`, pins SHA256
`b9cebvdhVKqAto25HDIEv+hOU6v3LM86OOvQDQLyVe0` before authentication and forwards
only to `127.0.0.1:5432`. PostgreSQL is fixed to `nc_probe` / `nc_db_probe`. The
plugin cannot supply SQL, network targets, users, keys, passwords or file paths.
The host-side psql process has a minimal environment, ignores startup files and
executes only `SELECT 1`. PG traffic runs inside the authenticated SSH forward.
1. `listHostsForDatabase` returns an optional `liveSshPg` fixture descriptor and
revision; selecting it does not connect or access secrets.
2. `openHostLiveSshPgFixture({hostId, revision, openId})` authorizes vault metadata,
secrets and database read access to `database-host:live-ssh-pg-fixture`.
The host checks revision and runtime identity around prompts, before dialing
and before returning proof. Only authenticated `SELECT 1 = 1` can return
`LIVE_OK`, `connected:true`, `fixture:true`, and a session ID.
3. `closeHostLiveSshPgSession({sessionId})` is owner-scoped and idempotent. Its
closed acknowledgement waits for the PostgreSQL process and listener cleanup.
`cancelHostLiveSshPgFixture({openId})` cancels pending work or closes that open's
resource and remembers cancellation overtaking open.
Sessions expire after 30 seconds. Opens have a 15-second deadline; pending and
retained resources share an 8-global/2-per-runtime budget. Runtime release,
revocation, lock, shutdown and transport failures clean resources. No general SQL
query method is exposed. The plugin immediately closes successful sessions and
shows a completed fixture live-test result without changing SQLite connection
state. Synthetic `SYNTHETIC_OK` and TCP `PROBE_OK` retain their existing meanings.
Run the prepared-fixture integration tests explicitly:
```sh
NETCATTY_TEST_LIVE_SSH_PG=1 node --test electron/plugins/databaseHostLiveSshPg.test.cjs
```
Node tests use an explicitly identified AES-GCM test backend for PluginSecretStore;
they do not qualify native safeStorage. A real desktop secure backend is required
for native use. No production hosts, arbitrary SQLite admission, MySQL, SQLCipher,
AI, history, import/export or ER features are included.
+43
View File
@@ -0,0 +1,43 @@
# App-wide contributed modal views
Require feature `views.modals` and declare a normal contributed view with
`location: "modal"`. The existing `views` permission still applies. Register
both the source view and the modal with `registerHostReactView` (or
`registerHostDomView`). The render callback receives an instance-bound
`HostViewController`:
```tsx
registerHostReactView(context.views, 'com.example.plugin.home', controller =>
<button onClick={() => controller.openModal('com.example.plugin.editor')}>
Open editor
</button>);
registerHostReactView(context.views, 'com.example.plugin.editor', controller =>
<button onClick={() => controller.close()}>Done</button>);
```
`openModal` can present only a currently available modal contribution owned by
the same plugin/version/runtime. `close` can dismiss only the calling modal.
The main process validates the shared `HostDrawnViewMessage` schema, live source
instance, ownership and context before forwarding to its owning window. Requests
share the view message rate limit. Closed/revoked instances cannot navigate.
There is no plugin window event API, arbitrary overlay geometry, raw DOM access,
new native child view, or plugin JavaScript in the host renderer.
The single contribution host in each renderer owns a body portal, full-window
dimmer, title and close button, background inertness, Escape, Tab containment
(including closed shadow controls), and trigger focus restoration. Trusted host
security dialogs sit above plugin modals. Any host dialog or app lock temporarily
suspends plugin inertness/focus handling so approvals and unlocking stay usable. Backdrop
clicks deliberately retain the form. A second open request while a view is
already presented is ignored. Dismissal destroys the modal's logical session;
use component cleanup to cancel draft work and clear transient secrets. An
underlying plugin tab remains open. Runtime withdrawal, lock and owner teardown
continue through the existing view session lifecycle. Native child views yield
to the host `aria-modal` dialog through `pluginViewOcclusion`.
Content remains a validated, styled, clipped remote tree. The modal's title and
publisher identity are host-owned; author only the body and footer. Settings has
its own contribution host in its separate window route; do not mount another in
the main application. Keep application data with its existing owner and exchange
only runtime-local state between the plugin's registered views. Do not persist
password drafts in view state.
+12
View File
@@ -79,3 +79,15 @@ This is API/schema revision `0.1.0-internal.1`. An older host rejects the unknow
manifest field or missing required feature. The new host continues to offer
`0.1.0-internal` for legacy plugins without the new field, including exact old
API ranges. Existing plugins need no manifest or data migration.
## Brand marks inside host-drawn views
Use `src="brand:assets/engine-light.png"` on an `img` in a remote tree. The
resource remains relative to that view's verified installed package. The
`brand:` path reuses `inspectPluginBrandIcon` (static PNG/WebP, 256 KiB, 512px)
and the offline isolated contribution raster decoder; SVG, URLs and traversal
are rejected. Choose the light/dark package path from the host environment.
Require `metadata.brand-icon` for this form. This does not change the existing
`asset:` image contract or grant access to another package. A plugin can convert
its reviewed source SVGs offline and retain source/license hashes in its own
ledger; only the raster is sent through the brand path.
@@ -316,3 +316,17 @@ require that feature or handle its absence. Optional authorization defaults to
Bearer. Basic authorization accepts a bounded username. Plaintext is redeemed
only inside the host after origin permission and operation binding checks.
See the [synthetic fixture](../../examples/plugins/lease-http/README.md).
### Experimental database tunnel probes
`database.tunnel-test.synthetic.v1` is a recorded, in-process fixture behind both
`NETCATTY_EXPERIMENTAL_DATABASE=1` and `NETCATTY_DATABASE_TUNNEL_SYNTHETIC=1`.
It is not an SSH transport. Only the host-created synthetic metadata row has a
`tunnelTest` descriptor; every row retains `tunnelAvailable: false`. Requests
carry host ID, revision and test ID, with no destination or credential fields.
The host uses a dedicated plugin/source-owned SecretStore namespace for a random
disposable adapter credential. It never reads real SSH credentials. Results
contain only status and an optional opaque ref, never secret bytes or a connected
handle. Cancel, lock, revocation and runtime shutdown discard the probe; any late
adapter resource is closed. PostgreSQL and MySQL remain unavailable. See
[the design and live blockers](database-tunnel-synthetic.md).
+509
View File
@@ -0,0 +1,509 @@
# Experimental SQLite fixture service
`database.sqlite-fixture.v1` is advertised only with
`NETCATTY_EXPERIMENTAL_DATABASE=1` and a host Node SQLite build with authorizer
and defensive-mode support. It is off by default, independent of advanced
plugin development mode. Public types come from the canonical contract schema.
The original target is an in-memory, synthetic `notes` fixture. M2 adds the
restricted Linux chooser described below. There is no path,
URL, connection string, executable, argument, environment or credential field.
The host selects a fixed checked-in subprocess script and its own executable.
Private IPC carries validated operations. The subprocess inherits only
`ELECTRON_RUN_AS_NODE=1` and `NODE_NO_WARNINGS=1`, not the host environment.
Plugin scripts never run there. No DBX or external driver is loaded.
Both `database.query.read` and `database.query.write` default to Ask. The existing
owner-aware permission engine handles declarations, policy, grants and audit.
Every in-memory write additionally presents the exact immutable SQL and bound parameters
in a native host dialog with Cancel as default; generic Allow cannot skip it.
The service rechecks owner/runtime/feature/lock/policy/session after each await.
Revocation closes sessions and prevents late approved actions. Audit contains
permission/resource metadata only, never SQL, parameter values or result bodies.
SQLite's default-deny authorizer permits only SELECT and recursive SELECT,
reads of admitted fixture objects in `main`, an explicit finite function list and, in write mode,
INSERT/UPDATE/DELETE on notes. It rejects schema changes, PRAGMA, ATTACH, virtual
tables, extension loading, transaction commands, system-table reads and unsafe
functions. Trailing statements are rejected after prepare. Only anonymous `?`
bindings are accepted; missing/extra/named/numbered bindings fail. Parser text
alone is never read-only proof. Writes with RETURNING are unavailable.
Limits: two sessions/runtime, eight/host, one operation/session, ten-minute
absolute session lifetime, 3-second execution deadline, 16 KiB total request,
8 KiB SQL, 32 parameters/columns, 100 preview rows, 2048 characters/string and
96 KiB result rows. Blobs have length-only markers. The fixture permits at most
1000 IDs and bounded title/status values. Deadline/cancel/close kills the owned
subprocess and discards memory; no write is replayed. Native SQLite calls cannot
be reliably interrupted by `Worker.terminate`, hence the subprocess boundary.
The V8 heap flag is not a hard native-memory limit: OS memory containment and
untrusted-file handling remain qualification blockers for general databases.
## Linux worker qualification
`node --test electron/plugins/sqliteFixtureService.test.cjs` includes live Linux
process checks. They observe increasing user/system CPU ticks in `/proc` before
the default 3-second deadline, explicit cancel and RPC abort; then require
`exit(null, SIGKILL)`, disappearance from `/proc`, and `kill(pid, 0)` returning
ESRCH. A reopened fixture must contain the original three notes, including after
a cancelled session had approved writes. Malformed-query/cancel races are also
reaped; a parser error may win the race, so this is not a claim that malformed
SQL necessarily executes for a measurable duration.
SQL is limited to 8192 UTF-8 bytes as well as the wire schema's character limit.
Oversized SQL, bindings and total requests fail before IPC dispatch. More than
32 result columns fail. Row, string and result-byte excess retains the existing
bounded-preview contract (`truncated: true`), rather than returning oversized
data. Tests verify clean pending/review state and subsequent reads in each case.
These checks qualify termination on the tested Linux kernel, not hard resource
isolation. The parent event loop owns the wall-clock deadline. There is no
per-worker RLIMIT/cgroup CPU or native-memory quota, and a large SQLite
intermediate value can allocate before preview bounds apply. A parent crash
during synchronous native execution is not covered by the IPC-disconnect hook.
Hard native-memory containment, parent-death cleanup and bounded cleanup under
host overload remain production gates before arbitrary files or broader SQL
are exposed. The experimental feature remains default-off and disposable-fixture-only.
## M2 restricted Linux file chooser
`database.sqlite-file-fixture.v1` is negotiated separately, under the same
experiment flag on Linux. `database.openSqliteFile({})` calls the injected
Electron native chooser; cancellation returns null. No plugin path is accepted.
Only direct regular `.sqlite`/`.db` files under the fixed evidence directory
`/workspace/agent-tools/database/m2-chooser/fixtures/` are admitted. This is not
a general user database opener. This M2 directory still exposes only ordinary `notes`.
Approval binds realpath, device/inode, size, mtime and ctime. Symlinks,
noncanonical ancestors, hard links, WAL headers, and any WAL/SHM/journal sidecar
are rejected. Checks run after approval and before/after worker open and queries.
Changes invalidate sessions. These checks detect stable path/content changes;
they do not eliminate native pathname-open TOCTOU/ABA races against hostile
local writers. Keep the directory trusted and disposable.
The result has only an opaque handle, required revision, constant display label,
engine, fixture and readOnly flags. File requests must echo the revision; memory
requests remain backward compatible. Owner/runtime/source checks still apply.
The distinct read resource is `sqlite:disposable-file`. File writes are denied
before any write grant/review and independently by the worker, SQLite read-only
open and query_only. Defensive mode, trusted_schema off, a 100 ms busy timeout,
existing result limits and worker deadlines apply. Cancellation kills the worker;
it does not delete the fixture file. Close can release a target after deletion.
Tests cover chooser cancellation, feature negotiation, file read/close/reap,
read-only defenses, revisions/ownership, chooser/approval/worker-boundary swaps,
content changes, deletion, sidecar gates and an external-process exclusive lock.
WAL correctness, corrupt files, concurrent sidecar races, hostile filesystem
writers, arbitrary schemas, file writes and hard resource isolation remain
unqualified. PostgreSQL/MySQL and other platforms are out of scope.
## M3b readonly multi-table fixture
The same chooser additionally admits direct regular `.sqlite`/`.db` files under
`/workspace/agent-tools/database/m3b-multitable/fixtures/`. No configurable root,
plugin-supplied path or arbitrary user-file admission is added. All M2 identity,
link, sidecar, permission, revision, worker-open and saved-reopen checks apply
unchanged. The new directory is trusted, synthetic evidence only; the old M2
directory and memory fixture remain notes-only. `openFixture` still opens memory;
`openSqliteFile` opens the new file through the existing host chooser.
Only this new directory enables discovery of ordinary tables and views in `main`.
The authorizer reads only that discovered object set; `sqlite_*`, PRAGMA, unsafe
functions, virtual/shadow tables and all file writes remain unavailable. View
queries also authorize their underlying reads/functions. Generated columns are
not qualified. Discovery fails closed above 32 objects, 32 columns/object or
96 KiB serialized metadata, or above the contract's identifier/type limits.
Existing query deadlines, row/byte limits and kill/reap behavior are unchanged.
`DatabaseSchemaResult.tables` now holds up to 32 table/view objects. Optional
`kind` distinguishes them (absent means table for legacy hosts); optional column
`nullable` reports SQLite NULL acceptance, including rowid aliases, ordinary
nullable primary keys, STRICT and WITHOUT ROWID tables. View nullability is
omitted, not inferred. No DDL, index details or defaults are returned. Existing
single-table responses remain valid; paired host/plugin builds are required for
the expanded schema response. There is no second private structure API.
The disposable `commerce.sqlite` fixture and reproducible creation helper live
under the M3b evidence directory. It contains `customers`, `products`, `orders`,
`order_items` and view `order_totals`. Its SHA and test results are recorded in
`fixture.json` and `astra-m3b-multitable-report.md` in the evidence workspace.
Native full-host GUI/chooser/keychain/IME acceptance remains the next gate.
## Gate C held identity and strict WAL rejection (Linux)
The implementation now supersedes M2's pathname-only identity checks for
fixture inode binding. `database.sqlite-fd-identity.fixture.v1` is advertised
with the existing default-off Linux file experiment. All file operations use
this hardening, including callers that only negotiate the earlier file feature;
there is no pathname-only fallback or new plugin-supplied path field.
Admission walks directories using held O_DIRECTORY|O_NOFOLLOW descriptors and
opens the main file O_RDONLY|O_NOFOLLOW. The main descriptor stays held across
approval and the session and is inherited by the worker as fd 4. Validation uses
fstat plus pathname/ancestor checks, link count, bounded size (32 MiB maximum),
mtime/ctime and SHA-256 through the held fd. Fingerprinting catches same-size
rewrites even on filesystems whose timestamps do not advance between writes.
Old saved identities without a fingerprint remain readable; a successful reopen
acquires a fingerprint for the session, and new saves include it. Persisted
records and public responses never contain descriptors.
SQLite canonicalizes `/proc/self/fd/4` back to a pathname. The worker therefore
also audits its newly opened native regular-file descriptors immediately after
DatabaseSync construction, before schema/data operations. Exactly one must
match the held inode and metadata. An unexpected descriptor or identity fails
closed. The verified native descriptor is checked around operations as well.
Holding the original inode prevents inode-reuse ABA; the native-fd audit catches
a substituted open even if the pathname has already been restored. This is
verified-inode reopening, not a custom fd-native SQLite VFS. A rejected native
open can transiently touch a replacement pathname; it cannot publish its schema
or rows. Procfs/kernel integrity and trusted single-purpose worker code are
assumptions, not an arbitrary-user-file safety claim.
Identity checks no longer reopen and close the main inode, which would release
all POSIX locks for that inode in the checking process. Tests retain a shared
SQLite transaction through 100 identity checks while a separate process fails
three exclusive-lock attempts at the 100 ms busy timeout, then succeeds after
rollback. Session close/cancel/deadline kill and reap the worker; the host closes
its held descriptors. Pending permission abort/revoke/shutdown also closes them.
WAL remains explicitly rejected: no live-reader feature is advertised. WAL
headers and any WAL/SHM/rollback-journal entry, including dangling and external
symlinks, are rejected through the held main/directory identities. Tests include
prepared WAL files and concurrent hostile sidecar replacement. No checkpoint,
recovery, live WAL or atomic snapshot is qualified. In particular, raw in-place
writes that ignore SQLite advisory locking can race inside a native call;
pre/post validation is not an atomic content snapshot and cannot prove zero SHM
side effects during an adversarial journal-mode transition. A qualified VFS or
immutable snapshot design is still needed for that stronger guarantee. Boundary
rewrite/truncate races fail closed; this is not a guarantee against content being
changed and restored entirely within a native call and filesystem timestamp tick.
The fixed M2/M3b directories, mock-only AI, readonly file surface and existing M1
resource/parent-death limitations remain. General user files and other platforms
are not admitted by this gate.
## Gate E stable WAL fixture snapshots (Linux, opt-in)
`database.sqlite-wal-readonly.fixture.v1` is advertised only with the same
Linux, default-off database file experiment. The plugin negotiates it optionally;
callers without it retain the Gate C WAL-header and all-sidecar reject lane.
There is no new path input or public contract/SDK shape. This supersedes the
blanket WAL non-claim above only for a stable prepared fixture snapshot. It is
not a native live connection to a changing WAL database.
The host retains the original main fd and ancestor descriptors. It also retains
no-follow, read-only WAL and optional SHM fds; each must be a regular singly linked
file in the same fixed fixture directory. Inode, size, timestamps, SHA-256 and
namespace checks cover admission, approval, snapshot construction, worker entry
and result publication. Absence of SHM is bound too. Rollback journals, missing
WAL, links, replacement, changed contents and unsupported files fail closed.
Saved metadata adds optional sidecar identities; older rollback records remain
readable. A changed saved WAL must be selected and saved again.
Bounded source buffers must match the captured hashes. The snapshot builder
validates WAL version, page size, salts and rolling checksums, requiring complete
frames and a final commit. It overlays the committed pages in a derived image;
only that image's journal-version bytes change to rollback mode. Partial tails,
uncommitted tails, stale reset frames, inconsistent headers and images over
32 MiB are rejected, not recovered. Main, WAL and optional SHM each have a 32 MiB
limit. Checksums follow [SQLite's WAL format](https://sqlite.org/fileformat2.html#walformat).
They detect corruption; they do not authenticate an attacker-controlled database.
The derived image is an exclusively created mode-0600 disposable fixture in the
same allowlisted directory. Its separate held fd is inherited as fd 5 and audited
against SQLite's native fd before schema/data statements. Source main remains fd
4, source WAL fd 6, optional SHM fd 7. SQLite never opens the source main or its
sidecars on this lane. SHM is fingerprinted, never interpreted, copied, mapped or
written. Tests prove unchanged source bytes and committed WAL rows for the
prepared notes/commerce corpus, and no snapshot SHM creation on these inputs.
The existing authorizer, defensive mode, query_only, trusted_schema off, output
limits and worker deadline remain. Close/cancel/revoke/deadline reap the worker,
close retained fds and unlink the owned derived image. A host crash can leave a
mode-0600 derived fixture; crash cleanup/recovery is not qualified.
The session does not refresh. Any detected source or sidecar change invalidates
it; reopen explicitly. No coordinated concurrent writer/reader, checkpoint,
recovery, custom VFS, SQLCipher or general user-file support is claimed. Acquisition
is not an atomic multi-file filesystem snapshot. Pre/post checks retain C's
residual for fully restored in-place content changes inside a timestamp tick,
and derived-image native reopening retains C's pathname/native-call residuals.
Thus this does not claim zero side effects under arbitrary hostile in-place
journal-mode transitions on the derived image. A new general user-file gate would
still require stronger isolation/VFS qualification. The parser handles a narrow
stable format subset, not a broad malformed-database or crash-recovery corpus.
Snapshot preparation runs bounded synchronous work on the host before the worker
deadline; M1 native CPU/memory quotas and event-loop overload remain unqualified.
Gate D's optional unexecuted host AI drafts are unchanged; the earlier mock-only
AI note is historical, not a rollback of Gate D.
Derived-image creation and cleanup use the retained fixture directory fd, not
mutable ancestor paths. Creation is exclusive; unlink occurs before releasing
that directory fd. If hostile replacement/permissions prevent unlink, fds still
close and no recursive deletion is attempted; an artifact may remain. Renamed
ancestor paths invalidate the source identity; no atomic namespace guarantee is
claimed beyond confinement to the retained original fixture directory inode.
## Gate F concurrent fixture writer qualification (Linux, opt-in)
`database.sqlite-wal-concurrent.fixture.v1` is an additive qualification marker,
only advertised alongside Gate E and the default-off Linux file experiment.
Gate E remains the admission switch; F alone cannot enable WAL. No new public
wire shape, plugin path input, native source connection or write capability is
introduced. English/zh-CN notices require both E and F. The C/E parser, permission and result-publication checks are unchanged; the
identity admission fence below additionally addresses a same-tick ABA failure.
A test-only separate-process writer (`scripts/sqlite-wal-concurrent-fixture.cjs`)
creates unique synthetic notes files inside the existing M2 fixture directory.
It keeps SQLite open with automatic checkpoints disabled. With a real host
snapshot session open, repeated reads return the same committed rows until a
source change is observed. Six acknowledged commits invalidate six old handles;
each fresh explicit chooser admission after writing pauses reads the new rows.
This is reselection into a new session/revision, not an in-session re-snapshot,
automatic retry or live refresh. Existing saved fingerprints reject changed
sources and require reselection/saving again. No availability promise is made
while writing continues or capture races with changes.
Commits after host preflight, during a CPU-observed native query, and between
worker result and host publication reject without returning stale rows. Detection
occurs at operation/publication boundaries, not through a background watcher.
An invalidated handle closes, kills/reaps its worker, releases held fds and
removes its derived image. Already displayed rows are historical; they are not
a continuously current view. Starting BEGIN IMMEDIATE can itself modify SHM and
invalidate a session before any row is committed. This conservative rejection
is intentional. Replacing either sidecar while a source write transaction is
held still fails at worker validation; C/E hostile-link/ABA tests remain required.
Held source fds do not establish native SQLite WAL read transactions. They do
not block or coordinate source writers/checkpoints. A second writer gets
SQLITE_BUSY (code 5) at the configured 100 ms busy timeout while the first holds
BEGIN IMMEDIATE, including across repeated host identity checks. It commits
after explicit rollback; that change invalidates the reader. Product timeout,
generic bounded SQL errors and no-automatic-retry policy are unchanged. C's
separate-process rollback shared/exclusive lock tests still apply independently.
PASSIVE/FULL/RESTART/TRUNCATE checkpoints on this narrow corpus complete with
busy=0 and invalidate the old reader. This proves rejection of observed changes,
not supported checkpoint/recovery operation or compatibility of reset WAL files.
A truncated WAL is rejected on fresh admission. Crash recovery, interrupted
commits, live refresh, continuous-writer capture, broad malformed inputs,
cross-platform locks, custom VFS and general user-file admission remain next
gates. Source SHM is still never natively opened by the product reader. C/E's
non-atomic capture, fully restored within-boundary content ABA, native snapshot
reopen, host-crash cleanup and M1 resource/parent-death residuals are retained.
Electron verification exposed an E regression: a sidecar renamed away and back
with identical bytes could retain the captured ctime within one filesystem tick.
Admission now keeps the original identities but waits until the newest captured
ctime is at least 50 ms old, then revalidates the full held set. A required wait
above 100 ms or a backward clock during the wait rejects and closes the fds.
This performs no source writes, metadata updates or descriptor reopening. The
original E ABA test is unchanged; an additional 36 immediate same-inode,
same-byte main/WAL/SHM rename/restore attempts reject. This fence is qualified on
the fixed Linux evidence filesystem, not coarse/foreign filesystems, wall-clock
rollback or privileged metadata manipulation. It is not an atomic snapshot or
namespace-history monitor. Admission may synchronously wait up to 100 ms before
the worker deadline; M1 event-loop/resource limitations remain explicit.
## Gate G post-checkpoint fresh selection (Linux, opt-in)
`database.sqlite-wal-checkpoint.fixture.v1` is a qualification marker advertised
only with the default-off Linux file experiment and E + F. E still controls WAL
admission; G alone cannot enable it. No identity, parser, worker, public wire,
source write, path input or admitted-root change. The optional English/zh-CN
notice requires file + E + F + G. Earlier E/F checkpoint non-claims describe
those gates; G adds only the following measured fresh-admission slice.
On the owned M2 notes corpus, four additional commits produce six exact rows and
five WAL frames. PASSIVE/FULL/RESTART each report busy=0, log=checkpointed=5.
The original session invalidates, its worker is reaped and derived image removed.
After writing pauses, three explicit fresh chooser opens per mode read the exact
schema and six committed rows through E's existing verified snapshot. All source
main/WAL/SHM hashes stay unchanged and fd counts return to baseline. This does
not preserve old handles or provide a checkpoint RPC, live refresh, automatic
retry or in-session re-snapshot. Saved fingerprints still require reselection.
TRUNCATE reports zeroes and leaves an empty WAL: fresh selection rejects it.
One subsequent committed insert creates a complete valid WAL that fresh selection
can read (three rows). RESTART followed by a shorter WAL epoch leaves older
physical frames on this corpus: the strict full-stream parser rejects the stale
salts instead of silently ignoring the tail. No stale-tail skipping was added.
The test-only F writer also spills 128 uncommitted synthetic rows with an eight
page cache, then is killed with SIGKILL after acknowledgement. The 8,272-byte
committed prefix remains intact inside a 519,152-byte WAL; its terminal frame
has no commit marker. Both this actual uncommitted tail and a copy of that state
with the final 17 bytes removed reject before any session publication. A native
SQLite oracle recovers separate disposable copies to exactly three committed
rows and passes integrity_check. The original source remains untouched. The
reset/stale-tail oracle recovers seven rows while the product rejects. These
are specific recoverable-input **reject** tests, not product crash recovery,
salvage, durable power-loss simulation or broad malformed-database support.
Held product fds still do not coordinate source checkpoints. With another native
connection holding BEGIN IMMEDIATE, PASSIVE reports busy=0; FULL/RESTART/TRUNCATE
report busy=1 (log=checkpointed=1). Backfill can change the source even when busy,
so the old reader invalidates. After explicit rollback the checkpoints succeed.
F's independent writer SQLITE_BUSY test and C's rollback lock test still apply;
no automatic retries, new public BUSY code or cross-platform claims.
Remaining gates: broader checkpoint/reset availability and actual recovery/tail
salvage, continuous-writer capture/live refresh, broader admission, malformed DB
corpus and cross-platform locks. C/E/F hostile-sidecar, native-inode and ABA guards
are unchanged. All prior non-atomic capture, native reopen, host-crash cleanup,
timestamp-filesystem and M1 resource/parent-death residuals remain. Evidence and
reproducible tests: `electron/plugins/sqliteFixtureService.test.cjs` (Gate G),
`scripts/sqlite-wal-concurrent-fixture.cjs`, and
`/workspace/agent-tools/database/gate-g-checkpoint-recovery/`.
## Gate H bounded writer pause / verified capture (Linux, opt-in)
`database.sqlite-wal-capture.fixture.v1` is a qualification marker alongside
file + E + F + G under the same default-off Linux experiment. It is deliberately
not a live-refresh feature. No admission root, RPC/SDK shape, source write,
identity/parser/worker check or saved-fingerprint policy changes. E remains the
WAL admission switch; H alone cannot admit WAL. Plugin en/zh-CN notices require
all dependencies and describe pause, fresh selection and historical rows.
The test-only F/G writer now has an autonomous timer lane (20-500 ms between
commits, 1-128 commits per run), pause/resume/status acknowledgements and bounded
progress waits. It retains one process and native connection across three
capture windows. Autonomous commits happen before and after each window. The
cooperating writer pauses only from capture through final read publication;
explicit chooser selection creates a new handle/revision, returns exact schema
and all committed notes, and preserves main/WAL/SHM hashes. Resuming commits
invalidates the old session and removes its worker/snapshot. Close and cancel
return descriptors to baseline. This extends F's individually commanded writes
to an autonomous writer with controlled capture windows, not uninterrupted capture.
Pause is test orchestration, **not a product API or a SQLite lock**. Users must
arrange quiescence externally and select again; the plugin cannot pause a writer.
All writers must remain quiescent through admission and reads. A second writer
can still commit during the first writer's pause and invalidate the session.
Autonomous writes during pending admission or before result publication reject
without publishing a session/rows. Pausing only long enough to copy bytes is
insufficient under E/F's source-validity contract. There is no automatic retry,
in-session refresh, silent handle reuse, polling UI or background watcher.
Already displayed rows are historical until an explicit new selection and read
succeed; they are not continuously current.
PASSIVE/FULL/RESTART/TRUNCATE during a pause still invalidate captured sessions;
G's narrow fresh-admission and empty/stale/interrupted-tail rules remain. H also
tests hostile WAL/SHM replacement during pauses and fresh partial-tail rejection.
C/E/F/G hostile identity, ABA and native lock regressions remain required. A
second native BEGIN IMMEDIATE causes the autonomous writer to report SQLITE_BUSY
(code 5), stop scheduling and perform no retry; only an explicit new test run
after rollback succeeds. Native timeout remains 100 ms. Held source fds do not
coordinate source SQLite WAL writers/checkpoints or prove cross-platform locks.
Next gates: uninterrupted capture and explicit in-session refresh, broader
checkpoint/reset availability and recovery/tail salvage, broader admission,
broad malformed corpus and macOS/Windows locks. All prior M1/C/E/F/G filesystem,
non-atomic capture, fully restored content ABA, native reopen, host-crash cleanup,
native full-GUI/release-build and Gate D SKIPPED_NO_PROVIDER residuals remain.
Evidence/design and exact test counts:
`/workspace/agent-tools/database/gate-h-continuous-writer/`.
## Gate I fixed malformed fixture rejection (Linux, opt-in)
`database.sqlite-malformed-reject.fixture.v1` is a qualification marker advertised
only with the default-off Linux file experiment and C/E/F/G/H markers. It enables
no admission or SQL capability. The safety check applies to all file clients,
including ones without I; absence of the marker is not a bypass. Memory behavior
and public contract/SDK shapes are unchanged.
Before returning a file session, the worker runs host-owned
`PRAGMA main.integrity_check(1)` after defensive, trusted-schema-off and query-only
setup and requires exactly the `ok` result. Native exceptions or non-ok diagnostics
reject initialization. The existing parent deadline/cancellation controls cover
this native scan; identity is checked before/after and again before publication.
For WAL this scans E's verified rollback image, never a native source WAL
connection. Plugin SQL still cannot run PRAGMA. Diagnostics are not exposed.
The fixed corpus has ten malformed variants: zero-length, non-SQLite bytes,
wrong magic, truncated header, truncated main DB, damaged data leaf with intact
schema/root, inconsistent freelist count, truncated WAL header, partial final
WAL frame, and a checksum-valid WAL with a damaged data leaf. The last variant
proves WAL checksums alone are insufficient. Each rejects at chooser/open with
no returned handle/schema/rows, source mutation, retained worker/fd or derived
image. Early identity rejection is `permissionDenied`; worker integrity and WAL
snapshot rejection are `failedPrecondition` with bounded content-free messages.
Two controls return exact 40/41-row IDs; existing M2/M3b and C/E/F/G/H stay required.
Close/cancel and rejection restore warmed descriptor baselines.
Reproduce the corpus with `node scripts/sqlite-malformed-fixture.cjs > inventory.json`.
The test-only builder creates unique mode-0600 files directly in the existing
M2 allowlist, prints their mutation/size/hash inventory, and never accepts an
output path. No allowlist expansion: the Gate I evidence directory itself is not
admitted. Tests remove owned inputs; retained evidence paths/hashes are recorded
in `/workspace/agent-tools/database/gate-i-malformed-corpus/corpus-manifest.json`.
SQLite-generated WAL salts vary between builds. Mutation recipes are fixed;
checksums in a manifest bind that particular evidence instance. The builder is
not packaged as a product capability.
English/zh-CN UI qualifies only this fixed Linux corpus, with broader corruption
handling and recovery explicitly unqualified. This is not a general corruption
validator, corruption repair, crash recovery, tail salvage or SQLCipher support.
Scanning has native CPU/memory cost under the existing 3-second worker deadline;
M1 hard quotas remain unqualified. No uninterrupted capture, in-session refresh,
automatic retry, broader file admission, lock coordination or macOS/Windows lock
claim. C/E/F/G/H race, ABA, timestamp/native-reopen/non-atomic capture, host-crash
cleanup and D SKIPPED_NO_PROVIDER residuals remain. See the Gate I design/report
for exact evidence, tests and next gates.
## Gate J explicit quiescent WAL session refresh (Linux, opt-in)
`database.sqlite-wal-session-refresh.fixture.v1` adds
`database.refreshSqliteFile(DatabaseHandleRequest) -> DatabaseFileOpenResult`.
The SDK/runtime use the existing canonical request/result shapes; no path is
accepted. All file/C/E/F/G/H/I markers and the default-off Linux database
experiment are required. H remains pause-required; J is **not uninterrupted
capture** or a background live view.
Pause every writer externally through refresh AND reads, then explicitly click
**Refresh WAL fixture**. A still-open WAL session keeps its handle and receives
a new opaque revision, without another chooser. The UI clears all old rows and
schema before requesting refresh, loads schema for the new revision, and runs
SQL only on another explicit action. English/zh-CN describe this requirement.
No polling, automatic retry, product writer pause, AI execution or saved-target
fingerprint update occurs. Old revisions reject. A previously invalidated or
closed session still needs chooser selection; rollback/memory sessions cannot
refresh. A failed admitted refresh closes the session and clears the UI.
Authority remains the old host-held ancestors and main fd. The main identity,
metadata and hash must be unchanged; fresh WAL/SHM must preserve inode/presence,
single-link/no-follow rules, and the entire previous WAL byte prefix. Only
appended complete committed WAL frames qualify. Full fresh C identity/hash/
timestamp-age checks, E strict reconstruction, I integrity scan, worker checks,
and final publication checks remain. Checkpoints, resets, truncation, replaced
files, rewritten prefixes, partial tails and source changes during refresh
reject. Ordinary reads retain their full old-source checks and invalidate on
resumed commits; they never silently rebase. Saved connections retain the old
fingerprint unless separately saved through the existing explicit path.
A candidate worker is linked to the original session while initializing. Query,
schema/save and duplicate refresh reject during the transition. Close/cancel,
abort, revocation and runtime release reap both workers and snapshots. Staging
uses an available slot within the unchanged global eight / runtime two worker
limits; at capacity refresh fails closed. Publication swaps the handle/revision
synchronously after checks. Old worker exit callbacks cannot delete the new
session. Repeated paused refreshes prove exact IDs 1..4, 1..6 and 1..8 with one
chooser and four distinct revisions; resume still invalidates. Lifecycle,
publication mutation, hostile sidecar and restored-name ABA tests run on Node
and Electron with warmed fd/derived-image cleanup checks.
J explicitly authorizes new sidecar bytes and metadata between revisions. It
cannot establish continuous sidecar provenance: a sidecar renamed and restored
before a fresh capture, together with otherwise valid appends, is outside that
claim. Main identity is never renewed. Within captured refresh boundaries,
main/WAL/SHM restored-name ABA still rejects; ordinary C/F checks are unchanged.
Fully restored in-place content ABA, non-atomic capture, native reopen and tested
filesystem timestamp assumptions remain. No cross-platform locking claim.
Next production gates: uninterrupted capture, refresh across broader checkpoint/
reset/recovery cases, broader admission, expanded fixed malformed/fuzz corpus
beyond I and macOS/Windows locks. All M1, C-I and D SKIPPED_NO_PROVIDER residuals
remain except this exact explicit quiescent append-only refresh lane. Earlier
sections describe their original gates; their no-refresh statements are lifted
only when J and every dependency are negotiated. Evidence/design/report:
`/workspace/agent-tools/database/gate-j-uninterrupted-capture/`.
+2
View File
@@ -3,6 +3,8 @@
// Presentation only. Admission and grants remain owned by the canonical schema
// and permission engine. Tests require exact coverage of its permission enum.
const PERMISSION_DESCRIPTIONS = {
"database.query.read": [true, "Read disposable SQLite", "Read synthetic memory or a host-selected disposable SQLite fixture file. No user database files.", "Read disposable SQLite", "Read synthetic memory or a host-selected disposable SQLite fixture file. No user database files."],
"database.query.write": [true, "Change synthetic SQLite", "Change synthetic fixture rows after a separate host review of the exact statement. No user database files.", "Change synthetic SQLite", "Change synthetic fixture rows after a separate host review of the exact statement. No user database files."],
"ai.agent.use": [true, "Agent conversations", "Use configured host Agents and read this plugin's own chat history. Model or Agent service usage may incur costs.", "Agent 会话", "使用宿主已配置的 Agent,并读取此插件自己的聊天历史;模型或 Agent 服务可能产生费用。"],
"ai.agent.actions": [true, "Agent actions", "Authorize Agent tools against explicitly selected targets under this plugin's policy. Commands can change remote systems.", "Agent 操作", "根据插件策略授权 Agent 工具操作明确选中的目标;命令可能更改远程系统。"],
storage: [false, "Plugin storage", "Save and read this plugin's local data.", "插件存储", "保存和读取此插件自己的本地数据。"],
+5 -2
View File
@@ -5,6 +5,7 @@ const { validatePluginInlineStyle } = require("./pluginViewStylePolicy.cjs");
// These are HTML primitives, not a fixed design-system component catalogue.
// Active elements, custom elements and URL attributes need separate authority.
const ELEMENTS = new Set(["form", "img", "div", "span", "p", "h1", "h2", "h3", "h4", "h5", "h6", "section", "article", "header", "footer", "main", "aside", "nav", "ul", "ol", "li", "dl", "dt", "dd", "strong", "em", "small", "b", "i", "code", "pre", "blockquote", "br", "hr", "table", "thead", "tbody", "tfoot", "tr", "th", "td", "button", "input", "textarea", "label", "select", "option", "fieldset", "legend", "progress", "details", "summary"]);
const HOST_ICON_NAMES = new Set(["database", "plus", "file-code", "play", "square", "x", "chevron-right", "chevron-down", "table", "eye", "search", "refresh", "sparkles", "unplug", "folder", "key", "check", "alert-circle", "loader", "arrow-right", "panel-left", "shield", "settings"]);
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"]);
@@ -24,9 +25,10 @@ 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");
if (name === "data-plugin-icon" && (!HOST_ICON_NAMES.has(value) || (element && element !== "span"))) throw new TypeError("Forbidden host icon");
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");
if (name === "src" && (!/^(?:asset|brand):[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");
if (name === "style") validatePluginInlineStyle(value);
}
/** Validate a complete, data-only snapshot before touching a host DOM. */
@@ -43,6 +45,7 @@ function validatePluginRemoteTree(root) {
if (node.type !== 1 || typeof node.element !== "string" || !ELEMENTS.has(node.element)
|| !Array.isArray(node.children) || !record(node.attributes)
|| Object.keys(node).some((key) => !["id", "type", "element", "attributes", "children"].includes(key))) throw new TypeError("Forbidden view element");
if (Object.hasOwn(node.attributes, "data-plugin-icon") && (node.element !== "span" || node.children.length)) throw new TypeError("Host icons must be span leaves");
if (VOID_ELEMENTS.has(node.element) && node.children.length) throw new TypeError("Void view elements cannot have children");
const attributes = Object.entries(node.attributes);
if (attributes.length > 64) throw new TypeError("Too many view attributes");
@@ -78,4 +81,4 @@ function validatePluginMutationBatch(batch) {
}
return true;
}
module.exports = { validatePluginRemoteTree, validatePluginMutationBatch, validateAttribute, ELEMENTS };
module.exports = { validatePluginRemoteTree, validatePluginMutationBatch, validateAttribute, ELEMENTS, HOST_ICON_NAMES };
+14
View File
@@ -44,3 +44,17 @@ test("void children are rejected in snapshots and mutation insertions", () => {
assert.throws(() => validatePluginMutationBatch([[0, "~", node, 0]]), /Void view elements/);
}
});
test('host icon requests accept only fixed decorative span leaves', () => {
const icon = (name, element = 'span', children = []) => ({ children: [{ id: 'icon', type: 1, element, attributes: { 'data-plugin-icon': name }, children }] });
assert.doesNotThrow(() => validatePluginRemoteTree(icon('database')));
for (const name of ['constructor', '__proto__', 'https://invalid/icon.svg', '../x', '<svg>', 'not-an-icon']) assert.throws(() => validatePluginRemoteTree(icon(name)));
assert.throws(() => validatePluginRemoteTree(icon('database', 'button')));
assert.throws(() => validatePluginRemoteTree(icon('database', 'span', [{ id: 'text', type: 3, data: 'hidden text' }])));
});
test('brand image paths accept only package-relative references', () => {
const { validateAttribute } = require('./pluginRemoteTreePolicy.cjs');
assert.doesNotThrow(() => validateAttribute('img', 'src', 'brand:assets/sqlite-light.png'));
for (const value of ['brand:../a.png', 'brand:https://example.invalid/a.png', 'brand:/a.png']) assert.throws(() => validateAttribute('img', 'src', value));
});
+1 -1
View File
@@ -14,7 +14,7 @@ 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", "--muted", "--muted-foreground", "--border", "--primary", "--primary-foreground", "--font-sans", "--font-mono", "--radius", "--input", "--ring", "--accent", "--accent-foreground", "--destructive"]);
const decode = (name) => cssTree.ident.decode(name).toLowerCase();
/** Returns canonical CSS only if every construct is safe for a clipped shadow root. */
+6
View File
@@ -24,3 +24,9 @@ test("plugin CSS rejects network loads, escapes and access outside the surface",
for (const attack of attacks) assert.throws(() => validatePluginStylesheet(attack), undefined, attack);
assert.throws(() => validatePluginStylesheet('x'.repeat(65537)));
});
test('host typography and control tokens are readable but never writable', () => {
assert.doesNotThrow(() => validatePluginStylesheet('.view{font-family:var(--font-sans);border-radius:var(--radius);border-color:hsl(var(--input));outline-color:hsl(var(--ring));background:hsl(var(--accent));font-family:var(--font-mono)}'));
assert.throws(() => validatePluginStylesheet('.view{--font-sans:evil}'));
assert.throws(() => validatePluginStylesheet('.view{font-family:var(--private-host-setting)}'));
});
+4
View File
@@ -211,6 +211,10 @@ module.exports = {
'node_modules/@netcatty/plugin-contract/**/*',
'node_modules/@netcatty/plugin-sdk/**/*',
'electron/plugins/runtime/**/*',
// Fixed host-owned SQLite subprocess; no plugin-selected executable.
'electron/plugins/sqliteFixtureWorker.cjs',
'electron/plugins/sqliteFixtureSql.cjs',
'electron/plugins/sqliteFileIdentity.cjs',
'node_modules/ajv/**/*',
'node_modules/ajv-formats/**/*',
'node_modules/fast-deep-equal/**/*',
+1
View File
@@ -1094,6 +1094,7 @@ function reportOpenedSessionActivity(event) {
}
module.exports = {
listDatabaseHosts: () => registeredVaultAgentBridge?.invokeVaultAgent("host.list", {}) ?? Promise.resolve({ ok: false }),
init,
registerHandlers,
cleanup,
+1
View File
@@ -164,6 +164,7 @@ function createBridgeRegistrar(context) {
app,
electron: electronModule,
safeStorage,
getDatabaseHosts: () => aiBridge.listDatabaseHosts(),
getInteractionWindow: () => win,
getPermissionWindows: () => getWindowManager().getManagedAppWindows(),
getTerminalWorkerManager: () => terminalWorkerManager,
+3 -1
View File
@@ -7,6 +7,8 @@ const { DatabaseSync } = require("node:sqlite");
const { LOCAL_SOURCE, assertSource, privateOwner } = require("./sourceIdentity.cjs");
const { defaultPermissionMode } = require("./permissionResources.cjs");
const SCHEMA_VERSION = 7;
const MAX_SECURITY_AUDIT_DETAILS_BYTES = 16 * 1024;
const MAX_SECURITY_AUDIT_RECORDS_PER_PLUGIN = 1_000;
@@ -1176,7 +1178,7 @@ class PluginDatabase {
getPermissionMode(pluginId, permission) {
const key = `permission:${this.privateOwner(pluginId)}:${permission}`;
const row = this.db.prepare("SELECT value_json FROM plugin_host_preferences WHERE key = ?").get(key);
const mode = row ? parseJson(row.value_json, "permission mode") : "allow";
const mode = row ? parseJson(row.value_json, "permission mode") : defaultPermissionMode(permission);
if (!["allow", "ask", "deny"].includes(mode)) throw new Error("Corrupt plugin permission mode");
return mode;
}
@@ -0,0 +1,73 @@
"use strict";
const fs = require("node:fs");
const path = require("node:path");
const { createDefinitionValidator } = require("./contractValidator.cjs");
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
const fail = () => new PluginRpcError(RPC_ERRORS.failedPrecondition, "Saved connection storage is unavailable");
// Host-owned metadata only. Credentials live separately in PluginSecretStore.
class DatabaseConnectionStore {
constructor(file) { this.file = file; this.validMeta = createDefinitionValidator("DatabaseSavedConnection"); }
read() {
try {
if (!fs.existsSync(this.file)) return [];
if (fs.statSync(this.file).size > 2 * 1024 * 1024) throw fail();
const data = JSON.parse(fs.readFileSync(this.file, "utf8"));
if (data.version !== 1 || !Array.isArray(data.connections) || data.connections.length > 1000) throw fail();
for (const entry of data.connections) {
if (typeof entry.owner !== "string" || !this.validMeta(entry.meta)
|| Object.keys(entry).some((key) => !["owner", "meta", "target"].includes(key))
|| (entry.meta.targetKind === "file") !== Boolean(entry.target)) throw fail();
if (entry.target) {
const { sidecars, ...main } = entry.target;
if (!["ctime,dev,ino,mtime,path,size", "ctime,dev,ino,mtime,path,sha256,size"].includes(Object.keys(main).sort().join())
|| Object.values(main).some((value) => typeof value !== "string" || value.length > 4096)
|| (main.sha256 !== undefined && !/^[a-f0-9]{64}$/.test(main.sha256))) throw fail();
if (sidecars !== undefined) {
if (!sidecars || Object.keys(sidecars).sort().join() !== "shm,wal" || !main.sha256) throw fail();
for (const name of ["wal", "shm"]) {
const item = sidecars[name];
if (name === "shm" && item === null) continue;
if (!item || Object.keys(item).sort().join() !== "ctime,dev,ino,mtime,sha256,size"
|| Object.values(item).some((value) => typeof value !== "string" || value.length > 128)
|| !/^[a-f0-9]{64}$/.test(item.sha256)) throw fail();
}
}
}
}
if (new Set(data.connections.map((e) => e.meta.id)).size !== data.connections.length) throw fail();
return data.connections;
} catch { throw fail(); }
}
list(owner) { return this.read().filter((entry) => entry.owner === owner).map((entry) => entry.meta); }
get(owner, id) {
const entry = this.read().find((entry) => entry.owner === owner && entry.meta.id === id);
if (!entry) throw new PluginRpcError(RPC_ERRORS.notFound, "Saved connection was not found");
return entry;
}
add(entry) {
const entries = this.read();
if (entries.length >= 1000 || entries.filter((e) => e.owner === entry.owner).length >= 100) {
throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Saved connection limit reached");
}
this.write([...entries, entry]);
}
delete(owner, id) { this.write(this.read().filter((entry) => entry.owner !== owner || entry.meta.id !== id)); }
write(connections) {
const serialized = JSON.stringify({ version: 1, connections });
if (Buffer.byteLength(serialized) > 2 * 1024 * 1024) throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Saved connection storage limit reached");
const temporary = `${this.file}.tmp`; let fd; let created = false; let committed = false;
try {
fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
fd = fs.openSync(temporary, "wx", 0o600); created = true;
fs.writeFileSync(fd, serialized); fs.fsyncSync(fd);
fs.closeSync(fd); fd = undefined;
fs.renameSync(temporary, this.file); committed = true;
} catch { throw fail(); }
finally {
if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
if (created && !committed) { try { fs.unlinkSync(temporary); } catch {} }
}
}
}
module.exports = { DatabaseConnectionStore };
@@ -0,0 +1,34 @@
"use strict";
// Host-owned profiles. Public tokens and data come only from the contract registry.
const registry = require('./generated/database-drivers.json');
function resolveProfile(driverId, variant) {
const driver = registry.find(d => d.id === driverId);
if (!driver) throw Error('Driver not packaged');
let profile;
if (driver.variants) {
profile = driver.variants.find(v => v.id === variant);
if (!profile) throw Error('Choose a supported database variant');
} else {
if (variant !== undefined) throw Error('Database variant does not match driver');
profile = { ...driver, authPolicy: driver.wireFamily === 'postgres' ? 'postgres' : 'mysql', metadata: driver.wireFamily === 'postgres' ? 'pg' : 'mysql', modeCheck: 'none' };
}
if (!['postgres', 'mysql'].includes(profile.wireFamily)) throw Error('Database variant driver not packaged');
return profile;
}
function metadataQueries(profile) {
if (profile.metadata === 'mysql') return {
tables: 'SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = DATABASE() ORDER BY table_name LIMIT 32',
columns: 'SELECT column_name, data_type, is_nullable, column_key FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=? ORDER BY ordinal_position LIMIT 32',
};
const prefix = profile.metadata === 'sys' ? 'sys' : 'pg';
return {
tables: 'SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = current_schema() ORDER BY table_name LIMIT 32',
columns: `SELECT c.column_name, c.data_type, c.is_nullable, EXISTS (SELECT 1 FROM ${prefix}_catalog.${prefix}_index i JOIN ${prefix}_catalog.${prefix}_class r ON r.oid=i.indrelid JOIN ${prefix}_catalog.${prefix}_namespace n ON n.oid=r.relnamespace JOIN ${prefix}_catalog.${prefix}_attribute a ON a.attrelid=r.oid AND a.attnum=ANY(i.indkey) WHERE i.indisprimary AND n.nspname=c.table_schema AND r.relname=c.table_name AND a.attname=c.column_name) FROM information_schema.columns c WHERE c.table_schema=current_schema() AND c.table_name=$1 ORDER BY c.ordinal_position LIMIT 32`,
};
}
async function validateServerMode(client, profile) {
if (profile.modeCheck !== 'pg-compatibility') return;
const result = await client.execute('SELECT datcompatibility FROM pg_catalog.pg_database WHERE datname = current_database()', [], 1);
if (result.rows.length !== 1 || !['PG', 'P'].includes(result.rows[0][0])) throw Error('Unsupported database compatibility mode');
}
module.exports = { resolveProfile, metadataQueries, validateServerMode };
@@ -0,0 +1,42 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict');
const {resolveProfile,metadataQueries}=require('./databaseDriverProfiles.cjs');
const {DatabaseTcpService}=require('./databaseTcpService.cjs');
const {createDefinitionValidator}=require('./contractValidator.cjs');
const owner={pluginId:'test',runtimeId:'r',sourceOwner:'o',sourceId:'s',securityPrincipal:'p'};
test('explicit variants choose transport/auth/defaults and reject ambiguous or unsupported products',()=>{
for(const id of ['goldendb','opengauss','gaussdb','kingbase','highgo','vastbase','gbase8c'])assert.throws(()=>resolveProfile(id),/variant/i);
assert.equal(resolveProfile('gaussdb','gaussdb-dws').defaultPort,8000);
assert.equal(resolveProfile('gaussdb','gaussdb-mysql').wireFamily,'mysql');
assert.equal(resolveProfile('kingbase','kingbase-pg').metadata,'sys');
assert.equal(resolveProfile('vastbase','vastbase-g100-pg').modeCheck,'pg-compatibility');
assert.equal(resolveProfile('postgres').authPolicy,'postgres');
for(const [id,variant] of [['gbase8c','gbase-8a'],['gbase8c','gbase-8s'],['gbase8c','gbase-8c'],['gaussdb','gaussdb-native'],['kingbase','kingbase-oracle'],['highgo','highgo-secure'],['vastbase','vastbase-e100'],['vastbase','vastbase-g100-other'],['postgres','gaussdb-dws'],['gaussdb','unknown']])assert.throws(()=>resolveProfile(id,variant),/variant|not packaged/i);
});
test('schema accepts only known variant tokens; runtime checks ownership of tokens',()=>{
const valid=createDefinitionValidator('DatabaseTcpOpenRequest');const base={driverId:'gaussdb',variant:'gaussdb-dws',hostname:'127.0.0.1',port:8000,database:'db',username:'reader',password:'',tls:false};assert.equal(valid(base),true);assert.equal(valid({...base,variant:'guess'}),false);
});
test('unavailable and mismatched variants fail before authorization or socket creation',async()=>{
const service=new DatabaseTcpService();let calls=0;const hooks={authorize:async()=>calls++,authenticate:async()=>calls++};
for(const request of [{driverId:'gaussdb'},{driverId:'gbase8c',variant:'gbase-8s'},{driverId:'postgres',variant:'gaussdb-dws'}])await assert.rejects(service.open(request,owner,hooks),/variant|not packaged/i);
assert.equal(calls,0);assert.equal(service.sessions.size,0);
});
test('Kingbase metadata uses native sys catalog and PG stays scoped/bound/bounded',()=>{
const kes=metadataQueries(resolveProfile('kingbase','kingbase-pg')),pg=metadataQueries(resolveProfile('postgres'));
assert.match(kes.columns,/sys_catalog.sys_index/);assert.match(kes.columns,/sys_catalog.sys_attribute/);assert.doesNotMatch(kes.columns,/pg_catalog/);
assert.match(pg.columns,/pg_catalog.pg_index/);
for(const query of [kes,pg]){assert.match(query.tables,/current_schema\(\)/);assert.match(query.columns,/table_name=\$1/);assert.match(query.columns,/LIMIT 32/);}
});
test('Vastbase validates PG mode before publishing a handle; rejects modes without fallback',async()=>{
const {validateServerMode}=require('./databaseDriverProfiles.cjs');let statements=[];
for(const mode of ['PG','P'])await validateServerMode({execute:async sql=>{statements.push(sql);return{rows:[[mode]]};}},resolveProfile('vastbase','vastbase-g100-pg'));
for(const mode of ['A','B','MSSQL','unknown',null])await assert.rejects(validateServerMode({execute:async()=>({rows:[[mode]]})},resolveProfile('vastbase','vastbase-g100-pg')),/mode/i);
assert.ok(statements.every(sql=>sql.includes('datcompatibility')&&!/SET|ALTER/i.test(sql)));
});
test('service executes Kingbase adapter metadata with bound table names and native boolean flags',async()=>{
const {EventEmitter}=require('node:events');const service=new DatabaseTcpService();const statements=[];
const profile=resolveProfile('kingbase','kingbase-pg');const socket=new EventEmitter();socket.destroyed=false;
const client={socket,close(){socket.destroyed=true;},execute:async(sql,values=[])=>{statements.push({sql,values});return sql===metadataQueries(profile).tables?{rows:[['quoted\'name','BASE TABLE'],['stock','VIEW']]}:{rows:[['id','integer','NO','t'],['note','text','YES','f']]};}};
const s={id:'synthetic',owner,client,profile,driver:{wireFamily:'postgres'}};service.sessions.set(s.id,s);
const result=await service.schema(s,owner,{authorize:async()=>{},authenticate:async()=>{}});assert.equal(result.tables[0].columns[0].primaryKey,true);assert.equal(result.tables[0].columns[0].nullable,false);assert.equal(result.tables[1].kind,'view');assert.deepEqual(statements[1].values,["quoted'name"]);assert.ok(!statements[1].sql.includes("quoted'name"));service.release();
});
+116
View File
@@ -0,0 +1,116 @@
"use strict";
const { randomUUID, createHash } = require("node:crypto");
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
const { hostRevision } = require("./databaseHostPortProbe.cjs");
const { LiveSshPgAdapter, LiveFixtureError, loadFixtureCredentials } = require("./databaseLiveSshPgAdapter.cjs");
const LIVE_FEATURE = "database.host-live-ssh-pg.fixture.v1";
const LIVE_RESOURCE = "database-host:live-ssh-pg-fixture";
const HOST_ID = "netcatty:live-ssh-pg-fixture";
const failure = (code) => ({ code, fixture: true, synthetic: false, connected: false });
const sameOwner = (a, b) => ["pluginId", "runtimeId", "sourceOwner", "sourceId", "securityPrincipal"].every((key) => a[key] === b[key]);
class DatabaseHostLiveSshPgService {
constructor({ secretStore, adapter = new LiveSshPgAdapter(), loadCredentials = loadFixtureCredentials, timeoutMs = 15000, sessionMs = 30000 }) {
Object.assign(this, { secretStore, adapter, loadCredentials, timeoutMs, sessionMs });
this.pending = new Map(); this.completed = new Map(); this.sessions = new Map(); this.closed = false;
}
metadata() {
const host = { hostId: HOST_ID, label: "Live SSH to PostgreSQL (loopback fixture only)", hostname: "127.0.0.1", port: 2222, username: "smoketest", capability: "metadata-only", tunnelAvailable: false };
return { ...host, liveSshPg: { kind: "fixture", revision: hostRevision(host) } };
}
key(c, id) { return JSON.stringify([c.pluginId, c.runtimeId, c.sourceOwner, c.sourceId, c.securityPrincipal, id]); }
prune() { for (const [key, entry] of this.completed) if (entry.expires <= Date.now()) this.completed.delete(key); }
remember(key, code) {
this.prune();
if (!this.completed.has(key) && this.completed.size >= 256) throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Live fixture replay budget reached");
this.completed.set(key, { code, expires: Date.now() + 120000 });
}
cancel({ openId }, context) {
const key = this.key(context, openId); this.pending.get(key)?.controller.abort();
for (const s of this.sessions.values()) if (s.key === key) void this.dispose(s).catch(() => {});
this.remember(key, "CANCELLED"); return null;
}
dispose(s) {
if (s.closing) return s.closing;
clearTimeout(s.timer);
const { promise, resolve, reject } = Promise.withResolvers(); s.closing = promise;
try { Promise.resolve(s.resource.close()).then(resolve, () => reject(new PluginRpcError(RPC_ERRORS.unavailable, "Live fixture cleanup failed"))); }
catch { reject(new PluginRpcError(RPC_ERRORS.unavailable, "Live fixture cleanup failed")); }
// Keep the owner-bound resource visible during cleanup. Concurrent close or
// cancel/close races must await the same acknowledgement, not report early.
void promise.finally(() => this.sessions.delete(s.id)).catch(() => {});
return promise;
}
async close({ sessionId }, context) {
const s = this.sessions.get(sessionId);
if (s && !sameOwner(s.context, context)) throw new PluginRpcError(RPC_ERRORS.permissionDenied, "Unknown live fixture session");
if (s) await this.dispose(s);
return { fixture: true, connected: false, closed: true };
}
async open(request, context, { authorize, assertActive }) {
this.prune(); const key = this.key(context, request.openId);
if (this.completed.get(key)?.code === "CANCELLED") return failure("CANCELLED");
if (this.closed) return failure("UNAVAILABLE");
if (this.pending.has(key) || this.completed.has(key)) throw new PluginRpcError(RPC_ERRORS.failedPrecondition, "Live fixture open ID already used");
const resources = [...this.pending.values(), ...this.sessions.values()];
if (resources.length >= 8 || resources.filter((p) => p.context.runtimeId === context.runtimeId).length >= 2 || this.completed.size >= 248) throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Live fixture budget reached");
const controller = new AbortController(); const scoped = { ...context, signal: controller.signal };
let abortCode = "CANCELLED"; let resource; let session; let retained = false;
const close = () => session ? this.dispose(session) : resource?.close();
const abort = () => controller.abort(); context.signal?.addEventListener("abort", abort, { once: true });
const timer = setTimeout(() => { abortCode = "DEADLINE_EXCEEDED"; abort(); }, this.timeoutMs);
this.remember(key, "running"); this.pending.set(key, { controller, context });
const current = () => {
controller.signal.throwIfAborted(); const meta = this.metadata();
if (request.hostId !== meta.hostId) throw new LiveFixtureError("UNKNOWN_HOST");
if (request.revision !== meta.liveSshPg.revision) throw new LiveFixtureError("STALE_HOST");
};
const check = async () => { current(); await assertActive(scoped); current(); };
let onAbort;
const cancelled = new Promise((resolve) => {
onAbort = () => { Promise.resolve(close()).then(() => resolve(failure(abortCode)), () => resolve(failure("UNAVAILABLE"))); };
controller.signal.addEventListener("abort", onAbort, { once: true });
});
if (context.signal?.aborted) abort();
const run = async () => {
try {
current(); await authorize(scoped); await check();
// A host-only source namespace prevents plugin secrets.set from replacing
// fixture credentials, even if it guesses the key or sees the opaque ID.
const owner = `source:${createHash("sha256").update(`host-live-fixture:${context.sourceOwner}`).digest("hex")}:${context.pluginId}`;
let sshRef = this.secretStore.getReference(owner, "ssh"); let pgRef = this.secretStore.getReference(owner, "pg");
if (!sshRef || !pgRef) {
let credentials = this.loadCredentials();
try {
if (!sshRef) sshRef = this.secretStore.set(owner, "ssh", credentials.privateKey);
if (!pgRef) pgRef = this.secretStore.set(owner, "pg", credentials.password);
} finally { credentials = undefined; }
}
resource = await this.adapter.open({ privateKey: this.secretStore.resolve(owner, sshRef), password: this.secretStore.resolve(owner, pgRef), signal: controller.signal, beforeDial: check });
await check();
if (!resource?.isAlive()) throw new LiveFixtureError("UNAVAILABLE");
const id = randomUUID(); const expiresAt = Date.now() + this.sessionMs;
session = { id, key, context, resource, timer: setTimeout(() => { void this.dispose(session).catch(() => {}); }, this.sessionMs) };
session.timer.unref(); this.sessions.set(id, session);
resource.onClose(() => { void this.dispose(session).catch(() => {}); });
current(); if (!resource.isAlive()) throw new LiveFixtureError("UNAVAILABLE");
retained = true;
return { code: "LIVE_OK", fixture: true, synthetic: false, connected: true, sessionId: id, expiresAt,
proof: { query: "SELECT 1", value: 1, pinnedHostKey: true }, secretRef: sshRef.id, pgSecretRef: pgRef.id };
} catch (error) {
const codes = ["AUTH_FAILED", "UNKNOWN_HOST_KEY", "HOST_KEY_MISMATCH", "UNKNOWN_HOST", "STALE_HOST"];
return failure(controller.signal.aborted ? abortCode : error instanceof LiveFixtureError && codes.includes(error.code) ? error.code : "UNAVAILABLE");
} finally { if (!retained || controller.signal.aborted) await close(); }
};
try { return await Promise.race([run(), cancelled]); }
finally { clearTimeout(timer); context.signal?.removeEventListener("abort", abort); controller.signal.removeEventListener("abort", onAbort); this.pending.delete(key); this.remember(key, controller.signal.aborted ? abortCode : "finished"); }
}
abortWhere(predicate) {
for (const p of this.pending.values()) if (predicate(p.context)) p.controller.abort();
for (const s of this.sessions.values()) if (predicate(s.context)) void this.dispose(s).catch(() => {});
}
releaseRuntime(id) { this.abortWhere((c) => c.runtimeId === id); }
revoke(id) { this.abortWhere((c) => c.pluginId === id); }
closeAll() { this.abortWhere(() => true); }
shutdown() { this.closed = true; this.closeAll(); }
}
module.exports = { DatabaseHostLiveSshPgService, LIVE_FEATURE, LIVE_RESOURCE, HOST_ID };
@@ -0,0 +1,166 @@
"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const { randomUUID, randomBytes, createCipheriv, createDecipheriv } = require("node:crypto");
const { EventEmitter } = require("node:events");
const { DatabaseHostLiveSshPgService, LIVE_FEATURE } = require("./databaseHostLiveSshPg.cjs");
const { LiveSshPgAdapter, loadFixtureCredentials } = require("./databaseLiveSshPgAdapter.cjs");
const { PluginSqliteFixtureService, FEATURE, SAVED_FEATURE } = require("./sqliteFixtureService.cjs");
const { PluginHostRpcRegistry } = require("./hostRpcRegistry.cjs");
const { PluginSecretStore } = require("./secretStore.cjs");
const tick = () => new Promise(setImmediate);
function fixture(t, options = {}) {
const records = new Map(); const encryptionKey = randomBytes(32); let loads = 0; let writes = 0;
// Explicit Node test backend: real authenticated encryption, NOT native safeStorage qualification.
const secretStore = new PluginSecretStore({ database: {
privateOwner: (id) => id, getSecretByKey: (id, key) => records.get(`${id}:${key}`),
getSecretByRef: (id, ref) => [...records.values()].find((r) => r.pluginId === id && r.secretRef === ref),
upsertSecret: (r) => { writes++; records.set(`${r.pluginId}:${r.key}`, r); },
}, safeStorage: { isEncryptionAvailable: () => true, getSelectedStorageBackend: () => "test-aes-gcm",
encryptString: (s) => { const iv = randomBytes(12); const c = createCipheriv("aes-256-gcm", encryptionKey, iv); const data = Buffer.concat([c.update(s), c.final()]); return Buffer.concat([iv, c.getAuthTag(), data]); },
decryptString: (b) => { const d = createDecipheriv("aes-256-gcm", encryptionKey, b.subarray(0, 12)); d.setAuthTag(b.subarray(12, 28)); return Buffer.concat([d.update(b.subarray(28)), d.final()]).toString(); },
} });
let active = 0;
const adapter = options.adapter ?? { async open({ beforeDial, signal }) {
await beforeDial(); signal.throwIfAborted(); active++; let closed = false; let onClose;
return { close() { if (!closed) { closed = true; active--; onClose?.(); } }, isAlive: () => !closed, onClose: (fn) => { onClose = fn; } };
} };
const live = new DatabaseHostLiveSshPgService({ secretStore, adapter, loadCredentials: () => { loads++; return options.real ? loadFixtureCredentials() : { privateKey: "unit-key", password: "unit-password" }; }, ...options });
const identity = { pluginId: "com.netcatty.live-test", pluginVersion: "0.1.0", runtimeId: "runtime-one", runtimeKind: "browser", sourceOwner: "owner-one", sourceId: "source-one", securityPrincipal: "principal", manifest: { features: { optional: [FEATURE, SAVED_FEATURE, LIVE_FEATURE] } } };
let revoke; let lock; let locked = false; let source = "source-one";
const service = new PluginSqliteFixtureService({ enabled: true, liveSshPg: live, connectionStore: {},
getDatabaseHosts: async () => ({ ok: true, hosts: [{ id: "ordinary", hostname: "127.0.0.1", port: 2222, username: "smoketest", password: "never-on-wire" }] }),
database: { getActivePlugin: () => ({ enabled: true, source: { id: source } }), getRetainedPluginSource: () => ({ id: source }), privateOwner: () => identity.sourceOwner, publicPluginId: () => identity.pluginId },
runtimeSupervisor: { getRuntimeIdentity: () => identity },
permissionEngine: { onDidRevoke: (fn) => { revoke = fn; return { dispose() {} }; }, authorize: async (c, d) => { await options.authorize?.(c, d); d.validateBeforeGrant(); } },
isLocked: () => locked, subscribeLock: (fn) => { lock = fn; },
});
const registry = new PluginHostRpcRegistry(); service.register(registry);
const routes = registry.createRoutes({ ...identity, assertCurrent() {} });
const call = (name, p = {}) => routes.requestHandlers[`database.${name}`](p, { signal: new AbortController().signal });
const request = () => ({ hostId: live.metadata().hostId, revision: live.metadata().liveSshPg.revision, openId: randomUUID() });
t.after(() => service.shutdown());
return { live, service, adapter, secretStore, identity, request, call, records, active: () => active, loads: () => loads, writes: () => writes,
open: (r = request()) => call("openHostLiveSshPgFixture", r), cancel: (r) => call("cancelHostLiveSshPgFixture", { openId: r.openId }),
close: (r) => call("closeHostLiveSshPgSession", { sessionId: r.sessionId }), revoke: () => revoke({ pluginId: identity.pluginId }), lock: () => { locked = true; lock(true); }, swap: () => { source = "source-two"; } };
}
test("metadata-only selection, feature gates, no credential loading, strict wire allowlist", async (t) => {
const f = fixture(t); const hosts = await f.call("listHostsForDatabase");
assert.equal(hosts.length, 2); assert.equal(hosts[0].liveSshPg, undefined); assert.equal(hosts[0].tunnelAvailable, false);
assert.equal(hosts[1].capability, "metadata-only"); assert.equal(hosts[1].tunnelAvailable, false); assert.equal(f.loads(), 0);
for (const field of ["hostname", "destination", "port", "username", "privateKey", "password", "sql", "pin", "secretRef"]) await assert.rejects(f.open({ ...f.request(), [field]: "forged" }), /contract/);
f.identity.manifest.features.optional.pop(); await assert.rejects(f.open(), /unavailable/);
assert.equal((await f.call("listHostsForDatabase")).length, 1); assert.equal(f.loads(), 0);
});
test("open returns proof-bound closeable resource and host-only opaque credentials reused", async (t) => {
const f = fixture(t); const a = await f.open(); assert.equal(a.code, "LIVE_OK"); assert.equal(a.connected, true); assert.equal(a.fixture, true);
assert.equal(a.proof.value, 1); assert.equal(f.active(), 1); assert.equal(f.live.sessions.size, 1);
assert.equal(JSON.stringify(a).includes("unit-"), false);
assert.equal(f.secretStore.getReference(f.identity.pluginId, "ssh"), undefined);
assert.throws(() => f.secretStore.resolve(f.identity.pluginId, { kind: "secret", id: a.secretRef, key: "ssh" }), /not found/);
assert.deepEqual(await f.close(a), { fixture: true, connected: false, closed: true }); await f.close(a);
const b = await f.open(); assert.equal(a.secretRef, b.secretRef); assert.equal(a.pgSecretRef, b.pgSecretRef);
assert.equal(f.loads(), 1); assert.equal(f.writes(), 2); await f.close(b); assert.equal(f.active(), 0);
});
test("unknown/stale hosts and metadata revision change after prompt fail before loading", async (t) => {
const f = fixture(t); assert.equal((await f.open({ ...f.request(), hostId: "ordinary" })).code, "UNKNOWN_HOST");
assert.equal((await f.open({ ...f.request(), revision: "stale" })).code, "STALE_HOST"); assert.equal(f.loads(), 0);
const g = fixture(t, { authorize: async () => { const metadata = g.live.metadata(); g.live.metadata = () => ({ ...metadata, liveSshPg: { kind: "fixture", revision: "changed" } }); } });
assert.equal((await g.open()).code, "STALE_HOST"); assert.equal(g.loads(), 0);
});
test("post-proof metadata/source changes withhold resource and close it", async (t) => {
for (const change of ["revision", "source"]) {
const f = fixture(t); const open = f.adapter.open.bind(f.adapter);
f.adapter.open = async (p) => { const resource = await open(p); if (change === "source") f.swap(); else { const meta = f.live.metadata(); f.live.metadata = () => ({ ...meta, liveSshPg: { kind: "fixture", revision: "changed" } }); } return resource; };
const result = await f.open(); assert.equal(result.code, change === "revision" ? "STALE_HOST" : "UNAVAILABLE"); assert.equal(result.sessionId, undefined); assert.equal(f.active(), 0);
}
});
test("cancel while prompting, cancel before dispatch and late auth cannot publish success", async (t) => {
let resume; const f = fixture(t, { authorize: () => new Promise((r) => { resume = r; }) }); const r = f.request(); const p = f.open(r);
while (!resume) await tick(); await f.cancel(r); assert.equal((await p).code, "CANCELLED"); resume(); await tick(); assert.equal(f.loads(), 0);
const early = f.request(); await f.cancel(early); assert.equal((await f.open(early)).code, "CANCELLED");
let finish; let closed = 0; const g = fixture(t, { adapter: { open: () => new Promise((r) => { finish = r; }) } }); const req = g.request(); const pending = g.open(req);
while (!finish) await tick(); await g.cancel(req); assert.equal((await pending).code, "CANCELLED");
finish({ close: () => closed++, isAlive: () => true }); await tick(); assert.equal(closed, 1); assert.equal(g.live.sessions.size, 0);
});
for (const mode of ["cancel", "releaseRuntime", "revoke", "lock", "shutdown", "ttl"]) test(`${mode} cleans a proven session`, async (t) => {
const f = fixture(t, { sessionMs: mode === "ttl" ? 10 : 30000 }); const r = f.request(); const result = await f.open(r); assert.equal(result.code, "LIVE_OK");
if (mode === "cancel") await f.cancel(r); else if (mode === "releaseRuntime") f.service.releaseRuntime(f.identity.runtimeId);
else if (mode === "shutdown") f.service.shutdown(); else if (mode === "ttl") await new Promise((r) => setTimeout(r, 30)); else f[mode]();
await tick();
assert.equal(f.active(), 0); assert.equal(f.live.sessions.size, 0);
});
test("session isolation and budgets include retained resources", async (t) => {
const f = fixture(t); const a = await f.open(); const b = await f.open(); await assert.rejects(f.open(), /budget/);
await assert.rejects(() => f.live.close({ sessionId: a.sessionId }, { ...f.identity, runtimeId: "other" }), /Unknown/);
f.live.cancel({ openId: "not-owned" }, { ...f.identity, runtimeId: "other" }); assert.equal(f.active(), 2);
await f.close(a); await f.close(b); assert.equal(f.active(), 0);
});
test("safeStorage unavailable fails closed, no plaintext fallback", async (t) => {
const f = fixture(t); f.secretStore.safeStorage = null; assert.equal((await f.open()).code, "UNAVAILABLE"); assert.equal(f.active(), 0);
});
test("adapter cancel during SSH auth destroys client, late ready cannot advance", async () => {
const ssh = new EventEmitter(); let destroyed = 0; ssh.connect = () => {}; ssh.destroy = () => { destroyed++; };
const adapter = new LiveSshPgAdapter({ createClient: () => ssh }); const abort = new AbortController();
const p = adapter.open({ privateKey: "unit-key", password: "unit-password", signal: abort.signal, beforeDial: async () => {} });
await tick(); abort.abort(); await assert.rejects(p, (e) => e.code === "CANCELLED"); ssh.emit("ready"); assert.equal(destroyed, 1); assert.equal(adapter.active, 0);
});
test("deadline during auth destroys resources", async (t) => {
let destroyed = 0; const ssh = new EventEmitter(); ssh.connect = () => {}; ssh.destroy = () => { destroyed++; };
const f = fixture(t, { timeoutMs: 15, adapter: new LiveSshPgAdapter({ createClient: () => ssh }) });
assert.equal((await f.open()).code, "DEADLINE_EXCEEDED"); await tick(); assert.equal(destroyed, 1); assert.equal(f.live.pending.size, 0);
});
const real = process.env.NETCATTY_TEST_LIVE_SSH_PG === "1";
test("LIVE host API: pinned SSH -> PostgreSQL SELECT 1 -> explicit closed cleanup", { skip: !real }, async (t) => {
const adapter = new LiveSshPgAdapter(); const f = fixture(t, { real: true, adapter });
const hosts = await f.call("listHostsForDatabase"); const host = hosts.find((h) => h.liveSshPg);
const r = await f.open({ hostId: host.hostId, revision: host.liveSshPg.revision, openId: randomUUID() });
assert.equal(r.code, "LIVE_OK"); assert.deepEqual(r.proof, { query: "SELECT 1", value: 1, pinnedHostKey: true }); assert.equal(adapter.active, 1);
await f.close(r); await tick(); assert.equal(adapter.active, 0); assert.equal(f.live.sessions.size, 0); assert.equal(f.live.pending.size, 0);
const again = await f.open(); assert.equal(again.code, "LIVE_OK"); assert.equal(again.secretRef, r.secretRef); await f.close(again);
});
for (const [pin, code] of [["wrong-pin", "HOST_KEY_MISMATCH"], ["", "UNKNOWN_HOST_KEY"]]) test(`LIVE host API: ${code}, no session`, { skip: !real }, async (t) => {
const adapter = new LiveSshPgAdapter({ pin }); const f = fixture(t, { real: true, adapter }); const r = await f.open();
assert.equal(r.code, code); assert.equal(r.connected, false); assert.equal(r.sessionId, undefined); assert.equal(adapter.active, 0);
});
test("LIVE host API: wrong SSH credential fails authentication", { skip: !real }, async (t) => {
const { generateKeyPairSync } = require("node:crypto");
const badKey = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ format: "pem", type: "pkcs1" });
const adapter = new LiveSshPgAdapter(); const f = fixture(t, { real: true, adapter, loadCredentials: () => ({ ...loadFixtureCredentials(), privateKey: badKey.toString() }) });
const r = await f.open(); assert.equal(r.code, "AUTH_FAILED"); assert.equal(r.sessionId, undefined); assert.equal(adapter.active, 0);
});
test("LIVE cancel mid-query kills client and destroys forward, suppresses late proof", { skip: !real }, async (t) => {
const { spawn } = require("node:child_process"); let child; let blocked = false;
// Real psql/auth/forward/query; delay delivery of the actual fixed-query proof.
const adapter = new LiveSshPgAdapter({ spawnClient: (...args) => {
child = spawn(...args); const on = child.stdout.on.bind(child.stdout);
child.stdout.on = (event, callback) => event === "data" ? on(event, () => { blocked = true; }) : on(event, callback);
return child;
} });
const f = fixture(t, { real: true, adapter }); const req = f.request(); const p = f.open(req);
while (!blocked) await tick(); await f.cancel(req); assert.equal((await p).code, "CANCELLED");
await new Promise((resolve) => child.exitCode !== null || child.signalCode !== null ? resolve() : child.once("exit", resolve));
assert.equal(child.killed, true); assert.equal(adapter.active, 0); assert.equal(f.live.sessions.size, 0);
});
test("LIVE repeated API opens and awaited closes leave no child processes or socket fds", { skip: !real }, async (t) => {
const fs = require("node:fs");
const children = () => fs.readFileSync(`/proc/self/task/${process.pid}/children`, "utf8").trim();
const sockets = () => fs.readdirSync("/proc/self/fd").filter((fd) => { try { return fs.readlinkSync(`/proc/self/fd/${fd}`).startsWith("socket:"); } catch { return false; } }).length;
await tick(); const beforeChildren = children(); const beforeSockets = sockets();
const f = fixture(t, { real: true, adapter: new LiveSshPgAdapter() });
for (let i = 0; i < 3; i++) { const r = await f.open(); assert.equal(r.code, "LIVE_OK"); await f.close(r); }
await tick(); assert.equal(children(), beforeChildren); assert.equal(sockets(), beforeSockets);
});
test("concurrent close and cancel-close wait for the same resource cleanup", async (t) => {
const f = fixture(t); const req = f.request(); const result = await f.open(req);
const s = f.live.sessions.get(result.sessionId); const original = s.resource.close; let finish;
s.resource.close = () => { original(); return new Promise((resolve) => { finish = resolve; }); };
await f.cancel(req); let first = false; let second = false;
const a = f.close(result).then(() => { first = true; }); const b = f.close(result).then(() => { second = true; });
await tick(); assert.equal(first, false); assert.equal(second, false); assert.equal(f.live.sessions.size, 1);
finish(); await Promise.all([a, b]); assert.equal(f.live.sessions.size, 0);
});
+119
View File
@@ -0,0 +1,119 @@
"use strict";
const net = require("node:net");
const { createHash } = require("node:crypto");
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
const PORT_PROBE_FEATURE = "database.host-port-probe.v1";
const PORT_PROBE_RESOURCE = "database-host:common-ports";
const COMMON_DATABASE_PORTS = Object.freeze([
[5432, "PostgreSQL"], [3306, "MySQL / MariaDB"], [1433, "Microsoft SQL Server"],
[27017, "MongoDB"], [6379, "Redis"],
].map(([port, serviceLabel]) => Object.freeze({ port, serviceLabel })));
// Only sanitized metadata is hashed. No credential material enters this service.
const hostRevision = (host) => createHash("sha256").update(JSON.stringify([
host.hostId, host.hostname, host.port, host.username, host.label,
])).digest("hex");
class ProbeError extends Error {
constructor(code) { super("Host port probe failed"); this.code = code; }
}
function probeTcp({ hostname, port, signal, timeoutMs }) {
return new Promise((resolve, reject) => {
const started = performance.now(); const socket = new net.Socket(); let settled = false; let timer;
const finish = (status, error) => {
if (settled) return; settled = true;
clearTimeout(timer); signal.removeEventListener("abort", abort); socket.destroy();
if (error) reject(error); else resolve({ status, latencyMs: Math.round(performance.now() - started) });
};
const abort = () => finish(undefined, new ProbeError("CANCELLED"));
socket.once("connect", () => finish("open"));
socket.once("error", (error) => {
if (error.code === "ECONNREFUSED") finish("closed");
else if (error.code === "ETIMEDOUT") finish("timeout");
else finish(undefined, new ProbeError("UNAVAILABLE"));
});
signal.addEventListener("abort", abort, { once: true });
if (signal.aborted) { abort(); return; }
// A wall timer also bounds DNS lookup, unlike the socket inactivity timer.
timer = setTimeout(() => finish("timeout"), timeoutMs);
try { socket.connect({ host: hostname, port }); } catch { finish(undefined, new ProbeError("UNAVAILABLE")); }
});
}
class DatabaseHostPortProbeService {
constructor({ tcpProbe = probeTcp, portTimeoutMs = 1200, timeoutMs = 7000 } = {}) {
this.tcpProbe = tcpProbe; this.portTimeoutMs = portTimeoutMs; this.timeoutMs = timeoutMs;
this.pending = new Map(); this.completed = new Map(); this.closed = false;
}
metadata(host) { return { ...host, portProbe: { revision: hostRevision(host) } }; }
key(context, id) { return JSON.stringify([context.pluginId, context.runtimeId, context.sourceOwner, context.sourceId, context.securityPrincipal, id]); }
prune() { for (const [key, value] of this.completed) if (value.expires <= Date.now()) this.completed.delete(key); }
remember(key, code) {
this.prune();
if (!this.completed.has(key) && this.completed.size >= 256) throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Port probe replay budget reached");
this.completed.set(key, { code, expires: Date.now() + 120_000 });
}
cancel({ probeId }, context) {
const key = this.key(context, probeId);
this.pending.get(key)?.controller.abort(); this.remember(key, "CANCELLED"); return null;
}
async probe(request, context, { authorize, readHosts, assertActive }) {
let hostname;
const result = (code, ports = []) => ({ hostId: request.hostId, ...(hostname ? { hostname } : {}), synthetic: false, connected: false, ports, code });
this.prune(); const key = this.key(context, request.probeId);
if (this.completed.get(key)?.code === "CANCELLED") return result("CANCELLED");
if (this.closed) return result("UNAVAILABLE");
if (this.pending.has(key) || this.completed.has(key)) throw new PluginRpcError(RPC_ERRORS.failedPrecondition, "Port probe ID already used");
if (this.pending.size >= 8 || [...this.pending.values()].filter((p) => p.context.runtimeId === context.runtimeId).length >= 2 || this.completed.size >= 248) {
throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Port probe budget reached");
}
const controller = new AbortController(); const scoped = { ...context, signal: controller.signal };
let abortCode = "CANCELLED"; let selected = false; let onAbort;
const check = () => controller.signal.throwIfAborted();
const current = async () => {
check(); await assertActive(scoped); check();
const hosts = await readHosts(scoped); check();
const host = hosts.find((h) => h.hostId === request.hostId);
if (!host) throw new ProbeError(selected ? "STALE_HOST" : "UNKNOWN_HOST");
if (hostRevision(host) !== request.revision) throw new ProbeError("STALE_HOST");
selected = true; hostname = host.hostname;
return host;
};
this.remember(key, "running"); this.pending.set(key, { context, controller });
const abort = () => controller.abort();
context.signal?.addEventListener("abort", abort, { once: true });
const timer = setTimeout(() => { abortCode = "DEADLINE_EXCEEDED"; controller.abort(); }, this.timeoutMs);
const aborted = new Promise((resolve) => {
onAbort = () => resolve(result(abortCode)); controller.signal.addEventListener("abort", onAbort, { once: true });
});
if (context.signal?.aborted) abort();
const run = async () => {
try {
check(); await authorize(scoped); check(); await current();
const ports = new Array(COMMON_DATABASE_PORTS.length); let next = 0;
const worker = async () => {
while (next < COMMON_DATABASE_PORTS.length) {
check(); const index = next++; const spec = COMMON_DATABASE_PORTS[index];
const host = await current(); check();
const value = await this.tcpProbe({ hostname: host.hostname, port: spec.port, signal: controller.signal, timeoutMs: this.portTimeoutMs });
check(); ports[index] = { ...spec, ...value };
}
};
await Promise.all([worker(), worker()]); await current(); check();
return result("PROBE_OK", ports);
} catch (error) {
return result(controller.signal.aborted ? abortCode : error instanceof ProbeError ? error.code : "UNAVAILABLE");
}
};
try { return await Promise.race([run(), aborted]); }
finally {
clearTimeout(timer); context.signal?.removeEventListener("abort", abort);
controller.signal.removeEventListener("abort", onAbort);
// Also destroy the sibling worker's socket if one worker failed.
controller.abort(); this.pending.delete(key); this.remember(key, "finished");
}
}
abortWhere(predicate) { for (const p of this.pending.values()) if (predicate(p.context)) p.controller.abort(); }
releaseRuntime(runtimeId) { this.abortWhere((c) => c.runtimeId === runtimeId); }
revoke(pluginId) { this.abortWhere((c) => c.pluginId === pluginId); }
closeAll() { this.abortWhere(() => true); }
shutdown() { this.closed = true; this.closeAll(); }
}
module.exports = { DatabaseHostPortProbeService, PORT_PROBE_FEATURE, PORT_PROBE_RESOURCE, COMMON_DATABASE_PORTS, hostRevision, probeTcp };
@@ -0,0 +1,89 @@
"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const { randomUUID } = require("node:crypto");
const { DatabaseHostPortProbeService, COMMON_DATABASE_PORTS, probeTcp } = require("./databaseHostPortProbe.cjs");
const tick = () => new Promise(setImmediate);
function fixture(t, options = {}) {
const calls = []; let active = 0; let peak = 0;
const service = new DatabaseHostPortProbeService({ tcpProbe: async (p) => {
calls.push({ hostname: p.hostname, port: p.port }); active++; peak = Math.max(peak, active);
try { await tick(); return { status: p.port === 5432 ? "open" : "closed", latencyMs: 1 }; } finally { active--; }
}, ...options });
let hosts = [{ hostId: "saved", hostname: "127.0.0.1", label: "Saved loopback", port: 2222, username: "smoketest", capability: "metadata-only", tunnelAvailable: false }];
const context = { pluginId: "fixture.plugin", runtimeId: "runtime", sourceOwner: "owner", sourceId: "source", securityPrincipal: "principal", signal: new AbortController().signal };
const request = () => ({ hostId: "saved", revision: service.metadata(hosts[0]).portProbe.revision, probeId: randomUUID() });
const hooks = { authorize: async () => {}, readHosts: async () => hosts, assertActive: async () => {} };
t.after(() => service.shutdown());
return { service, calls, peak: () => peak, context, request, hooks, setHosts: (value) => { hosts = value; },
run: (r = request(), c = context, h = hooks) => service.probe(r, c, h) };
}
test("ordinary metadata selection opens nothing; probe uses exactly the host-owned five ports", async (t) => {
const f = fixture(t); const r = f.request(); assert.equal(f.calls.length, 0);
const value = await f.run(r);
assert.equal(value.code, "PROBE_OK"); assert.equal(value.connected, false); assert.equal(value.synthetic, false);
assert.deepEqual(f.calls.map((c) => c.port), [5432, 3306, 1433, 27017, 6379]);
assert.ok(f.calls.every((c) => c.hostname === "127.0.0.1")); assert.equal(f.peak(), 2);
assert.equal(value.ports[0].status, "open"); assert.equal(value.handleId, undefined);
assert.equal(f.service.pending.size, 0);
});
test("prepared PostgreSQL TCP fixture: 5432 open, other common database ports closed", { skip: process.env.NETCATTY_TEST_PREPARED_DB_PROBE !== "1" }, async (t) => {
const f = fixture(t, { tcpProbe: probeTcp }); const r = await f.run();
assert.equal(r.code, "PROBE_OK"); assert.equal(r.connected, false);
assert.deepEqual(r.ports.map(({ port, status }) => ({ port, status })), COMMON_DATABASE_PORTS.map(({ port }) => ({ port, status: port === 5432 ? "open" : "closed" })));
assert.ok(r.ports.every((p) => Number.isInteger(p.latencyMs)));
});
test("unknown ID and stale revision fail before any socket", async (t) => {
const f = fixture(t);
assert.equal((await f.run({ ...f.request(), hostId: "forged" })).code, "UNKNOWN_HOST");
assert.equal((await f.run({ ...f.request(), revision: "stale" })).code, "STALE_HOST");
assert.equal(f.calls.length, 0);
});
test("hostname replacement during authorization and deletion during probe fail closed", async (t) => {
const f = fixture(t); const r = f.request();
assert.equal((await f.run(r, f.context, { ...f.hooks, authorize: async () => { f.setHosts([{ hostId: "saved", hostname: "forged.invalid" }]); } })).code, "STALE_HOST");
assert.equal(f.calls.length, 0);
const g = fixture(t, { tcpProbe: async () => { g.setHosts([]); return { status: "open" }; } });
const result = await g.run(); assert.equal(result.code, "STALE_HOST"); assert.deepEqual(result.ports, []);
});
test("permission failure neither reads host data nor leaks diagnostics", async (t) => {
const f = fixture(t); let reads = 0;
const r = await f.run(f.request(), f.context, { ...f.hooks, authorize: async () => { throw new Error("private diagnostic"); }, readHosts: async () => { reads++; return []; } });
assert.equal(r.code, "UNAVAILABLE"); assert.equal(r.hostname, undefined); assert.equal(reads, 0); assert.equal(f.calls.length, 0);
assert.equal(JSON.stringify(r).includes("private diagnostic"), false);
});
test("cancel before start, repeated cancel and cross-runtime IDs are isolated", async (t) => {
const f = fixture(t); const r = f.request(); f.service.cancel(r, f.context); f.service.cancel(r, f.context);
assert.equal((await f.run(r)).code, "CANCELLED"); assert.equal(f.calls.length, 0);
assert.equal((await f.run(r, { ...f.context, runtimeId: "other" })).code, "PROBE_OK");
});
test("cancel during authorization suppresses late prompts and sockets", async (t) => {
const f = fixture(t); let finish; const r = f.request();
const pending = f.run(r, f.context, { ...f.hooks, authorize: () => new Promise((resolve) => { finish = resolve; }) });
f.service.cancel(r, f.context); assert.equal((await pending).code, "CANCELLED");
finish(); await tick(); assert.equal(f.calls.length, 0); assert.equal(f.service.pending.size, 0);
});
for (const method of ["cancel", "releaseRuntime", "revoke", "closeAll", "shutdown", "deadline"]) test(`${method} aborts all socket work and prevents subsequent probes`, async (t) => {
let started = 0; let stopped = 0;
const f = fixture(t, { timeoutMs: method === "deadline" ? 30 : 1000, tcpProbe: ({ signal }) => new Promise((resolve) => {
started++; signal.addEventListener("abort", () => { stopped++; resolve({ status: "open" }); }, { once: true });
}) });
const r = f.request(); const pending = f.run(r); while (started < 2) await tick();
if (method === "cancel") f.service.cancel(r, f.context);
else if (method !== "deadline") f.service[method](method === "revoke" ? f.context.pluginId : f.context.runtimeId);
assert.equal((await pending).code, method === "deadline" ? "DEADLINE_EXCEEDED" : "CANCELLED");
await tick(); assert.equal(started, 2); assert.equal(stopped, 2); assert.equal(f.service.pending.size, 0);
});
test("timeouts remain timeouts; network failures are never called closed", async (t) => {
const f = fixture(t, { tcpProbe: async () => ({ status: "timeout", latencyMs: 1200 }) });
assert.ok((await f.run()).ports.every((p) => p.status === "timeout"));
f.service.tcpProbe = async () => { throw new Error("DNS unavailable"); };
const r = await f.run(); assert.equal(r.code, "UNAVAILABLE"); assert.deepEqual(r.ports, []);
});
test("operation/replay budgets reject excess requests and cancel frees pending capacity", async (t) => {
const f = fixture(t); const wait = { ...f.hooks, authorize: () => new Promise(() => {}) };
const a = f.request(); const b = f.request(); const p = f.run(a, f.context, wait); const q = f.run(b, f.context, wait);
await assert.rejects(f.run(), /budget/); f.service.cancel(a, f.context); f.service.cancel(b, f.context);
await Promise.all([p, q]); await assert.rejects(f.run(a), /already used/);
assert.equal((await f.run()).code, "PROBE_OK");
});
@@ -0,0 +1,111 @@
"use strict";
const fs = require("node:fs");
const net = require("node:net");
const { spawn } = require("node:child_process");
const { createHash } = require("node:crypto");
const { Client } = require("ssh2");
const FIXTURE_ROOT = "/workspace/agent-tools/database/existing-host-probe/fixture";
const PIN = "b9cebvdhVKqAto25HDIEv+hOU6v3LM86OOvQDQLyVe0";
class LiveFixtureError extends Error {
constructor(code) { super("Live fixture operation failed"); this.code = code; }
}
function loadFixtureCredentials() {
const read = (file) => {
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
try { const stat = fs.fstatSync(fd); if (!stat.isFile() || stat.size > 16384 || (stat.mode & 0o077)) throw new Error(); return fs.readFileSync(fd, "utf8"); }
finally { fs.closeSync(fd); }
};
// Parse only a literal assignment. Never source a shell file or evaluate expansion.
const env = read(`${FIXTURE_ROOT}/pg-connect.env`);
const match = env.match(/^(?:export )?PGPASSWORD=(?:'([^'\r\n]*)'|"([^"$`\\\r\n]*)"|([^\s'"$`\\]+))\s*$/m);
if (!match) throw new LiveFixtureError("UNAVAILABLE");
return { privateKey: read(`${FIXTURE_ROOT}/ssh/id_ed25519`), password: match[1] ?? match[2] ?? match[3] };
}
/** Host-only adapter. Constructor injection is for tests, never RPC parameters. */
class LiveSshPgAdapter {
constructor({ pin = PIN, createClient = () => new Client(), spawnClient = spawn } = {}) {
this.pin = pin; this.createClient = createClient; this.spawnClient = spawnClient; this.active = 0;
}
async open({ privateKey, password, signal, beforeDial }) {
if (!this.pin) throw new LiveFixtureError("UNKNOWN_HOST_KEY");
signal.throwIfAborted();
const ssh = this.createClient(); let server; let child; let key; let pinMatched = false; let pinRejected = false;
let closed = false; let closePromise; let opened = false; const sockets = new Set(); const listeners = new Set();
let rejectStage = () => {};
const close = () => {
if (closed) return closePromise; closed = true;
// A closed acknowledgement waits for the PG child and listener to finish,
// not merely for SIGKILL to be sent. Socket destruction starts immediately.
const reaped = child && child.exitCode === null && child.signalCode === null
? new Promise((resolve) => child.once("close", resolve)) : Promise.resolve();
const listenerClosed = server ? new Promise((resolve) => server.close(resolve)) : Promise.resolve();
closePromise = Promise.all([reaped, listenerClosed]).then(() => undefined);
signal.removeEventListener("abort", abort);
child?.kill("SIGKILL"); child?.stdin?.destroy(); child?.stdout?.destroy();
for (const socket of sockets) socket.destroy();
ssh.destroy(); key?.fill(0);
if (opened) { opened = false; this.active--; }
for (const listener of listeners) listener(); listeners.clear();
return closePromise;
};
const fail = (code) => { rejectStage(new LiveFixtureError(code)); close(); };
const abort = () => fail("CANCELLED");
const stage = (start) => new Promise((resolve, reject) => {
rejectStage = reject;
if (closed || signal.aborted) { reject(new LiveFixtureError("CANCELLED")); return; }
try { start(resolve, reject); } catch { fail("UNAVAILABLE"); }
});
signal.addEventListener("abort", abort, { once: true });
ssh.on("error", (e) => fail(pinRejected ? "HOST_KEY_MISMATCH" : e.level === "client-authentication" ? "AUTH_FAILED" : "UNAVAILABLE"));
ssh.on("close", () => fail("UNAVAILABLE"));
try {
await beforeDial(); signal.throwIfAborted();
key = Buffer.from(privateKey); privateKey = undefined;
await stage((resolve) => {
ssh.once("ready", resolve);
ssh.connect({ host: "127.0.0.1", port: 2222, username: "smoketest", privateKey: key, readyTimeout: 5000,
hostVerifier: (bytes) => {
pinMatched = createHash("sha256").update(bytes).digest("base64").replace(/=+$/, "") === this.pin;
pinRejected = !pinMatched; return pinMatched;
} });
});
if (!pinMatched) throw new LiveFixtureError("HOST_KEY_MISMATCH");
key.fill(0); key = undefined;
await beforeDial(); signal.throwIfAborted();
let accepted = false;
server = net.createServer((socket) => {
if (closed || accepted) { socket.destroy(); return; }
accepted = true; sockets.add(socket); socket.on("error", () => fail("UNAVAILABLE"));
socket.on("close", () => { if (!closed) fail("UNAVAILABLE"); });
ssh.forwardOut("127.0.0.1", 0, "127.0.0.1", 5432, (error, stream) => {
if (error || closed) { stream?.destroy(); socket.destroy(); if (!closed) fail("UNAVAILABLE"); return; }
sockets.add(stream); stream.on("error", () => fail("UNAVAILABLE"));
stream.on("close", () => { if (!closed) fail("UNAVAILABLE"); }); socket.pipe(stream).pipe(socket);
});
});
server.on("error", () => fail("UNAVAILABLE"));
await stage((resolve) => server.listen(0, "127.0.0.1", resolve));
await stage((resolve) => {
child = this.spawnClient(`${FIXTURE_ROOT}/pg/pgsql/bin/psql`, ["-X", "-w", "-h", "127.0.0.1", "-p", String(server.address().port), "-U", "nc_db_probe", "-d", "nc_probe", "-At", "-v", "ON_ERROR_STOP=1"], {
env: { PATH: "/usr/bin:/bin", PGPASSWORD: password, PGCONNECT_TIMEOUT: "5", PGSSLMODE: "disable", PGOPTIONS: "-c statement_timeout=5000" },
stdio: ["pipe", "pipe", "ignore"],
});
password = undefined;
child.on("error", () => fail("UNAVAILABLE")); child.on("exit", () => fail(opened ? "UNAVAILABLE" : "AUTH_FAILED"));
child.stdin.on("error", () => fail("UNAVAILABLE"));
let output = "";
child.stdout.on("data", (bytes) => {
output += bytes.toString();
if (output.length > 128) { fail("UNAVAILABLE"); return; }
if (output === "1\nNETCATTY_PROBE_DONE\n") resolve();
});
child.stdin.write("SELECT 1;\n\\echo NETCATTY_PROBE_DONE\n");
});
signal.throwIfAborted(); if (closed) throw new LiveFixtureError("UNAVAILABLE");
opened = true; this.active++;
return { close, isAlive: () => !closed, onClose: (listener) => { if (closed) listener(); else listeners.add(listener); } };
} catch (error) { await close(); throw error; }
finally { privateKey = undefined; password = undefined; key?.fill(0); }
}
}
module.exports = { LiveSshPgAdapter, LiveFixtureError, loadFixtureCredentials, PIN };
+24
View File
@@ -0,0 +1,24 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),net=require('node:net');
const {PgWire,MysqlWire}=require('./databaseTcpWire.cjs');
const i32=n=>{const b=Buffer.alloc(4);b.writeInt32BE(n);return b;};
const message=(type,body)=>Buffer.concat([Buffer.from(type),i32(body.length+4),body]);
const auth=(kind,body=Buffer.alloc(0))=>message('R',Buffer.concat([i32(kind),body]));
async function endpoint(t,run){const sockets=new Set();const server=net.createServer(s=>{sockets.add(s);s.on('error',()=>{});s.on('close',()=>sockets.delete(s));run(s);});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>{for(const s of sockets)s.destroy();server.close();});return {hostname:'127.0.0.1',port:server.address().port,username:'disposable',database:'synthetic',password:'disposable-only',tls:false};}
test('Gauss auth code ten never enters PG SASL or sends a password response',async t=>{
let responses=0;const c=await endpoint(t,s=>s.once('data',()=>{s.write(auth(10,Buffer.from('SCRAM-SHA-256\0\0')));s.once('data',()=>{responses++;s.write(Buffer.concat([auth(0),message('Z',Buffer.from('I'))]));});}));
const p=new PgWire('gauss-legacy');t.after(()=>p.close());p.execute=async()=>({rows:[]});await assert.rejects(p.open(c),/Authentication not packaged/);assert.equal(responses,0);
});
test('unknown vendor authentication codes fail closed without response',async t=>{
let responses=0;const c=await endpoint(t,s=>s.once('data',()=>{s.on('data',()=>responses++);s.write(auth(13));}));const p=new PgWire('gauss-legacy');t.after(()=>p.close());await assert.rejects(p.open(c),/Authentication not packaged/);assert.equal(responses,0);
});
test('PG ReadyForQuery requires AuthenticationOk',async t=>{
const c=await endpoint(t,s=>s.once('data',()=>s.write(message('Z',Buffer.from('I')))));const p=new PgWire();t.after(()=>p.close());p.execute=async()=>({rows:[]});await assert.rejects(p.open(c),/authentication|Authentication/);
});
test('PG SCRAM cannot finish by skipping server proof',async t=>{
const c=await endpoint(t,s=>s.once('data',()=>{s.write(auth(10,Buffer.from('SCRAM-SHA-256\0\0')));s.once('data',()=>s.write(Buffer.concat([auth(0),message('Z',Buffer.from('I'))])));}));const p=new PgWire();t.after(()=>p.close());p.execute=async()=>({rows:[]});await assert.rejects(p.open(c),/authentication|Authentication/);
});
test('unknown MySQL auth plugin is rejected even for an empty password',()=>{
const m=new MysqlWire();for(const password of ['', 'synthetic'])assert.throws(()=>m.auth('unpackaged_vendor_auth',password,Buffer.alloc(20)),/Authentication not packaged/);
assert.equal(m.auth('mysql_native_password','',Buffer.alloc(20)).length,0);
});
+74
View File
@@ -0,0 +1,74 @@
"use strict";
const {randomUUID}=require("node:crypto");
const {PgWire,MysqlWire,bind}=require("./databaseTcpWire.cjs");
const {PluginRpcError,RPC_ERRORS}=require("./rpcRouter.cjs");
const {createDefinitionValidator}=require("./contractValidator.cjs");
const registry=require("./generated/database-drivers.json");
const {resolveProfile,metadataQueries,validateServerMode}=require('./databaseDriverProfiles.cjs');
const fail=(code,message)=>new PluginRpcError(RPC_ERRORS[code],message);
const ownerKeys=["pluginId","runtimeId","sourceOwner","sourceId","securityPrincipal"];
class DatabaseTcpService {
constructor(){this.sessions=new Map();this.closed=false;}
get(id,context){const s=this.sessions.get(id);if(!s||ownerKeys.some(k=>s.owner[k]!==context[k]))throw fail("permissionDenied","Unknown database session");return s;}
close(s){if(this.sessions.get(s.id)!==s)return;this.sessions.delete(s.id);clearTimeout(s.idle);s.abort?.();s.client.close();}
release(predicate=()=>true){for(const s of this.sessions.values())if(predicate(s.owner))this.close(s);}
async run(s,context,authenticate,work,timeout=3000){
if(s.busy)throw fail("failedPrecondition","A database operation is already active");s.busy=true;
let timer,abort;
try {
const cancellation=new Promise((_,reject)=>{abort=()=>{s.client.close();reject(fail("cancelled","Database operation cancelled"));};s.abort=abort;context.signal?.addEventListener("abort",abort,{once:true});timer=setTimeout(()=>{s.client.close();reject(fail("deadlineExceeded","Database deadline exceeded"));},timeout);});
context.signal?.throwIfAborted();
const result=await Promise.race([Promise.resolve().then(()=>{this.get(s.id,context);context.signal?.throwIfAborted();return work();}),cancellation]);
await authenticate(context);this.get(s.id,context);
if(!s.client.socket || s.client.socket.destroyed)throw new Error("Database transport closed");
return result;
}catch(error){this.close(s);if(error instanceof PluginRpcError)throw error;throw fail("unavailable","Database connection or statement failed. Check authentication, server compatibility and TLS.");}
finally{clearTimeout(timer);context.signal?.removeEventListener("abort",abort);s.abort=null;s.busy=false;}
}
async open(request,context,{authorize,authenticate}){
const driver=registry.find(d=>d.id===request.driverId);
let profile;
try{profile=resolveProfile(request.driverId,request.variant);}catch(error){throw fail('unsupported',error.message);}
if(this.closed)throw fail("unavailable","Database TCP service stopped");
if(!request.tls && !["127.0.0.1","::1"].includes(request.hostname))throw fail("permissionDenied","Verified TLS is required outside loopback");
if([request.database,request.username,request.password].some(v=>v.includes("\0")))throw fail("invalidArgument","Invalid connection field");
await authorize(context,`${driver.label} @ ${request.hostname}:${request.port} / ${request.database}`);await authenticate(context);
if(this.sessions.size>=8||[...this.sessions.values()].filter(s=>s.owner.runtimeId===context.runtimeId).length>=2)throw fail("resourceExhausted","Database session budget reached");
const client=profile.wireFamily==="postgres"?new PgWire(profile.authPolicy):new MysqlWire();
const s={id:randomUUID(),client,driver,profile,owner:context,busy:false};this.sessions.set(s.id,s);
s.idle=setTimeout(()=>this.close(s),600000);s.idle.unref();
await this.run(s,context,authenticate,async()=>{await client.open(request);await validateServerMode(client,profile);},8000);
s.client.socket.once("close",()=>this.close(s));
const result={handleId:s.id,engine:profile.wireFamily,driverId:driver.id,label:driver.label,readOnly:true,fixture:false};
if(!createDefinitionValidator("DatabaseTcpOpenResult")(result)){this.close(s);throw fail("unavailable","Invalid database session");}return result;
}
async schema(s,context,hooks){
await hooks.authorize(context);this.get(s.id,context);
return this.run(s,context,hooks.authenticate,async()=>{
const pg=s.profile.wireFamily==="postgres", metadata=metadataQueries(s.profile);
const tables=await s.client.execute(metadata.tables);
const result={tables:[]};
for(const [name,kind] of tables.rows){
const rows=await s.client.execute(pg?metadata.columns:bind(metadata.columns,[name],'mysql'),pg?[name]:[]);
result.tables.push({name,kind:kind==="VIEW"?"view":"table",columns:rows.rows.map(([name,type,nullable,pk])=>({name,type,nullable:nullable==="YES",primaryKey:pg?pk==="t":pk==="PRI"}))});
}
if(!createDefinitionValidator("DatabaseSchemaResult")(result))throw Error("Schema exceeds contract");return result;
});
}
async query(s,request,context,hooks){
if(request.mode!=="read")throw fail("permissionDenied","Network sessions are read-only");
const sql=bind(request.sql,request.parameters,s.profile.wireFamily);
if(!/^\s*(SELECT|WITH|EXPLAIN)\b/i.test(sql)||/\b(INTO|OUTFILE|DUMPFILE|LOAD_FILE|SLEEP|BENCHMARK|SET_CONFIG|PG_SLEEP|DBLINK)\b/i.test(sql))throw fail("permissionDenied","Read query rejected");
await hooks.authorize(context);this.get(s.id,context);
const start=Date.now();
return this.run(s,context,hooks.authenticate,async()=>{
await s.client.execute(s.profile.wireFamily==="postgres"?"BEGIN READ ONLY":"START TRANSACTION READ ONLY");
try {
const r=await s.client.execute(sql,s.profile.wireFamily==="postgres"?request.parameters:[],request.maxRows??100);
const result={...r,changes:0,elapsedMs:Date.now()-start};
if(!createDefinitionValidator("DatabaseQueryResult")(result))throw Error("Result exceeds contract");return result;
}finally{await s.client.execute("ROLLBACK");}
},request.timeoutMs??3000);
}
}
module.exports={DatabaseTcpService,registry};
@@ -0,0 +1,94 @@
"use strict";
const test=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const {DatabaseTcpService,registry}=require('./databaseTcpService.cjs');
const {bind}=require('./databaseTcpWire.cjs');
const {createDefinitionValidator}=require('./contractValidator.cjs');
const owner={pluginId:'test.db',runtimeId:'a',sourceOwner:'source',sourceId:'local',securityPrincipal:'p'};
const hooks={authorize:async()=>{},authenticate:async()=>{}};
test('registry copies, schema IDs, verified families and vendor fail-closed distinction',()=>{
assert.deepEqual(registry,require('../../packages/plugin-contract/schema/database-drivers.json'));
const ids=createDefinitionValidator('DatabaseDriverId');
for(const d of registry){assert.equal(createDefinitionValidator('DatabaseDriverProfile')(d),true);assert.equal(ids(d.id),true);assert.ok(d.fields.length);assert.ok(d.source);}
assert.equal(new Set(registry.map(d=>d.id)).size,registry.length);
for(const id of ['mysql','mariadb','goldendb','tidb','oceanbase'])assert.equal(registry.find(d=>d.id===id).wireFamily,'mysql');
for(const id of ['postgres','opengauss','gaussdb','highgo','kingbase','vastbase','uxdb'])assert.equal(registry.find(d=>d.id===id).wireFamily,'postgres');
assert.equal(registry.find(d=>d.id==='gbase8c').wireFamily,'unpackaged');
assert.equal(registry.find(d=>d.id==='kingbase').defaultPort,54321);
});
test('TCP request schema refuses URLs, arbitrary fields, bad ports and engines',()=>{
const valid=createDefinitionValidator('DatabaseTcpOpenRequest');const request={driverId:'postgres',hostname:'127.0.0.1',port:5432,database:'fixture',username:'reader',password:'ephemeral',tls:false};
assert.equal(valid(request),true);
for(const patch of [{port:0},{port:65536},{port:'5432'},{hostname:'tcp://host'},{path:'/tmp/socket'},{driverId:'guess'},{secretRef:'forged'}])assert.equal(valid({...request,...patch}),false);
});
test('wire binding never interpolates strings and rejects ambiguous or multiple statements',()=>{
assert.equal(bind("SELECT ?, '?', \"?\"",['x'],'postgres'),"SELECT $1, '?', \"?\"");
assert.equal(bind('SELECT ?, ?, ?, ?',["x' OR TRUE",null,true,42],'mysql'),"SELECT CONVERT(X'7827204f522054525545' USING utf8mb4), NULL, TRUE, 42");
for(const sql of ['SELECT ?; DROP TABLE x','SELECT $$text$$','SELECT ? -- hi',"SELECT 'unterminated",'SELECT :named'])assert.throws(()=>bind(sql,[1],'postgres'));
assert.throws(()=>bind('SELECT ?',[],'mysql'));
});
test('unpackaged and non-TLS remote addresses fail before permissions or dialing',async()=>{
const s=new DatabaseTcpService();let calls=0;const h={...hooks,authorize:async()=>{calls++;}};
await assert.rejects(s.open({driverId:'oracle'},owner,h),/not packaged/);
await assert.rejects(s.open({driverId:'postgres',hostname:'remote.example',tls:false},owner,h),/TLS/);
assert.equal(calls,0);assert.equal(s.sessions.size,0);
});
test('cancellation closes a real pending TCP socket and prevents late handle publication',async(t)=>{
const net=require('node:net');const sockets=new Set();const server=net.createServer(socket=>{sockets.add(socket);socket.on('close',()=>sockets.delete(socket));});
await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>{for(const socket of sockets)socket.destroy();server.close();});
const controller=new AbortController(),service=new DatabaseTcpService();t.after(()=>service.release());
const opening=service.open({driverId:'mysql',hostname:'127.0.0.1',port:server.address().port,database:'fixture',username:'reader',password:'',tls:false},{...owner,signal:controller.signal},hooks);
while(!sockets.size)await new Promise(setImmediate);controller.abort();await assert.rejects(opening,/cancelled/);assert.equal(service.sessions.size,0);
});
const fixturePath=process.env.NETCATTY_TEST_DATABASE_FIXTURE;
const config=fixturePath&&fs.existsSync(fixturePath)?JSON.parse(fs.readFileSync(fixturePath)):{};
test('verified TLS rejects an IP target with a trusted DNS-only certificate before PG startup',{skip:!fixturePath?'SKIPPED_NO_FIXTURE: disposable TLS output directory required':false},async(t)=>{
const path=require('node:path'),net=require('node:net'),tls=require('node:tls');const {execFileSync,execFile}=require('node:child_process');const {promisify}=require('node:util');
const dir=path.join(path.dirname(fixturePath),'tls');fs.mkdirSync(dir,{recursive:true,mode:0o700});
const key=path.join(dir,'key.pem'),cert=path.join(dir,'cert.pem');
execFileSync('openssl',['req','-x509','-newkey','rsa:2048','-nodes','-keyout',key,'-out',cert,'-days','1','-subj','/CN=localhost','-addext','subjectAltName=DNS:localhost'],{stdio:'ignore'});fs.chmodSync(key,0o600);
const secureContext=tls.createSecureContext({key:fs.readFileSync(key),cert:fs.readFileSync(cert)});const sockets=new Set();let startupSeen=false;
const server=net.createServer(socket=>{sockets.add(socket);socket.on('error',()=>{});socket.once('data',data=>{
assert.equal(data.readInt32BE(4),80877103);socket.write('S');const secured=new tls.TLSSocket(socket,{isServer:true,secureContext});sockets.add(secured);secured.on('error',()=>{});secured.on('data',()=>{startupSeen=true;secured.destroy();});
});});
await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>{for(const socket of sockets)socket.destroy();server.close();fs.unlinkSync(key);});
const script=`const {PgWire}=require(${JSON.stringify(require.resolve('./databaseTcpWire.cjs'))});const p=new PgWire();p.open({hostname:'127.0.0.1',port:${server.address().port},database:'test',username:'test',password:'',tls:true}).then(()=>{process.exitCode=1;},e=>{if(e.code!=='ERR_TLS_CERT_ALTNAME_INVALID')process.exitCode=1;}).finally(()=>p.close());`;
await promisify(execFile)(process.execPath,['-e',script],{env:{PATH:process.env.PATH,NODE_EXTRA_CA_CERTS:cert},timeout:10000});
assert.equal(startupSeen,false,'Credentials/startup reached a server with the wrong certificate name');
});
for(const engine of ['postgres','mysql'])test(`real ${engine} TCP authentication/schema/bound SELECT/owner/write/close`,{skip:!config[engine]?(engine==='mysql'?'SKIPPED_NO_LOCAL_SERVER: local binaries/cache absent; offline fixture preparation attempted':'SKIPPED_NO_FIXTURE: set NETCATTY_TEST_DATABASE_FIXTURE to disposable connections.json'):false},async(t)=>{
const service=new DatabaseTcpService();t.after(()=>service.release());const opened=await service.open(config[engine],owner,hooks);const s=service.get(opened.handleId,owner);
assert.equal(opened.engine,engine);assert.equal(opened.fixture,false);assert.equal(opened.readOnly,true);assert.ok(!('password' in opened));
assert.throws(()=>service.get(opened.handleId,{...owner,runtimeId:'foreign'}),/Unknown/);
const schema=await service.schema(s,owner,hooks);assert.ok(schema.tables.some(t=>t.name==='inventory'));assert.ok(schema.tables.some(t=>t.kind==='view'));assert.equal(schema.tables.find(t=>t.name==='inventory').columns.find(c=>c.name==='id').primaryKey,true);assert.equal(schema.tables.find(t=>t.name==='inventory').columns.find(c=>c.name==='id').nullable,false);
const result=await service.query(s,{sql:'SELECT product, quantity, note FROM inventory WHERE id = ?',parameters:[1],mode:'read'},owner,hooks);
assert.match(result.rows[0][0],/Loopback/);assert.equal(result.rows[0][1],'37');assert.equal(result.rows[0][2],null);
const injection=await service.query(s,{sql:'SELECT product FROM inventory WHERE product = ?',parameters:["x' OR TRUE --"],mode:'read'},owner,hooks);assert.equal(injection.rows.length,0);
const limited=await service.query(s,{sql:'SELECT * FROM inventory ORDER BY id',parameters:[],mode:'read',maxRows:1},owner,hooks);assert.equal(limited.rows.length,1);assert.equal(limited.truncated,true);
await assert.rejects(service.query(s,{sql:'DELETE FROM inventory',parameters:[],mode:'write'},owner,hooks),/read-only/);
await assert.rejects(service.query(s,{sql:'WITH deleted AS (DELETE FROM inventory RETURNING *) SELECT * FROM deleted',parameters:[],mode:'read'},owner,hooks),/failed/);
assert.equal(service.sessions.size,0);
const bad={...config[engine],password:'incorrect-disposable-password'};await assert.rejects(service.open(bad,owner,hooks),/failed/);assert.equal(service.sessions.size,0);
const fresh=await service.open(config[engine],owner,hooks);service.release(c=>c.runtimeId===owner.runtimeId);assert.throws(()=>service.get(fresh.handleId,owner),/Unknown/);
});
test('base PG query routing for explicit profiles is NOT_VENDOR_QUALIFIED',{skip:!config.postgres?'SKIPPED_NO_FIXTURE':false},async(t)=>{
const service=new DatabaseTcpService();t.after(()=>service.release());
for(const [driverId,variant] of [['highgo','highgo-pg'],['kingbase','kingbase-pg'],['uxdb',undefined]]){
const opened=await service.open({...config.postgres,driverId,...(variant?{variant}:{})},owner,hooks);assert.equal(opened.driverId,driverId);
const s=service.get(opened.handleId,owner);const r=await service.query(s,{sql:'SELECT quantity FROM inventory WHERE id=?',parameters:[1],mode:'read'},owner,hooks);assert.deepEqual(r.rows,[['37']]);service.close(s);
}
});
test('public TCP route reuses host permission/source checks and revocation cleanup',{skip:!config.postgres?'SKIPPED_NO_FIXTURE':false},async(t)=>{
const {PluginSqliteFixtureService,FEATURE}=require('./sqliteFixtureService.cjs');const {PluginHostRpcRegistry}=require('./hostRpcRegistry.cjs');
let revoke;const grants=[];let source='local';
const identity={...owner,pluginVersion:'test',runtimeKind:'browser',manifest:{features:{optional:[FEATURE,'database.tcp.v1']}}};
const service=new PluginSqliteFixtureService({enabled:true,database:{getActivePlugin:()=>({enabled:true,source:{id:source}}),getRetainedPluginSource:()=>({id:source}),privateOwner:()=>owner.sourceOwner,publicPluginId:()=>owner.pluginId},runtimeSupervisor:{getRuntimeIdentity:()=>identity},permissionEngine:{onDidRevoke:fn=>{revoke=fn;return{dispose(){}};},authorize:async(c,d)=>{grants.push(d);d.validateBeforeGrant();}}});t.after(()=>service.shutdown());
const registry=new PluginHostRpcRegistry();service.register(registry);const routes=registry.createRoutes({...identity,assertCurrent(){}});const call=(method,params)=>routes.requestHandlers['database.'+method](params,{});
await assert.rejects(call('openTcp',{...config.postgres,path:'/tmp/socket'}),/contract/);
let opened=await call('openTcp',config.postgres);assert.ok(grants.some(g=>g.resources[0]==='database:tcp'));
const schema=await call('readSchema',{handleId:opened.handleId});assert.ok(schema.tables.some(t=>t.name==='inventory'));
const r=await call('query',{handleId:opened.handleId,sql:'SELECT quantity FROM inventory WHERE id=?',parameters:[1],mode:'read'});assert.deepEqual(r.rows,[['37']]);
revoke({pluginId:owner.pluginId});assert.equal(service.tcp.sessions.size,0);await assert.rejects(call('query',{handleId:opened.handleId,sql:'SELECT 1',parameters:[],mode:'read'}),/Unknown/);
opened=await call('openTcp',config.postgres);source='changed';await assert.rejects(call('readSchema',{handleId:opened.handleId}),/binding/);service.releaseRuntime(owner.runtimeId);assert.equal(service.tcp.sessions.size,0);
});
+139
View File
@@ -0,0 +1,139 @@
"use strict";
// Bounded host-owned wire clients. No plugin-supplied URL, socket path, module or file.
const net = require("node:net");
const tls = require("node:tls");
const crypto = require("node:crypto");
const u32 = n => { const b = Buffer.alloc(4); b.writeInt32BE(n); return b; };
const u16 = n => { const b = Buffer.alloc(2); b.writeInt16BE(n); return b; };
const str = s => Buffer.from(s + "\0");
const digest = (name, ...parts) => crypto.createHash(name).update(Buffer.concat(parts)).digest();
const xor = (a, b) => Buffer.from(a.map((v, i) => v ^ b[i]));
class Reader {
constructor(socket) {
this.socket = socket; this.buffer = Buffer.alloc(0); this.waiter = null; this.error = null;
this.data = b => { if (this.buffer.length + b.length > 2 * 1024 * 1024) return this.fail(); this.buffer = Buffer.concat([this.buffer, b]); this.wake(); };
this.failed = () => this.fail();
socket.on("data", this.data); socket.on("error", this.failed); socket.on("close", this.failed);
}
fail() { this.error = new Error("Database transport closed or exceeded limits"); this.socket.destroy(); this.wake(); }
wake() { const w = this.waiter; this.waiter = null; w?.(); }
async read(n) {
if (!Number.isSafeInteger(n) || n < 0 || n > 1024 * 1024) { this.fail(); throw this.error; }
while (this.buffer.length < n) { if (this.error) throw this.error; await new Promise(r => { this.waiter = r; }); }
const b = this.buffer.subarray(0, n); this.buffer = this.buffer.subarray(n); return b;
}
detach() { this.socket.off("data", this.data); this.socket.off("error", this.failed); this.socket.off("close", this.failed); }
}
async function connect(config, retain) {
const socket = net.connect({host:config.hostname, port:config.port}); retain(socket);
await new Promise((resolve, reject) => { socket.once("connect", resolve); socket.once("error", reject); socket.once("close", () => reject(new Error("Database transport closed"))); });
socket.setNoDelay(true); return socket;
}
async function secure(socket, config) {
const secured = tls.connect({socket, host:config.hostname, servername:net.isIP(config.hostname) ? undefined : config.hostname, rejectUnauthorized:true, minVersion:"TLSv1.2"});
await new Promise((resolve, reject) => { secured.once("secureConnect", resolve); secured.once("error", reject); }); return secured;
}
// Anonymous ? bindings outside strings/comments; reject unsupported lexical forms.
// Reject multi-statement payloads, dollar quotes and backslash escapes rather than
// silently interpreting them differently between wire families.
function bind(sql, values, family) {
let out = "", index = 0;
for (let i = 0; i < sql.length; i++) {
const c = sql[i], n = sql[i+1];
if (c === ";" || c === "$" || c === "\\" || c === "#") throw new Error("Unsupported SQL syntax");
if ((c === "-" && n === "-") || (c === "/" && n === "*")) throw new Error("SQL comments are unavailable");
if (c === "\u0027" || c === "\u0022" || c === "`") {
const end = c; out += c; let closed = false;
while (++i < sql.length) { const v=sql[i]; if (v === "\\") throw new Error("SQL backslash escapes are unavailable"); out += v; if (v === end) { if (sql[i+1] === end) out += sql[++i]; else { closed=true; break; } } }
if (!closed) throw new Error("Unterminated SQL string");
} else if (c === "?") {
if (index >= values.length) throw new Error("Binding count mismatch");
const v = values[index++];
out += family === "postgres" ? "$" + index : v === null ? "NULL" : typeof v === "boolean" ? v ? "TRUE" : "FALSE" : typeof v === "number" ? String(v) : "CONVERT(X\u0027" + Buffer.from(v).toString("hex") + "\u0027 USING utf8mb4)";
} else out += c;
}
if (index !== values.length) throw new Error("Binding count mismatch"); return out;
}
class PgWire {
constructor(authPolicy = 'postgres') {
if (!['postgres', 'gauss-legacy'].includes(authPolicy)) throw Error('Authentication policy not packaged');
this.socket = null; this.authPolicy = authPolicy;
}
close() { this.socket?.destroy(); }
async message() { const h=await this.reader.read(5); return [String.fromCharCode(h[0]), await this.reader.read(h.readInt32BE(1)-4)]; }
send(type, b) { this.socket.write(Buffer.concat([Buffer.from(type), u32(b.length+4), b])); }
async open(c) {
this.socket = await connect(c, socket => { this.socket=socket; }); this.reader = new Reader(this.socket);
if (c.tls) { this.socket.write(Buffer.concat([u32(8),u32(80877103)])); if ((await this.reader.read(1))[0]!==83) throw new Error("TLS required"); this.reader.detach(); this.socket=await secure(this.socket,c); this.reader=new Reader(this.socket); }
const body=Buffer.concat([u32(196608),str("user"),str(c.username),str("database"),str(c.database),str("client_encoding"),str("UTF8"),Buffer.from([0])]); this.socket.write(Buffer.concat([u32(body.length+4),body]));
let scram, authenticated = false, challenged = false;
for (;;) {
const [t,b]=await this.message(); if(t==="Z") { if(!authenticated) throw Error('Database authentication incomplete'); break; } if(t==="E") throw new Error("Database authentication failed"); if(t!=="R") continue;
if(b.length<4||authenticated) throw Error('Invalid authentication state');
const kind=b.readInt32BE(0);
if(kind===0) { if(b.length!==4 || (scram && !scram.verified)) throw Error('Database authentication proof incomplete'); authenticated=true; continue; }
// Gauss SHA256 uses code 10 too, but is not PostgreSQL SASL. Never
// reinterpret that challenge or suggest changing server authentication.
if(this.authPolicy==='gauss-legacy' && ![3,5].includes(kind)) throw Error('Authentication not packaged');
if([3,5,10].includes(kind)) { if(challenged) throw Error('Invalid authentication state'); challenged=true; }
if(kind===3 && b.length!==4 || kind===5 && b.length!==8) throw Error('Invalid authentication challenge');
if(kind===3) this.send("p",str(c.password));
else if(kind===5) { const inner=digest("md5",Buffer.from(c.password+c.username)).toString("hex"); this.send("p",str("md5"+digest("md5",Buffer.from(inner),b.subarray(4)).toString("hex"))); }
else if(kind===10) {
if(!b.subarray(4).toString().split("\0").includes("SCRAM-SHA-256")) throw new Error("Authentication not packaged");
const nonce=crypto.randomBytes(24).toString("base64"), first="n=,r="+nonce; scram={nonce,first}; const initial=Buffer.from("n,,"+first); this.send("p",Buffer.concat([str("SCRAM-SHA-256"),u32(initial.length),initial]));
} else if(kind===11 && scram && !scram.signature) {
const server=b.subarray(4).toString(), fields=Object.fromEntries(server.split(",").map(p=>[p.slice(0,1),p.slice(2)])); const iterations=Number(fields.i);
if(!fields.r?.startsWith(scram.nonce)||fields.r.length<=scram.nonce.length||!Number.isInteger(iterations)||iterations<4096||iterations>1000000) throw new Error("Invalid authentication challenge");
const salted=crypto.pbkdf2Sync(c.password.normalize("NFKC"),Buffer.from(fields.s,"base64"),iterations,32,"sha256"), key=crypto.createHmac("sha256",salted).update("Client Key").digest();
const final="c=biws,r="+fields.r, auth=scram.first+","+server+","+final;
const signature=crypto.createHmac("sha256",digest("sha256",key)).update(auth).digest(); scram.signature=crypto.createHmac("sha256",crypto.createHmac("sha256",salted).update("Server Key").digest()).update(auth).digest("base64");
this.send("p",Buffer.from(final+",p="+xor(key,signature).toString("base64")));
} else if(kind===12 && scram?.signature && !scram.verified) { if(b.subarray(4).toString()!=="v="+scram.signature) throw new Error("Invalid server signature"); scram.verified=true; }
else throw new Error("Authentication not packaged");
}
// Session-level read-only remains in force across all user queries.
await this.execute("SET default_transaction_read_only = on",[]); await this.execute("SET statement_timeout = 3000",[]);
}
async execute(sql, parameters=[], maxRows=100) {
const p=parameters.map(v=>v===null?u32(-1):(()=>{const b=Buffer.from(String(v));return Buffer.concat([u32(b.length),b]);})());
this.send("P",Buffer.concat([str(""),str(sql),u16(0)]));
this.send("B",Buffer.concat([str(""),str(""),u16(0),u16(p.length),...p,u16(0)]));
this.send("D",Buffer.from([80,0])); this.send("E",Buffer.concat([str(""),u32(maxRows+1)])); this.send("S",Buffer.alloc(0));
const columns=[], rows=[]; let error=false, bytes=0, truncated=false;
for (;;) {
const [t,b]=await this.message();
if(t==="Z") break; if(t==="E") error=true;
if(t==="T") { let pos=2; const count=b.readUInt16BE(0);if(count>32)throw Error("Column limit exceeded");for(let i=0;i<count;i++){const end=b.indexOf(0,pos);if(end<0||end+19>b.length)throw Error("Invalid metadata");columns.push(b.subarray(pos,end).toString());pos=end+19;} }
if(t==="D") {let pos=2; const row=[];const count=b.readUInt16BE(0);if(count!==columns.length)throw Error("Invalid row");for(let i=0;i<count;i++){const len=b.readInt32BE(pos);pos+=4;if(len < -1 || pos+Math.max(0,len)>b.length)throw Error("Invalid row length");row.push(len===-1?null:b.subarray(pos,pos+len).toString());if(len>=0)pos+=len;}bytes+=b.length;if(rows.length<maxRows&&bytes<96000)rows.push(row);else truncated=true;}
if(t==="s") truncated=true;
}
if(error) throw new Error("Database statement rejected");return {columns,rows,truncated};
}
}
const lenenc = (b, p) => { const n=b[p]; if(n<251)return [n,p+1]; if(n===251)return [null,p+1]; if(n===252)return [b.readUInt16LE(p+1),p+3]; if(n===253)return [b.readUIntLE(p+1,3),p+4]; if(n===254){const v=Number(b.readBigUInt64LE(p+1));if(!Number.isSafeInteger(v))throw Error("Invalid packet");return [v,p+9];}throw Error("Invalid packet"); };
class MysqlWire {
constructor(){this.socket=null;this.seq=0;}
close(){this.socket?.destroy();}
async packet(){const h=await this.reader.read(4);if(h[3]!==this.seq)throw Error("Invalid packet sequence");this.seq=(h[3]+1)&255;return this.reader.read(h.readUIntLE(0,3));}
send(b){const h=Buffer.alloc(4);h.writeUIntLE(b.length,0,3);h[3]=this.seq++ &255;this.socket.write(Buffer.concat([h,b]));}
auth(plugin,password,salt){if(!['mysql_native_password','caching_sha2_password'].includes(plugin))throw Error('Authentication not packaged');if(!password)return Buffer.alloc(0);const b=Buffer.from(password);if(plugin==="mysql_native_password"){const a=digest("sha1",b);return xor(a,digest("sha1",salt,digest("sha1",a)));}if(plugin==="caching_sha2_password"){const a=digest("sha256",b);return xor(a,digest("sha256",digest("sha256",a),salt));}throw Error("Authentication not packaged");}
async open(c){
this.socket=await connect(c, socket => { this.socket=socket; });this.reader=new Reader(this.socket);const b=await this.packet();let pos=b.indexOf(0,1)+1;if(b[0]!==10||pos<2)throw Error("Unsupported MySQL handshake");pos+=4;const saltA=b.subarray(pos,pos+8);pos+=9;const low=b.readUInt16LE(pos);pos+=2;pos+=3;const high=b.readUInt16LE(pos);pos+=2;const caps=(high*65536+low)>>>0;const authLength=b[pos++];pos+=10;const saltB=b.subarray(pos,pos+Math.max(13,authLength-8));pos+=saltB.length;const salt=Buffer.concat([saltA,saltB]).subarray(0,20);let plugin=b.subarray(pos).toString().replace(/\0.*$/s,"")||"mysql_native_password";
let flags=(0x200|0x8000|0x80000|0x8|0x4)>>>0;if(c.tls)flags|=0x800;if((caps&0x200)===0)throw Error("Protocol not packaged");
const header=Buffer.alloc(32);header.writeUInt32LE(flags,0);header.writeUInt32LE(1024*1024,4);header[8]=45;
if(c.tls){if(!(caps&0x800))throw Error("TLS required");this.send(header);this.reader.detach();this.socket=await secure(this.socket,c);this.reader=new Reader(this.socket);}
const auth=this.auth(plugin,c.password,salt);this.send(Buffer.concat([header,str(c.username),Buffer.from([auth.length]),auth,str(c.database),str(plugin)]));
for(;;){const reply=await this.packet();if(reply[0]===0)break;if(reply[0]===255)throw Error("Database authentication failed");if(reply[0]===254){const end=reply.indexOf(0,1);plugin=reply.subarray(1,end).toString();this.send(this.auth(plugin,c.password,reply.subarray(end+1).subarray(0,20)));}else if(reply[0]===1&&reply[1]===3&&plugin==='caching_sha2_password')continue;else if(reply[0]===1&&reply[1]===4&&c.tls&&plugin==='caching_sha2_password')this.send(str(c.password));else throw Error("Authentication requires verified TLS");}
await this.execute("SET SESSION TRANSACTION READ ONLY");
}
async execute(sql,parameters=[],maxRows=100){
this.seq=0;this.send(Buffer.concat([Buffer.from([3]),Buffer.from(sql)]));let b=await this.packet();if(b[0]===255)throw Error("Database statement rejected");if(b[0]===0)return {columns:[],rows:[],truncated:false};
const [count]=lenenc(b,0);if(count>32)throw Error("Column limit exceeded");const columns=[];
for(let i=0;i<count;i++){b=await this.packet();let pos=0,name="";for(let j=0;j<6;j++){const [n,start]=lenenc(b,pos);if(j===4)name=b.subarray(start,start+n).toString();pos=start+n;}columns.push(name);}
b=await this.packet();if(b[0]!==254)throw Error("Invalid metadata terminator");const rows=[];let bytes=0,truncated=false,packets=0;
for(;;){b=await this.packet();if(b[0]===254&&b.length<9)break;if(b[0]===255)throw Error("Database statement rejected");if(++packets>10000)throw Error("Result exceeds transport budget");const row=[];let pos=0;for(let i=0;i<count;i++){const [n,start]=lenenc(b,pos);row.push(n===null?null:b.subarray(start,start+n).toString());pos=start+(n??0);}bytes+=b.length;if(rows.length<maxRows&&bytes<96000)rows.push(row);else truncated=true;}
return {columns,rows,truncated};
}
}
module.exports={PgWire,MysqlWire,bind};
+119
View File
@@ -0,0 +1,119 @@
"use strict";
const { randomBytes, randomUUID } = require("node:crypto");
const { setTimeout: delay } = require("node:timers/promises");
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
const TUNNEL_TEST_FEATURE = "database.tunnel-test.synthetic.v1";
const HOST_ID = "netcatty:synthetic-tunnel-fixture";
const SECRET_KEY = "database-tunnel:synthetic-loopback";
const TARGET = Object.freeze({ hostname: "127.0.0.1", port: 2222, username: "smoketest",
destination: "127.0.0.1", destinationPort: 5432, fingerprint: "synthetic-pinned-key-not-a-real-ssh-key" });
const result = (code, secretRef, closed = true) => ({ status: code === "SYNTHETIC_OK" ? "synthetic-passed" : code === "CANCELLED" ? "cancelled" : "failed",
code, synthetic: true, connected: false, closed, ...(secretRef ? { secretRef } : {}) });
class TunnelFixtureError extends Error {
constructor(code) { super("Synthetic tunnel fixture failed"); this.code = code; }
}
/** Host-only interface: open({target, credential, signal}) -> {close(): void}.
* No sockets, SSH library, production resolver or plugin-selected destination.
* Outcomes are recorded fixtures, never evidence of live authentication.
*/
class SyntheticTunnelAdapter {
constructor({ outcome = "SYNTHETIC_OK", delayMs = 25 } = {}) { this.outcome = outcome; this.delayMs = delayMs; this.active = 0; }
async open({ target, credential, signal }) {
if (target !== TARGET || typeof credential !== "string" || !credential) throw new TunnelFixtureError("UNAVAILABLE");
await delay(this.delayMs, undefined, { signal });
if (this.outcome !== "SYNTHETIC_OK") throw new TunnelFixtureError(this.outcome);
this.active++; let closed = false;
return { close: () => { if (!closed) { closed = true; this.active--; } } };
}
}
class DatabaseTunnelTestService {
constructor({ secretStore, adapter = new SyntheticTunnelAdapter(), timeoutMs = 5000 }) {
this.secretStore = secretStore; this.adapter = adapter; this.timeoutMs = timeoutMs;
this.revision = randomUUID(); this.pending = new Map(); this.completed = new Map(); this.closed = false;
}
metadata() {
return { hostId: HOST_ID, label: "Synthetic tunnel adapter (no SSH connection)", hostname: TARGET.hostname,
port: TARGET.port, username: TARGET.username, capability: "metadata-only", tunnelAvailable: false,
tunnelTest: { kind: "synthetic", revision: this.revision } };
}
key(context, testId) { return JSON.stringify([context.pluginId, context.runtimeId, context.sourceOwner, context.sourceId, context.securityPrincipal, testId]); }
prune() { for (const [key, entry] of this.completed) if (entry.expires <= Date.now()) this.completed.delete(key); }
remember(key, code) {
this.prune();
if (!this.completed.has(key) && this.completed.size >= 256) throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Tunnel test replay budget reached");
this.completed.set(key, { code, expires: Date.now() + 120_000 });
}
cancel({ testId }, context) {
const key = this.key(context, testId);
if (this.pending.has(key)) this.pending.get(key).controller.abort();
// Also covers cancellation overtaking the original test request.
this.remember(key, "CANCELLED"); return null;
}
async test(request, context, { authorize, assertActive }) {
this.prune(); const key = this.key(context, request.testId);
if (this.completed.get(key)?.code === "CANCELLED") return result("CANCELLED");
if (this.closed) return result("UNAVAILABLE");
if (this.pending.has(key) || this.completed.has(key)) throw new PluginRpcError(RPC_ERRORS.failedPrecondition, "Tunnel test ID already used");
if (this.pending.size >= 8 || [...this.pending.values()].filter((p) => p.context.runtimeId === context.runtimeId).length >= 2 || this.completed.size >= 248) {
throw new PluginRpcError(RPC_ERRORS.resourceExhausted, "Tunnel test budget reached");
}
const controller = new AbortController(); const scoped = { ...context, signal: controller.signal };
let code = "CANCELLED"; let resource; let disposed = false; let cleanupFailed = false;
const close = () => {
if (resource && !disposed) {
disposed = true;
try { resource.close(); } catch { cleanupFailed = true; }
}
};
const abort = () => controller.abort();
context.signal?.addEventListener("abort", abort, { once: true });
const timer = setTimeout(() => { code = "DEADLINE_EXCEEDED"; controller.abort(); }, this.timeoutMs);
const current = () => {
controller.signal.throwIfAborted();
if (request.hostId !== HOST_ID) throw new TunnelFixtureError("UNKNOWN_HOST");
if (request.revision !== this.revision) throw new TunnelFixtureError("STALE_HOST");
};
this.remember(key, "running");
this.pending.set(key, { controller, context });
if (context.signal?.aborted) abort();
let onAbort;
const aborted = new Promise((resolve) => {
onAbort = () => { close(); resolve(cleanupFailed ? result("UNAVAILABLE", undefined, false) : result(code)); };
controller.signal.addEventListener("abort", onAbort, { once: true });
if (controller.signal.aborted) onAbort();
});
const run = async () => {
let outcome;
try {
current(); await authorize(scoped); current(); await assertActive(scoped); current();
// Dedicated fixture namespace only. Never resolve vault SSH credentials.
let reference = this.secretStore.getReference(context.pluginId, SECRET_KEY);
if (!reference) reference = this.secretStore.set(context.pluginId, SECRET_KEY, randomBytes(32).toString("base64url"));
let credential;
try {
credential = this.secretStore.resolve(context.pluginId, reference);
resource = await this.adapter.open({ target: TARGET, credential, signal: controller.signal });
} finally { credential = undefined; }
if (!resource || typeof resource.close !== "function") throw new TunnelFixtureError("UNAVAILABLE");
current(); await assertActive(scoped); current();
outcome = result("SYNTHETIC_OK", reference.id);
} catch (error) {
const safeCodes = ["AUTH_FAILED", "UNKNOWN_HOST_KEY", "HOST_KEY_MISMATCH", "UNKNOWN_HOST", "STALE_HOST"];
outcome = result(controller.signal.aborted ? code : error instanceof TunnelFixtureError && safeCodes.includes(error.code) ? error.code : "UNAVAILABLE");
} finally { close(); }
return cleanupFailed ? result("UNAVAILABLE", undefined, false) : outcome;
};
try { return await Promise.race([run(), aborted]); }
finally {
clearTimeout(timer); context.signal?.removeEventListener("abort", abort);
controller.signal.removeEventListener("abort", onAbort);
this.pending.delete(key); this.remember(key, controller.signal.aborted ? code : "finished");
}
}
abortWhere(predicate) { for (const p of this.pending.values()) if (predicate(p.context)) p.controller.abort(); }
releaseRuntime(runtimeId) { this.abortWhere((c) => c.runtimeId === runtimeId); }
revoke(pluginId) { this.abortWhere((c) => c.pluginId === pluginId); }
closeAll() { this.abortWhere(() => true); }
shutdown() { this.closed = true; this.closeAll(); }
}
module.exports = { DatabaseTunnelTestService, SyntheticTunnelAdapter, TunnelFixtureError, TUNNEL_TEST_FEATURE, HOST_ID };
@@ -0,0 +1,135 @@
"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const { randomBytes, randomUUID } = require("node:crypto");
const { DatabaseTunnelTestService, SyntheticTunnelAdapter, TunnelFixtureError } = require("./databaseTunnelTest.cjs");
const { PluginSecretStore } = require("./secretStore.cjs");
const tick = () => new Promise(setImmediate);
function fixture(t, options = {}) {
const records = new Map(); let resolutions = 0; let writes = 0;
// In-memory encryption stand-in for unit tests only; real safeStorage has its own suite.
const mask = randomBytes(32);
const crypt = (bytes) => Buffer.from(bytes).map((byte, index) => byte ^ mask[index % mask.length]);
const store = new PluginSecretStore({ database: {
privateOwner: (id) => id,
getSecretByKey: (id, key) => records.get(`${id}:${key}`),
getSecretByRef: (id, ref) => [...records.values()].find((r) => r.pluginId === id && r.secretRef === ref),
upsertSecret: (r) => { writes++; records.set(`${r.pluginId}:${r.key}`, r); },
}, safeStorage: { isEncryptionAvailable: () => true, getSelectedStorageBackend: () => "test-encrypted",
encryptString: (s) => crypt(Buffer.from(s)), decryptString: (b) => { resolutions++; return crypt(b).toString(); } } });
const adapter = options.adapter ?? new SyntheticTunnelAdapter({ delayMs: 0, outcome: options.outcome });
const service = new DatabaseTunnelTestService({ secretStore: store, adapter, timeoutMs: options.timeoutMs ?? 1000 });
const context = { pluginId: "fixture.plugin", runtimeId: "runtime-one", sourceOwner: "owner-one", sourceId: "source-one", securityPrincipal: "principal-one", signal: new AbortController().signal };
const request = () => ({ hostId: service.metadata().hostId, revision: service.metadata().tunnelTest.revision, testId: randomUUID() });
const callbacks = { authorize: async () => {}, assertActive: async () => {} };
t.after(() => service.shutdown());
return { service, adapter, context, request, callbacks, records, writes: () => writes, resolutions: () => resolutions,
run: (r = request(), c = context, hooks = callbacks) => service.test(r, c, hooks) };
}
test("metadata selection cannot connect, allocate a resource or resolve secrets", (t) => {
const f = fixture(t); const meta = f.service.metadata();
assert.equal(meta.capability, "metadata-only"); assert.equal(meta.tunnelAvailable, false);
assert.equal(meta.tunnelTest.kind, "synthetic"); assert.equal(f.adapter.active, 0);
assert.equal(f.writes(), 0); assert.equal(f.resolutions(), 0); assert.equal(f.service.pending.size, 0);
});
test("recorded success closes and reconnects with the same opaque SecretStore ref only", async (t) => {
const f = fixture(t); const first = await f.run(); const second = await f.run();
assert.equal(first.status, "synthetic-passed"); assert.equal(first.connected, false);
assert.equal(first.closed, true); assert.equal(first.synthetic, true);
assert.equal(first.secretRef, second.secretRef); assert.ok(first.secretRef.length >= 16);
assert.equal(f.writes(), 1); assert.equal(f.resolutions(), 2); assert.equal(f.adapter.active, 0);
assert.deepEqual(Object.keys(first).sort(), ["closed", "code", "connected", "secretRef", "status", "synthetic"]);
assert.equal(f.service.pending.size, 0);
});
for (const code of ["AUTH_FAILED", "UNKNOWN_HOST_KEY", "HOST_KEY_MISMATCH"]) test(`${code} is stable, closed, and never returns a handle or plaintext`, async (t) => {
const f = fixture(t, { outcome: code }); const r = await f.run();
assert.deepEqual(r, { status: "failed", code, synthetic: true, connected: false, closed: true });
assert.equal(f.adapter.active, 0); assert.equal(f.service.pending.size, 0);
});
test("arbitrary adapter and secret errors are discarded, including credential bytes", async (t) => {
let sensitive;
const f = fixture(t, { adapter: { open: async ({ credential }) => { sensitive = credential; throw new Error(credential); } } });
const r = await f.run(); assert.equal(r.code, "UNAVAILABLE"); assert.ok(sensitive);
assert.equal(JSON.stringify(r).includes(sensitive), false);
f.service.secretStore.resolve = () => { throw new Error(sensitive); };
assert.deepEqual(await f.run(), r);
});
test("unknown host and stale selection fail before credential resolution", async (t) => {
const f = fixture(t);
assert.equal((await f.run({ ...f.request(), hostId: "user-host" })).code, "UNKNOWN_HOST");
assert.equal((await f.run({ ...f.request(), revision: randomUUID() })).code, "STALE_HOST");
const stale = await f.run(f.request(), f.context, { ...f.callbacks, authorize: async () => { f.service.revision = randomUUID(); } });
assert.equal(stale.code, "STALE_HOST"); assert.equal(f.resolutions(), 0);
});
test("abort during authorization prevents credential resolution after a late prompt", async (t) => {
const f = fixture(t); const abort = new AbortController(); let finish;
const p = f.run(f.request(), { ...f.context, signal: abort.signal }, { ...f.callbacks, authorize: () => new Promise((r) => { finish = r; }) });
abort.abort(); assert.equal((await p).code, "CANCELLED"); finish(); await tick();
assert.equal(f.resolutions(), 0); assert.equal(f.service.pending.size, 0);
});
test("cancel during adapter auth closes a late resource exactly once", async (t) => {
let finish; let closed = 0;
const f = fixture(t, { adapter: { open: () => new Promise((r) => { finish = r; }) } });
const request = f.request(); const p = f.run(request);
while (!finish) await tick();
f.service.cancel(request, f.context); f.service.cancel(request, f.context);
assert.equal((await p).code, "CANCELLED"); assert.equal(f.service.pending.size, 0);
finish({ close: () => closed++ }); await tick(); assert.equal(closed, 1);
f.service.cancel(request, f.context); assert.equal(closed, 1);
});
test("cancel overtaking start is remembered and scoped to authenticated identity", async (t) => {
const f = fixture(t); const r = f.request(); f.service.cancel(r, f.context);
assert.equal((await f.run(r)).code, "CANCELLED"); assert.equal(f.resolutions(), 0);
assert.equal((await f.run(r, { ...f.context, runtimeId: "runtime-two" })).code, "SYNTHETIC_OK");
assert.equal((await f.run(r, { ...f.context, sourceOwner: "owner-two", pluginId: "other.plugin" })).code, "SYNTHETIC_OK");
});
test("revision change or runtime invalidation after adapter open cleans up", async (t) => {
for (const mode of ["revision", "identity"]) {
const f = fixture(t); let calls = 0;
const r = await f.run(f.request(), f.context, { ...f.callbacks, assertActive: async () => {
if (++calls === 2) { if (mode === "revision") f.service.revision = randomUUID(); else throw new Error("Runtime retired"); }
} });
assert.equal(r.code, mode === "revision" ? "STALE_HOST" : "UNAVAILABLE"); assert.equal(f.adapter.active, 0);
}
});
test("abort at post-open validation closes an already acquired resource", async (t) => {
const f = fixture(t); let calls = 0; let finish; const r = f.request();
const p = f.run(r, f.context, { ...f.callbacks, assertActive: async () => { if (++calls === 2) await new Promise((resolve) => { finish = resolve; }); } });
while (!finish) await tick(); assert.equal(f.adapter.active, 1);
f.service.cancel(r, f.context); assert.equal((await p).code, "CANCELLED"); assert.equal(f.adapter.active, 0);
finish(); await tick(); assert.equal(f.adapter.active, 0);
});
for (const method of ["releaseRuntime", "revoke", "closeAll", "shutdown"]) test(`${method} aborts pending auth and cleanup remains idempotent`, async (t) => {
const f = fixture(t, { adapter: new SyntheticTunnelAdapter({ delayMs: 500 }) }); const p = f.run(); await tick();
f.service[method](method === "revoke" ? f.context.pluginId : f.context.runtimeId);
assert.equal((await p).code, "CANCELLED"); assert.equal(f.adapter.active, 0); assert.equal(f.service.pending.size, 0);
f.service[method](method === "revoke" ? f.context.pluginId : f.context.runtimeId);
});
test("deadline bounds adapter auth and repeated test IDs cannot reopen", async (t) => {
const f = fixture(t, { adapter: new SyntheticTunnelAdapter({ delayMs: 100 }), timeoutMs: 5 }); const r = f.request();
assert.equal((await f.run(r)).code, "DEADLINE_EXCEEDED"); assert.equal(f.adapter.active, 0);
await assert.rejects(f.run(r), /already used/);
});
test("untrusted diagnostic-like fixture codes cannot cross the result boundary", async (t) => {
const f = fixture(t, { adapter: { open() { throw new TunnelFixtureError("not-allowlisted"); } } });
assert.equal((await f.run()).code, "UNAVAILABLE");
});
test("adapter cleanup errors never expose bytes or claim successful cleanup", async (t) => {
let sensitive;
const f = fixture(t, { adapter: { async open({ credential }) {
sensitive = credential;
return { close() { throw new Error(credential); } };
} } });
const r = await f.run();
assert.deepEqual(r, { status: "failed", code: "UNAVAILABLE", synthetic: true, connected: false, closed: false });
assert.equal(JSON.stringify(r).includes(sensitive), false); assert.equal(f.service.pending.size, 0);
});
test("pending resource budgets reject excess work and remain usable after cancellation", async (t) => {
const f = fixture(t, { adapter: new SyntheticTunnelAdapter({ delayMs: 100 }) });
const one = f.request(); const two = f.request(); const p1 = f.run(one); const p2 = f.run(two);
await assert.rejects(f.run(), /budget/);
f.service.cancel(one, f.context); f.service.cancel(two, f.context);
assert.equal((await p1).code, "CANCELLED"); assert.equal((await p2).code, "CANCELLED");
assert.equal((await f.run()).code, "SYNTHETIC_OK"); assert.equal(f.adapter.active, 0);
});
@@ -0,0 +1,524 @@
[
{
"id": "sqlite",
"label": "SQLite",
"category": "lightweight",
"wireFamily": "sqlite",
"defaultPort": 0,
"fields": [
"source"
],
"icon": "sqlite",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "fixture"
},
{
"id": "postgres",
"label": "PostgreSQL",
"category": "relational",
"wireFamily": "postgres",
"defaultPort": 5432,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "postgresql",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "wire"
},
{
"id": "mysql",
"label": "MySQL",
"category": "relational",
"wireFamily": "mysql",
"defaultPort": 3306,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "mysql",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "wire"
},
{
"id": "mariadb",
"label": "MariaDB",
"category": "relational",
"wireFamily": "mysql",
"defaultPort": 3306,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "mariadb",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "wire"
},
{
"id": "goldendb",
"label": "GoldenDB",
"category": "domestic",
"wireFamily": "mysql",
"defaultPort": 3306,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "goldendb",
"source": "plugins/connection-types/profiles/catalog.yaml; plugins/connection-types/goldendb.yaml; crates/dbx-sql-dialect/src/sql_dialect/descriptor.rs; agents/drivers/goldendb/src/main/java/com/dbx/agent/goldendb/GoldendbAgent.java buildUrl jdbc:mysql",
"qualification": "alias",
"variants": [
{
"id": "goldendb-mysql",
"label": "GoldenDB / MySQL endpoint",
"defaultPort": 3306,
"wireFamily": "mysql",
"authPolicy": "mysql",
"metadata": "mysql",
"modeCheck": "none"
}
]
},
{
"id": "opengauss",
"label": "openGauss",
"category": "domestic",
"wireFamily": "postgres",
"defaultPort": 5432,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "opengauss",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "alias",
"variants": [
{
"id": "opengauss-pg",
"label": "openGauss / PG-compatible endpoint",
"defaultPort": 5432,
"wireFamily": "postgres",
"authPolicy": "gauss-legacy",
"metadata": "pg",
"modeCheck": "pg-compatibility"
}
]
},
{
"id": "gaussdb",
"label": "GaussDB",
"category": "domestic",
"wireFamily": "postgres",
"defaultPort": 5432,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "gaussdb",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "alias",
"variants": [
{
"id": "gaussdb-dws",
"label": "GaussDB DWS",
"defaultPort": 8000,
"wireFamily": "postgres",
"authPolicy": "gauss-legacy",
"metadata": "pg",
"modeCheck": "none"
},
{
"id": "gaussdb-mysql",
"label": "GaussDB for MySQL",
"defaultPort": 3306,
"wireFamily": "mysql",
"authPolicy": "mysql",
"metadata": "mysql",
"modeCheck": "none"
},
{
"id": "gaussdb-native",
"label": "GaussDB native / M-compatible",
"defaultPort": 5432,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
}
]
},
{
"id": "kingbase",
"label": "KingbaseES",
"category": "domestic",
"wireFamily": "postgres",
"defaultPort": 54321,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "kingbase",
"source": "plugins/connection-types/profiles/catalog.yaml; plugins/connection-types/kingbase.yaml; crates/dbx-sql-dialect/src/sql_dialect/descriptor.rs",
"qualification": "alias",
"variants": [
{
"id": "kingbase-pg",
"label": "KingbaseES / PG mode",
"defaultPort": 54321,
"wireFamily": "postgres",
"authPolicy": "postgres",
"metadata": "sys",
"modeCheck": "none"
},
{
"id": "kingbase-oracle",
"label": "KingbaseES / Oracle mode",
"defaultPort": 54321,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
}
]
},
{
"id": "highgo",
"label": "HighGo",
"category": "domestic",
"wireFamily": "postgres",
"defaultPort": 5866,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "highgo",
"source": "plugins/connection-types/profiles/catalog.yaml; plugins/connection-types/highgo.yaml; crates/dbx-sql-dialect/src/sql_dialect/descriptor.rs",
"qualification": "alias",
"variants": [
{
"id": "highgo-pg",
"label": "HighGo / PG-compatible edition",
"defaultPort": 5866,
"wireFamily": "postgres",
"authPolicy": "postgres",
"metadata": "pg",
"modeCheck": "none"
},
{
"id": "highgo-secure",
"label": "HighGo / secure or national-crypto edition",
"defaultPort": 5866,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
}
]
},
{
"id": "vastbase",
"label": "Vastbase",
"category": "domestic",
"wireFamily": "postgres",
"defaultPort": 5432,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "vastbase",
"source": "plugins/connection-types/profiles/catalog.yaml; plugins/connection-types/vastbase.yaml; crates/dbx-sql-dialect/src/sql_dialect/descriptor.rs",
"qualification": "alias",
"variants": [
{
"id": "vastbase-g100-pg",
"label": "Vastbase G100 / PG mode",
"defaultPort": 5432,
"wireFamily": "postgres",
"authPolicy": "gauss-legacy",
"metadata": "pg",
"modeCheck": "pg-compatibility"
},
{
"id": "vastbase-g100-other",
"label": "Vastbase G100 / other modes",
"defaultPort": 5432,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
},
{
"id": "vastbase-e100",
"label": "Vastbase E100",
"defaultPort": 5432,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
}
]
},
{
"id": "uxdb",
"label": "UXDB",
"category": "domestic",
"wireFamily": "postgres",
"defaultPort": 52025,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": null,
"source": "plugins/connection-types/profiles/catalog.yaml; plugins/connection-types/uxdb.yaml; crates/dbx-sql-dialect/src/sql_dialect/descriptor.rs",
"qualification": "alias"
},
{
"id": "gbase8c",
"label": "GBase",
"category": "domestic",
"wireFamily": "unpackaged",
"defaultPort": 5432,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "gbase8c",
"source": "plugins/connection-types/profiles/catalog.yaml; agents/drivers/gbase8c/src/main/java/com/dbx/agent/gbase8c/Gbase8cAgent.java requires vendor driver",
"qualification": "catalog",
"variants": [
{
"id": "gbase-8c",
"label": "GBase 8c",
"defaultPort": 5432,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
},
{
"id": "gbase-8a",
"label": "GBase 8a",
"defaultPort": 5258,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
},
{
"id": "gbase-8s",
"label": "GBase 8s",
"defaultPort": 9088,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
}
]
},
{
"id": "tidb",
"label": "TiDB",
"category": "domestic",
"wireFamily": "mysql",
"defaultPort": 4000,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "tidb",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "alias"
},
{
"id": "oceanbase",
"label": "OceanBase",
"category": "domestic",
"wireFamily": "mysql",
"defaultPort": 2883,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": null,
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "alias"
},
{
"id": "dameng",
"label": "Dameng",
"category": "domestic",
"wireFamily": "unpackaged",
"defaultPort": 5236,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": null,
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
},
{
"id": "oracle",
"label": "Oracle",
"category": "relational",
"wireFamily": "unpackaged",
"defaultPort": 1521,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": null,
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
},
{
"id": "sqlserver",
"label": "SQL Server",
"category": "relational",
"wireFamily": "unpackaged",
"defaultPort": 1433,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": null,
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
},
{
"id": "clickhouse",
"label": "ClickHouse",
"category": "analytics",
"wireFamily": "unpackaged",
"defaultPort": 8123,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "clickhouse",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
},
{
"id": "redis",
"label": "Redis",
"category": "document",
"wireFamily": "unpackaged",
"defaultPort": 6379,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "redis",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
},
{
"id": "mongodb",
"label": "MongoDB",
"category": "document",
"wireFamily": "unpackaged",
"defaultPort": 27017,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "mongodb",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
},
{
"id": "firebird",
"label": "Firebird",
"category": "relational",
"wireFamily": "unpackaged",
"defaultPort": 3050,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "firebird",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
}
]
File diff suppressed because it is too large. Load diff
+12 -2
View File
@@ -87,15 +87,25 @@ class HostDrawnViewHost {
receive(event) {
if (!event) return;
const message = event.message;
if (!validateMessage(message) || message.kind !== "host-ui.update") return;
if (!validateMessage(message) || !["host-ui.update", "host-ui.present", "host-ui.dismiss"].includes(message.kind)) return;
const instance = this.instances.get(message.instanceId);
if (!instance || instance.pluginId !== event.pluginId || instance.viewId !== event.viewId || this.isLocked()) return;
try {
this.contributions.assertViewActivationCurrent(instance.activation, { context: instance.context });
if (message.sequence !== instance.sequence + 1) throw new Error("Invalid view update sequence");
if (message.kind === "host-ui.update" && message.sequence !== instance.sequence + 1) throw new Error("Invalid view update sequence");
const now = Date.now();
if (now - instance.rateStart >= 1000) { instance.rateStart = now; instance.rateCount = 0; }
if (++instance.rateCount > 120) throw new Error("Plugin view update rate exceeded");
if (message.kind !== "host-ui.update") {
const source = this.contributions.assertViewActivationCurrent(instance.activation, { context: instance.context });
if (message.kind === "host-ui.present") {
if (!message.targetViewId.startsWith(`${instance.pluginId}.`)) return;
const target = this.contributions.assertViewActivationCurrent({ ...instance.activation, viewId: message.targetViewId }, { context: { 'netcatty.surface': 'modal' } });
if (target.view.location !== "modal") return;
} else if (source.view.location !== "modal") return;
if (!instance.sender.isDestroyed?.()) instance.sender.send("netcatty:plugins:host-ui-update", { viewId: instance.viewId, ...message });
return;
}
validatePluginMutationBatch(message.mutations); validatePluginStylesheet(message.css);
instance.sequence = message.sequence;
if (!instance.sender.isDestroyed?.()) instance.sender.send("netcatty:plugins:host-ui-update", { viewId: instance.viewId, ...message });
+38 -2
View File
@@ -10,8 +10,8 @@ function fixture(resources) {
let onMessage, onChange, locked = false, valid = true; const notifications = [];
const contributions = {
onDidPostViewMessage(fn) { onMessage = fn; return { dispose() {} }; }, onDidChange(fn) { onChange = fn; return { dispose() {} }; },
async activateView() { return { plugin: { id: identity.pluginId, activeVersion: identity.pluginVersion }, view: { id: "com.test.plugin.view" }, identity }; },
assertViewActivationCurrent() { if (!valid) throw new Error("stale"); return { plugin: { id: identity.pluginId } }; },
async activateView(viewId) { return { plugin: { id: identity.pluginId, activeVersion: identity.pluginVersion }, view: { id: viewId }, identity }; },
assertViewActivationCurrent(expected) { if (!valid) throw new Error("stale"); return { plugin: { id: identity.pluginId }, view: { id: expected.viewId, location: expected.viewId === "com.test.plugin.modal" ? "modal" : "vault-page" } }; },
runtimeSupervisor: { async notify(...args) { notifications.push(args); } },
};
const host = new HostDrawnViewHost({ electron: { BrowserWindow: { fromWebContents: (s) => s === sender ? owner : null } }, contributionService: contributions, resources, isLocked: () => locked });
@@ -76,3 +76,39 @@ test("updates are rate limited and resource caches are bounded", async () => {
for (let i = 1; i <= 121; i++) f.message({ ...update(i), mutations: [] });
assert.equal(f.host.instances.size, 0); await f.host.shutdown();
});
test("modal presentation is source-instance bound, same-plugin and modal-only", async () => {
const f = fixture(); await open(f);
const present = { kind: "host-ui.present", instanceId: "instance-1", targetViewId: "com.test.plugin.modal" };
f.message(present);
assert.equal(f.sender.sent.at(-1)?.[1].kind, "host-ui.present");
assert.equal(f.sender.sent.at(-1)[1].targetViewId, "com.test.plugin.modal");
const count = f.sender.sent.length;
for (const m of [{ ...present, targetViewId: "com.evil.modal" }, { ...present, targetViewId: "com.test.plugin.view" }, { ...present, instanceId: "unknown" }, { ...present, extra: true }]) f.message(m);
assert.equal(f.sender.sent.length, count, "no unsafe navigation forwarded");
f.message({ kind: "host-ui.dismiss", instanceId: "instance-1" });
assert.equal(f.sender.sent.length, count, "non-modal source cannot dismiss shell views");
await f.host.shutdown();
});
test("presentation cannot survive runtime withdrawal or a closed instance", async () => {
const f = fixture(); await open(f); f.stale();
f.message({ kind: "host-ui.present", instanceId: "instance-1", targetViewId: "com.test.plugin.modal" });
assert.equal(f.sender.sent.some(([,m]) => m.kind === "host-ui.present"), false);
await f.host.close("instance-1");
f.message({ kind: "host-ui.present", instanceId: "instance-1", targetViewId: "com.test.plugin.modal" });
assert.equal(f.sender.sent.some(([,m]) => m.kind === "host-ui.present"), false);
await f.host.shutdown();
});
test("a live modal can dismiss only through its own instance", async () => {
const f = fixture();
await f.host.open({ viewId: "com.test.plugin.modal", instanceId: "modal", scopeId: "scope", context: {} }, f.sender);
const message = { kind: "host-ui.dismiss", instanceId: "modal" };
f.message(message); assert.equal(f.sender.sent.length, 0, "source view identity is required");
f.message(message, { viewId: "com.test.plugin.modal" });
assert.equal(f.sender.sent.at(-1)[1].kind, "host-ui.dismiss");
await f.host.close("modal", f.sender);
const count = f.sender.sent.length;
f.message(message, { viewId: "com.test.plugin.modal" }); assert.equal(f.sender.sent.length, count);
await f.host.shutdown();
});
+22 -3
View File
@@ -10,6 +10,7 @@ const INTERACTIVE_COMMAND_FEATURE = require("./generated/plugin-contract.schema.
const { assertBrowserOnlyPlugin } = require("../../domain/pluginRuntimePolicy.cjs");
const { isPluginDevelopmentEnabled, PLUGIN_API_VERSION } = require("./constants.cjs");
const { DatabaseConnectionStore } = require("./databaseConnectionStore.cjs");
const { PluginDatabase } = require("./database.cjs");
const { PluginCompanionSupervisor } = require("./companionSupervisor.cjs");
const { PluginCredentialBroker, assertLeaseParams } = require("./credentialBroker.cjs");
@@ -31,6 +32,10 @@ const { PackageStore } = require("./packageStore.cjs");
const { createPluginPaths } = require("./paths.cjs");
const { PluginManager } = require("./pluginManager.cjs");
const { PluginNetworkBroker } = require("./networkBroker.cjs");
const { DatabaseHostLiveSshPgService, LIVE_FEATURE } = require("./databaseHostLiveSshPg.cjs");
const { DatabaseHostPortProbeService, PORT_PROBE_FEATURE } = require("./databaseHostPortProbe.cjs");
const { DatabaseTunnelTestService, TUNNEL_TEST_FEATURE } = require("./databaseTunnelTest.cjs");
const { PluginSqliteFixtureService, sqliteFixtureAvailable, FEATURE: SQLITE_FIXTURE_FEATURE, FILE_FEATURE: SQLITE_FILE_FEATURE, FD_FEATURE: SQLITE_FD_FEATURE, WAL_FEATURE: SQLITE_WAL_FEATURE, WAL_CONCURRENT_FEATURE: SQLITE_WAL_CONCURRENT_FEATURE, WAL_CHECKPOINT_FEATURE: SQLITE_WAL_CHECKPOINT_FEATURE, WAL_CAPTURE_FEATURE: SQLITE_WAL_CAPTURE_FEATURE, WAL_REFRESH_FEATURE: SQLITE_WAL_REFRESH_FEATURE, MALFORMED_FEATURE: SQLITE_MALFORMED_FEATURE, SAVED_FEATURE: SQLITE_SAVED_FEATURE } = require("./sqliteFixtureService.cjs");
const { PluginByteStreamService, FEATURE: BYTE_STREAM_FEATURE } = require("./byteStreamService.cjs");
const { PluginAIContextService, PLUGIN_AI_CONTEXT_FEATURES } = require("./ai/aiContextService.cjs");
const { PluginAITrustedHostAdapter } = require("./ai/trustedHostAdapter.cjs");
@@ -103,13 +108,22 @@ function createPluginHostService(options) {
const paths = createPluginPaths(options.app.getPath("userData"));
const appRoot = options.appRoot ?? options.app.getAppPath();
const runtimeDirectory = options.runtimeDirectory ?? path.join(__dirname, "runtime");
const sqliteFixtureEnabled = (options.env ?? process.env).NETCATTY_EXPERIMENTAL_DATABASE === "1" && sqliteFixtureAvailable();
const liveSshPgEnabled = sqliteFixtureEnabled && (options.env ?? process.env).NETCATTY_DATABASE_LIVE_SSH_PG_FIXTURE === "1";
const tunnelTestEnabled = sqliteFixtureEnabled && (options.env ?? process.env).NETCATTY_DATABASE_TUNNEL_SYNTHETIC === "1";
const supportedFeatures = [...new Set(["terminal.input-drafts", "terminal.selection-sharing", "appearance.theme-packs", "metadata.brand-icon", BYTE_STREAM_FEATURE, ...PLUGIN_AI_CONTEXT_FEATURES, PLUGIN_AGENT_FEATURE, NETWORK_CREDENTIAL_LEASE_FEATURE, HOST_INTERACTION_FEATURE, HOST_VAULT_FEATURE, VAULT_PAGES_FEATURE, TERMINAL_SIDEBAR_FEATURE, INTERACTIVE_COMMAND_FEATURE, ...(options.supportedFeatures ?? [])])]
.filter((feature) => feature !== DIRECTORY_ENUMERATION_FEATURE);
.filter((feature) => feature !== DIRECTORY_ENUMERATION_FEATURE && ![SQLITE_FIXTURE_FEATURE, SQLITE_FILE_FEATURE, SQLITE_FD_FEATURE, SQLITE_WAL_CONCURRENT_FEATURE, SQLITE_WAL_CHECKPOINT_FEATURE, SQLITE_WAL_CAPTURE_FEATURE, SQLITE_MALFORMED_FEATURE, SQLITE_WAL_REFRESH_FEATURE, SQLITE_WAL_FEATURE, SQLITE_SAVED_FEATURE, TUNNEL_TEST_FEATURE, PORT_PROBE_FEATURE, LIVE_FEATURE, "database.tcp.v1"].includes(feature));
if (liveSshPgEnabled) supportedFeatures.push(LIVE_FEATURE);
if (tunnelTestEnabled) supportedFeatures.push(TUNNEL_TEST_FEATURE);
if (sqliteFixtureEnabled) supportedFeatures.push(SQLITE_FIXTURE_FEATURE, SQLITE_SAVED_FEATURE, PORT_PROBE_FEATURE, "database.tcp.v1");
if (sqliteFixtureEnabled && process.platform === "linux") supportedFeatures.push(SQLITE_FILE_FEATURE, SQLITE_FD_FEATURE, SQLITE_WAL_CONCURRENT_FEATURE, SQLITE_WAL_CHECKPOINT_FEATURE, SQLITE_WAL_CAPTURE_FEATURE, SQLITE_MALFORMED_FEATURE, SQLITE_WAL_REFRESH_FEATURE, SQLITE_WAL_FEATURE);
if (!supportedFeatures.includes("views.host-drawn")) supportedFeatures.push("views.host-drawn");
supportedFeatures.push("views.modals");
if (typeof options.openPluginDirectoryHandle === "function") supportedFeatures.push(DIRECTORY_ENUMERATION_FEATURE);
const database = new PluginDatabase(paths.database);
let interactionService;
let byteStreamService;
let sqliteFixtureService;
let aiContextService;
let aiHostAdapter;
let agentService;
@@ -172,8 +186,8 @@ function createPluginHostService(options) {
quotaManager,
openDirectoryHandle: options.openPluginDirectoryHandle,
protectedDirectories: [paths.logs, path.join(paths.root, "agent-chats")],
protectedReadDirectories: [path.join(paths.root, "agent-chats")],
protectedFiles: [logService.preferencesPath, `${logService.preferencesPath}.tmp`],
protectedReadDirectories: [path.join(paths.root, "agent-chats"), path.join(paths.root, "database-connections.json"), path.join(paths.root, "database-connections.json.tmp")],
protectedFiles: [path.join(paths.root, "database-connections.json"), path.join(paths.root, "database-connections.json.tmp"), logService.preferencesPath, `${logService.preferencesPath}.tmp`],
});
const networkBroker = new PluginNetworkBroker({
fetch: options.fetch ?? (options.electron.net?.fetch
@@ -303,6 +317,7 @@ function createPluginHostService(options) {
runtimeResourceMonitor: quotaManager,
runtimeCleanup: async (identity) => {
byteStreamService?.releaseRuntime(identity.runtimeId);
sqliteFixtureService?.releaseRuntime(identity.runtimeId);
aiContextService?.releaseRuntime(identity.runtimeId);
agentService?.releaseRuntime(identity.runtimeId);
interactionService?.releaseRuntime(identity.runtimeId);
@@ -313,6 +328,8 @@ function createPluginHostService(options) {
});
byteStreamService = new PluginByteStreamService({ database, permissionEngine, quotaManager, runtimeSupervisor });
byteStreamService.register(rpcRegistry);
sqliteFixtureService = new PluginSqliteFixtureService({ liveSshPg: liveSshPgEnabled ? new DatabaseHostLiveSshPgService({ secretStore }) : undefined, portProbes: sqliteFixtureEnabled ? new DatabaseHostPortProbeService() : undefined, tunnelTests: tunnelTestEnabled ? new DatabaseTunnelTestService({ secretStore }) : undefined, connectionStore: new DatabaseConnectionStore(path.join(paths.root, "database-connections.json")), secretStore, getDatabaseHosts: options.getDatabaseHosts, database, permissionEngine, runtimeSupervisor, enabled: sqliteFixtureEnabled, dialog: options.electron.dialog, getInteractionWindow: options.getInteractionWindow, isLocked: options.isAppLocked, subscribeLock: options.subscribeAppLock });
sqliteFixtureService.register(rpcRegistry);
aiHostAdapter = options.pluginAIHostAdapter ?? new PluginAITrustedHostAdapter({
getWindow: options.getInteractionWindow ?? (() => null),
isLocked: options.isAppLocked,
@@ -490,6 +507,7 @@ function createPluginHostService(options) {
themeService.shutdown();
interactionService.shutdown();
byteStreamService.shutdown();
sqliteFixtureService.shutdown();
aiContextService.shutdown();
agentService.shutdown();
terminalDataPipelineService?.shutdown();
@@ -547,6 +565,7 @@ function createPluginHostService(options) {
try { permissionDecisionHost?.shutdown(); } catch {}
try { interactionService?.shutdown(); } catch {}
try { byteStreamService?.shutdown(); } catch {}
try { sqliteFixtureService?.shutdown(); } catch {}
try { aiContextService?.shutdown(); } catch {}
try { agentService?.shutdown(); } catch {}
if (!agentService) { try { agentHostAdapter?.shutdown?.(); } catch {} }
+58
View File
@@ -520,3 +520,61 @@ test("production host composition does not advertise or prompt for unavailable d
(error) => error.code === -32012 && /unavailable/.test(error.message));
assert.equal(authorizations, 0); assert.equal(prompts, 0); assert.equal(probes, 0);
});
test("SQLite chooser feature follows the default-off experiment and Linux gate", (t) => {
const { sqliteFixtureAvailable, FILE_FEATURE, FD_FEATURE, WAL_FEATURE, WAL_CONCURRENT_FEATURE, WAL_CHECKPOINT_FEATURE, WAL_CAPTURE_FEATURE, MALFORMED_FEATURE, WAL_REFRESH_FEATURE, SAVED_FEATURE } = require("./sqliteFixtureService.cjs");
const root = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-chooser-feature-"));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
for (const enabled of [false, true]) {
const service = createPluginHostService({ ...createOptions(path.join(root, String(enabled))), env: enabled ? { NETCATTY_EXPERIMENTAL_DATABASE: "1" } : {}, supportedFeatures: [FILE_FEATURE, FD_FEATURE, WAL_FEATURE, WAL_CONCURRENT_FEATURE, WAL_CHECKPOINT_FEATURE, WAL_CAPTURE_FEATURE, MALFORMED_FEATURE, WAL_REFRESH_FEATURE, SAVED_FEATURE, "database.host-port-probe.v1"] });
t.after(() => service.database.close());
const expected = enabled && process.platform === "linux" && sqliteFixtureAvailable();
assert.equal(service.runtimeSupervisor.supportedFeatures.includes(FILE_FEATURE), expected);
assert.equal(service.packageStore.supportedFeatures.includes(FILE_FEATURE), expected);
assert.equal(service.packageStore.supportedFeatures.includes(FD_FEATURE), expected);
assert.equal(service.packageStore.supportedFeatures.includes(WAL_REFRESH_FEATURE), expected);
assert.equal(service.runtimeSupervisor.supportedFeatures.includes(WAL_REFRESH_FEATURE), expected);
assert.equal(service.packageStore.supportedFeatures.includes(MALFORMED_FEATURE), expected);
assert.equal(service.runtimeSupervisor.supportedFeatures.includes(MALFORMED_FEATURE), expected);
assert.equal(service.packageStore.supportedFeatures.includes(WAL_CAPTURE_FEATURE), expected);
assert.equal(service.runtimeSupervisor.supportedFeatures.includes(WAL_CAPTURE_FEATURE), expected);
assert.equal(service.packageStore.supportedFeatures.includes(WAL_CHECKPOINT_FEATURE), expected);
assert.equal(service.runtimeSupervisor.supportedFeatures.includes(WAL_CHECKPOINT_FEATURE), expected);
assert.equal(service.packageStore.supportedFeatures.includes(WAL_CONCURRENT_FEATURE), expected);
assert.equal(service.runtimeSupervisor.supportedFeatures.includes(WAL_CONCURRENT_FEATURE), expected);
assert.equal(service.packageStore.supportedFeatures.includes(WAL_FEATURE), expected);
assert.equal(service.runtimeSupervisor.supportedFeatures.includes(WAL_FEATURE), expected);
assert.equal(service.runtimeSupervisor.supportedFeatures.includes(FD_FEATURE), expected);
assert.equal(service.packageStore.supportedFeatures.includes(SAVED_FEATURE), enabled && sqliteFixtureAvailable());
assert.equal(service.packageStore.supportedFeatures.includes("database.host-port-probe.v1"), enabled && sqliteFixtureAvailable());
assert.equal(service.runtimeSupervisor.supportedFeatures.includes("database.host-port-probe.v1"), enabled && sqliteFixtureAvailable());
}
});
test("synthetic tunnel capability requires both explicit experiment gates", (t) => {
const { TUNNEL_TEST_FEATURE } = require("./databaseTunnelTest.cjs");
const { sqliteFixtureAvailable } = require("./sqliteFixtureService.cjs");
const root = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-tunnel-feature-"));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
for (const database of [false, true]) for (const tunnel of [false, true]) {
const service = createPluginHostService({ ...createOptions(path.join(root, `${database}-${tunnel}`)),
env: { NETCATTY_EXPERIMENTAL_DATABASE: database ? "1" : "0", NETCATTY_DATABASE_TUNNEL_SYNTHETIC: tunnel ? "1" : "0" }, supportedFeatures: [TUNNEL_TEST_FEATURE] });
t.after(() => service.database.close());
assert.equal(service.packageStore.supportedFeatures.includes(TUNNEL_TEST_FEATURE), database && tunnel && sqliteFixtureAvailable());
assert.equal(service.runtimeSupervisor.supportedFeatures.includes(TUNNEL_TEST_FEATURE), database && tunnel && sqliteFixtureAvailable());
}
});
test("live SSH PG capability requires both explicit experiment gates", (t) => {
const { LIVE_FEATURE } = require("./databaseHostLiveSshPg.cjs");
const { sqliteFixtureAvailable } = require("./sqliteFixtureService.cjs");
const root = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-live-feature-"));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
for (const database of [false, true]) for (const tunnel of [false, true]) {
const service = createPluginHostService({ ...createOptions(path.join(root, `${database}-${tunnel}`)),
env: { NETCATTY_EXPERIMENTAL_DATABASE: database ? "1" : "0", NETCATTY_DATABASE_LIVE_SSH_PG_FIXTURE: tunnel ? "1" : "0" }, supportedFeatures: [LIVE_FEATURE] });
t.after(() => service.database.close());
assert.equal(service.packageStore.supportedFeatures.includes(LIVE_FEATURE), database && tunnel && sqliteFixtureAvailable());
assert.equal(service.runtimeSupervisor.supportedFeatures.includes(LIVE_FEATURE), database && tunnel && sqliteFixtureAvailable());
}
});
+2 -1
View File
@@ -8,6 +8,7 @@ const {
canonicalizePermissionResource,
declarationAllowsResource,
defaultSecurityPrincipal,
defaultPermissionMode,
normalizePermissionDeclarations,
permissionDeclarationHash,
permissionResourceCovers,
@@ -335,7 +336,7 @@ class PluginPermissionEngine {
if (context.sourceOwner && this.database.privateOwner(context.pluginId) !== context.sourceOwner) {
throw permissionDenied("Plugin permission source changed");
}
return this.database.getPermissionMode?.(context.pluginId, permission) ?? "allow";
return this.database.getPermissionMode?.(context.pluginId, permission) ?? defaultPermissionMode(permission);
}
getPolicyRevision(plugin) {
+5
View File
@@ -180,7 +180,12 @@ function declarationAllowsResource(declaration, requestedResource) {
));
}
function defaultPermissionMode(permission) {
return ["database.query.read", "database.query.write"].includes(permission) ? "ask" : "allow";
}
module.exports = {
defaultPermissionMode,
PLUGIN_PERMISSIONS,
RESOURCE_SCOPED_PERMISSIONS,
assertPluginPermission,
+1 -1
View File
@@ -1681,7 +1681,7 @@ function registerPluginBridge(ipcMain, options) {
handle("netcatty:plugins:host-ui-resource", async (_activeManager, payload, event) => {
if (!hostDrawnViewHost) throw new Error("Plugin views unavailable");
if (!validatePluginViewResourceRequest(payload)) throw new TypeError("Invalid plugin resource request");
return hostDrawnViewHost.resource(payload.instanceId, payload.path, event.sender);
return hostDrawnViewHost.resource(payload.instanceId, payload.kind === "brand-icon" ? `brand:${payload.path}` : payload.path, event.sender);
});
handle(CHANNELS.hostDrawnEvent, async (_activeManager, payload, event) => {
if (!hostDrawnViewHost) throw new Error("Host-drawn plugin views are unavailable");
+14
View File
@@ -394,6 +394,19 @@ function createPluginContext(config, client, runtimeApi) {
deadlineMs: forwardedDeadline(request?.timeoutMs, 300_000),
}),
};
const database = Object.fromEntries(["openTcp", "openHostLiveSshPgFixture", "cancelHostLiveSshPgFixture", "closeHostLiveSshPgSession", "probeHostDatabasePorts", "cancelHostDatabasePorts", "testTunnel", "cancelTunnelTest", "openFixture", "openSqliteFile", "refreshSqliteFile", "readSchema", "query", "cancel", "close", "listSavedConnections", "saveConnection", "deleteConnection", "openSavedConnection", "listHostsForDatabase"].map((operation) => [
operation, (params = {}) => {
if (!config.enabledFeatures?.includes("database.sqlite-fixture.v1")) return Promise.reject(new Error("Experimental SQLite fixture service is unavailable"));
if (operation === "openTcp" && !config.enabledFeatures?.includes("database.tcp.v1")) return Promise.reject(new Error("Database TCP service is unavailable"));
if (["openHostLiveSshPgFixture", "cancelHostLiveSshPgFixture", "closeHostLiveSshPgSession"].includes(operation) && !config.enabledFeatures?.includes("database.host-live-ssh-pg.fixture.v1")) return Promise.reject(new Error("Live SSH PostgreSQL fixture is unavailable"));
if (["probeHostDatabasePorts", "cancelHostDatabasePorts"].includes(operation) && !config.enabledFeatures?.includes("database.host-port-probe.v1")) return Promise.reject(new Error("Host port probing is unavailable"));
if (["testTunnel", "cancelTunnelTest"].includes(operation) && !config.enabledFeatures?.includes("database.tunnel-test.synthetic.v1")) return Promise.reject(new Error("Synthetic tunnel testing is unavailable"));
if (operation === "refreshSqliteFile" && !config.enabledFeatures?.includes("database.sqlite-wal-session-refresh.fixture.v1")) return Promise.reject(new Error("Explicit SQLite WAL refresh is unavailable"));
if (operation === "openSqliteFile" && !config.enabledFeatures?.includes("database.sqlite-file-fixture.v1")) return Promise.reject(new Error("SQLite file chooser is unavailable"));
if (["listSavedConnections", "saveConnection", "deleteConnection", "openSavedConnection", "listHostsForDatabase"].includes(operation) && !config.enabledFeatures?.includes("database.saved-connections.v1")) return Promise.reject(new Error("Saved connections are unavailable"));
return client.request(`database.${operation}`, params, { deadlineMs: 65_000 });
},
]));
const ai = Object.fromEntries(["openChat", "startTurn", "readTurn", "stopTurn", "closeChat"].map((operation) => [
operation, (params) => client.request(`ai.${operation}`, params, operation === "readTurn" ? { deadlineMs: 65_000 } : {}),
]));
@@ -589,6 +602,7 @@ function createPluginContext(config, client, runtimeApi) {
secrets,
credentials,
network,
database,
ai,
agent,
selectedContext,
+146
View File
@@ -636,3 +636,149 @@ test("actual SDK directory call rejects an unnegotiated feature without sending
await host.request("plugin.activate", {});
assert.equal(requests, 0);
});
test("SQLite file chooser is negotiated independently and preserves opaque revisions over RPC", async (t) => {
const { startPluginRuntime } = await import("./runtime/runtimePeer.mjs");
for (const enabled of [false, true]) {
const features = ["database.sqlite-fixture.v1", ...(enabled ? ["database.sqlite-file-fixture.v1"] : [])];
const { port1, port2 } = new MessageChannel(); let requests = 0;
const opened = { handleId: "opaque-file", revision: "opaque-revision", engine: "sqlite", fixture: true, readOnly: true, label: "Disposable SQLite file (read-only)" };
const host = new PluginRpcRouter({ pluginId: "com.example.database", send: (message) => port1.postMessage(message), handlers: {
"database.openSqliteFile": async (params) => { requests++; assert.deepEqual(params, {}); return opened; },
"database.close": async (params) => { assert.deepEqual(params, { handleId: opened.handleId, revision: opened.revision }); return null; },
"log.write": async () => null,
} });
port1.on("message", (message) => host.accept(message));
const peer = await startPluginRuntime({ port: port2,
config: { pluginId: "com.example.database", pluginVersion: "1.0.0", netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", enabledFeatures: features },
async loadPlugin() { return { default: { async activate(context) {
if (!enabled) await assert.rejects(context.database.openSqliteFile(), /unavailable/);
else {
const target = await context.database.openSqliteFile(); assert.deepEqual(target, opened);
await context.database.close({ handleId: target.handleId, revision: target.revision });
}
} } }; } });
t.after(async () => { await peer.dispose(); host.close(); port1.close(); port2.close(); });
await host.request("plugin.initialize", { netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", supportedFeatures: features });
await host.request("plugin.activate", {}); assert.equal(requests, enabled ? 1 : 0);
}
});
test("saved-connection SDK methods gate independently and forward canonical requests", async (t) => {
const { startPluginRuntime } = await import("./runtime/runtimePeer.mjs");
for (const enabled of [false, true]) {
const features = ["database.sqlite-fixture.v1", ...(enabled ? ["database.saved-connections.v1"] : [])];
const { port1, port2 } = new MessageChannel(); const seen = [];
const calls = { listSavedConnections: {}, listHostsForDatabase: {}, saveConnection: { handleId: "opaque", meta: { name: "Synthetic", color: "blue" } }, openSavedConnection: { id: "saved" }, deleteConnection: { id: "saved" } };
const handlers = Object.fromEntries(Object.entries(calls).map(([method, expected]) => [`database.${method}`, async (params) => { assert.deepEqual(params, expected); seen.push(method); return null; }]));
const host = new PluginRpcRouter({ pluginId: "com.example.database", send: (message) => port1.postMessage(message), handlers: { ...handlers, "log.write": async () => null } });
port1.on("message", (message) => host.accept(message));
const peer = await startPluginRuntime({ port: port2,
config: { pluginId: "com.example.database", pluginVersion: "1.0.0", netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", enabledFeatures: features },
async loadPlugin() { return { default: { async activate(context) {
for (const [method, params] of Object.entries(calls)) {
if (!enabled) await assert.rejects(context.database[method](params), /unavailable/);
else await context.database[method](params);
}
} } }; } });
t.after(async () => { await peer.dispose(); host.close(); port1.close(); port2.close(); });
await host.request("plugin.initialize", { netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", supportedFeatures: features });
await host.request("plugin.activate", {}); assert.deepEqual(seen, enabled ? Object.keys(calls) : []);
}
});
test("synthetic tunnel SDK methods gate independently and forward canonical requests", async (t) => {
const { startPluginRuntime } = await import("./runtime/runtimePeer.mjs");
for (const enabled of [false, true]) {
const features = ["database.sqlite-fixture.v1", ...(enabled ? ["database.tunnel-test.synthetic.v1"] : [])];
const { port1, port2 } = new MessageChannel(); const seen = [];
const calls = { testTunnel: { hostId: "fixture", revision: "revision", testId: "probe" }, cancelTunnelTest: { testId: "probe" } };
const handlers = Object.fromEntries(Object.entries(calls).map(([method, expected]) => [`database.${method}`, async (params) => { assert.deepEqual(params, expected); seen.push(method); return null; }]));
const host = new PluginRpcRouter({ pluginId: "com.example.database", send: (message) => port1.postMessage(message), handlers: { ...handlers, "log.write": async () => null } });
port1.on("message", (message) => host.accept(message));
const peer = await startPluginRuntime({ port: port2,
config: { pluginId: "com.example.database", pluginVersion: "1.0.0", netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", enabledFeatures: features },
async loadPlugin() { return { default: { async activate(context) {
for (const [method, params] of Object.entries(calls)) {
if (!enabled) await assert.rejects(context.database[method](params), /unavailable/);
else await context.database[method](params);
}
} } }; } });
t.after(async () => { await peer.dispose(); host.close(); port1.close(); port2.close(); });
await host.request("plugin.initialize", { netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", supportedFeatures: features });
await host.request("plugin.activate", {}); assert.deepEqual(seen, enabled ? Object.keys(calls) : []);
}
});
test("host port probe SDK methods gate independently and forward canonical requests", async (t) => {
const { startPluginRuntime } = await import("./runtime/runtimePeer.mjs");
for (const enabled of [false, true]) {
const features = ["database.sqlite-fixture.v1", ...(enabled ? ["database.host-port-probe.v1"] : [])];
const { port1, port2 } = new MessageChannel(); const seen = [];
const calls = { probeHostDatabasePorts: { hostId: "fixture", revision: "revision", probeId: "probe" }, cancelHostDatabasePorts: { probeId: "probe" } };
const handlers = Object.fromEntries(Object.entries(calls).map(([method, expected]) => [`database.${method}`, async (params) => { assert.deepEqual(params, expected); seen.push(method); return null; }]));
const host = new PluginRpcRouter({ pluginId: "com.example.database", send: (message) => port1.postMessage(message), handlers: { ...handlers, "log.write": async () => null } });
port1.on("message", (message) => host.accept(message));
const peer = await startPluginRuntime({ port: port2,
config: { pluginId: "com.example.database", pluginVersion: "1.0.0", netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", enabledFeatures: features },
async loadPlugin() { return { default: { async activate(context) {
for (const [method, params] of Object.entries(calls)) {
if (!enabled) await assert.rejects(context.database[method](params), /unavailable/);
else await context.database[method](params);
}
} } }; } });
t.after(async () => { await peer.dispose(); host.close(); port1.close(); port2.close(); });
await host.request("plugin.initialize", { netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", supportedFeatures: features });
await host.request("plugin.activate", {}); assert.deepEqual(seen, enabled ? Object.keys(calls) : []);
}
});
test("live fixture SDK methods gate independently and forward canonical requests", async (t) => {
const { startPluginRuntime } = await import("./runtime/runtimePeer.mjs");
for (const enabled of [false, true]) {
const features = ["database.sqlite-fixture.v1", ...(enabled ? ["database.host-live-ssh-pg.fixture.v1"] : [])];
const { port1, port2 } = new MessageChannel(); const seen = [];
const calls = { openHostLiveSshPgFixture: { hostId: "fixture", revision: "revision", openId: "open" }, cancelHostLiveSshPgFixture: { openId: "open" }, closeHostLiveSshPgSession: { sessionId: "session" } };
const handlers = Object.fromEntries(Object.entries(calls).map(([method, expected]) => [`database.${method}`, async (params) => { assert.deepEqual(params, expected); seen.push(method); return null; }]));
const host = new PluginRpcRouter({ pluginId: "com.example.database", send: (message) => port1.postMessage(message), handlers: { ...handlers, "log.write": async () => null } });
port1.on("message", (message) => host.accept(message));
const peer = await startPluginRuntime({ port: port2,
config: { pluginId: "com.example.database", pluginVersion: "1.0.0", netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", enabledFeatures: features },
async loadPlugin() { return { default: { async activate(context) {
for (const [method, params] of Object.entries(calls)) {
if (!enabled) await assert.rejects(context.database[method](params), /unavailable/);
else await context.database[method](params);
}
} } }; } });
t.after(async () => { await peer.dispose(); host.close(); port1.close(); port2.close(); });
await host.request("plugin.initialize", { netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", supportedFeatures: features });
await host.request("plugin.activate", {}); assert.deepEqual(seen, enabled ? Object.keys(calls) : []);
}
});
test("Gate J explicit refresh is feature-gated and forwards the old revision over RPC", async (t) => {
const { startPluginRuntime } = await import("./runtime/runtimePeer.mjs");
for (const enabled of [false, true]) {
const features = ["database.sqlite-fixture.v1", ...(enabled ? ["database.sqlite-wal-session-refresh.fixture.v1"] : [])];
const { port1, port2 } = new MessageChannel(); let requests = 0;
const opened = { handleId: "opaque-file", revision: "opaque-revision", engine: "sqlite", fixture: true, readOnly: true, label: "Disposable SQLite file (read-only)" };
const host = new PluginRpcRouter({ pluginId: "com.example.database", send: (message) => port1.postMessage(message), handlers: {
"database.refreshSqliteFile": async (params) => { requests++; assert.deepEqual(params, { handleId: opened.handleId, revision: "previous-revision" }); return opened; },
"database.close": async (params) => { assert.deepEqual(params, { handleId: opened.handleId, revision: opened.revision }); return null; },
"log.write": async () => null,
} });
port1.on("message", (message) => host.accept(message));
const peer = await startPluginRuntime({ port: port2,
config: { pluginId: "com.example.database", pluginVersion: "1.0.0", netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", enabledFeatures: features },
async loadPlugin() { return { default: { async activate(context) {
if (!enabled) await assert.rejects(context.database.refreshSqliteFile({ handleId: opened.handleId, revision: "previous-revision" }), /unavailable/);
else {
const target = await context.database.refreshSqliteFile({ handleId: opened.handleId, revision: "previous-revision" }); assert.deepEqual(target, opened);
await context.database.close({ handleId: target.handleId, revision: target.revision });
}
} } }; } });
t.after(async () => { await peer.dispose(); host.close(); port1.close(); port2.close(); });
await host.request("plugin.initialize", { netcattyVersion: "1.0.0", apiVersion: "0.1.0-internal", supportedFeatures: features });
await host.request("plugin.activate", {}); assert.equal(requests, enabled ? 1 : 0);
}
});
+195
View File
@@ -0,0 +1,195 @@
"use strict";
const fs = require("node:fs");
const path = require("node:path");
const { createHash } = require("node:crypto");
// Deliberately fixed evidence-only gate, never a plugin or environment parameter.
const FIXTURE_DIRECTORY = "/workspace/agent-tools/database/m2-chooser/fixtures";
const MULTITABLE_FIXTURE_DIRECTORY = "/workspace/agent-tools/database/m3b-multitable/fixtures";
const MAX_FILE_BYTES = 32 * 1024 * 1024;
const timestampFence = new Int32Array(new SharedArrayBuffer(4));
const keys = ["dev", "ino", "size", "mtime", "ctime"];
function ageCapturedTimestamps(target) {
// On the qualified Linux fixture filesystem, rapid rename/restore can reuse
// the capture tick's ctime. Keep the ORIGINAL identities, but do not publish
// them until that tick is past. No source write, reopen, or metadata refresh.
// This is a bounded admission fence, not a lock or a general filesystem VFS.
const identities = [target, ...Object.values(target.sidecars ?? {}).filter(Boolean)];
const newest = identities.reduce((value, entry) => BigInt(entry.ctime) > value ? BigInt(entry.ctime) : value, 0n);
const readyAt = Number(newest / 1000000n) + 50;
const waitMs = readyAt - Date.now();
if (waitMs > 100) throw new Error("SQLite fixture timestamp is unavailable");
if (waitMs > 0) Atomics.wait(timestampFence, 0, 0, waitMs);
if (Date.now() < readyAt) throw new Error("SQLite fixture clock changed");
}
function identity(stat, minimum = 100) {
if (!stat.isFile() || stat.nlink !== 1n || stat.size < BigInt(minimum) || stat.size > BigInt(MAX_FILE_BYTES)) throw new Error("Unavailable SQLite fixture target");
return { dev: String(stat.dev), ino: String(stat.ino), size: String(stat.size), mtime: String(stat.mtimeNs), ctime: String(stat.ctimeNs) };
}
function assertStat(target, stat) {
const current = identity(stat, 0);
if (keys.some((key) => current[key] !== target[key])) throw new Error("SQLite fixture identity changed");
}
function fingerprint(fd, size) {
const hash = createHash("sha256"); const buffer = Buffer.alloc(64 * 1024);
for (let offset = 0; offset < size;) {
const length = Math.min(buffer.length, size - offset);
const count = fs.readSync(fd, buffer, 0, length, offset);
if (!count) throw new Error("SQLite fixture identity changed");
hash.update(buffer.subarray(0, count)); offset += count;
}
return hash.digest("hex");
}
function validatePath(file) {
if (process.platform !== "linux" || typeof file !== "string" || path.normalize(file) !== file
|| ![FIXTURE_DIRECTORY, MULTITABLE_FIXTURE_DIRECTORY].includes(path.dirname(file)) || !/\.(sqlite|db)$/.test(file)) {
throw new Error("Unavailable SQLite fixture target");
}
}
function assertRollback(fd, file) {
const header = Buffer.alloc(20);
if (fs.readSync(fd, header, 0, header.length, 0) !== 20 || header.subarray(0, 16).toString("hex") !== "53514c69746520666f726d6174203300"
|| header[18] !== 1 || header[19] !== 1) throw new Error("Only rollback-mode SQLite fixtures are available");
for (const suffix of ["-wal", "-shm", "-journal"]) {
try { fs.lstatSync(file + suffix); }
catch (error) { if (error.code === "ENOENT") continue; throw error; }
throw new Error("SQLite sidecars are unavailable in this slice");
}
}
// Own descriptors separately from serializable/saved identity. In particular,
// never open/close the main inode merely to revalidate: POSIX locks are per pid.
function holdFileIdentity(file, { allowWal = false } = {}) {
validatePath(file);
const directories = []; let fd; let held;
try {
let current = "";
for (const component of ["", ...path.dirname(file).split("/").filter(Boolean)]) {
current = component ? `${current}/${component}` : "/";
if (current.startsWith("//")) current = current.slice(1);
const parent = directories.at(-1);
const dirFd = fs.openSync(parent ? `/proc/self/fd/${parent.fd}/${component}` : "/",
fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
const stat = fs.fstatSync(dirFd, { bigint: true });
directories.push({ fd: dirFd, path: current, dev: stat.dev, ino: stat.ino });
}
const anchoredPath = `/proc/self/fd/${directories.at(-1).fd}/${path.basename(file)}`;
fd = fs.openSync(anchoredPath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
held = { fd, directories, anchoredPath, target: { path: file, ...identity(fs.fstatSync(fd, { bigint: true })) } };
held.target.sha256 = fingerprint(fd, Number(held.target.size));
const header = Buffer.alloc(20); fs.readSync(fd, header, 0, 20, 0);
if (allowWal && header[18] === 2 && header[19] === 2) holdSidecars(held);
ageCapturedTimestamps(held.target);
assertFileIdentity(held.target, held);
return held;
} catch (error) { closeFileIdentity(held ?? { fd, directories }); throw error; }
}
function closeFileIdentity(held) {
if (!held) return;
for (const sidecar of Object.values(held.sidecars ?? {})) {
if (sidecar?.fd !== undefined) { fs.closeSync(sidecar.fd); sidecar.fd = undefined; }
}
if (held.fd !== undefined) { fs.closeSync(held.fd); held.fd = undefined; }
for (const directory of held.directories ?? []) fs.closeSync(directory.fd);
held.directories = [];
}
function assertFileIdentity(target, held) {
validatePath(target.path);
if (!held || held.fd === undefined) throw new Error("Held SQLite descriptor required");
for (const directory of held.directories ?? []) {
const current = fs.lstatSync(directory.path, { bigint: true });
if (!current.isDirectory() || current.dev !== directory.dev || current.ino !== directory.ino) throw new Error("SQLite fixture directory changed");
}
// The worker inherits only the main descriptor. realpath/lstat do not open
// another regular-file fd and catch noncanonical or moved ancestors there.
if (fs.realpathSync(target.path) !== target.path) throw new Error("SQLite fixture identity changed");
assertStat(target, fs.lstatSync(target.path, { bigint: true }));
assertStat(target, fs.fstatSync(held.fd, { bigint: true }));
if (target.sidecars) assertSidecars(target, held);
else {
if (held.target?.sidecars) throw new Error("SQLite journal mode changed");
assertRollback(held.fd, held.anchoredPath ?? target.path);
}
if (target.sha256 && fingerprint(held.fd, Number(target.size)) !== target.sha256) throw new Error("SQLite fixture content changed");
assertStat(target, fs.fstatSync(held.fd, { bigint: true }));
}
function absent(file) {
try { fs.lstatSync(file); } catch (error) { if (error.code === "ENOENT") return; throw error; }
throw new Error("Unexpected SQLite sidecar");
}
function holdSidecars(held) {
held.sidecars = {}; held.target.sidecars = {};
absent(held.anchoredPath + "-journal");
for (const name of ["wal", "shm"]) {
const file = held.anchoredPath + "-" + name;
try { fs.lstatSync(file); }
catch (error) {
if (name === "shm" && error.code === "ENOENT") { held.target.sidecars.shm = null; continue; }
throw error;
}
const sidecar = held.sidecars[name] = {};
sidecar.fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
const target = identity(fs.fstatSync(sidecar.fd, { bigint: true }), 32);
target.sha256 = fingerprint(sidecar.fd, Number(target.size));
held.target.sidecars[name] = target;
}
}
function assertSidecars(target, held) {
const header = Buffer.alloc(20); fs.readSync(held.fd, header, 0, 20, 0);
if (header.subarray(0, 16).toString("hex") !== "53514c69746520666f726d6174203300"
|| header[18] !== 2 || header[19] !== 2) throw new Error("SQLite WAL header changed");
const anchored = held.anchoredPath ?? target.path;
absent(anchored + "-journal");
for (const name of ["wal", "shm"]) {
const expected = target.sidecars[name];
const file = target.path + "-" + name;
if (!expected) { absent(anchored + "-" + name); continue; }
const fd = held.sidecars?.[name]?.fd;
if (fd === undefined || fs.realpathSync(file) !== file) throw new Error("Held SQLite sidecar required");
assertStat(expected, fs.lstatSync(file, { bigint: true }));
assertStat(expected, fs.lstatSync(anchored + "-" + name, { bigint: true }));
assertStat(expected, fs.fstatSync(fd, { bigint: true }));
if (fingerprint(fd, Number(expected.size)) !== expected.sha256) throw new Error("SQLite sidecar content changed");
assertStat(expected, fs.fstatSync(fd, { bigint: true }));
}
}
// Explicit refresh permits only appended WAL content between revisions. It does
// not renew the main-file identity or weaken assertFileIdentity for normal reads.
function assertRefreshIdentity(previous, fresh) {
if (!previous?.target.sidecars || !fresh?.target.sidecars) throw new Error("WAL refresh required");
const old = previous.target; const next = fresh.target;
for (const name of ["wal", "shm"]) {
const a = old.sidecars[name]; const b = next.sidecars[name];
if (Boolean(a) !== Boolean(b) || (a && (a.dev !== b.dev || a.ino !== b.ino))) throw new Error("SQLite refresh sidecar changed");
}
if (BigInt(next.sidecars.wal.size) < BigInt(old.sidecars.wal.size)
|| fingerprint(previous.sidecars.wal.fd, Number(old.sidecars.wal.size)) !== old.sidecars.wal.sha256) {
throw new Error("SQLite refresh WAL prefix changed");
}
// Validate the old held ancestors/main AND both sets of held sidecar fds
// against the newly captured full sidecar identities before publication.
assertFileIdentity({ ...old, sidecars: next.sidecars }, previous);
assertFileIdentity(next, fresh);
}
function descriptorSnapshot() {
return new Set(fs.readdirSync("/proc/self/fd").map(Number).filter((fd) => {
try { fs.fstatSync(fd); return true; }
catch (error) { if (error.code === "EBADF") return false; throw error; }
}));
}
function bindSqliteDescriptor(target, held, before) {
// SQLite's unix VFS canonicalizes /proc/self/fd/N. Audit the native reopen,
// not just its reported filename. This worker runs one DatabaseSync only.
const opened = [];
for (const fd of descriptorSnapshot()) {
if (before.has(fd)) continue;
let stat;
try { stat = fs.fstatSync(fd, { bigint: true }); }
catch (error) { if (error.code === "EBADF") continue; throw error; } // readdir fd
if (stat.isFile()) { assertStat(target, stat); opened.push(fd); }
}
if (opened.length !== 1) throw new Error("SQLite native descriptor binding unavailable");
assertFileIdentity(target, held);
return opened[0];
}
function assertSqliteDescriptor(target, fd) { assertStat(target, fs.fstatSync(fd, { bigint: true })); }
module.exports = { FIXTURE_DIRECTORY, MULTITABLE_FIXTURE_DIRECTORY, MAX_FILE_BYTES,
holdFileIdentity, closeFileIdentity, assertFileIdentity, assertRefreshIdentity, descriptorSnapshot, bindSqliteDescriptor, assertSqliteDescriptor };
@@ -0,0 +1,165 @@
"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const { randomUUID } = require("node:crypto");
const { spawn } = require("node:child_process");
const { DatabaseSync } = require("node:sqlite");
const { FIXTURE_DIRECTORY, MAX_FILE_BYTES, holdFileIdentity, closeFileIdentity, assertFileIdentity,
descriptorSnapshot, bindSqliteDescriptor, assertSqliteDescriptor } = require("./sqliteFileIdentity.cjs");
const linux = { skip: process.platform !== "linux" };
function fixture(t) {
fs.mkdirSync(FIXTURE_DIRECTORY, { recursive: true });
const file = `${FIXTURE_DIRECTORY}/gate-c-${randomUUID()}.sqlite`;
const db = new DatabaseSync(file);
db.exec("CREATE TABLE notes(id INTEGER PRIMARY KEY,title TEXT); INSERT INTO notes VALUES(1,'original');"); db.close();
t.after(() => { for (const suffix of ["", ".old", "-wal", "-shm", "-journal"]) fs.rmSync(file + suffix, { force: true }); });
return file;
}
function hold(t, file) { const held = holdFileIdentity(file); t.after(() => closeFileIdentity(held)); return held; }
test("held fd survives namespace replacement; symlink, hardlink, rename, ABA, rewrite and dangling links fail closed", linux, (t) => {
for (const mutation of ["symlink", "hardlink", "rename", "aba", "rewrite", "truncate", "dangling"]) {
const file = fixture(t); const attacker = fixture(t); const held = hold(t, file);
const inode = fs.fstatSync(held.fd, { bigint: true }).ino;
if (mutation === "rewrite") {
const bytes = fs.readFileSync(file); bytes[bytes.length - 1] ^= 1;
fs.writeFileSync(file, bytes);
} else if (mutation === "truncate") fs.truncateSync(file, 100);
else {
if (mutation === "aba") fs.unlinkSync(file); else fs.renameSync(file, file + ".old");
if (["rename", "aba"].includes(mutation)) fs.copyFileSync(attacker, file);
else if (mutation === "hardlink") fs.linkSync(attacker, file);
else fs.symlinkSync(mutation === "dangling" ? attacker + ".missing" : attacker, file);
}
assert.equal(fs.fstatSync(held.fd, { bigint: true }).ino, inode);
assert.throws(() => assertFileIdentity(held.target, held), undefined, mutation);
closeFileIdentity(held);
}
});
test("native SQLite descriptor audit rejects substituted open even when every pathname check passes", linux, (t) => {
const file = fixture(t); const attacker = fixture(t); const held = hold(t, file);
const before = descriptorSnapshot();
// Model the VFS canonicalization/open interval: the native open landed on a
// different inode, but the namespace was restored before the postflight.
const wrong = new DatabaseSync(attacker, { readOnly: true });
try {
assertFileIdentity(held.target, held);
assert.throws(() => bindSqliteDescriptor(held.target, held, before), /identity changed/);
} finally { wrong.close(); }
const next = descriptorSnapshot();
const db = new DatabaseSync(`/proc/self/fd/${held.fd}`, { readOnly: true });
try {
const fd = bindSqliteDescriptor(held.target, held, next);
assert.notEqual(fd, held.fd);
assertSqliteDescriptor(held.target, fd);
assert.deepEqual(db.prepare("SELECT title FROM notes").all().map((r) => r.title), ["original"]);
} finally { db.close(); }
});
test("identity validation does not open/close the main inode or release a retained SQLite shared lock", linux, async (t) => {
const file = fixture(t); const held = hold(t, file);
const before = descriptorSnapshot();
const db = new DatabaseSync(`/proc/self/fd/${held.fd}`, { readOnly: true });
const fd = bindSqliteDescriptor(held.target, held, before);
db.exec("BEGIN"); db.prepare("SELECT * FROM notes").all();
const baseline = descriptorSnapshot();
for (let i = 0; i < 100; i++) { assertFileIdentity(held.target, held); assertSqliteDescriptor(held.target, fd); }
assert.deepEqual(descriptorSnapshot(), baseline);
const writer = spawn(process.execPath, ["-e", `
const db = new (require('node:sqlite').DatabaseSync)(process.argv[1], {timeout:100});
process.on('message', () => {
const start=Date.now();
try { db.exec('BEGIN EXCLUSIVE; ROLLBACK'); process.send({locked:false,ms:Date.now()-start}); }
catch { process.send({locked:true,ms:Date.now()-start}); }
}); process.send('ready');
`, file], { stdio: ["ignore", "ignore", "ignore", "ipc"] });
t.after(() => { writer.kill("SIGKILL"); });
const message = () => new Promise((resolve, reject) => { writer.once("message", resolve); writer.once("error", reject); });
try {
await message();
for (let i = 0; i < 3; i++) {
const result = message(); writer.send("probe"); const busy = await result;
assert.equal(busy.locked, true); assert.ok(busy.ms >= 80 && busy.ms < 1500);
assertFileIdentity(held.target, held);
}
db.exec("ROLLBACK");
const result = message(); writer.send("probe"); assert.equal((await result).locked, false);
} finally {
db.close();
const exited = new Promise((resolve) => writer.once("exit", resolve)); writer.kill("SIGKILL"); await exited;
}
});
test("WAL headers and symlink sidecars reject without descriptor leaks; fixture size is bounded", linux, (t) => {
const file = fixture(t); const baseline = descriptorSnapshot();
for (const suffix of ["-wal", "-shm", "-journal"]) {
fs.symlinkSync(`${FIXTURE_DIRECTORY}/missing-sidecar`, file + suffix);
for (let i = 0; i < 20; i++) assert.throws(() => holdFileIdentity(file), /sidecars/);
fs.unlinkSync(file + suffix);
}
const writer = new DatabaseSync(file); writer.exec("PRAGMA journal_mode=WAL; INSERT INTO notes VALUES(2,'wal');");
for (let i = 0; i < 20; i++) assert.throws(() => holdFileIdentity(file), /rollback-mode/);
writer.close();
assert.throws(() => holdFileIdentity(file), /rollback-mode/);
assert.deepEqual(descriptorSnapshot(), baseline);
const large = fixture(t); fs.truncateSync(large, MAX_FILE_BYTES + 1);
assert.throws(() => holdFileIdentity(large), /Unavailable/);
});
test("prepared WAL main rejects throughout concurrent sidecar replacement, including links outside the allowlist", linux, async (t) => {
const source = fixture(t); const file = fixture(t);
const writer = new DatabaseSync(source);
writer.exec("PRAGMA journal_mode=WAL; INSERT INTO notes VALUES(2,'uncheckpointed');");
for (const suffix of ["", "-wal", "-shm"]) fs.copyFileSync(source + suffix, file + suffix);
writer.close();
const baseline = descriptorSnapshot();
const child = spawn(process.execPath, ["-e", `
const fs=require('node:fs'); const file=process.argv[1]; let rounds=0; let stop=false;
const bytes=fs.readFileSync(file+'-wal');
function race(){
for(const suffix of ['-wal','-shm','-journal']){
fs.rmSync(file+suffix,{force:true}); fs.symlinkSync('/workspace/agent-tools/database/gate-c-wal-toctou/outside-sidecar',file+suffix);
fs.rmSync(file+suffix,{force:true}); fs.writeFileSync(file+suffix,bytes);
}
if(++rounds===1)process.send('ready');
if(stop){process.send({rounds});process.exit(0);}else setImmediate(race);
}
process.on('message',()=>{stop=true;});race();
`, file], { stdio: ["ignore", "ignore", "ignore", "ipc"] });
t.after(() => { if (child.exitCode === null) child.kill("SIGKILL"); });
const message = () => new Promise((resolve, reject) => { child.once("message", resolve); child.once("error", reject); });
await message();
for (let i = 0; i < 100; i++) assert.throws(() => holdFileIdentity(file), /rollback-mode/);
const result = message(); const exited = new Promise((resolve) => child.once("exit", resolve)); child.send("stop");
const { rounds } = await result; await exited; assert.ok(rounds > 1);
assert.deepEqual(descriptorSnapshot(), baseline);
assert.throws(() => holdFileIdentity("/workspace/agent-tools/database/gate-c-wal-toctou/outside.sqlite"), /Unavailable/);
t.diagnostic(JSON.stringify({ walRejects: 100, concurrentSidecarReplacementRounds: rounds }));
});
test("actual worker rejects a substituted native open before any schema/data statement", linux, async (t) => {
const file = fixture(t); const attacker = fixture(t); const held = hold(t, file);
const worker = require.resolve("./sqliteFixtureWorker.cjs");
const child = spawn(process.execPath, ["-e", `
const sqlite=require('node:sqlite'); const Native=sqlite.DatabaseSync;
sqlite.DatabaseSync=class extends Native {
constructor(file,options){
if(file!=='/proc/self/fd/4')throw new Error('Expected inherited fd alias');
super(process.argv[1],options);
}
prepare(...args){process.send({unexpectedStatement:true});return super.prepare(...args);}
exec(...args){process.send({unexpectedStatement:true});return super.exec(...args);}
};
require(process.argv[2]);
`, attacker, worker], { env: { ELECTRON_RUN_AS_NODE: "1", NODE_NO_WARNINGS: "1" }, stdio: ["ignore", "ignore", "ignore", "ipc", held.fd] });
t.after(() => { if (child.exitCode === null) child.kill("SIGKILL"); });
const message = () => new Promise((resolve, reject) => { child.once("message", resolve); child.once("error", reject); });
assert.deepEqual(await message(), { ready: true });
const response = message(); child.send({ id: "gate-c-native-substitution", operation: "schema", request: { target: held.target } });
const result = await response;
assert.equal(result.fatal, true); assert.equal(result.result, undefined); assert.equal(result.unexpectedStatement, undefined);
assertFileIdentity(held.target, held); // pathname-only pre/post checks both pass
const exited = new Promise((resolve) => child.once("exit", resolve)); child.kill("SIGKILL"); await exited;
});
+450
View File
@@ -0,0 +1,450 @@
"use strict";
const { DatabaseTcpService } = require("./databaseTcpService.cjs");
const { randomUUID } = require("node:crypto");
const { fork } = require("node:child_process");
const path = require("node:path");
const { PluginRpcError, RPC_ERRORS } = require("./rpcRouter.cjs");
const { createDefinitionValidator } = require("./contractValidator.cjs");
const { escapePermissionText } = require("./nativePermissionDecision.cjs");
const { FIXTURE_DIRECTORY, holdFileIdentity, closeFileIdentity, assertFileIdentity, assertRefreshIdentity } = require("./sqliteFileIdentity.cjs");
const { PORT_PROBE_FEATURE, PORT_PROBE_RESOURCE } = require("./databaseHostPortProbe.cjs");
const { TUNNEL_TEST_FEATURE } = require("./databaseTunnelTest.cjs");
const { LIVE_FEATURE, LIVE_RESOURCE } = require("./databaseHostLiveSshPg.cjs");
const { createWalSnapshot, removeWalSnapshot } = require("./sqliteWalSnapshot.cjs");
const WAL_REFRESH_FEATURE = "database.sqlite-wal-session-refresh.fixture.v1";
// Qualification marker only: E still controls WAL admission and invalidation.
const MALFORMED_FEATURE = "database.sqlite-malformed-reject.fixture.v1";
const WAL_CAPTURE_FEATURE = "database.sqlite-wal-capture.fixture.v1";
const WAL_CHECKPOINT_FEATURE = "database.sqlite-wal-checkpoint.fixture.v1";
const WAL_CONCURRENT_FEATURE = "database.sqlite-wal-concurrent.fixture.v1";
const WAL_FEATURE = "database.sqlite-wal-readonly.fixture.v1";
const SAVED_FEATURE = "database.saved-connections.v1";
const FD_FEATURE = "database.sqlite-fd-identity.fixture.v1";
const FILE_FEATURE = "database.sqlite-file-fixture.v1";
const FILE_RESOURCE = "sqlite:disposable-file";
const FEATURE = "database.sqlite-fixture.v1";
const RESOURCE = "sqlite:synthetic-notes";
const fail = (code, message) => new PluginRpcError(RPC_ERRORS[code], message);
const validators = new Map();
function validate(name, value) {
if (name.endsWith("Request") && Buffer.byteLength(JSON.stringify(value) ?? "") > 16384) throw fail("invalidArgument", "Database request exceeds 16 KiB");
if (name === "DatabaseQueryRequest" && typeof value?.sql === "string" && Buffer.byteLength(value.sql) > 8192) throw fail("invalidArgument", "Database SQL exceeds 8 KiB");
if (!validators.has(name)) validators.set(name, createDefinitionValidator(name));
if (!validators.get(name)(value)) throw fail("invalidArgument", "Database parameters violate the contract");
if (Array.isArray(value)) return Object.freeze(value);
return Object.freeze({ ...value, ...(value.parameters ? { parameters: Object.freeze([...value.parameters]) } : {}) });
}
class PluginSqliteFixtureService {
constructor(options) {
Object.assign(this, options); this.tcp = new DatabaseTcpService(); this.sessions = new Map(); this.pendingFiles = new Map(); this.closed = false; this.revisions = new Map();
this.revocation = options.permissionEngine.onDidRevoke?.(({ pluginId }) => {
this.revisions.set(pluginId, (this.revisions.get(pluginId) ?? 0) + 1);
for (const s of this.sessions.values()) if (s.owner.pluginId === pluginId) this.closeSession(s);
this.releasePendingFiles((owner) => owner.pluginId === pluginId);
this.tcp.release(c => c.pluginId === pluginId); this.liveSshPg?.revoke(pluginId); this.tunnelTests?.revoke(pluginId); this.portProbes?.revoke(pluginId);
});
this.unlock = options.subscribeLock?.((locked) => { if (locked) this.closeAll(); });
}
async authenticate(context) {
await context.assertActive();
this.assertIdentity(context);
}
assertIdentity(context) {
context.signal?.throwIfAborted();
const active = this.database.getActivePlugin(context.pluginId);
const retained = this.database.getRetainedPluginSource(context.pluginId);
const current = this.runtimeSupervisor.getRuntimeIdentity(context.pluginId);
if (!this.enabled || this.closed || this.isLocked?.() || !active?.enabled || !current
|| !context.sourceOwner || !context.sourceId || active.source?.id !== context.sourceId
|| retained?.id !== context.sourceId || this.database.privateOwner(context.pluginId) !== context.sourceOwner
|| this.database.publicPluginId(context.sourceOwner) !== context.pluginId
|| ["runtimeId", "pluginVersion", "securityPrincipal", "sourceOwner", "sourceId"].some((k) => current[k] !== context[k])) {
throw fail("permissionDenied", "Database runtime or source binding is unavailable");
}
if (![...(context.manifest.features?.required ?? []), ...(context.manifest.features?.optional ?? [])].includes(FEATURE)) {
throw fail("unsupported", "Database feature was not negotiated");
}
}
get(handleId, context, revision, allowRefreshing = false) {
const s = this.sessions.get(handleId);
if (!s || ["pluginId", "runtimeId", "sourceOwner", "sourceId", "securityPrincipal"].some((k) => s.owner[k] !== context[k])) {
throw fail("permissionDenied", "Unknown database session");
}
if (s.target && revision !== s.revision) throw fail("permissionDenied", "Stale database revision");
if (s.refreshing && !allowRefreshing) throw fail("failedPrecondition", "A database refresh is active");
return s;
}
async authorize(context, mode, resource = RESOURCE, tcpTarget = "") {
await this.permissionEngine.authorize(context, { permission: `database.query.${mode}`, resources: [resource],
validateBeforeGrant: () => this.assertIdentity(context), reason: resource === "database:tcp" ? `Read-only TCP database session ${tcpTarget}; credentials are not persisted` : resource === LIVE_RESOURCE ? "Authenticate pinned loopback SSH and run SELECT 1 on the PostgreSQL fixture only" : resource === PORT_PROBE_RESOURCE ? "Probe five common database TCP ports on the selected saved host directly from Netcatty; no SSH tunnel or database authentication" : resource === "database-tunnel:synthetic-loopback" ? "Test a recorded synthetic tunnel adapter; no SSH or PostgreSQL connection" : mode === "write" ? "Modify disposable synthetic notes after exact-statement review" : resource === FILE_RESOURCE ? "Read a host-selected disposable SQLite file" : "Read disposable synthetic notes", allowedScopes: ["once", "application"] });
await this.authenticate(context);
}
register(registry) {
const route = (operation, definition, handler) => registry.registerRequest(`database.${operation}`, async (params, context) => {
const revision = this.revisions.get(context.pluginId) ?? 0;
context.addAuthorizationGuard?.(() => {
if ((this.revisions.get(context.pluginId) ?? 0) !== revision) throw fail("permissionDenied", "Database permission policy changed");
});
await this.authenticate(context); return handler.call(this, params, context);
}, { validateParams: (p) => validate(definition, p), metadata: { capability: "database", public: true, mutating: true } });
const liveRoute = (operation, definition, handler) => route(operation, definition, async function (params, context) {
if (!this.liveSshPg || !this.hasLiveFeature(context)) throw fail("unsupported", "Live SSH PostgreSQL fixture is unavailable");
return handler.call(this, params, context);
});
liveRoute("openHostLiveSshPgFixture", "DatabaseHostLiveSshPgOpenRequest", async function (request, context) {
return validate("DatabaseHostLiveSshPgOpenResult", await this.liveSshPg.open(request, context, {
authorize: async (scoped) => {
await this.authorizeMetadata(scoped, "vault.metadata");
await this.authorizeMetadata(scoped, "secrets");
await this.authorize(scoped, "read", LIVE_RESOURCE);
},
assertActive: (scoped) => this.authenticate(scoped),
}));
});
liveRoute("cancelHostLiveSshPgFixture", "DatabaseHostLiveSshPgCancelRequest", function (request, context) { return this.liveSshPg.cancel(request, context); });
liveRoute("closeHostLiveSshPgSession", "DatabaseHostLiveSshPgCloseRequest", async function (request, context) {
return validate("DatabaseHostLiveSshPgCloseResult", await this.liveSshPg.close(request, context));
});
const probeRoute = (operation, definition, handler) => route(operation, definition, async function (params, context) {
if (!this.portProbes || !this.hasPortProbeFeature(context)) throw fail("unsupported", "Host port probing is unavailable");
return handler.call(this, params, context);
});
probeRoute("probeHostDatabasePorts", "DatabaseHostPortProbeRequest", async function (request, context) {
return validate("DatabaseHostPortProbeResult", await this.portProbes.probe(request, context, {
authorize: async (scoped) => {
await this.authorizeMetadata(scoped, "vault.metadata");
await this.authorize(scoped, "read", PORT_PROBE_RESOURCE);
},
readHosts: (scoped) => this.readDatabaseHosts(scoped),
assertActive: (scoped) => this.authenticate(scoped),
}));
});
probeRoute("cancelHostDatabasePorts", "DatabaseHostPortProbeCancelRequest", function (request, context) {
return this.portProbes.cancel(request, context);
});
const tunnelRoute = (operation, definition, handler) => route(operation, definition, async function (params, context) {
if (!this.tunnelTests || !this.hasTunnelFeature(context)) throw fail("unsupported", "Synthetic tunnel testing is unavailable");
return handler.call(this, params, context);
});
tunnelRoute("testTunnel", "DatabaseTunnelTestRequest", async function (request, context) {
return validate("DatabaseTunnelTestResult", await this.tunnelTests.test(request, context, {
authorize: async (scoped) => {
await this.authorizeMetadata(scoped, "vault.metadata");
await this.authorizeMetadata(scoped, "secrets");
await this.authorize(scoped, "read", "database-tunnel:synthetic-loopback");
},
assertActive: (scoped) => this.authenticate(scoped),
}));
});
tunnelRoute("cancelTunnelTest", "DatabaseTunnelCancelRequest", function (request, context) {
return this.tunnelTests.cancel(request, context);
});
const tcpHooks = {
authorize: (context, label) => this.authorize(context, "read", "database:tcp", label),
authenticate: (context) => this.authenticate(context),
};
route("openTcp", "DatabaseTcpOpenRequest", async function (request, context) {
if (![...(context.manifest.features?.required ?? []), ...(context.manifest.features?.optional ?? [])].includes("database.tcp.v1")) throw fail("unsupported", "Database TCP feature was not negotiated");
return this.tcp.open(request, context, tcpHooks);
});
route("openFixture", "DatabaseEmptyRequest", async function (_, context) {
await this.authorize(context, "read");
return this.openSession(context);
});
route("openSqliteFile", "DatabaseEmptyRequest", async function (_, context) {
const features = [...(context.manifest.features?.required ?? []), ...(context.manifest.features?.optional ?? [])];
if (process.platform !== "linux" || !features.includes(FILE_FEATURE) || !this.dialog?.showOpenDialog) throw fail("unsupported", "SQLite file chooser is unavailable");
const chooserOptions = { title: "Open disposable SQLite file (read-only)", defaultPath: FIXTURE_DIRECTORY,
properties: ["openFile"], filters: [{ name: "Disposable SQLite", extensions: ["sqlite", "db"] }] };
const parent = this.getInteractionWindow?.();
const selection = await this.dialog.showOpenDialog(...(parent ? [parent, chooserOptions] : [chooserOptions]));
await this.authenticate(context);
if (selection.canceled) return null;
let held;
try {
if (selection.filePaths?.length !== 1) throw new Error();
held = holdFileIdentity(selection.filePaths[0], { allowWal: features.includes(WAL_FEATURE) });
} catch { throw fail("permissionDenied", "Select a regular disposable SQLite fixture with a stable supported journal and no links"); }
const untrack = this.trackPendingFile(held, context);
try {
// GTK resolves the chooser before Electron delivers the parent focus event.
// Wait for that event; never focus the window or bypass the permission gate.
if (parent && !parent.isFocused()) {
await new Promise((resolve, reject) => {
const done = (error) => {
clearTimeout(timer); parent.removeListener("focus", focused); parent.removeListener("closed", closed);
context.signal?.removeEventListener("abort", closed);
if (error) reject(error); else resolve();
};
const focused = () => done();
const closed = () => done(fail("permissionDenied", "SQLite chooser requires a focused app window; try again"));
const timer = setTimeout(closed, 1000);
parent.once("focus", focused); parent.once("closed", closed);
context.signal?.addEventListener("abort", closed, { once: true });
if (parent.isDestroyed() || context.signal?.aborted) closed();
else if (parent.isFocused()) focused();
});
}
await this.authorize(context, "read", FILE_RESOURCE);
try { assertFileIdentity(held.target, held); }
catch { throw fail("failedPrecondition", "SQLite target is stale or unavailable"); }
return await this.openSession(context, held.target, held);
} finally { untrack(); if (![...this.sessions.values()].some((s) => s.held === held)) closeFileIdentity(held); }
});
route("refreshSqliteFile", "DatabaseHandleRequest", async function ({ handleId, revision }, context) {
const features = [...(context.manifest.features?.required ?? []), ...(context.manifest.features?.optional ?? [])];
if (process.platform !== "linux" || ![FILE_FEATURE, FD_FEATURE, WAL_FEATURE, WAL_CONCURRENT_FEATURE,
WAL_CHECKPOINT_FEATURE, WAL_CAPTURE_FEATURE, MALFORMED_FEATURE, WAL_REFRESH_FEATURE].every((f) => features.includes(f))) {
throw fail("unsupported", "Explicit SQLite WAL refresh is unavailable");
}
const s = this.get(handleId, context, revision);
if (!s.target?.sidecars) throw fail("unsupported", "Only open WAL fixture sessions can refresh");
if (s.pending || s.reviewing) throw fail("failedPrecondition", "A database operation is already active");
s.refreshing = true;
const abort = () => this.closeSession(s, fail("cancelled", "SQLite refresh cancelled"));
context.signal?.addEventListener("abort", abort, { once: true });
let held; let untrack; let candidate;
try {
context.signal?.throwIfAborted();
// Capture before the permission await; changes during review must reject.
try {
held = holdFileIdentity(s.target.path, { allowWal: true });
s.refreshHeld = held;
assertRefreshIdentity(s.held, held);
} catch { throw fail("failedPrecondition", "SQLite refresh requires an unchanged main file and stable appended WAL"); }
untrack = this.trackPendingFile(held, context);
await this.authorize(context, "read", FILE_RESOURCE);
this.get(handleId, context, revision, true);
try { assertRefreshIdentity(s.held, held); }
catch { throw fail("failedPrecondition", "SQLite source changed during refresh"); }
const opened = await this.openSession(context, held.target, held, s);
candidate = this.sessions.get(opened.handleId);
await this.authenticate(context);
this.get(handleId, context, revision, true);
try { assertRefreshIdentity(s.held, held); this.checkTarget(candidate); }
catch { throw fail("failedPrecondition", "SQLite source changed during refresh"); }
// No await between the final checks and the atomic handle/revision swap.
s.refreshCandidate = null; s.refreshHeld = null;
this.closeSession(s);
this.sessions.delete(candidate.handleId);
candidate.handleId = handleId; this.sessions.set(handleId, candidate);
return validate("DatabaseFileOpenResult", { ...opened, handleId });
} catch (error) {
if (candidate) this.closeSession(candidate);
this.closeSession(s);
throw error;
} finally {
context.signal?.removeEventListener("abort", abort);
untrack?.();
if (![...this.sessions.values()].some((entry) => entry.held === held)) closeFileIdentity(held);
}
});
const savedRoute = (operation, definition, handler) => route(operation, definition, async function (params, context) {
const features = [...(context.manifest.features?.required ?? []), ...(context.manifest.features?.optional ?? [])];
if (!features.includes(SAVED_FEATURE) || !this.connectionStore) throw fail("unsupported", "Saved connections are unavailable");
return handler.call(this, params, context);
});
savedRoute("listSavedConnections", "DatabaseEmptyRequest", async function (_, context) {
await this.authorize(context, "read");
return validate("DatabaseSavedConnectionList", this.connectionStore.list(context.sourceOwner));
});
savedRoute("listHostsForDatabase", "DatabaseEmptyRequest", async function (_, context) {
return this.listDatabaseHosts(context);
});
savedRoute("saveConnection", "DatabaseSaveConnectionRequest", async function (request, context) {
const s = this.get(request.handleId, context, request.revision);
await this.authorize(context, "read", s.target ? FILE_RESOURCE : RESOURCE);
await this.authorizeMetadata(context, "storage");
let host;
if (request.meta.hostId) {
host = (await this.listDatabaseHosts(context)).find((h) => h.hostId === request.meta.hostId);
if (!host) throw fail("failedPrecondition", "Selected host is no longer available");
}
if (request.secret) await this.authorizeMetadata(context, "secrets");
await this.authenticate(context); this.get(s.handleId, context, s.revision); this.checkTarget(s);
const id = randomUUID(); const key = `database-connection:${id}`;
let secretRef;
try {
if (request.secret) {
if (!this.secretStore) throw fail("unavailable", "Secure credential storage is unavailable");
// Never resolve credentials here or return password bytes to the runtime.
try { secretRef = this.secretStore.set(context.pluginId, key, request.secret.value).id; }
catch { throw fail("unavailable", "Secure credential storage is unavailable"); }
}
const meta = validate("DatabaseSavedConnection", { id, name: request.meta.name, color: request.meta.color,
engine: "sqlite", targetKind: s.target ? "file" : "memory", readOnly: Boolean(s.target),
...(host ? { hostId: host.hostId, hostLabel: host.label } : {}), ...(secretRef ? { secretRef } : {}) });
this.connectionStore.add({ owner: context.sourceOwner, meta, ...(s.target ? { target: s.target } : {}) });
return meta;
} catch (error) { if (secretRef) this.secretStore.delete(context.pluginId, key); throw error; }
});
savedRoute("deleteConnection", "DatabaseConnectionIdRequest", async function ({ id }, context) {
await this.authorizeMetadata(context, "storage");
const entry = this.connectionStore.get(context.sourceOwner, id);
if (entry.meta.secretRef) this.secretStore.delete(context.pluginId, `database-connection:${id}`);
this.connectionStore.delete(context.sourceOwner, id); return null;
});
savedRoute("openSavedConnection", "DatabaseConnectionIdRequest", async function ({ id }, context) {
const entry = this.connectionStore.get(context.sourceOwner, id);
if (entry.target && (process.platform !== "linux" || ![...(context.manifest.features?.required ?? []), ...(context.manifest.features?.optional ?? [])].includes(FILE_FEATURE))) {
throw fail("unsupported", "SQLite file fixture feature is unavailable");
}
let held; let untrack;
try {
if (entry.target) {
try { held = holdFileIdentity(entry.target.path, { allowWal: [...(context.manifest.features?.required ?? []), ...(context.manifest.features?.optional ?? [])].includes(WAL_FEATURE) }); untrack = this.trackPendingFile(held, context); assertFileIdentity(entry.target, held); }
catch { throw fail("failedPrecondition", "Saved SQLite target changed; select and save it again"); }
}
await this.authorize(context, "read", entry.target ? FILE_RESOURCE : RESOURCE);
// Deletion during a native permission prompt revokes this pending reopen.
this.connectionStore.get(context.sourceOwner, id);
if (entry.target) {
try { assertFileIdentity(entry.target, held); }
catch { throw fail("failedPrecondition", "Saved SQLite target changed; select and save it again"); }
}
return await this.openSession(context, held?.target, held);
} finally { untrack?.(); if (![...this.sessions.values()].some((s) => s.held === held)) closeFileIdentity(held); }
});
route("readSchema", "DatabaseHandleRequest", async function ({ handleId, revision }, context) {
if (this.tcp.sessions.has(handleId)) return this.tcp.schema(this.tcp.get(handleId, context), context, tcpHooks);
const s = this.get(handleId, context, revision); await this.authorize(context, "read", s.target ? FILE_RESOURCE : RESOURCE);
return this.run(s, "schema", {}, context);
});
route("query", "DatabaseQueryRequest", async function (request, context) {
if (this.tcp.sessions.has(request.handleId)) return this.tcp.query(this.tcp.get(request.handleId, context), request, context, tcpHooks);
const s = this.get(request.handleId, context, request.revision);
if (s.target && request.mode === "write") throw fail("permissionDenied", "SQLite file targets are read-only");
if (s.pending || s.reviewing) throw fail("failedPrecondition", "A database operation is already active");
s.reviewing = true;
try {
await this.authorize(context, request.mode, s.target ? FILE_RESOURCE : RESOURCE);
if (request.mode === "write") {
if (!this.dialog?.showMessageBox) throw fail("permissionDenied", "A trusted write reviewer is unavailable");
const decision = await this.dialog.showMessageBox({ type: "warning", title: "Review synthetic SQLite write", message: "Change disposable synthetic notes?",
detail: `Plugin: ${escapePermissionText(context.pluginId)}\nTarget: ${RESOURCE}\nSQL:\n${escapePermissionText(request.sql, 8192)}\nParameters:\n${escapePermissionText(JSON.stringify(request.parameters), 65536)}\nThis changes only the in-memory fixture.`,
buttons: ["Cancel", "Execute this statement"], defaultId: 0, cancelId: 0, noLink: true, signal: context.signal });
if (decision.response !== 1) throw fail("permissionDenied", "Write was not approved");
}
await this.authenticate(context); this.get(s.handleId, context, s.revision);
return await this.run(s, "query", request, context);
} finally { s.reviewing = false; }
});
for (const operation of ["cancel", "close"]) route(operation, "DatabaseHandleRequest", async function ({ handleId, revision }, context) {
if (this.tcp.sessions.has(handleId)) { this.tcp.close(this.tcp.get(handleId, context)); return null; }
this.closeSession(this.get(handleId, context, revision, true), fail("cancelled", "Database session closed; reopen the target")); return null;
});
}
async authorizeMetadata(context, permission) {
await this.permissionEngine.authorize(context, { permission, resources: ["*"],
validateBeforeGrant: () => this.assertIdentity(context), allowedScopes: ["once", "application"],
reason: permission === "vault.metadata" ? "Share host labels and SSH context only; no database tunnel" : permission === "secrets" ? "Store a database credential using OS-backed encryption" : "Manage saved database connection metadata" });
await this.authenticate(context);
}
hasLiveFeature(context) { return [...(context.manifest.features?.required ?? []), ...(context.manifest.features?.optional ?? [])].includes(LIVE_FEATURE); }
hasTunnelFeature(context) { return [...(context.manifest.features?.required ?? []), ...(context.manifest.features?.optional ?? [])].includes(TUNNEL_TEST_FEATURE); }
hasPortProbeFeature(context) { return [...(context.manifest.features?.required ?? []), ...(context.manifest.features?.optional ?? [])].includes(PORT_PROBE_FEATURE); }
async listDatabaseHosts(context) {
await this.authorizeMetadata(context, "vault.metadata");
return this.readDatabaseHosts(context);
}
async readDatabaseHosts(context) {
let response;
try { response = await this.getDatabaseHosts?.(); } catch { throw fail("unavailable", "Host metadata is unavailable"); }
await this.authenticate(context);
if (!response?.ok || !Array.isArray(response.hosts) || response.hosts.length > 500) throw fail("unavailable", "Host metadata is unavailable");
// Explicit allowlist: never pass the renderer object or credentials through.
let hosts = response.hosts.filter((h) => !h.protocol || h.protocol === "ssh").map((h) => ({
hostId: h.id, label: h.label || h.hostname, hostname: h.hostname, port: h.port ?? 22,
username: h.username ?? "", capability: "metadata-only", tunnelAvailable: false,
}));
if (this.tunnelTests && this.hasTunnelFeature(context)) {
const fixture = this.tunnelTests.metadata();
hosts = [...hosts.filter((h) => h.hostId !== fixture.hostId).slice(0, 499), fixture];
}
if (this.liveSshPg && this.hasLiveFeature(context)) {
const fixture = this.liveSshPg.metadata();
hosts = [...hosts.filter((h) => h.hostId !== fixture.hostId).slice(0, 499), fixture];
}
if (this.portProbes && this.hasPortProbeFeature(context)) hosts = hosts.map((h) => this.portProbes.metadata(h));
return validate("DatabaseHostList", hosts);
}
trackPendingFile(held, context) {
this.pendingFiles.set(held, context);
const abort = () => { closeFileIdentity(held); this.pendingFiles.delete(held); };
context.signal?.addEventListener("abort", abort, { once: true });
if (context.signal?.aborted) abort();
return () => { context.signal?.removeEventListener("abort", abort); this.pendingFiles.delete(held); };
}
releasePendingFiles(predicate = () => true) {
for (const [held, owner] of this.pendingFiles) if (predicate(owner)) {
closeFileIdentity(held); this.pendingFiles.delete(held);
}
}
async openSession(context, target, held, replacing) {
if (this.sessions.size >= 8) throw fail("resourceExhausted", "Host database session budget reached");
if ([...this.sessions.values()].filter((s) => s.owner.runtimeId === context.runtimeId).length >= 2) throw fail("resourceExhausted", "Two database sessions per runtime maximum");
let snapshot;
try { snapshot = target?.sidecars ? createWalSnapshot(held) : undefined; }
catch { throw fail("failedPrecondition", "Stable committed WAL fixture required"); }
let s;
try { s = { handleId: randomUUID(), target, held, snapshot, revision: target ? randomUUID() : undefined, owner: context, pending: null, worker: fork(require.resolve("./sqliteFixtureWorker.cjs").replace(`app.asar${path.sep}`, `app.asar.unpacked${path.sep}`), [], { execArgv: ["--max-old-space-size=32"], env: { ELECTRON_RUN_AS_NODE: "1", NODE_NO_WARNINGS: "1" }, stdio: ["ignore", "ignore", "ignore", "ipc", ...(held ? [held.fd] : []), ...(snapshot ? [snapshot.fd, held.sidecars.wal.fd, held.sidecars.shm?.fd ?? "ignore"] : [])] }) };
} catch (error) { removeWalSnapshot(snapshot); throw error; }
let snapshotRemoved = false;
const cleanupSnapshot = () => { if (!snapshotRemoved) { snapshotRemoved = true; removeWalSnapshot(snapshot); } };
this.sessions.set(s.handleId, s);
if (replacing) replacing.refreshCandidate = s;
s.worker.on("error", () => this.closeSession(s, fail("unavailable", "SQLite worker unavailable")));
s.worker.on("exit", () => { this.closeSession(s, fail("unavailable", "SQLite worker stopped")); cleanupSnapshot(); });
s.worker.once("close", cleanupSnapshot);
s.worker.on("message", (message) => {
if (!s.pending || message.id !== s.pending.id) return;
if (message.fatal) this.closeSession(s, fail("failedPrecondition", "SQLite target is stale or unavailable"));
else if (message.error) s.pending.reject(fail("invalidArgument", message.error));
else s.pending.resolve(message.result);
});
s.idle = setTimeout(() => this.closeSession(s), 10 * 60_000); s.idle.unref();
try { await this.run(s, "schema", target ? { target, ...(snapshot ? { snapshotTarget: snapshot.target } : {}) } : {}, context); await this.authenticate(context); }
catch (error) { this.closeSession(s); throw error; }
return target
? validate("DatabaseFileOpenResult", { handleId: s.handleId, revision: s.revision, engine: "sqlite", label: "Disposable SQLite file (read-only)", fixture: true, readOnly: true })
: { handleId: s.handleId, engine: "sqlite", label: "Disposable synthetic notes", fixture: true };
}
checkTarget(s) {
if (!s.target) return;
try { assertFileIdentity(s.target, s.held); if (s.snapshot) assertFileIdentity(s.snapshot.target, s.snapshot); }
catch { const error = fail("failedPrecondition", "SQLite target is stale or unavailable"); this.closeSession(s, error); throw error; }
}
async run(s, operation, request, context) {
this.get(s.handleId, context, s.revision);
if (s.pending) throw fail("failedPrecondition", "A database operation is already active");
this.checkTarget(s);
const id = randomUUID(); let timer; let abort;
try {
const result = await new Promise((resolve, reject) => {
s.pending = { id, resolve, reject };
abort = () => this.closeSession(s, fail("cancelled", "Database operation cancelled; fixture discarded"));
context.signal?.addEventListener("abort", abort, { once: true });
timer = setTimeout(() => this.closeSession(s, fail("deadlineExceeded", "Database deadline exceeded; fixture discarded")), request.timeoutMs ?? 3000);
if (context.signal?.aborted) abort(); else s.worker.send({ id, operation, request });
});
await this.authenticate(context); this.get(s.handleId, context, s.revision);
this.checkTarget(s);
return validate(operation === "schema" ? "DatabaseSchemaResult" : "DatabaseQueryResult", result);
} finally { clearTimeout(timer); context.signal?.removeEventListener("abort", abort); s.pending = null; }
}
closeSession(s, error = fail("cancelled", "Database session closed")) {
if (this.sessions.get(s.handleId) !== s) return;
this.sessions.delete(s.handleId);
if (s.refreshCandidate) this.closeSession(s.refreshCandidate, error);
closeFileIdentity(s.refreshHeld);
clearTimeout(s.idle); s.pending?.reject(error); s.worker.kill("SIGKILL"); closeFileIdentity(s.held);
}
closeAll() { this.tcp.release(); this.releasePendingFiles(); this.liveSshPg?.closeAll(); this.portProbes?.closeAll(); this.tunnelTests?.closeAll(); for (const s of this.sessions.values()) this.closeSession(s); }
releaseRuntime(runtimeId) { this.tcp.release(c => c.runtimeId === runtimeId); this.releasePendingFiles((owner) => owner.runtimeId === runtimeId); this.liveSshPg?.releaseRuntime(runtimeId); this.portProbes?.releaseRuntime(runtimeId); this.tunnelTests?.releaseRuntime(runtimeId); for (const s of this.sessions.values()) if (s.owner.runtimeId === runtimeId) this.closeSession(s); }
shutdown() { this.tcp.closed = true; this.liveSshPg?.shutdown(); this.portProbes?.shutdown(); this.tunnelTests?.shutdown(); this.closed = true; this.closeAll(); this.revocation?.dispose(); if (typeof this.unlock === "function") this.unlock(); else this.unlock?.dispose(); }
}
function sqliteFixtureAvailable() {
try { const { DatabaseSync } = require("node:sqlite"); return typeof DatabaseSync.prototype.setAuthorizer === "function" && typeof DatabaseSync.prototype.enableDefensive === "function"; }
catch { return false; }
}
module.exports = { PluginSqliteFixtureService, FEATURE, FILE_FEATURE, FD_FEATURE, WAL_FEATURE, WAL_CONCURRENT_FEATURE, WAL_CHECKPOINT_FEATURE, WAL_CAPTURE_FEATURE, MALFORMED_FEATURE, WAL_REFRESH_FEATURE, SAVED_FEATURE, RESOURCE, FILE_RESOURCE, sqliteFixtureAvailable };
File diff suppressed because it is too large. Load diff
+18
View File
@@ -0,0 +1,18 @@
"use strict";
// Only anonymous positional placeholders are supported in this experimental slice.
// SQL semantics and read/write authority are always checked by SQLite itself.
function bindingCount(sql) {
let count = 0;
for (let i = 0; i < sql.length; i++) {
const ch = sql[i]; const next = sql[i + 1];
if (ch === "-" && next === "-") { while (i < sql.length && sql[i] !== "\n") i++; }
else if (ch === "/" && next === "*") { i += 2; while (i < sql.length && !(sql[i] === "*" && sql[i + 1] === "/")) i++; i++; }
else if (["'", '"', "`", "["].includes(ch)) {
const end = ch === "[" ? "]" : ch;
for (i++; i < sql.length; i++) if (sql[i] === end) { if (ch !== "[" && sql[i + 1] === end) i++; else break; }
} else if (ch === "?") { if (/[0-9]/.test(next ?? "")) throw new Error("Numbered bindings unavailable"); count++; }
else if ([":", "$", "@"].includes(ch)) throw new Error("Named bindings unavailable");
}
return count;
}
module.exports = { bindingCount };
+129
View File
@@ -0,0 +1,129 @@
"use strict";
// Trusted host worker. Only host-selected fixture targets; no plugin paths or code.
const { bindingCount } = require("./sqliteFixtureSql.cjs");
const parentPort = { on: (event, listener) => process.on(event, listener), postMessage: (message) => process.send(message) };
process.on("disconnect", () => process.exit(0));
const { DatabaseSync, constants: C } = require("node:sqlite");
const { assertFileIdentity, descriptorSnapshot, bindSqliteDescriptor, assertSqliteDescriptor, MULTITABLE_FIXTURE_DIRECTORY } = require("./sqliteFileIdentity.cjs");
const path = require("node:path");
let db; let schema; let target; let nativeFd; let snapshotTarget;
const snapshotHeld = { fd: 5 };
const held = { fd: 4 };
function checkTarget() {
if (!target) return;
assertFileIdentity(target, held);
if (snapshotTarget) assertFileIdentity(snapshotTarget, snapshotHeld);
if (nativeFd !== undefined) assertSqliteDescriptor(snapshotTarget ?? target, nativeFd);
}
let mode = "read";
const safeFunctions = new Set(["count", "sum", "avg", "min", "max", "length", "lower", "upper", "substr", "substring", "coalesce", "ifnull", "nullif", "abs", "round", "typeof"]);
function initialize(selectedTarget, selectedSnapshot) {
target = selectedTarget; snapshotTarget = selectedSnapshot;
if (target?.sidecars) {
if (!snapshotTarget) throw new Error("Verified WAL snapshot required");
held.sidecars = { wal: { fd: 6 }, ...(target.sidecars.shm ? { shm: { fd: 7 } } : {}) };
}
checkTarget();
const before = target ? descriptorSnapshot() : null;
db = new DatabaseSync(target ? (snapshotTarget ? "/proc/self/fd/5" : "/proc/self/fd/4") : ":memory:", { allowExtension: false, readOnly: Boolean(target), timeout: 100 });
if (target) nativeFd = bindSqliteDescriptor(snapshotTarget ?? target, snapshotTarget ? snapshotHeld : held, before);
db.enableDefensive(true);
if (target) {
checkTarget();
db.exec("PRAGMA trusted_schema=OFF; PRAGMA query_only=ON;");
// Schema enumeration alone can admit damaged data pages. Check the held
// rollback image (or E's verified WAL-derived image) before any publication.
// Limit diagnostics to one; never send native text to the plugin. Native
// work stays inside the service's existing kill/cancel deadline.
if (db.prepare("PRAGMA main.integrity_check(1)").get()?.integrity_check !== "ok") {
throw new Error("SQLite fixture integrity unavailable");
}
checkTarget();
} else {
db.exec("CREATE TABLE notes(id INTEGER PRIMARY KEY CHECK(id BETWEEN 1 AND 1000), title TEXT NOT NULL CHECK(length(title)<=2048), status TEXT NOT NULL CHECK(length(status)<=128)); INSERT INTO notes VALUES(1,'Synthetic launch checklist','open'),(2,'Disposable fixture review','done'),(3,'Parameter binding example','open');");
}
// Only the new fixed disposable directory admits multi-table schemas. M2 and
// memory keep their notes-only surface. Never authorize sqlite_* or shadows.
const multi = target && path.dirname(target.path) === MULTITABLE_FIXTURE_DIRECTORY;
const objects = db.prepare("PRAGMA table_list").all().filter((t) => t.schema === "main"
&& (multi ? !t.name.toLowerCase().startsWith("sqlite_") : t.name === "notes"))
.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
if (!objects.length || objects.length > 32 || objects.some((t) => !["table", ...(multi ? ["view"] : [])].includes(t.type)
|| t.name.length > 64 || t.ncol > 32)) throw new Error("Fixture schema unavailable");
const quote = (name) => '"' + name.replaceAll('"', '""') + '"';
schema = { tables: objects.map((t) => {
const columns = db.prepare(`PRAGMA main.table_xinfo(${quote(t.name)})`).all();
if (columns.some((c) => c.hidden || c.name.length > 128 || c.type.length > 64)) throw new Error("Fixture columns unavailable");
// INTEGER PRIMARY KEY aliases rowid unless SQLite created a PK index (e.g.
// PRIMARY KEY DESC). Ordinary rowid tables can otherwise have nullable PKs.
const rowidPk = t.type === "table" && !t.wr && columns.filter((c) => c.pk).length === 1
&& !db.prepare(`PRAGMA main.index_list(${quote(t.name)})`).all().some((i) => i.origin === "pk");
return { name: t.name, kind: t.type, columns: columns.map((c) => ({
name: c.name, type: c.type || "ANY", primaryKey: c.pk > 0,
...(t.type === "table" ? { nullable: !(c.notnull || c.pk && (t.wr || t.strict || rowidPk && c.type.toUpperCase() === "INTEGER")) } : {}),
})) };
}) };
if (Buffer.byteLength(JSON.stringify(schema)) > 96 * 1024) throw new Error("Schema budget exceeded");
const readable = new Set(objects.map((t) => t.name));
db.setAuthorizer((action, arg1, arg2, database) => {
if (action === C.SQLITE_SELECT || action === C.SQLITE_RECURSIVE) return C.SQLITE_OK;
if (action === C.SQLITE_READ && (database === "main" || database === null) && readable.has(arg1)) return C.SQLITE_OK;
if (action === C.SQLITE_FUNCTION && safeFunctions.has(String(arg2).toLowerCase())) return C.SQLITE_OK;
if (!target && mode === "write" && database === "main" && arg1 === "notes" && [C.SQLITE_INSERT, C.SQLITE_UPDATE, C.SQLITE_DELETE].includes(action)) return C.SQLITE_OK;
return C.SQLITE_DENY;
});
checkTarget();
}
function scalar(value) {
if (typeof value === "bigint") return value.toString();
if (value instanceof Uint8Array) return `[BLOB ${value.byteLength} bytes: preview unavailable]`;
if (typeof value === "string") return value.slice(0, 2048);
if (typeof value === "number" && !Number.isFinite(value)) return String(value);
return value;
}
parentPort.on("message", ({ id, operation, request }) => {
const started = Date.now(); let statement; let fatal = !db;
try {
if (!db) initialize(request.target, request.snapshotTarget);
fatal = true;
checkTarget();
fatal = false;
if (target && request.mode === "write") throw new Error("File writes unavailable");
if (operation === "schema") { parentPort.postMessage({ id, result: schema }); return; }
if (bindingCount(request.sql) !== request.parameters.length) throw new Error("Binding count mismatch");
mode = request.mode;
statement = db.prepare(request.sql);
// prepare() otherwise silently ignores trailing statements. No scripts here.
if (request.sql.slice(statement.sourceSQL.length).trim()) throw new Error("Multiple statements are unavailable");
statement.setReadBigInts(true);
statement.setReturnArrays(true);
const columns = statement.columns().map((c) => c.name.slice(0, 128));
if (columns.length > 32) throw new Error("Column budget exceeded");
const parameters = request.parameters.map((v) => typeof v === "boolean" ? Number(v) : v);
const rows = []; let truncated = false; let changes = 0; let bytes = 0;
if (columns.length) {
// Writes with RETURNING are intentionally unavailable: stopping iteration
// would otherwise obscure statement completion and affected-row semantics.
if (mode === "write") throw new Error("Write RETURNING is unavailable");
for (const values of statement.iterate(...parameters)) {
const row = values.map(scalar); const size = Buffer.byteLength(JSON.stringify(row));
if (rows.length >= (request.maxRows ?? 100) || bytes + size > 96 * 1024) { truncated = true; break; }
if (values.some((v) => typeof v === "string" && v.length > 2048)) truncated = true;
rows.push(row); bytes += size;
}
} else {
if (mode !== "write") throw new Error("Read requires a result statement");
changes = Number(statement.run(...parameters).changes);
}
fatal = true;
checkTarget();
fatal = false;
parentPort.postMessage({ id, result: { columns, rows, changes, truncated, elapsedMs: Date.now() - started } });
} catch {
if (target) { try { checkTarget(); } catch { fatal = true; } }
// SQL diagnostics may contain input/values. Keep this public error bounded
// and content-free; the editor retains the user's statement locally.
parentPort.postMessage({ id, fatal, error: "Statement rejected or failed: check SQL, bindings and fixture-only restrictions" });
} finally { statement?.close?.(); mode = "read"; }
});
parentPort.postMessage({ ready: true });
+101
View File
@@ -0,0 +1,101 @@
"use strict";
const fs = require("node:fs");
const path = require("node:path");
const { createHash, randomUUID } = require("node:crypto");
const { MAX_FILE_BYTES, assertFileIdentity, holdFileIdentity, closeFileIdentity } = require("./sqliteFileIdentity.cjs");
const reject = () => { throw new Error("Stable committed WAL fixture required"); };
const magic = "53514c69746520666f726d6174203300";
// Deliberately narrow WAL reader: no recovery, tail salvage, reset-tail skipping
// or writer coordination. Format: https://sqlite.org/fileformat2.html#walformat
function committedWalImage(main, wal) {
if (main.length < 100 || main.length > MAX_FILE_BYTES || wal.length < 32 || wal.length > MAX_FILE_BYTES
|| main.subarray(0, 16).toString("hex") !== magic || main[18] !== 2 || main[19] !== 2) reject();
const pageSize = main.readUInt16BE(16) === 1 ? 65536 : main.readUInt16BE(16);
const marker = wal.readUInt32BE(0);
if (![0x377f0682, 0x377f0683].includes(marker) || wal.readUInt32BE(4) !== 3007000
|| pageSize < 512 || pageSize > 65536 || (pageSize & (pageSize - 1)) !== 0
|| wal.readUInt32BE(8) !== pageSize || main.length % pageSize
|| (wal.length - 32) % (pageSize + 24) || wal.length === 32) reject();
let a = 0; let b = 0;
const word = marker === 0x377f0682 ? (offset) => wal.readUInt32LE(offset) : (offset) => wal.readUInt32BE(offset);
const checksum = (start, end) => {
for (let offset = start; offset < end; offset += 8) {
a = (a + word(offset) + b) >>> 0; b = (b + word(offset + 4) + a) >>> 0;
}
};
checksum(0, 24);
if (a !== wal.readUInt32BE(24) || b !== wal.readUInt32BE(28)) reject();
const pages = new Map(); let committedSize = 0; let basePages = main.length / pageSize;
for (let offset = 32; offset < wal.length; offset += pageSize + 24) {
const page = wal.readUInt32BE(offset); const size = wal.readUInt32BE(offset + 4);
if (!page || page * pageSize > MAX_FILE_BYTES || size * pageSize > MAX_FILE_BYTES
|| !wal.subarray(offset + 8, offset + 16).equals(wal.subarray(16, 24))) reject();
checksum(offset, offset + 8); checksum(offset + 24, offset + 24 + pageSize);
if (a !== wal.readUInt32BE(offset + 16) || b !== wal.readUInt32BE(offset + 20)) reject();
pages.set(page, offset + 24);
committedSize = size; // Final frame MUST commit; no uncommitted tail salvage.
if (size) {
basePages = Math.min(basePages, size);
for (const p of pages.keys()) if (p > size) pages.delete(p);
}
}
if (!committedSize) reject();
const image = Buffer.alloc(committedSize * pageSize);
main.copy(image, 0, 0, Math.min(basePages * pageSize, image.length));
for (let page = 1; page <= committedSize; page++) {
const offset = pages.get(page);
if (offset !== undefined) wal.copy(image, (page - 1) * pageSize, offset, offset + pageSize);
else if (page > basePages) reject();
}
if (image.subarray(0, 16).toString("hex") !== magic || image.readUInt16BE(16) !== main.readUInt16BE(16)
|| image[18] !== 2 || image[19] !== 2 || image.readUInt32BE(28) !== committedSize
|| image.readUInt32BE(24) !== image.readUInt32BE(92)) reject();
image[18] = 1; image[19] = 1;
return image;
}
function readVerified(fd, target) {
const bytes = Buffer.alloc(Number(target.size));
for (let offset = 0; offset < bytes.length;) {
const count = fs.readSync(fd, bytes, offset, bytes.length - offset, offset);
if (!count) reject(); offset += count;
}
if (createHash("sha256").update(bytes).digest("hex") !== target.sha256) reject();
return bytes;
}
function createWalSnapshot(source) {
assertFileIdentity(source.target, source);
const main = readVerified(source.fd, source.target);
const wal = readVerified(source.sidecars.wal.fd, source.target.sidecars.wal);
const image = committedWalImage(main, wal);
assertFileIdentity(source.target, source);
// An owned derived fixture, never a plugin-controlled output or user path.
const file = path.join(path.dirname(source.target.path), `gate-e-snapshot-${randomUUID()}.sqlite`);
const directoryFd = source.directories?.at(-1)?.fd;
if (directoryFd === undefined) reject();
const anchoredPath = `/proc/self/fd/${directoryFd}/${path.basename(file)}`;
let fd; let held; let created = false;
try {
fd = fs.openSync(anchoredPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | fs.constants.O_NOFOLLOW, 0o600);
created = true; fs.writeFileSync(fd, image); fs.closeSync(fd); fd = undefined;
held = holdFileIdentity(file);
if (held.target.sha256 !== createHash("sha256").update(image).digest("hex")) reject();
assertFileIdentity(source.target, source);
return held;
} catch (error) {
if (fd !== undefined) fs.closeSync(fd);
closeFileIdentity(held);
if (created) { try { fs.unlinkSync(anchoredPath); } catch (cleanupError) { if (cleanupError.code !== "ENOENT") throw cleanupError; } }
throw error;
}
}
function removeWalSnapshot(snapshot) {
if (!snapshot) return;
// Retain the directory fd until unlink: never resolve mutable ancestors and
// never follow a substituted final symlink or recursively remove paths.
let removed = true;
try { fs.unlinkSync(snapshot.anchoredPath); }
catch (error) { removed = error.code === "ENOENT"; }
finally { closeFileIdentity(snapshot); }
return removed; // A hostile directory/permission replacement must not crash the host.
}
module.exports = { committedWalImage, createWalSnapshot, removeWalSnapshot };
+200
View File
@@ -0,0 +1,200 @@
"use strict";
const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const { randomUUID, createHash } = require("node:crypto");
const { DatabaseSync } = require("node:sqlite");
const { spawn } = require("node:child_process");
const { FIXTURE_DIRECTORY, MAX_FILE_BYTES, holdFileIdentity, closeFileIdentity, assertFileIdentity, descriptorSnapshot } = require("./sqliteFileIdentity.cjs");
const { committedWalImage, createWalSnapshot, removeWalSnapshot } = require("./sqliteWalSnapshot.cjs");
const linux = { skip: process.platform !== "linux" };
function fixture(t, pageSize = 4096) {
fs.mkdirSync(FIXTURE_DIRECTORY, { recursive: true });
const file = `${FIXTURE_DIRECTORY}/gate-e-test-${randomUUID()}.sqlite`;
const source = file + ".source";
const db = new DatabaseSync(source);
db.exec(`PRAGMA page_size=${pageSize}; CREATE TABLE notes(id INTEGER PRIMARY KEY,title TEXT); INSERT INTO notes VALUES(1,'main'); PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0; INSERT INTO notes VALUES(2,'committed WAL'); UPDATE notes SET title='latest WAL' WHERE id=1;`);
for (const suffix of ["", "-wal", "-shm"]) fs.copyFileSync(source + suffix, file + suffix);
db.close(); fs.rmSync(source);
t.after(() => { for (const suffix of ["", "-wal", "-shm", "-journal", ".old", "-wal.old", "-shm.old"]) fs.rmSync(file + suffix, { force: true }); });
return file;
}
function hold(t, file) { const held = holdFileIdentity(file, { allowWal: true }); t.after(() => closeFileIdentity(held)); return held; }
const sha = (file) => createHash("sha256").update(fs.readFileSync(file)).digest("hex");
test("committed WAL snapshots read latest rows across page sizes without source SHM changes", linux, (t) => {
for (const size of [512, 4096, 65536]) {
const file = fixture(t, size); const before = ["", "-wal", "-shm"].map((s) => sha(file + s));
const held = hold(t, file); const snapshot = createWalSnapshot(held);
try {
const db = new DatabaseSync(`/proc/self/fd/${snapshot.fd}`, { readOnly: true });
try { assert.deepEqual(db.prepare("SELECT title FROM notes ORDER BY id").all().map((r) => r.title), ["latest WAL", "committed WAL"]); }
finally { db.close(); }
assertFileIdentity(held.target, held);
assert.deepEqual(["", "-wal", "-shm"].map((s) => sha(file + s)), before);
assert.ok(!fs.existsSync(snapshot.target.path + "-shm"));
} finally { removeWalSnapshot(snapshot); }
}
});
test("WAL parser rejects damaged checksums, salts, format, partial frames and uncommitted tail", linux, (t) => {
const file = fixture(t); const main = fs.readFileSync(file); const wal = fs.readFileSync(file + "-wal");
for (const offset of [0, 4, 8, 16, 24, 32, 36, 40, 48, 56, wal.length - 1]) {
const corrupt = Buffer.from(wal); corrupt[offset] ^= 1;
assert.throws(() => committedWalImage(main, corrupt), /Stable committed/);
}
for (const length of [0, 31, 32, 33, wal.length - 1]) assert.throws(() => committedWalImage(main, wal.subarray(0, length)));
assert.throws(() => committedWalImage(main, Buffer.alloc(MAX_FILE_BYTES + 1)));
const invalidMain = Buffer.from(main); invalidMain[18] = 1; assert.throws(() => committedWalImage(invalidMain, wal));
// Recompute valid checksums after structural changes, testing beyond bitrot.
const resign = (bytes) => {
let a = 0; let b = 0;
const sum = (start, end) => { for (let i = start; i < end; i += 8) { a = (a + bytes.readUInt32LE(i) + b) >>> 0; b = (b + bytes.readUInt32LE(i + 4) + a) >>> 0; } };
sum(0, 24); bytes.writeUInt32BE(a, 24); bytes.writeUInt32BE(b, 28);
for (let i = 32; i < bytes.length; i += 4120) { sum(i, i + 8); sum(i + 24, i + 4120); bytes.writeUInt32BE(a, i + 16); bytes.writeUInt32BE(b, i + 20); }
return bytes;
};
for (const [offset, value] of [[wal.length - 4120 + 4, 0], [32, 0], [32, 1000000], [36, 1000000]]) {
const bytes = Buffer.from(wal); bytes.writeUInt32BE(value, offset); resign(bytes);
assert.throws(() => committedWalImage(main, bytes), /Stable committed/);
}
});
test("both sidecars reject symlinks, external links, hardlinks, rename, delete/recreate, ABA and rewrite", linux, (t) => {
const baseline = descriptorSnapshot();
for (const suffix of ["-wal", "-shm"]) for (const attack of ["symlink", "dangling", "external", "hardlink", "rename", "recreate", "aba", "rewrite"]) {
const file = fixture(t); const other = fixture(t); const held = hold(t, file);
const original = fs.readFileSync(file + suffix);
if (attack === "rewrite") { const changed = Buffer.from(original); changed[changed.length - 1] ^= 1; fs.writeFileSync(file + suffix, changed); }
else {
fs.renameSync(file + suffix, file + suffix + ".old");
if (attack === "symlink") fs.symlinkSync(other + suffix, file + suffix);
if (attack === "dangling") fs.symlinkSync(other + ".missing", file + suffix);
if (attack === "external") fs.symlinkSync("/etc/passwd", file + suffix);
if (attack === "hardlink") fs.linkSync(other + suffix, file + suffix);
if (["rename", "recreate", "aba"].includes(attack)) fs.writeFileSync(file + suffix, original);
if (attack === "aba") { fs.unlinkSync(file + suffix); fs.renameSync(file + suffix + ".old", file + suffix); }
}
assert.throws(() => assertFileIdentity(held.target, held), undefined, `${suffix} ${attack}`);
assert.throws(() => createWalSnapshot(held));
if (["symlink", "dangling", "external", "hardlink"].includes(attack)) assert.throws(() => holdFileIdentity(file, { allowWal: true }));
closeFileIdentity(held);
}
assert.deepEqual(descriptorSnapshot(), baseline);
});
test("optional SHM absence is bound; journal and WAL absence reject; source main races remain rejected", linux, (t) => {
const file = fixture(t); fs.unlinkSync(file + "-shm"); const held = hold(t, file);
const snapshot = createWalSnapshot(held); removeWalSnapshot(snapshot);
fs.writeFileSync(file + "-shm", Buffer.alloc(32)); assert.throws(() => assertFileIdentity(held.target, held));
fs.unlinkSync(file + "-shm"); fs.symlinkSync("/not-present", file + "-journal");
assert.throws(() => holdFileIdentity(file, { allowWal: true })); fs.unlinkSync(file + "-journal");
fs.unlinkSync(file + "-wal"); assert.throws(() => holdFileIdentity(file, { allowWal: true }));
const bytes = fs.readFileSync(file); bytes[100] ^= 1; fs.writeFileSync(file, bytes);
assert.throws(() => assertFileIdentity(held.target, held));
});
test("held WAL identities fail closed during separate-process hostile sidecar replacement", linux, async (t) => {
const file = fixture(t); const held = hold(t, file);
const child = spawn(process.execPath, ["-e", `
const fs=require('node:fs');const file=process.argv[1];let rounds=0;
const wal=fs.readFileSync(file+'-wal');
function race(){fs.rmSync(file+'-wal',{force:true});fs.symlinkSync('/etc/passwd',file+'-wal');
fs.rmSync(file+'-wal',{force:true});fs.writeFileSync(file+'-wal',wal);
if(++rounds===1)process.send('ready');setImmediate(race);}
race();
`, file], { env: { ELECTRON_RUN_AS_NODE: "1" }, stdio: ["ignore", "ignore", "ignore", "ipc"] });
t.after(() => child.kill("SIGKILL"));
await new Promise((resolve, reject) => { child.once("message", resolve); child.once("error", reject); });
for (let i = 0; i < 100; i++) assert.throws(() => createWalSnapshot(held));
const exited = new Promise((resolve) => child.once("exit", resolve)); child.kill("SIGKILL"); await exited;
});
test("actual WAL worker audits the snapshot inode before schema, including native-open ABA", linux, async (t) => {
const file = fixture(t); const held = hold(t, file); const snapshot = createWalSnapshot(held);
t.after(() => removeWalSnapshot(snapshot));
const attackerSource = hold(t, fixture(t)); const attacker = createWalSnapshot(attackerSource);
t.after(() => removeWalSnapshot(attacker));
const child = spawn(process.execPath, ["-e", `
const sqlite=require('node:sqlite');const Native=sqlite.DatabaseSync;
sqlite.DatabaseSync=class extends Native {
constructor(file,options){if(file!=='/proc/self/fd/5')throw new Error('Expected snapshot fd');super(process.argv[1],options);}
prepare(...args){process.send({unexpectedStatement:true});return super.prepare(...args);}
exec(...args){process.send({unexpectedStatement:true});return super.exec(...args);}
};require(process.argv[2]);
`, attacker.target.path, require.resolve("./sqliteFixtureWorker.cjs")], {
env: { ELECTRON_RUN_AS_NODE: "1", NODE_NO_WARNINGS: "1" },
stdio: ["ignore", "ignore", "ignore", "ipc", held.fd, snapshot.fd, held.sidecars.wal.fd, held.sidecars.shm.fd],
});
t.after(() => child.kill("SIGKILL"));
const next = () => new Promise((resolve, reject) => { child.once("message", resolve); child.once("error", reject); });
assert.deepEqual(await next(), { ready: true }); const response = next();
child.send({ id: "wal-aba", operation: "schema", request: { target: held.target, snapshotTarget: snapshot.target } });
const result = await response; assert.equal(result.fatal, true); assert.equal(result.result, undefined); assert.equal(result.unexpectedStatement, undefined);
assertFileIdentity(held.target, held); assertFileIdentity(snapshot.target, snapshot);
const exited = new Promise((resolve) => child.once("exit", resolve)); child.kill("SIGKILL"); await exited;
});
test("derived fixture creation and cleanup use held directory aliases, including failed admission", linux, (t) => {
const file = fixture(t); const held = hold(t, file);
const originalOpen = fs.openSync; const originalUnlink = fs.unlinkSync;
const created = []; const removed = [];
let failAdmission = false;
fs.openSync = (name, flags, ...args) => {
if (typeof name === "string" && name.includes("gate-e-snapshot-")) {
assert.match(name, /^\/proc\/self\/fd\/\d+\/gate-e-snapshot-/);
if (flags & fs.constants.O_CREAT) { created.push(name); assert.ok(flags & fs.constants.O_EXCL); }
else if (failAdmission) throw new Error("Synthetic ancestor replacement after creation");
}
return originalOpen(name, flags, ...args);
};
fs.unlinkSync = (name) => {
if (name.includes("gate-e-snapshot-")) { assert.match(name, /^\/proc\/self\/fd\/\d+\/gate-e-snapshot-/); removed.push(name); }
return originalUnlink(name);
};
try {
const snapshot = createWalSnapshot(held); const file = snapshot.target.path;
removeWalSnapshot(snapshot); assert.equal(fs.existsSync(file), false);
failAdmission = true; assert.throws(() => createWalSnapshot(held), /Synthetic ancestor/);
assert.equal(created.length, 2); assert.equal(removed.length, 2);
assert.ok(created.every((name) => !fs.existsSync(name)));
} finally { fs.openSync = originalOpen; fs.unlinkSync = originalUnlink; }
});
test("hostile derived output replacement cannot crash cleanup or retain descriptors", linux, (t) => {
const held = hold(t, fixture(t)); const before = descriptorSnapshot();
const snapshot = createWalSnapshot(held); const file = snapshot.target.path;
fs.unlinkSync(snapshot.anchoredPath); fs.mkdirSync(snapshot.anchoredPath);
try { assert.equal(removeWalSnapshot(snapshot), false); assert.deepEqual(descriptorSnapshot(), before); }
finally { fs.rmdirSync(file); }
});
test("admission ages captured timestamps before immediate same-inode main/WAL/SHM rename-restore ABA", linux, (t) => {
// No delay in the attack: this reproduced E's same-tick ctime false negative.
// The product admission fence, not test timing, separates capture from attack.
for (const suffix of ["", "-wal", "-shm"]) for (let attempt = 0; attempt < 12; attempt++) {
const file = fixture(t); const held = hold(t, file);
const expected = suffix ? held.target.sidecars[suffix.slice(1)] : held.target;
assert.ok(BigInt(Date.now()) * 1000000n - BigInt(expected.ctime) >= 49000000n);
const before = fs.readFileSync(file + suffix); const renamed = file + suffix + ".old";
fs.renameSync(file + suffix, renamed);
fs.writeFileSync(file + suffix, before);
fs.unlinkSync(file + suffix); fs.renameSync(renamed, file + suffix);
assert.equal(String(fs.statSync(file + suffix, { bigint: true }).ino), expected.ino);
assert.deepEqual(fs.readFileSync(file + suffix), before);
assert.throws(() => assertFileIdentity(held.target, held));
assert.throws(() => createWalSnapshot(held));
closeFileIdentity(held);
}
t.diagnostic(JSON.stringify({ immediateRestoredNameAttempts: 36, allRejected: true }));
});
test("admission rejects unsupported future capture clocks and closes every held fd", linux, (t) => {
const file = fixture(t); const baseline = descriptorSnapshot();
const now = Date.now;
try {
Date.now = () => now() - 1000;
assert.throws(() => holdFileIdentity(file, { allowWal: true }), /timestamp/);
} finally { Date.now = now; }
assert.deepEqual(descriptorSnapshot(), baseline);
});
+8
View File
@@ -9,11 +9,19 @@ class PluginViewResources {
this.rasterize = createBoundedIconRasterizer(createIsolatedContributionIconRasterizer(electron), { maxConcurrent: 2, maxQueued: 16 });
}
async image(plugin, resource) {
const brand = typeof resource === 'string' && resource.startsWith('brand:');
if (brand) resource = resource.slice(6);
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');
// UI brand rasters share metadata.brand-icon's static PNG/WebP bounds,
// then go through the existing isolated decoder. SVG handling is unchanged.
if (brand) {
const { inspectPluginBrandIcon } = await import('@netcatty/plugin-contract');
inspectPluginBrandIcon(file.body, resource);
}
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');
@@ -21,3 +21,15 @@ test('view images reject traversal, symlink escapes, external SVGs and oversize
}
assert.equal(decoded, 0);
});
test('brand view resources use the static brand contract before isolated decoding', async (t) => {
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'netcatty-view-brand-'));
t.after(() => fs.rm(directory, { recursive: true, force: true }));
const resources = new PluginViewResources({ electron: {}, packageStore: { preparePackageRoot: async () => directory } });
let decoded = 0; resources.rasterize = async () => { decoded++; throw new Error('Unexpected decoding'); };
await fs.writeFile(path.join(directory, 'engine.svg'), '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"/>');
await assert.rejects(resources.image({}, 'brand:engine.svg'), /PNG or WebP/);
await fs.writeFile(path.join(directory, 'engine.png'), Buffer.alloc(256 * 1024 + 1));
await assert.rejects(resources.image({}, 'brand:engine.png'), /size/);
for (const name of ['brand:../secret.png', 'brand:https://example.invalid/a.png', 'brand:/tmp/a.png']) await assert.rejects(resources.image({}, name), /path/);
assert.equal(decoded, 0);
});
+3 -2
View File
@@ -373,10 +373,11 @@ function validateSemantics(manifest: PluginManifest): string[] {
.some((declaration) => permissionName(declaration) === "network.stream");
if (hasByteStreams && !requiredFeatures.has("network.byte-streams")) errors.push("Byte streams require network.byte-streams");
const declaredCapabilityNames = new Set([...(manifest.permissions?.required ?? []), ...(manifest.permissions?.optional ?? [])].map(permissionName));
if (declaredCapabilityNames.has("ai.invoke") && !requiredFeatures.has("ai.model-invocation")) errors.push("AI invocation requires ai.model-invocation");
const allFeatures = new Set([...requiredFeatures, ...(manifest.features?.optional ?? [])]);
// AI can enhance a view without making the whole plugin require a model host.
if (declaredCapabilityNames.has("ai.invoke") && !allFeatures.has("ai.model-invocation")) errors.push("AI invocation requires ai.model-invocation");
if ((declaredCapabilityNames.has("context.selected.list") || declaredCapabilityNames.has("context.selected.read"))
&& !requiredFeatures.has("context.selected-read")) errors.push("Selected context requires context.selected-read");
const allFeatures = new Set([...requiredFeatures, ...(manifest.features?.optional ?? [])]);
for (const [permission, feature] of [['terminal.selection.read', 'terminal.selection-sharing'], ['terminal.input.propose', 'terminal.input-drafts']]) {
if ((manifest.permissions?.optional ?? []).some((p) => permissionName(p) === permission) && !allFeatures.has(feature)) errors.push(`${permission} requires ${feature}`);
}
@@ -0,0 +1,31 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { validateManifestValue } from './manifest.js';
import { checkPluginCompatibility } from './compatibility.js';
import type { PluginManifest } from '@netcatty/plugin-contract';
const manifest: PluginManifest = {
manifestVersion: 1, id: 'com.example.sql-draft', name: 'sql-draft', displayName: 'SQL draft',
version: '0.1.0', publisher: 'example', license: 'MIT',
engines: { netcatty: '>=0.0.0', api: '>=0.1.0-internal.1 <0.2.0' },
main: { browser: 'browser.js' }, activationEvents: ['onStartupFinished'],
features: { optional: ['ai.model-invocation'] },
permissions: { optional: [{ permission: 'ai.invoke', resources: ['*'], reason: 'Unexecuted drafts' }] },
};
test('optional AI declaration loads without host AI and negotiates it only when supported', () => {
assert.equal(validateManifestValue(manifest).valid, true, JSON.stringify(validateManifestValue(manifest).errors));
for (const features of [[], ['ai.model-invocation']]) {
const result = checkPluginCompatibility(manifest, { netcattyVersion: '0.0.0', features });
assert.equal(result.compatible, true);
assert.deepEqual(result.enabledFeatures, features);
}
});
test('AI permission still requires a declared feature; required feature still blocks incompatible hosts', () => {
const missing = structuredClone(manifest); missing.features = {};
assert.equal(validateManifestValue(missing).valid, false);
const required = structuredClone(manifest); required.features = { required: ['ai.model-invocation'] };
assert.equal(validateManifestValue(required).valid, true);
assert.equal(checkPluginCompatibility(required, { netcattyVersion: '0.0.0', features: [] }).compatible, false);
});
+2 -1
View File
@@ -13,7 +13,8 @@
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
},
"./schema/plugin-contract.schema.json": "./schema/plugin-contract.schema.json"
"./schema/plugin-contract.schema.json": "./schema/plugin-contract.schema.json",
"./schema/database-drivers.json": "./schema/database-drivers.json"
},
"scripts": {
"build": "tsc -p tsconfig.build.json"
@@ -0,0 +1,524 @@
[
{
"id": "sqlite",
"label": "SQLite",
"category": "lightweight",
"wireFamily": "sqlite",
"defaultPort": 0,
"fields": [
"source"
],
"icon": "sqlite",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "fixture"
},
{
"id": "postgres",
"label": "PostgreSQL",
"category": "relational",
"wireFamily": "postgres",
"defaultPort": 5432,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "postgresql",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "wire"
},
{
"id": "mysql",
"label": "MySQL",
"category": "relational",
"wireFamily": "mysql",
"defaultPort": 3306,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "mysql",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "wire"
},
{
"id": "mariadb",
"label": "MariaDB",
"category": "relational",
"wireFamily": "mysql",
"defaultPort": 3306,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "mariadb",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "wire"
},
{
"id": "goldendb",
"label": "GoldenDB",
"category": "domestic",
"wireFamily": "mysql",
"defaultPort": 3306,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "goldendb",
"source": "plugins/connection-types/profiles/catalog.yaml; plugins/connection-types/goldendb.yaml; crates/dbx-sql-dialect/src/sql_dialect/descriptor.rs; agents/drivers/goldendb/src/main/java/com/dbx/agent/goldendb/GoldendbAgent.java buildUrl jdbc:mysql",
"qualification": "alias",
"variants": [
{
"id": "goldendb-mysql",
"label": "GoldenDB / MySQL endpoint",
"defaultPort": 3306,
"wireFamily": "mysql",
"authPolicy": "mysql",
"metadata": "mysql",
"modeCheck": "none"
}
]
},
{
"id": "opengauss",
"label": "openGauss",
"category": "domestic",
"wireFamily": "postgres",
"defaultPort": 5432,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "opengauss",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "alias",
"variants": [
{
"id": "opengauss-pg",
"label": "openGauss / PG-compatible endpoint",
"defaultPort": 5432,
"wireFamily": "postgres",
"authPolicy": "gauss-legacy",
"metadata": "pg",
"modeCheck": "pg-compatibility"
}
]
},
{
"id": "gaussdb",
"label": "GaussDB",
"category": "domestic",
"wireFamily": "postgres",
"defaultPort": 5432,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "gaussdb",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "alias",
"variants": [
{
"id": "gaussdb-dws",
"label": "GaussDB DWS",
"defaultPort": 8000,
"wireFamily": "postgres",
"authPolicy": "gauss-legacy",
"metadata": "pg",
"modeCheck": "none"
},
{
"id": "gaussdb-mysql",
"label": "GaussDB for MySQL",
"defaultPort": 3306,
"wireFamily": "mysql",
"authPolicy": "mysql",
"metadata": "mysql",
"modeCheck": "none"
},
{
"id": "gaussdb-native",
"label": "GaussDB native / M-compatible",
"defaultPort": 5432,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
}
]
},
{
"id": "kingbase",
"label": "KingbaseES",
"category": "domestic",
"wireFamily": "postgres",
"defaultPort": 54321,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "kingbase",
"source": "plugins/connection-types/profiles/catalog.yaml; plugins/connection-types/kingbase.yaml; crates/dbx-sql-dialect/src/sql_dialect/descriptor.rs",
"qualification": "alias",
"variants": [
{
"id": "kingbase-pg",
"label": "KingbaseES / PG mode",
"defaultPort": 54321,
"wireFamily": "postgres",
"authPolicy": "postgres",
"metadata": "sys",
"modeCheck": "none"
},
{
"id": "kingbase-oracle",
"label": "KingbaseES / Oracle mode",
"defaultPort": 54321,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
}
]
},
{
"id": "highgo",
"label": "HighGo",
"category": "domestic",
"wireFamily": "postgres",
"defaultPort": 5866,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "highgo",
"source": "plugins/connection-types/profiles/catalog.yaml; plugins/connection-types/highgo.yaml; crates/dbx-sql-dialect/src/sql_dialect/descriptor.rs",
"qualification": "alias",
"variants": [
{
"id": "highgo-pg",
"label": "HighGo / PG-compatible edition",
"defaultPort": 5866,
"wireFamily": "postgres",
"authPolicy": "postgres",
"metadata": "pg",
"modeCheck": "none"
},
{
"id": "highgo-secure",
"label": "HighGo / secure or national-crypto edition",
"defaultPort": 5866,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
}
]
},
{
"id": "vastbase",
"label": "Vastbase",
"category": "domestic",
"wireFamily": "postgres",
"defaultPort": 5432,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "vastbase",
"source": "plugins/connection-types/profiles/catalog.yaml; plugins/connection-types/vastbase.yaml; crates/dbx-sql-dialect/src/sql_dialect/descriptor.rs",
"qualification": "alias",
"variants": [
{
"id": "vastbase-g100-pg",
"label": "Vastbase G100 / PG mode",
"defaultPort": 5432,
"wireFamily": "postgres",
"authPolicy": "gauss-legacy",
"metadata": "pg",
"modeCheck": "pg-compatibility"
},
{
"id": "vastbase-g100-other",
"label": "Vastbase G100 / other modes",
"defaultPort": 5432,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
},
{
"id": "vastbase-e100",
"label": "Vastbase E100",
"defaultPort": 5432,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
}
]
},
{
"id": "uxdb",
"label": "UXDB",
"category": "domestic",
"wireFamily": "postgres",
"defaultPort": 52025,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": null,
"source": "plugins/connection-types/profiles/catalog.yaml; plugins/connection-types/uxdb.yaml; crates/dbx-sql-dialect/src/sql_dialect/descriptor.rs",
"qualification": "alias"
},
{
"id": "gbase8c",
"label": "GBase",
"category": "domestic",
"wireFamily": "unpackaged",
"defaultPort": 5432,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "gbase8c",
"source": "plugins/connection-types/profiles/catalog.yaml; agents/drivers/gbase8c/src/main/java/com/dbx/agent/gbase8c/Gbase8cAgent.java requires vendor driver",
"qualification": "catalog",
"variants": [
{
"id": "gbase-8c",
"label": "GBase 8c",
"defaultPort": 5432,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
},
{
"id": "gbase-8a",
"label": "GBase 8a",
"defaultPort": 5258,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
},
{
"id": "gbase-8s",
"label": "GBase 8s",
"defaultPort": 9088,
"wireFamily": "unpackaged",
"authPolicy": "none",
"metadata": "none",
"modeCheck": "none"
}
]
},
{
"id": "tidb",
"label": "TiDB",
"category": "domestic",
"wireFamily": "mysql",
"defaultPort": 4000,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "tidb",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "alias"
},
{
"id": "oceanbase",
"label": "OceanBase",
"category": "domestic",
"wireFamily": "mysql",
"defaultPort": 2883,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": null,
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "alias"
},
{
"id": "dameng",
"label": "Dameng",
"category": "domestic",
"wireFamily": "unpackaged",
"defaultPort": 5236,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": null,
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
},
{
"id": "oracle",
"label": "Oracle",
"category": "relational",
"wireFamily": "unpackaged",
"defaultPort": 1521,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": null,
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
},
{
"id": "sqlserver",
"label": "SQL Server",
"category": "relational",
"wireFamily": "unpackaged",
"defaultPort": 1433,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": null,
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
},
{
"id": "clickhouse",
"label": "ClickHouse",
"category": "analytics",
"wireFamily": "unpackaged",
"defaultPort": 8123,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "clickhouse",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
},
{
"id": "redis",
"label": "Redis",
"category": "document",
"wireFamily": "unpackaged",
"defaultPort": 6379,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "redis",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
},
{
"id": "mongodb",
"label": "MongoDB",
"category": "document",
"wireFamily": "unpackaged",
"defaultPort": 27017,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "mongodb",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
},
{
"id": "firebird",
"label": "Firebird",
"category": "relational",
"wireFamily": "unpackaged",
"defaultPort": 3050,
"fields": [
"hostname",
"port",
"database",
"username",
"password",
"tls"
],
"icon": "firebird",
"source": "plugins/connection-types/profiles/catalog.yaml",
"qualification": "catalog"
}
]
File diff suppressed because it is too large. Load diff
@@ -21,6 +21,17 @@ function validator(definition: string) {
return ajv.compile({ $ref: `${schema.$id}#/$defs/${definition}` });
}
test("database schema accepts legacy columns and bounded table/view structure metadata", () => {
const validate = validator("DatabaseSchemaResult");
const column = { name: "id", type: "INTEGER", primaryKey: true };
assert.ok(validate({ tables: [{ name: "notes", columns: [column] }] }));
const tables = Array.from({ length: 32 }, (_, i) => ({ name: `object_${i}`, kind: i % 2 ? "view" : "table", columns: [{ ...column, nullable: false }] }));
assert.ok(validate({ tables }));
assert.equal(validate({ tables: [...tables, tables[0]] }), false);
assert.equal(validate({ tables: [{ ...tables[0], kind: "virtual" }] }), false);
assert.equal(validate({ tables: [{ ...tables[0], columns: [{ ...column, nullable: "unknown" }] }] }), false);
});
const validManifest = {
manifestVersion: 1,
id: "com.example.contract-test",
@@ -337,6 +348,8 @@ test("required resource-scoped permissions declare activation-time bounds", () =
["filesystem.read", "/tmp/plugin-read"],
["filesystem.write", "/tmp/plugin-write"],
["companion.execute", "com.example.contract-test.helper"],
["database.query.read", "sqlite:synthetic-notes"],
["database.query.write", "sqlite:synthetic-notes"],
] as const;
assert.deepEqual(
schema.$defs.ResourceScopedPermission.enum,
@@ -1492,3 +1505,52 @@ test("settings accept host-owned groups but reject custom rendering and settings
assert.equal(view({ id: "com.example.contract-test.view", title: "Custom", location }), true, JSON.stringify(view.errors));
}
});
test("synthetic tunnel contracts cannot carry credentials, destinations or connected handles", () => {
const request = validator("DatabaseTunnelTestRequest");
const params = { hostId: "fixture-host", revision: "fixture-revision", testId: "fixture-test" };
assert.ok(request(params));
for (const extra of [{ password: "fixture-only" }, { secretRef: "foreign" }, { destination: "external.invalid" }, { port: 5432 }]) assert.equal(request({ ...params, ...extra }), false);
const result = validator("DatabaseTunnelTestResult");
const value = { status: "synthetic-passed", code: "SYNTHETIC_OK", synthetic: true, connected: false, closed: true };
assert.ok(result(value));
for (const extra of [{ connected: true }, { handleId: "connected-handle" }, { password: "fixture-only" }, { synthetic: false }]) assert.equal(result({ ...value, ...extra }), false);
const meta = validator("DatabaseHostMeta");
const host = { hostId: "fixture", hostname: "127.0.0.1", label: "Synthetic", port: 2222, username: "smoketest", capability: "metadata-only", tunnelAvailable: false };
assert.ok(meta(host)); assert.ok(meta({ ...host, tunnelTest: { kind: "synthetic", revision: "fixture-revision" } }));
assert.equal(meta({ ...host, tunnelAvailable: true }), false);
});
test("host port probe schema rejects plugin destinations and cannot represent an authenticated session", () => {
const request = validator("DatabaseHostPortProbeRequest");
const params = { hostId: "saved", revision: "revision", probeId: "probe" };
assert.ok(request(params));
for (const extra of [{ hostname: "evil.invalid" }, { destination: "evil.invalid" }, { port: 22 }, { ports: [22] }, { password: "secret" }]) assert.equal(request({ ...params, ...extra }), false);
const result = validator("DatabaseHostPortProbeResult");
const value = { hostId: "saved", hostname: "127.0.0.1", code: "PROBE_OK", synthetic: false, connected: false, ports: [{ port: 5432, serviceLabel: "PostgreSQL", status: "open", latencyMs: 1 }] };
assert.ok(result(value));
for (const extra of [{ connected: true }, { synthetic: true }, { handleId: "session" }]) assert.equal(result({ ...value, ...extra }), false);
assert.equal(result({ ...value, ports: [{ ...value.ports[0], port: 22 }] }), false);
assert.equal(result({ ...value, ports: [{ ...value.ports[0], status: "authenticated" }] }), false);
});
test("live SSH PostgreSQL contract requires authentic fixture proof and rejects dial or SQL fields", () => {
const request = validator("DatabaseHostLiveSshPgOpenRequest");
const params = { hostId: "fixture", revision: "revision", openId: "open" };
assert.ok(request(params));
for (const field of ["host", "port", "destination", "username", "privateKey", "password", "sql", "pin"]) assert.equal(request({ ...params, [field]: "forged" }), false);
const result = validator("DatabaseHostLiveSshPgOpenResult");
const success = { code: "LIVE_OK", fixture: true, synthetic: false, connected: true, sessionId: "session", expiresAt: 1234, proof: { query: "SELECT 1", value: 1, pinnedHostKey: true }, secretRef: "opaque-reference-one", pgSecretRef: "opaque-reference-two" };
assert.ok(result(success));
for (const mutation of [{ proof: undefined }, { connected: false }, { synthetic: true }, { code: "SYNTHETIC_OK" }, { proof: { query: "SELECT 1", value: 0, pinnedHostKey: true } }]) assert.equal(result({ ...success, ...mutation }), false);
const failed = { code: "AUTH_FAILED", fixture: true, synthetic: false, connected: false };
assert.ok(result(failed)); assert.equal(result({ ...failed, sessionId: "leaked" }), false);
});
test("brand view resources keep relative package paths in the shared IPC contract", () => {
const validate = validator("PluginViewResourceRequest");
assert.equal(validate({ instanceId: "one", path: "assets/sqlite.png", kind: "brand-icon" }), true);
for (const path of ["brand:assets/sqlite.png", "../secret.png", "https://example.invalid/a.png"]) assert.equal(validate({ instanceId: "one", path, kind: "brand-icon" }), false);
assert.equal(validate({ instanceId: "one", path: "a.png", kind: "arbitrary-svg" }), false);
});
@@ -192,6 +192,274 @@ export type CredentialRef = {
id: string;
};
export type DatabaseConnectionIdRequest = {
id: DatabaseHandle;
};
export type DatabaseConnectionMeta = {
name: string;
color: "default" | "blue" | "green" | "purple" | "orange";
hostId?: string;
};
export type DatabaseDriverId = "sqlite" | "postgres" | "mysql" | "mariadb" | "goldendb" | "opengauss" | "gaussdb" | "kingbase" | "highgo" | "vastbase" | "uxdb" | "gbase8c" | "tidb" | "oceanbase" | "dameng" | "oracle" | "sqlserver" | "clickhouse" | "redis" | "mongodb" | "firebird";
export type DatabaseDriverProfile = {
id: DatabaseDriverId;
label: string;
category: "lightweight" | "relational" | "domestic" | "analytics" | "document";
wireFamily: "sqlite" | "postgres" | "mysql" | "unpackaged";
defaultPort: number;
fields: Array<string>;
icon: string | null;
source: string;
qualification: "fixture" | "wire" | "alias" | "catalog";
variants?: Array<DatabaseDriverVariant>;
};
export type DatabaseDriverVariant = {
id: DatabaseVariantId;
label: string;
defaultPort: number;
wireFamily: "postgres" | "mysql" | "unpackaged";
authPolicy: "postgres" | "gauss-legacy" | "mysql" | "none";
metadata: "pg" | "sys" | "mysql" | "none";
modeCheck: "none" | "pg-compatibility";
};
export type DatabaseEmptyRequest = Record<string, never>;
export type DatabaseFileFixtureFeature = "database.sqlite-file-fixture.v1";
export type DatabaseFileOpenResult = {
handleId: DatabaseHandle;
revision: DatabaseHandle;
engine: "sqlite";
label: "Disposable SQLite file (read-only)";
fixture: true;
readOnly: true;
};
export type DatabaseFixtureFeature = "database.sqlite-fixture.v1";
export type DatabaseHandle = string;
export type DatabaseHandleRequest = {
handleId: DatabaseHandle;
revision?: DatabaseHandle;
};
export type DatabaseHostList = Array<DatabaseHostMeta>;
export type DatabaseHostLiveSshPgCancelRequest = {
openId: DatabaseHandle;
};
export type DatabaseHostLiveSshPgCapability = {
kind: "fixture";
revision: DatabaseHandle;
};
export type DatabaseHostLiveSshPgCloseRequest = {
sessionId: DatabaseHandle;
};
export type DatabaseHostLiveSshPgCloseResult = {
fixture: true;
connected: false;
closed: true;
};
export type DatabaseHostLiveSshPgFeature = "database.host-live-ssh-pg.fixture.v1";
export type DatabaseHostLiveSshPgOpenRequest = {
hostId: string;
revision: DatabaseHandle;
openId: DatabaseHandle;
};
export type DatabaseHostLiveSshPgOpenResult = ({
code: "LIVE_OK";
fixture: true;
synthetic: false;
connected: true;
sessionId: DatabaseHandle;
expiresAt: number;
proof: {
query: "SELECT 1";
value: 1;
pinnedHostKey: true;
};
secretRef: string;
pgSecretRef: string;
}) | ({
code: "AUTH_FAILED" | "UNKNOWN_HOST_KEY" | "HOST_KEY_MISMATCH" | "UNKNOWN_HOST" | "STALE_HOST" | "CANCELLED" | "DEADLINE_EXCEEDED" | "UNAVAILABLE";
fixture: true;
synthetic: false;
connected: false;
});
export type DatabaseHostMeta = {
hostId: string;
label: string;
hostname: string;
port: number;
username: string;
capability: "metadata-only";
tunnelAvailable: false;
tunnelTest?: DatabaseTunnelTestCapability;
portProbe?: DatabaseHostPortProbeCapability;
liveSshPg?: DatabaseHostLiveSshPgCapability;
};
export type DatabaseHostPortProbeCancelRequest = {
probeId: DatabaseHandle;
};
export type DatabaseHostPortProbeCapability = {
revision: DatabaseHandle;
};
export type DatabaseHostPortProbeFeature = "database.host-port-probe.v1";
export type DatabaseHostPortProbeRequest = {
hostId: string;
revision: DatabaseHandle;
probeId: DatabaseHandle;
};
export type DatabaseHostPortProbeResult = {
hostId: string;
hostname?: string;
synthetic: false;
connected: false;
ports: Array<DatabaseHostPortResult>;
code: "PROBE_OK" | "UNKNOWN_HOST" | "STALE_HOST" | "CANCELLED" | "DEADLINE_EXCEEDED" | "UNAVAILABLE";
};
export type DatabaseHostPortResult = {
port: 5432 | 3306 | 1433 | 27017 | 6379;
serviceLabel: "PostgreSQL" | "MySQL / MariaDB" | "Microsoft SQL Server" | "MongoDB" | "Redis";
status: "open" | "closed" | "timeout";
latencyMs?: number;
};
export type DatabaseOpenResult = {
handleId: DatabaseHandle;
engine: "sqlite";
label: "Disposable synthetic notes";
fixture: true;
};
export type DatabaseQueryRequest = {
handleId: DatabaseHandle;
sql: string;
parameters: Array<DatabaseScalar>;
mode: "read" | "write";
maxRows?: number;
timeoutMs?: number;
revision?: DatabaseHandle;
};
export type DatabaseQueryResult = {
columns: Array<string>;
rows: Array<Array<DatabaseScalar>>;
truncated: boolean;
changes: number;
elapsedMs: number;
};
export type DatabaseSaveConnectionRequest = {
handleId: DatabaseHandle;
revision?: DatabaseHandle;
meta: DatabaseConnectionMeta;
secret?: {
kind: "password";
value: string;
};
};
export type DatabaseSavedConnection = {
id: DatabaseHandle;
name: string;
engine: "sqlite";
color: "default" | "blue" | "green" | "purple" | "orange";
targetKind: "memory" | "file";
readOnly: boolean;
hostId?: string;
hostLabel?: string;
secretRef?: string;
};
export type DatabaseSavedConnectionList = Array<DatabaseSavedConnection>;
export type DatabaseSavedConnectionsFeature = "database.saved-connections.v1";
export type DatabaseScalar = (null) | (boolean) | (number) | (string);
export type DatabaseSchemaResult = {
tables: Array<{
name: string;
columns: Array<{
name: string;
type: string;
primaryKey: boolean;
nullable?: boolean;
}>;
kind?: "table" | "view";
}>;
};
export type DatabaseTcpFeature = "database.tcp.v1";
export type DatabaseTcpOpenRequest = {
driverId: DatabaseDriverId;
hostname: string;
port: number;
database: string;
username: string;
password: string;
tls: boolean;
variant?: DatabaseVariantId;
};
export type DatabaseTcpOpenResult = {
handleId: DatabaseHandle;
engine: "postgres" | "mysql";
driverId: DatabaseDriverId;
label: string;
readOnly: true;
fixture: false;
};
export type DatabaseTunnelCancelRequest = {
testId: DatabaseHandle;
};
export type DatabaseTunnelTestCapability = {
kind: "synthetic";
revision: DatabaseHandle;
};
export type DatabaseTunnelTestFeature = "database.tunnel-test.synthetic.v1";
export type DatabaseTunnelTestRequest = {
hostId: string;
revision: DatabaseHandle;
testId: DatabaseHandle;
};
export type DatabaseTunnelTestResult = {
status: "synthetic-passed" | "failed" | "cancelled";
code: "SYNTHETIC_OK" | "AUTH_FAILED" | "UNKNOWN_HOST_KEY" | "HOST_KEY_MISMATCH" | "UNKNOWN_HOST" | "STALE_HOST" | "CANCELLED" | "DEADLINE_EXCEEDED" | "UNAVAILABLE";
synthetic: true;
connected: false;
closed: boolean;
secretRef?: string;
};
export type DatabaseVariantId = "goldendb-mysql" | "opengauss-pg" | "gaussdb-dws" | "gaussdb-mysql" | "gaussdb-native" | "kingbase-pg" | "kingbase-oracle" | "highgo-pg" | "highgo-secure" | "vastbase-g100-pg" | "vastbase-g100-other" | "vastbase-e100" | "gbase-8c" | "gbase-8a" | "gbase-8s";
export type FeatureId = string;
export type FilesystemDirectoryEnumerationFeature = "filesystem.directory-enumeration";
@@ -240,6 +508,13 @@ export type HostDrawnViewMessage = ({
kind: "host-ui.event";
instanceId: string;
event: HostDrawnViewEvent;
}) | ({
kind: "host-ui.present";
instanceId: string;
targetViewId: ContributionId;
}) | ({
kind: "host-ui.dismiss";
instanceId: string;
});
export type HostDrawnViewOpenRequest = {
@@ -1132,7 +1407,7 @@ export type PluginNetworkResponse = {
};
};
export type PluginPermission = "storage" | "ai.invoke" | "ai.agent.use" | "ai.agent.actions" | "context.selected.list" | "context.selected.read" | "runtime.advanced" | "settings.read" | "settings.write" | "commands" | "menus" | "views" | "ui.interact" | "clipboard.read" | "clipboard.write" | "terminal.metadata" | "terminal.output" | "terminal.input" | "terminal.decorate" | "terminal.complete" | "terminal.intercept.input" | "terminal.intercept.output" | "vault.metadata" | "vault.write" | "vault.credentials" | "sftp.read" | "sftp.write" | "network" | "network.stream" | "filesystem.read" | "filesystem.write" | "secrets" | "companion.execute" | "provider.terminal" | "provider.connection" | "provider.authentication" | "provider.sync" | "provider.importer" | "terminal.selection.read" | "terminal.input.propose";
export type PluginPermission = "storage" | "ai.invoke" | "ai.agent.use" | "ai.agent.actions" | "context.selected.list" | "context.selected.read" | "runtime.advanced" | "settings.read" | "settings.write" | "commands" | "menus" | "views" | "ui.interact" | "clipboard.read" | "clipboard.write" | "terminal.metadata" | "terminal.output" | "terminal.input" | "terminal.decorate" | "terminal.complete" | "terminal.intercept.input" | "terminal.intercept.output" | "vault.metadata" | "vault.write" | "vault.credentials" | "sftp.read" | "sftp.write" | "network" | "network.stream" | "filesystem.read" | "filesystem.write" | "secrets" | "companion.execute" | "provider.terminal" | "provider.connection" | "provider.authentication" | "provider.sync" | "provider.importer" | "terminal.selection.read" | "terminal.input.propose" | "database.query.read" | "database.query.write";
export type PluginSelectedContextContent = {
handle: string;
@@ -1171,6 +1446,7 @@ export type PluginViewFocusRequest = PluginViewFocusEvent;
export type PluginViewResourceRequest = {
instanceId: string;
path: RelativePackagePath;
kind?: "brand-icon";
};
export type PluginViewResourceResult = {
@@ -1252,7 +1528,7 @@ export type RequiredPermissionResourceDeclaration = {
reason?: string;
};
export type ResourceScopedPermission = "network" | "network.stream" | "filesystem.read" | "filesystem.write" | "companion.execute";
export type ResourceScopedPermission = "network" | "network.stream" | "filesystem.read" | "filesystem.write" | "companion.execute" | "database.query.read" | "database.query.write";
export type RpcCancel = {
jsonrpc: "2.0";
+12 -2
View File
@@ -2,8 +2,14 @@ import { RemoteMutationObserver, remoteId } from '@remote-dom/core/elements';
import type { HostDrawnViewEvent, JsonValue } from '@netcatty/plugin-contract';
import type { Disposable, PluginViews } from './index.js';
/** Instance-bound shell navigation; only same-plugin contributed modal views can open. */
export interface HostViewController {
openModal(viewId: string): void;
close(): void;
}
/** 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 {
export function registerHostDomView(views: PluginViews, viewId: string, mount: (container: HTMLElement, stateScope: string, controller: HostViewController) => (() => void) | void, css = ''): Disposable {
if (css.length > 65536) throw new TypeError('Plugin CSS exceeds the view limit');
type View = { container: HTMLDivElement; unmount: () => void; observer: RemoteMutationObserver; sequence: number; acknowledgedEvent: number; sentAck: number; poll: ReturnType<typeof setInterval>; controls: Map<string, string> };
const instances = new Map<string, View>();
@@ -93,7 +99,11 @@ export function registerHostDomView(views: PluginViews, viewId: string, mount: (
const mountRoot = document.createElement('div');
mountRoot.setAttribute('style', 'min-height:100%;height:100%');
container.appendChild(mountRoot);
const cleanup = mount(mountRoot, typeof message.stateScope === 'string' ? message.stateScope : viewId);
const controller: HostViewController = {
openModal(targetViewId) { if (instances.get(id) === view) views.postMessage(viewId, { kind: 'host-ui.present', instanceId: id, targetViewId }); },
close() { if (instances.get(id) === view) views.postMessage(viewId, { kind: 'host-ui.dismiss', instanceId: id }); },
};
const cleanup = mount(mountRoot, typeof message.stateScope === 'string' ? message.stateScope : viewId, controller);
if (typeof cleanup === 'function') view.unmount = cleanup;
} else if (message.kind === 'host-ui.close') close(id);
else if (message.kind === 'host-ui.event') {
+7 -2
View File
@@ -14,9 +14,11 @@ test('ordinary React view renders data updates and responds to its own forwarded
const { default: React, act, useState } = await import('react');
const { registerHostReactView } = await import('./hostReact.js');
let receive: (value: JsonValue) => void = () => {};
const navigation: JsonValue[] = [];
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 () => {} };
postMessage(_id: string, value: JsonValue) { if (value && typeof value === "object" && !Array.isArray(value) && value.kind !== "host-ui.update") { navigation.push(value); return; } messages.push(value as unknown as Extract<HostDrawnViewMessage, { kind: 'host-ui.update' }>); }, getState: async () => undefined, setState: async () => {} };
let controller: import("./hostDom.js").HostViewController | undefined;
let submissions = 0; let selected: string[] = [];
function Example() {
const [count, setCount] = useState(0); const [name, setName] = useState('');
@@ -31,7 +33,7 @@ test('ordinary React view renders data updates and responds to its own forwarded
</form>
</div>;
}
const registration = registerHostReactView(views, 'com.example.view', () => <Example />, '.my-button{display:grid}');
const registration = registerHostReactView(views, 'com.example.view', (value) => { controller = value; return <Example />; }, '.my-button{display:grid}');
try {
await act(async () => { receive({ kind: 'host-ui.open', instanceId: 'i1' }); await new Promise((resolve) => setTimeout(resolve, 20)); });
assert.equal(messages[0].sequence, 1); assert.deepEqual(messages[0].mutations, []);
@@ -49,7 +51,10 @@ test('ordinary React view renders data updates and responds to its own forwarded
});
assert.equal(submissions, 1, 'forwarded click and host submit must not submit twice');
assert.deepEqual(selected, ['a', 'c'], 'multiple selection reaches ordinary React handlers');
controller!.openModal('com.example.modal'); controller!.close();
assert.deepEqual(navigation, [{ kind: 'host-ui.present', instanceId: 'i1', targetViewId: 'com.example.modal' }, { kind: 'host-ui.dismiss', instanceId: 'i1' }]);
await act(async () => { receive({ kind: 'host-ui.close', instanceId: 'i1' }); });
controller!.openModal('com.example.modal'); controller!.close(); assert.equal(navigation.length, 2, 'disposed render controllers cannot navigate');
assert.equal(document.querySelector('button'), null);
} finally {
registration.dispose();
+6 -4
View File
@@ -1,12 +1,12 @@
import { createRoot } from 'react-dom/client';
import { createElement, useEffect, useRef, type ReactNode } from 'react';
import type { Disposable, PluginViews } from './index.js';
import { registerHostDomView } from './hostDom.js';
import { registerHostDomView, type HostViewController } from './hostDom.js';
/** Author ordinary React while Netcatty owns the visible DOM. */
export function registerHostReactView(views: PluginViews, viewId: string, render: () => ReactNode, css = ''): Disposable {
return registerHostDomView(views, viewId, (container) => {
const root = createRoot(container); root.render(render()); return () => root.unmount();
export function registerHostReactView(views: PluginViews, viewId: string, render: (controller: HostViewController) => ReactNode, css = ''): Disposable {
return registerHostDomView(views, viewId, (container, _scope, controller) => {
const root = createRoot(container); root.render(render(controller)); return () => root.unmount();
}, css);
}
@@ -20,3 +20,5 @@ export function PluginPopover({ anchor, open, onClose, children }: { anchor: str
}, [onClose]);
return createElement('div', { ref, 'data-plugin-popover': 'true', 'data-plugin-anchor': anchor, ...(open ? { open: true } : {}) }, children);
}
export type { HostViewController } from "./hostDom.js";
+26
View File
@@ -778,7 +778,33 @@ export interface PluginStreams {
openWritable(streamId: string, options?: Readonly<{ windowBytes?: number }>): Promise<PluginWritableByteStream>;
}
export interface PluginDatabaseClient {
/** Host-owned, authenticated, read-only TCP session. Password is never returned or persisted. */
openTcp(params: import("@netcatty/plugin-contract").DatabaseTcpOpenRequest): Promise<import("@netcatty/plugin-contract").DatabaseTcpOpenResult>;
openHostLiveSshPgFixture(params: import("@netcatty/plugin-contract").DatabaseHostLiveSshPgOpenRequest): Promise<import("@netcatty/plugin-contract").DatabaseHostLiveSshPgOpenResult>;
cancelHostLiveSshPgFixture(params: import("@netcatty/plugin-contract").DatabaseHostLiveSshPgCancelRequest): Promise<null>;
closeHostLiveSshPgSession(params: import("@netcatty/plugin-contract").DatabaseHostLiveSshPgCloseRequest): Promise<import("@netcatty/plugin-contract").DatabaseHostLiveSshPgCloseResult>;
probeHostDatabasePorts(params: import("@netcatty/plugin-contract").DatabaseHostPortProbeRequest): Promise<import("@netcatty/plugin-contract").DatabaseHostPortProbeResult>;
cancelHostDatabasePorts(params: import("@netcatty/plugin-contract").DatabaseHostPortProbeCancelRequest): Promise<null>;
testTunnel(params: import("@netcatty/plugin-contract").DatabaseTunnelTestRequest): Promise<import("@netcatty/plugin-contract").DatabaseTunnelTestResult>;
cancelTunnelTest(params: import("@netcatty/plugin-contract").DatabaseTunnelCancelRequest): Promise<null>;
listSavedConnections(params?: import("@netcatty/plugin-contract").DatabaseEmptyRequest): Promise<import("@netcatty/plugin-contract").DatabaseSavedConnectionList>;
saveConnection(params: import("@netcatty/plugin-contract").DatabaseSaveConnectionRequest): Promise<import("@netcatty/plugin-contract").DatabaseSavedConnection>;
deleteConnection(params: import("@netcatty/plugin-contract").DatabaseConnectionIdRequest): Promise<null>;
openSavedConnection(params: import("@netcatty/plugin-contract").DatabaseConnectionIdRequest): Promise<import("@netcatty/plugin-contract").DatabaseOpenResult | import("@netcatty/plugin-contract").DatabaseFileOpenResult>;
listHostsForDatabase(params?: import("@netcatty/plugin-contract").DatabaseEmptyRequest): Promise<import("@netcatty/plugin-contract").DatabaseHostList>;
/** Explicit quiescent WAL fixture refresh; preserves handle and replaces revision. */
refreshSqliteFile(params: import("@netcatty/plugin-contract").DatabaseHandleRequest): Promise<import("@netcatty/plugin-contract").DatabaseFileOpenResult>;
openSqliteFile(params?: import("@netcatty/plugin-contract").DatabaseEmptyRequest): Promise<import("@netcatty/plugin-contract").DatabaseFileOpenResult | null>;
openFixture(params?: import("@netcatty/plugin-contract").DatabaseEmptyRequest): Promise<import("@netcatty/plugin-contract").DatabaseOpenResult>;
readSchema(params: import("@netcatty/plugin-contract").DatabaseHandleRequest): Promise<import("@netcatty/plugin-contract").DatabaseSchemaResult>;
query(params: import("@netcatty/plugin-contract").DatabaseQueryRequest): Promise<import("@netcatty/plugin-contract").DatabaseQueryResult>;
cancel(params: import("@netcatty/plugin-contract").DatabaseHandleRequest): Promise<null>;
close(params: import("@netcatty/plugin-contract").DatabaseHandleRequest): Promise<null>;
}
export interface PluginContext {
readonly database: PluginDatabaseClient;
readonly pluginId: PluginId;
readonly netcattyVersion: SemanticVersion;
readonly apiVersion: SemanticVersion;
+12 -3
View File
@@ -41,10 +41,19 @@ function npmExecutable() {
function ensureCursorSdkPlatformPackages({
projectDir,
platform,
arch,
run = execFileSync,
logger = console,
}) {
const packages = CURSOR_PLATFORM_PACKAGES[platform] || [];
// Linux builds contain one architecture. Installing the other architecture
// needlessly reifies the whole dependency tree (including linked worktrees).
// Preserve the existing macOS/universal and Windows staging behavior.
if (platform === "linux" && !["x64", "arm64"].includes(arch)) {
throw new Error("Linux Cursor SDK staging requires an explicit x64 or arm64 target");
}
const packages = platform === "linux"
? [`@cursor/sdk-linux-${arch}`]
: CURSOR_PLATFORM_PACKAGES[platform] || [];
if (packages.length === 0) return [];
const version = getCursorSdkVersion(projectDir);
@@ -71,9 +80,9 @@ function ensureCursorSdkPlatformPackages({
function beforePackCursorSdk(context = {}) {
const projectDir = context.appDir || process.cwd();
const platform = context.electronPlatformName || process.platform;
const arch = normalizeWindowsHelperArch(context.arch || process.env.npm_config_arch || process.arch);
const arch = normalizeWindowsHelperArch(context.arch ?? process.env.npm_config_arch ?? process.arch);
const ensureCursor = context.ensureCursorSdkPlatformPackages || ensureCursorSdkPlatformPackages;
ensureCursor({ projectDir, platform });
ensureCursor({ projectDir, platform, arch });
const buildHelper = context.buildWindowsHelloHelper || buildWindowsHelloHelper;
if (platform === "win32") {
const result = buildHelper({ projectDir, platform, arch });
+18
View File
@@ -58,6 +58,7 @@ test("ensureCursorSdkPlatformPackages is a no-op when target packages exist", (t
const installed = ensureCursorSdkPlatformPackages({
projectDir: tempDir,
platform: "linux",
arch: "x64",
run: (...args) => calls.push(args),
logger: { log() {}, warn() {} },
});
@@ -66,6 +67,23 @@ test("ensureCursorSdkPlatformPackages is a no-op when target packages exist", (t
assert.deepEqual(calls, []);
});
test("Linux staging needs only the requested architecture and forwards builder arch", (t) => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "netcatty-cursor-pack-"));
t.after(() => fs.rmSync(tempDir, { recursive: true, force: true }));
writeJson(path.join(tempDir, "node_modules/@cursor/sdk/package.json"), { version: "1.0.18" });
writeJson(path.join(tempDir, "node_modules/@cursor/sdk-linux-x64/package.json"), { version: "1.0.18" });
const calls = [];
assert.deepEqual(ensureCursorSdkPlatformPackages({ projectDir: tempDir, platform: "linux", arch: "x64", run: (...args) => calls.push(args) }), []);
assert.equal(calls.length, 0);
assert.deepEqual(ensureCursorSdkPlatformPackages({ projectDir: tempDir, platform: "linux", arch: "arm64", run: (...args) => calls.push(args), logger: { log() {} } }), ["@cursor/sdk-linux-arm64"]);
assert.equal(calls.length, 1);
assert.equal(calls[0][1].at(-1), "@cursor/sdk-linux-arm64@1.0.18");
assert.throws(() => ensureCursorSdkPlatformPackages({ projectDir: tempDir, platform: "linux", arch: null }), /explicit/);
const targets = [];
for (const arch of [1, 3]) beforePackCursorSdk({ appDir: tempDir, electronPlatformName: "linux", arch, ensureCursorSdkPlatformPackages: (target) => targets.push(target) });
assert.deepEqual(targets.map((target) => target.arch), ["x64", "arm64"]);
});
test("beforePackCursorSdk builds Windows Hello helper only for Windows packages", () => {
const calls = [];
+5
View File
@@ -20,6 +20,9 @@ const electronBundlePath = path.join(
rootDir,
"electron/plugins/generated/plugin-contract.schema.json",
);
const driverRegistryPath = path.join(rootDir, "packages/plugin-contract/schema/database-drivers.json");
const driverRegistryBundlePath = path.join(rootDir, "electron/plugins/generated/database-drivers.json");
const driverRegistry = await readFile(driverRegistryPath, "utf8");
const checkOnly = process.argv.includes("--check");
const typescriptTypeOverrides = new Map([
["PermissionDeclaration", 'Exclude<PluginPermission, "network.stream"> | PermissionResourceDeclaration'],
@@ -376,6 +379,7 @@ if (checkOnly) {
await assertCurrent(generatedTypesPath, generatedTypes, "Generated plugin TypeScript contract");
await assertCurrent(generatedLimitsPath, generatedLimits, "Generated plugin JSON limits");
await assertCurrent(electronBundlePath, normalizedSchema, "Electron plugin schema bundle");
await assertCurrent(driverRegistryBundlePath, driverRegistry, "Database driver registry");
console.log("Plugin contract generated artifacts are current.");
} else {
await mkdir(path.dirname(generatedTypesPath), { recursive: true });
@@ -384,6 +388,7 @@ if (checkOnly) {
writeFile(generatedTypesPath, generatedTypes, "utf8"),
writeFile(generatedLimitsPath, generatedLimits, "utf8"),
writeFile(electronBundlePath, normalizedSchema, "utf8"),
writeFile(driverRegistryBundlePath, driverRegistry, "utf8"),
]);
console.log("Generated plugin TypeScript contract and Electron schema bundle.");
}
+77
View File
@@ -0,0 +1,77 @@
"use strict";
// Test-only fixed Gate I corpus. No product writes or arbitrary output roots.
const fs = require("node:fs");
const path = require("node:path");
const { randomUUID, createHash } = require("node:crypto");
const { DatabaseSync } = require("node:sqlite");
const { FIXTURE_DIRECTORY } = require("../electron/plugins/sqliteFileIdentity.cjs");
function rechecksum(wal) {
// Test construction only: make structural damage checksum-valid, so E's WAL
// checksum guard alone cannot masquerade as a database integrity check.
let a = 0; let b = 0;
const word = wal.readUInt32BE(0) === 0x377f0682 ? (i) => wal.readUInt32LE(i) : (i) => wal.readUInt32BE(i);
const sum = (start, end) => { for (let i = start; i < end; i += 8) { a = (a + word(i) + b) >>> 0; b = (b + word(i + 4) + a) >>> 0; } };
sum(0, 24); wal.writeUInt32BE(a, 24); wal.writeUInt32BE(b, 28);
const size = wal.readUInt32BE(8);
for (let i = 32; i < wal.length; i += size + 24) {
sum(i, i + 8); sum(i + 24, i + 24 + size);
wal.writeUInt32BE(a, i + 16); wal.writeUInt32BE(b, i + 20);
}
}
function buildMalformedCorpus() {
fs.mkdirSync(FIXTURE_DIRECTORY, { recursive: true });
const prefix = path.join(FIXTURE_DIRECTORY, `gate-i-${randomUUID()}`);
const owned = []; const entries = [];
const write = (file, bytes) => { fs.writeFileSync(file, bytes, { flag: "wx", mode: 0o600 }); owned.push(file); };
const cleanup = () => { for (const file of owned) fs.rmSync(file, { force: true }); };
const add = (name, main, wal, expected, mutation) => {
const file = `${prefix}-${name}.sqlite`; write(file, main);
if (wal) write(file + "-wal", wal);
entries.push({ name, file, expected, mutation, files: [file, ...(wal ? [file + "-wal"] : [])].map((p) => ({ path: p, bytes: fs.statSync(p).size, sha256: createHash("sha256").update(fs.readFileSync(p)).digest("hex") })) });
};
const seed = prefix + "-seed.sqlite"; write(seed, Buffer.alloc(0));
let db;
try {
db = new DatabaseSync(seed);
db.exec("PRAGMA page_size=1024; CREATE TABLE notes(id INTEGER PRIMARY KEY,title TEXT NOT NULL,status TEXT NOT NULL);");
const insert = db.prepare("INSERT INTO notes VALUES(?,?,?)");
for (let id = 1; id <= 40; id++) insert.run(id, `Gate I synthetic note ${id}: ` + "x".repeat(96), "open");
const root = db.prepare("SELECT rootpage FROM sqlite_schema WHERE name='notes'").get().rootpage;
db.close(); db = undefined;
const good = fs.readFileSync(seed);
add("good", good, null, "accept", "Unmodified 40-row notes control, page size 1024");
add("zero-length", Buffer.alloc(0), null, "permissionDenied", "Empty file");
add("non-sqlite", Buffer.alloc(512, 0x78), null, "permissionDenied", "512 ASCII x bytes");
const wrong = Buffer.from(good); wrong[0] = 0x58;
add("wrong-magic", wrong, null, "permissionDenied", "Main byte 0 changed to X");
add("truncated-header", good.subarray(0, 64), null, "permissionDenied", "Only first 64 main bytes retained");
add("truncated-db", good.subarray(0, good.length - 1024), null, "failedPrecondition", "Final main page removed; original page count retained");
const rootOffset = (Number(root) - 1) * 1024;
if (good[rootOffset] !== 5) throw new Error("Expected interior notes root");
const cell = good.readUInt16BE(rootOffset + 12);
const leaf = good.readUInt32BE(rootOffset + cell);
const damaged = Buffer.from(good); damaged[(leaf - 1) * 1024] = 0;
add("corrupt-data-page", damaged, null, "failedPrecondition", `Leaf page ${leaf} type byte at ${(leaf - 1) * 1024} changed to zero; schema/root untouched`);
const freelist = Buffer.from(good); freelist.writeUInt32BE(1, 36);
add("freelist-count", freelist, null, "failedPrecondition", "Header freelist count at byte 36 set to 1 with no trunk (integrity diagnostics, not necessarily a native exception)");
db = new DatabaseSync(seed); db.exec("PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0; INSERT INTO notes VALUES(41,'Gate I committed WAL note','done');");
const main = fs.readFileSync(seed); const wal = fs.readFileSync(seed + "-wal");
add("good-wal", main, wal, "accept", "Complete committed 41-row WAL control; optional SHM absent");
add("truncated-wal-header", main, wal.subarray(0, 16), "permissionDenied", "Only first 16 WAL bytes retained");
add("partial-wal-frame", main, wal.subarray(0, wal.length - 17), "failedPrecondition", "Final 17 WAL bytes removed");
const corruptWal = Buffer.from(wal); let offset;
for (let i = 32; i < wal.length; i += 1048) if (wal.readUInt32BE(i) !== 1 && wal[i + 24] === 13) { offset = i + 24; break; }
if (offset === undefined) throw new Error("Expected WAL leaf frame");
corruptWal[offset] = 0; rechecksum(corruptWal);
add("corrupt-wal-page", main, corruptWal, "failedPrecondition", `WAL leaf type byte at ${offset} changed to zero, all WAL checksums recomputed`);
db.close(); db = undefined;
fs.unlinkSync(seed); owned.splice(owned.indexOf(seed), 1);
return { entries, cleanup };
} catch (error) { db?.close(); cleanup(); throw error; }
}
module.exports = { buildMalformedCorpus };
if (require.main === module) {
const corpus = buildMalformedCorpus();
// Caller saves this bounded synthetic inventory as evidence; no secrets/data.
process.stdout.write(JSON.stringify({ version: 1, root: FIXTURE_DIRECTORY, entries: corpus.entries }, null, 2) + "\n");
}
+84
View File
@@ -0,0 +1,84 @@
"use strict";
// Test-only writer protocol. Never loaded by the host or shipped as a capability.
// Only generated Gate F files in the existing M2 fixture directory are writable.
const fs = require("node:fs");
const path = require("node:path");
const { randomUUID } = require("node:crypto");
const { DatabaseSync } = require("node:sqlite");
const { FIXTURE_DIRECTORY, holdFileIdentity, closeFileIdentity } = require("../electron/plugins/sqliteFileIdentity.cjs");
let db; let file;
let continuous; let timer;
const errorInfo = (error) => ({ code: error.code, errcode: error.errcode });
const rowCount = () => db.prepare("SELECT count(*) AS n FROM notes").get().n;
const status = () => ({ ...continuous, count: rowCount(), running: Boolean(timer) });
function schedule() {
if (continuous.remaining === 0 || continuous.paused || continuous.error) return;
timer = setTimeout(() => {
timer = undefined;
try {
db.exec("INSERT INTO notes(title) VALUES('Autonomous fixture commit');");
continuous.commits++; continuous.remaining--;
} catch (error) { continuous.error = errorInfo(error); continuous.paused = true; }
schedule();
process.send({ event: "writer-progress", result: status() });
}, continuous.intervalMs);
}
process.on("disconnect", () => process.exit(0));
process.on("message", ({ id, operation, target, mode, intervalMs, totalCommits }) => {
const started = Date.now();
try {
let result;
if (operation === "create" || operation === "attach") {
if (db) throw new Error("Already initialized");
if (operation === "create") {
fs.mkdirSync(FIXTURE_DIRECTORY, { recursive: true });
file = path.join(FIXTURE_DIRECTORY, `gate-f-writer-${randomUUID()}.sqlite`);
fs.closeSync(fs.openSync(file, "wx", 0o600));
} else {
if (path.dirname(target) !== FIXTURE_DIRECTORY || !/^gate-f-writer-[a-f0-9-]{36}\.sqlite$/.test(path.basename(target))) throw new Error("Not an owned fixture");
const held = holdFileIdentity(target, { allowWal: true });
closeFileIdentity(held); file = target;
}
db = new DatabaseSync(file, { timeout: 100 });
if (operation === "create") db.exec("CREATE TABLE notes(id INTEGER PRIMARY KEY, title TEXT); INSERT INTO notes VALUES(1,'Before WAL'); PRAGMA journal_mode=WAL;");
db.exec("PRAGMA wal_autocheckpoint=0;");
if (operation === "create") db.exec("INSERT INTO notes VALUES(2,'Initial committed WAL');");
result = { file, pid: process.pid };
} else {
if (!db) throw new Error("Not initialized");
if (operation === "start-continuous") {
if (!Number.isInteger(intervalMs) || intervalMs < 20 || intervalMs > 500
|| !Number.isInteger(totalCommits) || totalCommits < 1 || totalCommits > 128
|| (continuous?.remaining > 0 && !continuous.error)) throw new Error("Invalid bounded writer run");
continuous = { intervalMs, remaining: totalCommits, commits: 0, paused: false };
schedule(); result = status();
} else if (operation === "pause-continuous") {
if (!continuous) throw new Error("No continuous run");
clearTimeout(timer); timer = undefined; continuous.paused = true; result = status();
} else if (operation === "resume-continuous") {
if (!continuous?.paused || continuous.error || continuous.remaining === 0) throw new Error("Run cannot resume");
continuous.paused = false; schedule(); result = status();
} else if (operation === "continuous-status") {
if (!continuous) throw new Error("No continuous run");
result = status();
} else if (operation === "commit") {
db.exec("INSERT INTO notes(title) VALUES('Concurrent fixture commit');");
result = { count: db.prepare("SELECT count(*) AS n FROM notes").get().n };
} else if (operation === "begin") { db.exec("BEGIN IMMEDIATE;"); result = { locked: true }; }
else if (operation === "spill-uncommitted") {
// Bounded crash corpus: cache spill writes real frames without a commit.
// The parent SIGKILLs this process after the acknowledgement.
db.exec("PRAGMA cache_size=8; PRAGMA cache_spill=ON; BEGIN IMMEDIATE;");
const insert = db.prepare("INSERT INTO notes(title) VALUES(?)");
for (let i = 0; i < 128; i++) insert.run("Uncommitted fixture " + "x".repeat(4000));
result = { uncommittedRows: 128, walBytes: fs.statSync(file + "-wal").size };
}
else if (operation === "rollback") { db.exec("ROLLBACK;"); result = { locked: false }; }
else if (operation === "checkpoint" && ["PASSIVE", "FULL", "RESTART", "TRUNCATE"].includes(mode)) result = db.prepare(`PRAGMA wal_checkpoint(${mode})`).get();
else throw new Error("Unknown fixture operation");
}
process.send({ id, result, elapsedMs: Date.now() - started });
} catch (error) {
process.send({ id, error: errorInfo(error), elapsedMs: Date.now() - started });
}
});