@jini-ai/desktop-host 0.4.2 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/bridge.js +19 -18
- package/dist/electron/electron-render-service.d.ts +9 -1
- package/dist/electron/electron-render-service.js +21 -53
- package/dist/electron/electron-shell.js +4 -3
- package/dist/electron/electron-surfaces.d.ts +10 -0
- package/dist/electron/electron-url-capture.d.ts +16 -0
- package/dist/electron/electron-url-capture.js +92 -0
- package/dist/electron/render-window.d.ts +16 -0
- package/dist/electron/render-window.js +66 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/logging.d.ts +3 -0
- package/dist/logging.js +4 -3
- package/dist/node-toolchain/index.js +18 -15
- package/dist/paths.js +14 -12
- package/dist/render-bridge.d.ts +33 -0
- package/dist/render-bridge.js +147 -0
- package/dist/render-service.js +6 -2
- package/dist/speech/macos/mac-on-device-transcriber.js +7 -4
- package/dist/url-capture.d.ts +42 -0
- package/dist/url-capture.js +40 -0
- package/package.json +9 -3
package/CHANGELOG.md
CHANGED
package/dist/bridge.js
CHANGED
|
@@ -51,16 +51,10 @@ function hasFunction(record, key) {
|
|
|
51
51
|
// `details`, keeping the parameter here would be untestable dead code, so
|
|
52
52
|
// it's dropped; `JiniHostFailure.details` remains part of the public type
|
|
53
53
|
// for any external implementer that wants to populate it directly.
|
|
54
|
-
function failure(reason) {
|
|
54
|
+
function failure(reason = 'jini host is not available') {
|
|
55
55
|
return { ok: false, reason };
|
|
56
56
|
}
|
|
57
|
-
|
|
58
|
-
const { value } = requiredArgs;
|
|
59
|
-
if (!isRecord(value))
|
|
60
|
-
return false;
|
|
61
|
-
if (value.version !== JINI_HOST_VERSION)
|
|
62
|
-
return false;
|
|
63
|
-
const client = value.client;
|
|
57
|
+
function isHostClient({ client }, _options = {}) {
|
|
64
58
|
if (!isRecord(client))
|
|
65
59
|
return false;
|
|
66
60
|
const clientTypes = Object.values(JINI_HOST_CLIENT_TYPES);
|
|
@@ -70,6 +64,16 @@ export function isJiniHostBridge(requiredArgs) {
|
|
|
70
64
|
return false;
|
|
71
65
|
if (client.osLocale != null && typeof client.osLocale !== 'string')
|
|
72
66
|
return false;
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
export function isJiniHostBridge(requiredArgs) {
|
|
70
|
+
const { value } = requiredArgs;
|
|
71
|
+
if (!isRecord(value))
|
|
72
|
+
return false;
|
|
73
|
+
if (value.version !== JINI_HOST_VERSION)
|
|
74
|
+
return false;
|
|
75
|
+
if (!isHostClient({ client: value.client }))
|
|
76
|
+
return false;
|
|
73
77
|
const shell = value.shell;
|
|
74
78
|
if (!isRecord(shell) || !hasFunction(shell, 'openExternal') || !hasFunction(shell, 'openPath'))
|
|
75
79
|
return false;
|
|
@@ -98,42 +102,39 @@ export function isJiniHostAvailable(_requiredArgs, { scope = globalThis } = {})
|
|
|
98
102
|
export function detectJiniHostClientType(_requiredArgs, { scope = globalThis } = {}) {
|
|
99
103
|
return getJiniHost({}, { scope })?.client.type ?? 'web';
|
|
100
104
|
}
|
|
101
|
-
function unavailable(reason = 'jini host is not available') {
|
|
102
|
-
return failure(reason);
|
|
103
|
-
}
|
|
104
105
|
export async function openHostExternalUrl({ url }, { scope = globalThis } = {}) {
|
|
105
106
|
const host = getJiniHost({}, { scope });
|
|
106
107
|
if (host == null)
|
|
107
|
-
return
|
|
108
|
+
return failure();
|
|
108
109
|
try {
|
|
109
110
|
return await host.shell.openExternal({ url });
|
|
110
111
|
}
|
|
111
112
|
catch (error) {
|
|
112
|
-
return
|
|
113
|
+
return failure(error instanceof Error ? error.message : String(error));
|
|
113
114
|
}
|
|
114
115
|
}
|
|
115
116
|
export async function openHostPath({ path }, { scope = globalThis } = {}) {
|
|
116
117
|
const host = getJiniHost({}, { scope });
|
|
117
118
|
if (host == null)
|
|
118
|
-
return
|
|
119
|
+
return failure();
|
|
119
120
|
try {
|
|
120
121
|
return await host.shell.openPath({ path });
|
|
121
122
|
}
|
|
122
123
|
catch (error) {
|
|
123
|
-
return
|
|
124
|
+
return failure(error instanceof Error ? error.message : String(error));
|
|
124
125
|
}
|
|
125
126
|
}
|
|
126
127
|
export async function checkJiniHostUpdaterAvailability(_requiredArgs, { scope = globalThis } = {}) {
|
|
127
128
|
const host = getJiniHost({}, { scope });
|
|
128
129
|
if (host == null)
|
|
129
|
-
return
|
|
130
|
+
return failure();
|
|
130
131
|
if (host.updater == null)
|
|
131
|
-
return
|
|
132
|
+
return failure('host build does not support the updater extension point');
|
|
132
133
|
try {
|
|
133
134
|
return await host.updater.checkAvailability();
|
|
134
135
|
}
|
|
135
136
|
catch (error) {
|
|
136
|
-
return
|
|
137
|
+
return failure(error instanceof Error ? error.message : String(error));
|
|
137
138
|
}
|
|
138
139
|
}
|
|
139
140
|
//# sourceMappingURL=bridge.js.map
|
|
@@ -8,7 +8,15 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { type RenderService } from '../render-service.js';
|
|
10
10
|
import type { ElectronBrowserWindowFactory } from './electron-surfaces.js';
|
|
11
|
+
import { type ElectronUrlCaptureOptions } from './electron-url-capture.js';
|
|
12
|
+
import type { UrlCaptureRequest, UrlCaptureResult } from '../url-capture.js';
|
|
13
|
+
/** Bind HTML exports and bounded URL capture to an injected native window factory.
|
|
14
|
+
* @example const service = createElectronRenderService({ createBrowserWindow });
|
|
15
|
+
* @complexity O(1) setup; each operation owns one temporary native window.
|
|
16
|
+
*/
|
|
11
17
|
export declare function createElectronRenderService({ createBrowserWindow }: {
|
|
12
18
|
createBrowserWindow: ElectronBrowserWindowFactory;
|
|
13
|
-
}): RenderService
|
|
19
|
+
}, _options?: {}): RenderService & {
|
|
20
|
+
captureUrl(request: UrlCaptureRequest, options?: ElectronUrlCaptureOptions): Promise<UrlCaptureResult>;
|
|
21
|
+
};
|
|
14
22
|
//# sourceMappingURL=electron-render-service.d.ts.map
|
|
@@ -6,64 +6,32 @@
|
|
|
6
6
|
* `pdf-export.ts` (those are design/slide-specific business logic that
|
|
7
7
|
* would layer on top of this same port OD-side).
|
|
8
8
|
*/
|
|
9
|
-
import { RenderServiceError,
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
}
|
|
18
|
-
function attachResourcePolicy(webContents, policy) {
|
|
19
|
-
if (policy?.allowNavigation !== true) {
|
|
20
|
-
webContents.on({ event: 'will-navigate', listener: ({ event }) => event.preventDefault() });
|
|
21
|
-
}
|
|
22
|
-
// Omitted origins are an empty allowlist. Permissive rendering requires an explicit opt-out.
|
|
23
|
-
webContents.session.webRequest.onBeforeRequest({ listener: ({ details, callback }) => {
|
|
24
|
-
callback({ cancel: !isOriginAllowed({ url: details.url }, {
|
|
25
|
-
allowedOrigins: policy?.allowedOrigins,
|
|
26
|
-
allowUnrestrictedNetwork: policy?.allowUnrestrictedNetwork,
|
|
27
|
-
}) });
|
|
28
|
-
} });
|
|
29
|
-
}
|
|
30
|
-
async function withRenderWindow(createBrowserWindow, html, options, run) {
|
|
31
|
-
const win = createBrowserWindow({}, {
|
|
32
|
-
show: false,
|
|
33
|
-
width: options.viewport?.width ?? 1024,
|
|
34
|
-
height: options.viewport?.height ?? 768,
|
|
35
|
-
webPreferences: { javascript: options.resourcePolicy?.javascript ?? true },
|
|
36
|
-
});
|
|
37
|
-
try {
|
|
38
|
-
const task = (async () => {
|
|
39
|
-
attachResourcePolicy(win.webContents, options.resourcePolicy);
|
|
40
|
-
const loaded = waitForLoad(win.webContents);
|
|
41
|
-
await win.loadURL({ url: htmlToDataUrl({ html }) });
|
|
42
|
-
await loaded;
|
|
43
|
-
return await run(win);
|
|
44
|
-
})();
|
|
45
|
-
return await withRenderTimeout({ promise: task }, { timeoutMs: options.timeoutMs, signal: options.signal });
|
|
46
|
-
}
|
|
47
|
-
finally {
|
|
48
|
-
if (!win.isDestroyed())
|
|
49
|
-
win.destroy();
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
export function createElectronRenderService({ createBrowserWindow }) {
|
|
9
|
+
import { RenderServiceError, } from '../render-service.js';
|
|
10
|
+
import { withRenderWindow } from './render-window.js';
|
|
11
|
+
import { captureElectronUrl } from './electron-url-capture.js';
|
|
12
|
+
/** Bind HTML exports and bounded URL capture to an injected native window factory.
|
|
13
|
+
* @example const service = createElectronRenderService({ createBrowserWindow });
|
|
14
|
+
* @complexity O(1) setup; each operation owns one temporary native window.
|
|
15
|
+
*/
|
|
16
|
+
export function createElectronRenderService({ createBrowserWindow }, _options = {}) {
|
|
53
17
|
return {
|
|
18
|
+
captureUrl(request, options = {}) {
|
|
19
|
+
return captureElectronUrl({ createBrowserWindow, request }, options);
|
|
20
|
+
},
|
|
54
21
|
async renderToPdf({ html }, options = {}) {
|
|
55
|
-
const buffer = await withRenderWindow(createBrowserWindow, html, options, (win) => win.webContents.printToPDF({
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
22
|
+
const buffer = await withRenderWindow({ createBrowserWindow, html, options, run: (win) => win.webContents.printToPDF({
|
|
23
|
+
landscape: options.landscape ?? false,
|
|
24
|
+
printBackground: options.printBackground ?? true,
|
|
25
|
+
...(options.pageWidth != null && options.pageHeight != null
|
|
26
|
+
? { pageSize: { width: options.pageWidth, height: options.pageHeight } }
|
|
27
|
+
: {}),
|
|
28
|
+
...(options.margins == null ? {} : { margins: options.margins }),
|
|
29
|
+
}),
|
|
30
|
+
});
|
|
63
31
|
return new Uint8Array(buffer);
|
|
64
32
|
},
|
|
65
33
|
async capture({ html }, options = {}) {
|
|
66
|
-
const image = await withRenderWindow(createBrowserWindow, html, options, (win) => win.webContents.capturePage({}, { rect: options.clip }));
|
|
34
|
+
const image = await withRenderWindow({ createBrowserWindow, html, options, run: (win) => win.webContents.capturePage({}, { rect: options.clip }) });
|
|
67
35
|
return new Uint8Array(image.toPNG());
|
|
68
36
|
},
|
|
69
37
|
async exportArtifact({ format }) {
|
|
@@ -30,9 +30,10 @@ export function createElectronShellPort(surfaces) {
|
|
|
30
30
|
properties: ['openDirectory'],
|
|
31
31
|
...(options?.defaultPath !== undefined ? { defaultPath: options.defaultPath } : {}),
|
|
32
32
|
});
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
33
|
+
// One check covers both "nothing chosen" shapes; the former `filePaths[0] ?? null` fallback
|
|
34
|
+
// after a separate length check could never apply.
|
|
35
|
+
const [chosen] = result.filePaths;
|
|
36
|
+
return result.canceled || chosen === undefined ? null : chosen;
|
|
36
37
|
},
|
|
37
38
|
};
|
|
38
39
|
}
|
|
@@ -21,6 +21,7 @@ export interface ElectronNavigationEvent {
|
|
|
21
21
|
}
|
|
22
22
|
export interface ElectronBeforeRequestDetails {
|
|
23
23
|
url: string;
|
|
24
|
+
method?: string;
|
|
24
25
|
}
|
|
25
26
|
export type ElectronBeforeRequestCallback = (response: {
|
|
26
27
|
cancel: boolean;
|
|
@@ -71,6 +72,14 @@ export interface ElectronWebContentsLike {
|
|
|
71
72
|
}): Promise<{
|
|
72
73
|
toPNG(): Buffer;
|
|
73
74
|
}>;
|
|
75
|
+
/** Optional URL-capture capabilities; HTML-only hosts need not supply these. */
|
|
76
|
+
getURL?(): string;
|
|
77
|
+
getTitle?(): string;
|
|
78
|
+
executeJavaScript?(expression: string): Promise<unknown>;
|
|
79
|
+
debugger?: {
|
|
80
|
+
attach(version: string): void;
|
|
81
|
+
sendCommand(method: string, params?: Record<string, unknown>): Promise<unknown>;
|
|
82
|
+
};
|
|
74
83
|
}
|
|
75
84
|
export interface ElectronBrowserWindowLike {
|
|
76
85
|
readonly webContents: ElectronWebContentsLike;
|
|
@@ -90,6 +99,7 @@ export interface ElectronBrowserWindowLike {
|
|
|
90
99
|
}
|
|
91
100
|
export interface ElectronBrowserWindowOptions {
|
|
92
101
|
show?: boolean;
|
|
102
|
+
useContentSize?: boolean;
|
|
93
103
|
width?: number;
|
|
94
104
|
height?: number;
|
|
95
105
|
webPreferences?: {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type UrlCaptureRequest, type UrlCaptureResult } from '../url-capture.js';
|
|
2
|
+
import type { ElectronBrowserWindowFactory } from './electron-surfaces.js';
|
|
3
|
+
export interface ElectronUrlCaptureOptions {
|
|
4
|
+
allowedOrigins?: readonly string[];
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
}
|
|
7
|
+
/** Capture a validated own-origin page, bounded in time, CSS pixels and encoded PNG bytes.
|
|
8
|
+
* The host factory denies popups, downloads and permissions on the private session.
|
|
9
|
+
* @throws RenderServiceError on refusal, timeout or native renderer failure.
|
|
10
|
+
* @complexity O(pixels), capped at 1280×8000 CSS pixels and device scale 2.
|
|
11
|
+
*/
|
|
12
|
+
export declare function captureElectronUrl({ createBrowserWindow, request: input }: {
|
|
13
|
+
createBrowserWindow: ElectronBrowserWindowFactory;
|
|
14
|
+
request: UrlCaptureRequest;
|
|
15
|
+
}, { allowedOrigins, signal }?: ElectronUrlCaptureOptions): Promise<UrlCaptureResult>;
|
|
16
|
+
//# sourceMappingURL=electron-url-capture.d.ts.map
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/** URL extension of RenderService: native Chromium, never a second browser installation.
|
|
2
|
+
* Shares the existing render-window lifetime; each URL capture has a private memory session.
|
|
3
|
+
*/
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { RenderServiceError } from '../render-service.js';
|
|
6
|
+
import { isCaptureUrlAllowed, readUrlCaptureRequest, URL_CAPTURE_MAX_BYTES, URL_CAPTURE_TIMEOUT_MS } from '../url-capture.js';
|
|
7
|
+
import { withRenderWindow } from './render-window.js';
|
|
8
|
+
/** Capture a validated own-origin page, bounded in time, CSS pixels and encoded PNG bytes.
|
|
9
|
+
* The host factory denies popups, downloads and permissions on the private session.
|
|
10
|
+
* @throws RenderServiceError on refusal, timeout or native renderer failure.
|
|
11
|
+
* @complexity O(pixels), capped at 1280×8000 CSS pixels and device scale 2.
|
|
12
|
+
*/
|
|
13
|
+
export async function captureElectronUrl({ createBrowserWindow, request: input }, { allowedOrigins = [], signal } = {}) {
|
|
14
|
+
const request = readUrlCaptureRequest({ value: input });
|
|
15
|
+
if (!isCaptureUrlAllowed({ url: request.url, allowedOrigins })) {
|
|
16
|
+
throw new RenderServiceError({ code: 'navigation-blocked', message: 'capture URL must stay on the site origin' });
|
|
17
|
+
}
|
|
18
|
+
let blockedRequests = 0;
|
|
19
|
+
const factory = (required, options) => {
|
|
20
|
+
return createBrowserWindow(required, { ...options, useContentSize: true,
|
|
21
|
+
webPreferences: { ...options?.webPreferences, sandbox: true, nodeIntegration: false,
|
|
22
|
+
contextIsolation: true, webSecurity: true, backgroundThrottling: false,
|
|
23
|
+
partition: `capture-${randomUUID()}` },
|
|
24
|
+
});
|
|
25
|
+
};
|
|
26
|
+
try {
|
|
27
|
+
return await withRenderWindow({ createBrowserWindow: factory, url: request.url,
|
|
28
|
+
options: { viewport: request.viewport, timeoutMs: URL_CAPTURE_TIMEOUT_MS, ...(signal ? { signal } : {}) },
|
|
29
|
+
prepare: async (window) => {
|
|
30
|
+
// Electron can crash the main process if device emulation targets an unloaded webContents.
|
|
31
|
+
// Bootstrap before the strict request policy; emulation still precedes site navigation.
|
|
32
|
+
await window.loadURL({ url: 'about:blank' });
|
|
33
|
+
window.webContents.session.webRequest.onBeforeRequest({ listener: ({ details, callback }) => {
|
|
34
|
+
const cancel = details.method !== 'GET' || !isCaptureUrlAllowed({ url: details.url, allowedOrigins });
|
|
35
|
+
if (cancel)
|
|
36
|
+
blockedRequests++;
|
|
37
|
+
callback({ cancel });
|
|
38
|
+
} });
|
|
39
|
+
const debug = window.webContents.debugger;
|
|
40
|
+
if (!debug)
|
|
41
|
+
throw new RenderServiceError({ code: 'not-implemented', message: 'native device emulation unavailable' });
|
|
42
|
+
debug.attach('1.3');
|
|
43
|
+
await debug.sendCommand('Emulation.setDeviceMetricsOverride', {
|
|
44
|
+
width: request.viewport.width, height: request.viewport.height,
|
|
45
|
+
deviceScaleFactor: request.viewport.deviceScaleFactor ?? 1, mobile: request.viewport.isMobile ?? false,
|
|
46
|
+
});
|
|
47
|
+
}, run: async (win) => {
|
|
48
|
+
const page = win.webContents;
|
|
49
|
+
if (!page.debugger || !page.executeJavaScript || !page.getURL || !page.getTitle) {
|
|
50
|
+
throw new RenderServiceError({ code: 'not-implemented', message: 'host does not support URL capture' });
|
|
51
|
+
}
|
|
52
|
+
// Device emulation is configured before navigation, so responsive JS sees this viewport.
|
|
53
|
+
await settle({ page, request });
|
|
54
|
+
const finalUrl = page.getURL();
|
|
55
|
+
if (!isCaptureUrlAllowed({ url: finalUrl, allowedOrigins }))
|
|
56
|
+
throw new RenderServiceError({ code: 'navigation-blocked', message: 'capture redirected off site' });
|
|
57
|
+
const rawHeight = await page.executeJavaScript('Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0)');
|
|
58
|
+
const pageHeight = readPageHeight({ request, rawHeight });
|
|
59
|
+
const capturedHeight = Math.min(pageHeight, request.fullPage ? request.maxPageHeightPx : request.viewport.height);
|
|
60
|
+
const png = await capturePixels({ page, request, capturedHeight });
|
|
61
|
+
if (png.byteLength > URL_CAPTURE_MAX_BYTES)
|
|
62
|
+
throw new RenderServiceError({ code: 'load-failed', message: 'capture exceeds PNG byte limit' });
|
|
63
|
+
return { png, finalUrl, title: page.getTitle().slice(0, 300), status: null, pageHeight, capturedHeight, blockedRequests };
|
|
64
|
+
} });
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
if (error instanceof RenderServiceError)
|
|
68
|
+
throw error;
|
|
69
|
+
throw new RenderServiceError({ code: 'load-failed', message: 'native page capture failed' });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function readPageHeight({ request, rawHeight }, _options = {}) {
|
|
73
|
+
return request.fullPage && typeof rawHeight === 'number' && Number.isFinite(rawHeight)
|
|
74
|
+
? Math.max(1, Math.ceil(rawHeight)) : request.viewport.height;
|
|
75
|
+
}
|
|
76
|
+
/** Reveal lazy content with bounded scrolls, then charge the settle delay to the render deadline. */
|
|
77
|
+
async function settle({ page, request }) {
|
|
78
|
+
if (request.fullPage)
|
|
79
|
+
await page.executeJavaScript(`(async () => { const end = Math.min(document.documentElement.scrollHeight, ${request.maxPageHeightPx}); for (let y = 0; y < end; y += window.innerHeight) { window.scrollTo({ top: y, behavior: 'instant' }); await new Promise(r => setTimeout(r, 150)); } window.scrollTo({ top: 0, behavior: 'instant' }); })()`);
|
|
80
|
+
await new Promise(resolve => setTimeout(resolve, request.settleMs));
|
|
81
|
+
}
|
|
82
|
+
/** Native capturePage for a viewport; CDP's native beyond-viewport capture for capped full pages. */
|
|
83
|
+
async function capturePixels({ page, request, capturedHeight }) {
|
|
84
|
+
if (!request.fullPage)
|
|
85
|
+
return (await page.capturePage({})).toPNG();
|
|
86
|
+
const result = await page.debugger.sendCommand('Page.captureScreenshot', {
|
|
87
|
+
format: 'png', captureBeyondViewport: true,
|
|
88
|
+
clip: { x: 0, y: 0, width: request.viewport.width, height: capturedHeight, scale: 1 },
|
|
89
|
+
});
|
|
90
|
+
return Buffer.from(result.data, 'base64');
|
|
91
|
+
}
|
|
92
|
+
//# sourceMappingURL=electron-url-capture.js.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Shared native render-window lifetime for HTML exports and URL captures. */
|
|
2
|
+
import { type RenderOptions } from '../render-service.js';
|
|
3
|
+
import type { ElectronBrowserWindowFactory, ElectronBrowserWindowLike } from './electron-surfaces.js';
|
|
4
|
+
/** Allocate, load and consume one hidden window, always destroying it on failure or deadline.
|
|
5
|
+
* @throws RenderServiceError on abort/timeout; native failures propagate to the adapter edge.
|
|
6
|
+
* @complexity O(1) lifecycle work, apart from the injected renderer operation.
|
|
7
|
+
*/
|
|
8
|
+
export declare function withRenderWindow<T>({ createBrowserWindow, html, url, options, prepare, run }: {
|
|
9
|
+
createBrowserWindow: ElectronBrowserWindowFactory;
|
|
10
|
+
html?: string;
|
|
11
|
+
url?: string;
|
|
12
|
+
options: RenderOptions;
|
|
13
|
+
prepare?: (win: ElectronBrowserWindowLike) => Promise<void>;
|
|
14
|
+
run: (win: ElectronBrowserWindowLike) => Promise<T>;
|
|
15
|
+
}, _options?: {}): Promise<T>;
|
|
16
|
+
//# sourceMappingURL=render-window.d.ts.map
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** Shared native render-window lifetime for HTML exports and URL captures. */
|
|
2
|
+
import { RenderServiceError, htmlToDataUrl, isOriginAllowed, withRenderTimeout } from '../render-service.js';
|
|
3
|
+
/** HTML renderers report load events separately from their data-URL load promise. */
|
|
4
|
+
function waitForLoad(webContents) {
|
|
5
|
+
return new Promise((resolve, reject) => {
|
|
6
|
+
webContents.once({ event: 'did-finish-load', listener: () => resolve() });
|
|
7
|
+
webContents.once({ event: 'did-fail-load', listener: ({ errorCode, errorDescription }) => {
|
|
8
|
+
reject(new RenderServiceError({ message: `failed to load render document: ${errorDescription} (${errorCode})`, code: 'load-failed' }));
|
|
9
|
+
} });
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
/** Keep the existing HTML resource policy; URL captures install a stricter GET-only policy. */
|
|
13
|
+
function attachResourcePolicy(webContents, policy) {
|
|
14
|
+
if (policy?.allowNavigation !== true) {
|
|
15
|
+
webContents.on({ event: 'will-navigate', listener: ({ event }) => event.preventDefault() });
|
|
16
|
+
}
|
|
17
|
+
// Omitted origins are an empty allowlist. Permissive rendering requires an explicit opt-out.
|
|
18
|
+
webContents.session.webRequest.onBeforeRequest({ listener: ({ details, callback }) => {
|
|
19
|
+
callback({ cancel: !isOriginAllowed({ url: details.url }, {
|
|
20
|
+
allowedOrigins: policy?.allowedOrigins,
|
|
21
|
+
allowUnrestrictedNetwork: policy?.allowUnrestrictedNetwork,
|
|
22
|
+
}) });
|
|
23
|
+
} });
|
|
24
|
+
}
|
|
25
|
+
function createHiddenWindow({ createBrowserWindow, options }, _options = {}) {
|
|
26
|
+
return createBrowserWindow({}, {
|
|
27
|
+
show: false,
|
|
28
|
+
width: options.viewport?.width ?? 1024,
|
|
29
|
+
height: options.viewport?.height ?? 768,
|
|
30
|
+
webPreferences: { javascript: options.resourcePolicy?.javascript ?? true },
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
/** Allocate, load and consume one hidden window, always destroying it on failure or deadline.
|
|
34
|
+
* @throws RenderServiceError on abort/timeout; native failures propagate to the adapter edge.
|
|
35
|
+
* @complexity O(1) lifecycle work, apart from the injected renderer operation.
|
|
36
|
+
*/
|
|
37
|
+
export async function withRenderWindow({ createBrowserWindow, html = '', url, options, prepare, run }, _options = {}) {
|
|
38
|
+
if (options.signal?.aborted)
|
|
39
|
+
throw new RenderServiceError({ code: 'aborted', message: 'render aborted before starting' });
|
|
40
|
+
const win = createHiddenWindow({ createBrowserWindow, options });
|
|
41
|
+
try {
|
|
42
|
+
const task = (async () => {
|
|
43
|
+
await prepare?.(win);
|
|
44
|
+
if (options.signal?.aborted || win.isDestroyed())
|
|
45
|
+
throw new RenderServiceError({ code: 'aborted', message: 'render aborted during preparation' });
|
|
46
|
+
// Both paths share timeout and destruction ownership. URL capture's own factory installs
|
|
47
|
+
// its strict policy before loading; HTML retains its established data-document policy.
|
|
48
|
+
if (url === undefined) {
|
|
49
|
+
attachResourcePolicy(win.webContents, options.resourcePolicy);
|
|
50
|
+
const loaded = waitForLoad(win.webContents);
|
|
51
|
+
await win.loadURL({ url: htmlToDataUrl({ html }) });
|
|
52
|
+
await loaded;
|
|
53
|
+
}
|
|
54
|
+
else {
|
|
55
|
+
await win.loadURL({ url });
|
|
56
|
+
}
|
|
57
|
+
return await run(win);
|
|
58
|
+
})();
|
|
59
|
+
return await withRenderTimeout({ promise: task }, { timeoutMs: options.timeoutMs, signal: options.signal });
|
|
60
|
+
}
|
|
61
|
+
finally {
|
|
62
|
+
if (!win.isDestroyed())
|
|
63
|
+
win.destroy();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
//# sourceMappingURL=render-window.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -16,6 +16,7 @@ export * from './logging.js';
|
|
|
16
16
|
export * from './windows-registry.js';
|
|
17
17
|
export * from './bridge.js';
|
|
18
18
|
export * from './render-service.js';
|
|
19
|
+
export * from './url-capture.js';
|
|
19
20
|
export * from './shell.js';
|
|
20
21
|
export * from './ports.js';
|
|
21
22
|
export * from './tokens.js';
|
package/dist/index.js
CHANGED
|
@@ -16,6 +16,7 @@ export * from './logging.js';
|
|
|
16
16
|
export * from './windows-registry.js';
|
|
17
17
|
export * from './bridge.js';
|
|
18
18
|
export * from './render-service.js';
|
|
19
|
+
export * from './url-capture.js';
|
|
19
20
|
export * from './shell.js';
|
|
20
21
|
export * from './ports.js';
|
|
21
22
|
export * from './tokens.js';
|
package/dist/logging.d.ts
CHANGED
|
@@ -10,11 +10,14 @@ export declare function appendLogLine({ logPath, line }: {
|
|
|
10
10
|
}, { append }?: {
|
|
11
11
|
append?: LogAppend;
|
|
12
12
|
}): boolean;
|
|
13
|
+
/** Where echoed lines go; defaults to the process's global `console`. */
|
|
14
|
+
export type LogConsole = Pick<Console, 'error' | 'info' | 'warn'>;
|
|
13
15
|
export declare function createFileLogger({ logPath }: {
|
|
14
16
|
logPath: string;
|
|
15
17
|
}, options?: {
|
|
16
18
|
echoToConsole?: boolean;
|
|
17
19
|
append?: LogAppend;
|
|
20
|
+
console?: LogConsole;
|
|
18
21
|
}): Logger;
|
|
19
22
|
/**
|
|
20
23
|
* Matches the known-harmless undici `setTypeOfService EINVAL` shape (see
|
package/dist/logging.js
CHANGED
|
@@ -50,6 +50,7 @@ export function appendLogLine({ logPath, line }, { append = ({ path, data, encod
|
|
|
50
50
|
}
|
|
51
51
|
export function createFileLogger({ logPath }, options = {}) {
|
|
52
52
|
const echo = options.echoToConsole ?? true;
|
|
53
|
+
const out = options.console ?? console;
|
|
53
54
|
const write = (level, message, meta) => {
|
|
54
55
|
appendLogLine({ logPath, line: serializeMessage(level, message, meta) }, options.append === undefined ? {} : { append: options.append });
|
|
55
56
|
};
|
|
@@ -57,17 +58,17 @@ export function createFileLogger({ logPath }, options = {}) {
|
|
|
57
58
|
error({ message }, { meta, error } = {}) {
|
|
58
59
|
write('error', message, error === undefined ? meta : { ...meta, error });
|
|
59
60
|
if (echo)
|
|
60
|
-
|
|
61
|
+
out.error(message, error === undefined ? meta ?? '' : { ...meta, error });
|
|
61
62
|
},
|
|
62
63
|
info({ message }, { meta, error } = {}) {
|
|
63
64
|
write('info', message, error === undefined ? meta : { ...meta, error });
|
|
64
65
|
if (echo)
|
|
65
|
-
|
|
66
|
+
out.info(message, error === undefined ? meta ?? '' : { ...meta, error });
|
|
66
67
|
},
|
|
67
68
|
warn({ message }, { meta, error } = {}) {
|
|
68
69
|
write('warn', message, error === undefined ? meta : { ...meta, error });
|
|
69
70
|
if (echo)
|
|
70
|
-
|
|
71
|
+
out.warn(message, error === undefined ? meta ?? '' : { ...meta, error });
|
|
71
72
|
},
|
|
72
73
|
};
|
|
73
74
|
return logger;
|
|
@@ -45,6 +45,23 @@ export function buildNodeToolchainShims({ electronPath, npmRoot, platform, gener
|
|
|
45
45
|
npx: [...header, `exec '${exe}' '${npx}' "$@"`, ''].join('\n'),
|
|
46
46
|
};
|
|
47
47
|
}
|
|
48
|
+
function publishShim({ filesystem, target, contents, writerPid }, _options = {}) {
|
|
49
|
+
const temporary = `${target}.${writerPid}.tmp`;
|
|
50
|
+
// Same-directory rename publishes a complete executable atomically; a crash must not leave a
|
|
51
|
+
// half-written executable shim visible to another launcher.
|
|
52
|
+
try {
|
|
53
|
+
filesystem.writeFileSync({ path: temporary, data: contents }, { mode: 0o700 });
|
|
54
|
+
filesystem.chmodSync({ path: temporary, mode: 0o700 });
|
|
55
|
+
filesystem.renameSync({ oldPath: temporary, newPath: target });
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
try {
|
|
59
|
+
filesystem.unlinkSync({ path: temporary });
|
|
60
|
+
}
|
|
61
|
+
catch { /* Preserve the original write error. */ }
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
48
65
|
/** Atomically replace each executable shim in caller-selected directories, with owner-only modes.
|
|
49
66
|
* A transient launch preserves an existing durable launcher or returns null without writing.
|
|
50
67
|
* Filesystem/probe errors propagate; temporary files are cleaned up after a failed replacement.
|
|
@@ -68,21 +85,7 @@ export function writeNodeToolchain(input) {
|
|
|
68
85
|
filesystem.mkdirSync({ path: paths.npmPrefixDir }, { recursive: true });
|
|
69
86
|
for (const [name, contents] of Object.entries(shims)) {
|
|
70
87
|
const target = joinPath({ parts: [paths.binDir, name] });
|
|
71
|
-
|
|
72
|
-
// Same-directory rename publishes a complete executable atomically; a crash must not leave a
|
|
73
|
-
// half-written executable shim visible to another launcher.
|
|
74
|
-
try {
|
|
75
|
-
filesystem.writeFileSync({ path: temporary, data: contents }, { mode: 0o700 });
|
|
76
|
-
filesystem.chmodSync({ path: temporary, mode: 0o700 });
|
|
77
|
-
filesystem.renameSync({ oldPath: temporary, newPath: target });
|
|
78
|
-
}
|
|
79
|
-
catch (error) {
|
|
80
|
-
try {
|
|
81
|
-
filesystem.unlinkSync({ path: temporary });
|
|
82
|
-
}
|
|
83
|
-
catch { /* Preserve the original write error. */ }
|
|
84
|
-
throw error;
|
|
85
|
-
}
|
|
88
|
+
publishShim({ filesystem, target, contents, writerPid });
|
|
86
89
|
}
|
|
87
90
|
return paths;
|
|
88
91
|
}
|
package/dist/paths.js
CHANGED
|
@@ -50,21 +50,23 @@ function scopedNamespaceOf(raw) {
|
|
|
50
50
|
}
|
|
51
51
|
function resolveDataRoot(namespaceRoot, namespace, dataDirOverrideEnvVar, env) {
|
|
52
52
|
const override = dataDirOverrideEnvVar == null ? undefined : env[dataDirOverrideEnvVar]?.trim();
|
|
53
|
-
if (override
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
}
|
|
59
|
-
const scopedNamespace = scopedNamespaceOf(expanded);
|
|
60
|
-
if (scopedNamespace != null && scopedNamespace !== namespace) {
|
|
61
|
-
throw new DesktopHostPathError({ message: `${dataDirOverrideEnvVar} targets namespace "${scopedNamespace}" but the active namespace is "${namespace}"` });
|
|
62
|
-
}
|
|
63
|
-
return scopedNamespace != null ? expanded : join(expanded, 'namespaces', namespace, 'data');
|
|
53
|
+
if (override == null || override.length === 0)
|
|
54
|
+
return join(namespaceRoot, 'data');
|
|
55
|
+
const expanded = expandHomePrefix(override);
|
|
56
|
+
const isAbs = process.platform === 'win32' ? win32.isAbsolute(expanded) : isAbsolute(expanded);
|
|
57
|
+
if (!isAbs) {
|
|
58
|
+
throw new DesktopHostPathError({ message: `${dataDirOverrideEnvVar} must be an absolute path; got: ${override}` });
|
|
64
59
|
}
|
|
65
|
-
|
|
60
|
+
const scopedNamespace = scopedNamespaceOf(expanded);
|
|
61
|
+
if (scopedNamespace != null && scopedNamespace !== namespace) {
|
|
62
|
+
throw new DesktopHostPathError({ message: `${dataDirOverrideEnvVar} targets namespace "${scopedNamespace}" but the active namespace is "${namespace}"` });
|
|
63
|
+
}
|
|
64
|
+
return scopedNamespace != null ? expanded : join(expanded, 'namespaces', namespace, 'data');
|
|
66
65
|
}
|
|
67
66
|
export function resolveDesktopHostPathRoots(requiredArgs, optionalArgs = {}) {
|
|
67
|
+
if (!/^[A-Za-z0-9_-][A-Za-z0-9._-]*$/.test(requiredArgs.namespace)) {
|
|
68
|
+
throw new DesktopHostPathError({ message: 'namespace must be a single safe path segment' });
|
|
69
|
+
}
|
|
68
70
|
const options = { ...optionalArgs, ...requiredArgs };
|
|
69
71
|
const env = options.env ?? process.env;
|
|
70
72
|
const namespaceRoot = join(options.namespaceBaseRoot, options.namespace);
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { type UrlCapturePort } from './url-capture.js';
|
|
3
|
+
export declare const RENDER_BRIDGE_URL_ENV = "JINI_DESKTOP_RENDER_URL";
|
|
4
|
+
export declare const RENDER_BRIDGE_TOKEN_ENV = "JINI_DESKTOP_RENDER_TOKEN";
|
|
5
|
+
/** The per-request deadline clock; defaults to the global `setTimeout`/`clearTimeout`. */
|
|
6
|
+
export interface RenderBridgeTimers {
|
|
7
|
+
setTimeout(callback: () => void, ms: number): unknown;
|
|
8
|
+
clearTimeout(handle: unknown): void;
|
|
9
|
+
}
|
|
10
|
+
/** Start one per launched server. No public bind, browser credentials, redirects or cookies.
|
|
11
|
+
* @example const bridge = await startRenderBridge({ capture }); // pass bridge.env to the child
|
|
12
|
+
* @complexity O(bytes) per capture; one active render, at most 16 MiB of PNG output.
|
|
13
|
+
*/
|
|
14
|
+
export declare function startRenderBridge({ capture }: {
|
|
15
|
+
capture: UrlCapturePort;
|
|
16
|
+
}, { createServer: makeServer, timers }?: {
|
|
17
|
+
createServer?: typeof createServer;
|
|
18
|
+
timers?: RenderBridgeTimers;
|
|
19
|
+
}): Promise<{
|
|
20
|
+
env: Record<string, string>;
|
|
21
|
+
close(): void;
|
|
22
|
+
}>;
|
|
23
|
+
/** Detect a complete private bridge contract; a partial/invalid contract fails closed.
|
|
24
|
+
* No bridge returns null so hosts retain their current browser fallback.
|
|
25
|
+
* @example const capture = renderBridgeFromEnv({ env: process.env });
|
|
26
|
+
* @complexity O(1), plus bounded request/PNG bytes per capture.
|
|
27
|
+
*/
|
|
28
|
+
export declare function renderBridgeFromEnv({ env }: {
|
|
29
|
+
env: Record<string, string | undefined>;
|
|
30
|
+
}, { fetch: send }?: {
|
|
31
|
+
fetch?: typeof globalThis.fetch;
|
|
32
|
+
}): UrlCapturePort | null;
|
|
33
|
+
//# sourceMappingURL=render-bridge.d.ts.map
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/** Private native-render transport. The capability travels in the launcher environment, never
|
|
2
|
+
* a renderer/preload bridge or a boot-token log. Descendant daemons can use the same endpoint.
|
|
3
|
+
*/
|
|
4
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
5
|
+
import { createServer } from 'node:http';
|
|
6
|
+
import { RenderServiceError } from './render-service.js';
|
|
7
|
+
import { readUrlCaptureRequest, URL_CAPTURE_MAX_BYTES, URL_CAPTURE_TIMEOUT_MS } from './url-capture.js';
|
|
8
|
+
export const RENDER_BRIDGE_URL_ENV = 'JINI_DESKTOP_RENDER_URL';
|
|
9
|
+
export const RENDER_BRIDGE_TOKEN_ENV = 'JINI_DESKTOP_RENDER_TOKEN';
|
|
10
|
+
const MAX_WIRE_BYTES = Math.ceil(URL_CAPTURE_MAX_BYTES / 3) * 4 + 8192;
|
|
11
|
+
/** Bounded body reader shared by server requests and client responses; never buffers past cap.
|
|
12
|
+
* @throws RenderServiceError when the peer exceeds the byte limit. @complexity O(bytes).
|
|
13
|
+
*/
|
|
14
|
+
async function readBody({ stream, limit }) {
|
|
15
|
+
const chunks = [];
|
|
16
|
+
let size = 0;
|
|
17
|
+
for await (const chunk of stream) {
|
|
18
|
+
size += chunk.byteLength;
|
|
19
|
+
if (size > limit)
|
|
20
|
+
throw new RenderServiceError({ code: 'load-failed', message: 'capture transport size limit exceeded' });
|
|
21
|
+
chunks.push(Buffer.from(chunk));
|
|
22
|
+
}
|
|
23
|
+
return Buffer.concat(chunks);
|
|
24
|
+
}
|
|
25
|
+
/** Constant-time capability comparison, including a length check before the native primitive. */
|
|
26
|
+
function authorized({ authorization, token }) {
|
|
27
|
+
const actual = Buffer.from(authorization ?? '');
|
|
28
|
+
const expected = Buffer.from(`Bearer ${token}`);
|
|
29
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
30
|
+
}
|
|
31
|
+
/** Start one per launched server. No public bind, browser credentials, redirects or cookies.
|
|
32
|
+
* @example const bridge = await startRenderBridge({ capture }); // pass bridge.env to the child
|
|
33
|
+
* @complexity O(bytes) per capture; one active render, at most 16 MiB of PNG output.
|
|
34
|
+
*/
|
|
35
|
+
export async function startRenderBridge({ capture }, { createServer: makeServer = createServer, timers = { setTimeout, clearTimeout } } = {}) {
|
|
36
|
+
const token = randomBytes(32).toString('hex');
|
|
37
|
+
let active;
|
|
38
|
+
let closed = false;
|
|
39
|
+
const server = makeServer((req, res) => { void handle(req, res).catch(() => res.destroy()); });
|
|
40
|
+
server.requestTimeout = URL_CAPTURE_TIMEOUT_MS;
|
|
41
|
+
server.headersTimeout = 5000;
|
|
42
|
+
server.maxConnections = 4;
|
|
43
|
+
/** Auth and bounds precede rendering; disconnect cancels work and never leaks a native error. */
|
|
44
|
+
async function handle(req, res) {
|
|
45
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
46
|
+
if (req.method !== 'POST' || req.url !== '/capture' || req.headers.origin || !authorized({ authorization: req.headers.authorization, token })) {
|
|
47
|
+
res.writeHead(403).end();
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (closed || active) {
|
|
51
|
+
res.writeHead(429).end();
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const controller = new AbortController();
|
|
55
|
+
active = controller;
|
|
56
|
+
const abort = () => controller.abort();
|
|
57
|
+
res.once('close', abort);
|
|
58
|
+
const timer = timers.setTimeout(() => {
|
|
59
|
+
controller.abort();
|
|
60
|
+
// A peer that authenticated and then stopped sending its JSON must release the slot too.
|
|
61
|
+
req.destroy();
|
|
62
|
+
}, URL_CAPTURE_TIMEOUT_MS);
|
|
63
|
+
try {
|
|
64
|
+
const request = readUrlCaptureRequest({ value: JSON.parse((await readBody({ stream: req, limit: 8192 })).toString('utf8')) });
|
|
65
|
+
const result = await capture.captureUrl(request, { signal: controller.signal });
|
|
66
|
+
if (result.png.byteLength > URL_CAPTURE_MAX_BYTES)
|
|
67
|
+
throw new RenderServiceError({ code: 'load-failed', message: 'capture too large' });
|
|
68
|
+
res.setHeader('Content-Type', 'application/json');
|
|
69
|
+
res.end(JSON.stringify({ ...result, png: Buffer.from(result.png).toString('base64') }));
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
const code = error instanceof RenderServiceError ? error.code : 'load-failed';
|
|
73
|
+
res.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: code }));
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
timers.clearTimeout(timer);
|
|
77
|
+
res.removeListener('close', abort);
|
|
78
|
+
active = undefined;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
await new Promise((resolve, reject) => {
|
|
82
|
+
server.once('error', reject);
|
|
83
|
+
server.listen(0, '127.0.0.1', () => { server.removeListener('error', reject); resolve(); });
|
|
84
|
+
});
|
|
85
|
+
const address = server.address();
|
|
86
|
+
return { env: { [RENDER_BRIDGE_URL_ENV]: `http://127.0.0.1:${address.port}/capture`, [RENDER_BRIDGE_TOKEN_ENV]: token },
|
|
87
|
+
close() { closed = true; active?.abort(); server.close(); server.closeAllConnections(); } };
|
|
88
|
+
}
|
|
89
|
+
function isPrivateCaptureEndpoint({ url }, _options = {}) {
|
|
90
|
+
return url.protocol === 'http:' && url.hostname === '127.0.0.1' && url.pathname === '/capture'
|
|
91
|
+
&& !url.username && !url.password && !url.search && !url.hash;
|
|
92
|
+
}
|
|
93
|
+
async function readCaptureResponse({ response }, _options = {}) {
|
|
94
|
+
if (!response.body)
|
|
95
|
+
throw new RenderServiceError({ code: 'load-failed', message: 'empty desktop capture response' });
|
|
96
|
+
const data = JSON.parse((await readBody({ stream: response.body, limit: MAX_WIRE_BYTES })).toString('utf8'));
|
|
97
|
+
if (!response.ok) {
|
|
98
|
+
const known = ['timeout', 'aborted', 'load-failed', 'navigation-blocked', 'not-implemented'];
|
|
99
|
+
const code = known.includes(data.error) ? data.error : 'load-failed';
|
|
100
|
+
throw new RenderServiceError({ code, message: 'desktop capture failed' });
|
|
101
|
+
}
|
|
102
|
+
if (typeof data.png !== 'string' || data.png.length > MAX_WIRE_BYTES)
|
|
103
|
+
throw new RenderServiceError({ code: 'load-failed', message: 'invalid desktop capture response' });
|
|
104
|
+
const png = Buffer.from(data.png, 'base64');
|
|
105
|
+
if (png.byteLength > URL_CAPTURE_MAX_BYTES)
|
|
106
|
+
throw new RenderServiceError({ code: 'load-failed', message: 'capture too large' });
|
|
107
|
+
return { ...data, png };
|
|
108
|
+
}
|
|
109
|
+
/** Detect a complete private bridge contract; a partial/invalid contract fails closed.
|
|
110
|
+
* No bridge returns null so hosts retain their current browser fallback.
|
|
111
|
+
* @example const capture = renderBridgeFromEnv({ env: process.env });
|
|
112
|
+
* @complexity O(1), plus bounded request/PNG bytes per capture.
|
|
113
|
+
*/
|
|
114
|
+
export function renderBridgeFromEnv({ env }, { fetch: send = globalThis.fetch } = {}) {
|
|
115
|
+
const endpoint = env[RENDER_BRIDGE_URL_ENV];
|
|
116
|
+
const token = env[RENDER_BRIDGE_TOKEN_ENV];
|
|
117
|
+
if (endpoint === undefined && token === undefined)
|
|
118
|
+
return null;
|
|
119
|
+
let url;
|
|
120
|
+
try {
|
|
121
|
+
url = new URL(endpoint ?? '');
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
throw new RenderServiceError({ code: 'load-failed', message: 'invalid desktop capture channel' });
|
|
125
|
+
}
|
|
126
|
+
if (!isPrivateCaptureEndpoint({ url }) || !/^[a-f0-9]{64}$/.test(token ?? '')) {
|
|
127
|
+
throw new RenderServiceError({ code: 'load-failed', message: 'invalid desktop capture channel' });
|
|
128
|
+
}
|
|
129
|
+
return { async captureUrl(request, { signal } = {}) {
|
|
130
|
+
const timeout = AbortSignal.timeout(URL_CAPTURE_TIMEOUT_MS);
|
|
131
|
+
try {
|
|
132
|
+
const response = await send(url.href, { method: 'POST', redirect: 'error',
|
|
133
|
+
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
|
134
|
+
body: JSON.stringify(readUrlCaptureRequest({ value: request })),
|
|
135
|
+
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
|
136
|
+
});
|
|
137
|
+
return await readCaptureResponse({ response });
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (error instanceof RenderServiceError)
|
|
141
|
+
throw error;
|
|
142
|
+
const code = timeout.aborted ? 'timeout' : signal?.aborted ? 'aborted' : 'load-failed';
|
|
143
|
+
throw new RenderServiceError({ code, message: 'desktop capture channel unavailable' });
|
|
144
|
+
}
|
|
145
|
+
} };
|
|
146
|
+
}
|
|
147
|
+
//# sourceMappingURL=render-bridge.js.map
|
package/dist/render-service.js
CHANGED
|
@@ -56,14 +56,18 @@ export async function withRenderTimeout({ promise }, { timeoutMs, signal } = {})
|
|
|
56
56
|
? null
|
|
57
57
|
: setTimeout(() => {
|
|
58
58
|
settled = true;
|
|
59
|
+
signal?.removeEventListener('abort', onAbort);
|
|
59
60
|
reject(new RenderServiceError({ message: `render timed out after ${timeoutMs}ms`, code: 'timeout' }));
|
|
60
61
|
}, timeoutMs);
|
|
62
|
+
// No `if (settled) return` guard here either: every settling path (the
|
|
63
|
+
// timer above and both `promise.then` handlers) removes this listener as
|
|
64
|
+
// it settles, settling never happens synchronously inside an `abort`
|
|
65
|
+
// dispatch, and the listener is `once` — so it can only run unsettled.
|
|
61
66
|
const onAbort = () => {
|
|
62
|
-
if (settled)
|
|
63
|
-
return;
|
|
64
67
|
settled = true;
|
|
65
68
|
if (timer != null)
|
|
66
69
|
clearTimeout(timer);
|
|
70
|
+
signal?.removeEventListener('abort', onAbort);
|
|
67
71
|
reject(new RenderServiceError({ message: 'render aborted', code: 'aborted' }));
|
|
68
72
|
};
|
|
69
73
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
@@ -96,6 +96,12 @@ async function checkAvailability(deps) {
|
|
|
96
96
|
throw new Error(deps.messages.invalidOutput({ stdout: JSON.stringify(result) }));
|
|
97
97
|
return { available: result.available, reason: result.reason ?? undefined };
|
|
98
98
|
}
|
|
99
|
+
function readSuccessfulTranscription({ result, messages }, _options = {}) {
|
|
100
|
+
if ((result.text !== undefined && typeof result.text !== "string") || (result.elapsedMs !== undefined && (typeof result.elapsedMs !== "number" || !Number.isFinite(result.elapsedMs)))) {
|
|
101
|
+
throw new Error(messages.invalidOutput({ stdout: JSON.stringify(result) }));
|
|
102
|
+
}
|
|
103
|
+
return { text: result.text ?? "", elapsedMs: result.elapsedMs ?? 0 };
|
|
104
|
+
}
|
|
99
105
|
/** Transcribe scratch WAV input and remove the recording on every completion path. */
|
|
100
106
|
async function transcribeWav({ wavBuffer, ...deps }) {
|
|
101
107
|
const compiled = await ensureHelperCompiled(deps);
|
|
@@ -107,10 +113,7 @@ async function transcribeWav({ wavBuffer, ...deps }) {
|
|
|
107
113
|
const result = await runHelperJson({ execFileAsync: deps.execFileAsync, binaryPath: deps.binaryPath, args: ["transcribe", tempPath, deps.locale], messages: deps.messages });
|
|
108
114
|
if (result.ok !== true)
|
|
109
115
|
throw new Error(deps.messages.recognitionFailed({ reason: result.error ?? "" }));
|
|
110
|
-
|
|
111
|
-
throw new Error(deps.messages.invalidOutput({ stdout: JSON.stringify(result) }));
|
|
112
|
-
}
|
|
113
|
-
return { text: result.text ?? "", elapsedMs: result.elapsedMs ?? 0 };
|
|
116
|
+
return readSuccessfulTranscription({ result, messages: deps.messages });
|
|
114
117
|
}
|
|
115
118
|
finally {
|
|
116
119
|
deps.fs.rmSync({ path: tempPath }, { force: true });
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export declare const URL_CAPTURE_TIMEOUT_MS = 20000;
|
|
2
|
+
export declare const URL_CAPTURE_MAX_BYTES: number;
|
|
3
|
+
export interface UrlCaptureRequest {
|
|
4
|
+
url: string;
|
|
5
|
+
viewport: {
|
|
6
|
+
width: number;
|
|
7
|
+
height: number;
|
|
8
|
+
deviceScaleFactor?: number;
|
|
9
|
+
isMobile?: boolean;
|
|
10
|
+
};
|
|
11
|
+
fullPage: boolean;
|
|
12
|
+
maxPageHeightPx: number;
|
|
13
|
+
settleMs: number;
|
|
14
|
+
}
|
|
15
|
+
export interface UrlCaptureResult {
|
|
16
|
+
png: Uint8Array;
|
|
17
|
+
finalUrl: string;
|
|
18
|
+
title: string;
|
|
19
|
+
status: number | null;
|
|
20
|
+
pageHeight: number;
|
|
21
|
+
capturedHeight: number;
|
|
22
|
+
blockedRequests: number;
|
|
23
|
+
}
|
|
24
|
+
export interface UrlCapturePort {
|
|
25
|
+
captureUrl(required: UrlCaptureRequest, options?: {
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
}): Promise<UrlCaptureResult>;
|
|
28
|
+
}
|
|
29
|
+
/** Exact HTTP(S) origins only: redirects, subresources and WebSockets use this same decision.
|
|
30
|
+
* @complexity O(n), for the small host-owned origin allowlist.
|
|
31
|
+
*/
|
|
32
|
+
export declare function isCaptureUrlAllowed({ url, allowedOrigins }: {
|
|
33
|
+
url: string;
|
|
34
|
+
allowedOrigins: readonly string[];
|
|
35
|
+
}, _options?: {}): boolean;
|
|
36
|
+
/** Parse the wire request before allocating a renderer; reject oversized images and waits.
|
|
37
|
+
* @throws RenderServiceError for invalid input. @complexity O(url length).
|
|
38
|
+
*/
|
|
39
|
+
export declare function readUrlCaptureRequest({ value }: {
|
|
40
|
+
value: unknown;
|
|
41
|
+
}, _options?: {}): UrlCaptureRequest;
|
|
42
|
+
//# sourceMappingURL=url-capture.d.ts.map
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Bounded URL-capture contract shared by the native renderer and its private transport. */
|
|
2
|
+
import { RenderServiceError } from './render-service.js';
|
|
3
|
+
export const URL_CAPTURE_TIMEOUT_MS = 20_000;
|
|
4
|
+
export const URL_CAPTURE_MAX_BYTES = 16 * 1024 * 1024;
|
|
5
|
+
/** Exact HTTP(S) origins only: redirects, subresources and WebSockets use this same decision.
|
|
6
|
+
* @complexity O(n), for the small host-owned origin allowlist.
|
|
7
|
+
*/
|
|
8
|
+
export function isCaptureUrlAllowed({ url, allowedOrigins }, _options = {}) {
|
|
9
|
+
try {
|
|
10
|
+
const parsed = new URL(url);
|
|
11
|
+
return ['http:', 'https:'].includes(parsed.protocol) && !parsed.username && !parsed.password && allowedOrigins.includes(parsed.origin);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function integerInRange({ value, min, max }, _options = {}) {
|
|
18
|
+
return typeof value === 'number' && Number.isInteger(value) && value >= min && value <= max;
|
|
19
|
+
}
|
|
20
|
+
function validCaptureViewport({ viewport }, _options = {}) {
|
|
21
|
+
return !!viewport && integerInRange({ value: viewport.width, min: 1, max: 1280 })
|
|
22
|
+
&& integerInRange({ value: viewport.height, min: 1, max: 1024 })
|
|
23
|
+
&& [undefined, 1, 2].includes(viewport.deviceScaleFactor)
|
|
24
|
+
&& [undefined, true, false].includes(viewport.isMobile);
|
|
25
|
+
}
|
|
26
|
+
/** Parse the wire request before allocating a renderer; reject oversized images and waits.
|
|
27
|
+
* @throws RenderServiceError for invalid input. @complexity O(url length).
|
|
28
|
+
*/
|
|
29
|
+
export function readUrlCaptureRequest({ value }, _options = {}) {
|
|
30
|
+
const request = value;
|
|
31
|
+
const viewport = request?.viewport;
|
|
32
|
+
if (!request || typeof request.url !== 'string' || request.url.length > 2048 || !validCaptureViewport({ viewport })
|
|
33
|
+
|| typeof request.fullPage !== 'boolean' || !integerInRange({ value: request.maxPageHeightPx, min: 1, max: 8000 })
|
|
34
|
+
|| !integerInRange({ value: request.settleMs, min: 0, max: 5000 })) {
|
|
35
|
+
throw new RenderServiceError({ code: 'load-failed', message: 'invalid capture request' });
|
|
36
|
+
}
|
|
37
|
+
return { url: request.url, viewport: { ...viewport }, fullPage: request.fullPage,
|
|
38
|
+
maxPageHeightPx: request.maxPageHeightPx, settleMs: request.settleMs };
|
|
39
|
+
}
|
|
40
|
+
//# sourceMappingURL=url-capture.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/desktop-host",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.3",
|
|
4
4
|
"description": "Shell-agnostic desktop-host ports: single-instance lock, window lifecycle, protocol handling, sidecar launch, paths, and config. Electron and Tauri assemblies live behind ./electron and ./tauri.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
"entries": {
|
|
16
16
|
".": "desktop",
|
|
17
17
|
"./bridge-testing": "universal",
|
|
18
|
+
"./render-bridge": "node",
|
|
18
19
|
"./electron": "desktop",
|
|
19
20
|
"./tauri": "desktop",
|
|
20
21
|
"./shutdown": "node",
|
|
@@ -32,6 +33,11 @@
|
|
|
32
33
|
"main": "./dist/index.js",
|
|
33
34
|
"types": "./dist/index.d.ts",
|
|
34
35
|
"exports": {
|
|
36
|
+
"./render-bridge": {
|
|
37
|
+
"types": "./dist/render-bridge.d.ts",
|
|
38
|
+
"import": "./dist/render-bridge.js",
|
|
39
|
+
"default": "./dist/render-bridge.js"
|
|
40
|
+
},
|
|
35
41
|
".": {
|
|
36
42
|
"types": "./dist/index.d.ts",
|
|
37
43
|
"import": "./dist/index.js",
|
|
@@ -107,10 +113,10 @@
|
|
|
107
113
|
},
|
|
108
114
|
"devDependencies": {
|
|
109
115
|
"@vitest/coverage-v8": "^2.1.9",
|
|
110
|
-
"@jini-ai/core": "^0.4.
|
|
116
|
+
"@jini-ai/core": "^0.4.9"
|
|
111
117
|
},
|
|
112
118
|
"dependencies": {
|
|
113
|
-
"@jini-ai/core": "^0.4.
|
|
119
|
+
"@jini-ai/core": "^0.4.9"
|
|
114
120
|
},
|
|
115
121
|
"peerDependencies": {},
|
|
116
122
|
"peerDependenciesMeta": {},
|