blockflow-bridge 0.0.0-stage → 1.0.1
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/LICENSE +21 -0
- package/README.md +49 -2
- package/cli.d.mts +1 -0
- package/cli.mjs +127 -0
- package/client.d.mts +23 -0
- package/client.mjs +158 -0
- package/framing.d.mts +17 -0
- package/framing.mjs +132 -0
- package/host.d.mts +13 -0
- package/host.mjs +377 -0
- package/index.d.mts +6 -0
- package/index.mjs +25 -0
- package/install.d.mts +31 -0
- package/install.mjs +309 -0
- package/package.json +37 -4
- package/paths.d.mts +7 -0
- package/paths.mjs +95 -0
- package/protocol.d.mts +22 -0
- package/protocol.mjs +24 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 BlockFlow contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,50 @@
|
|
|
1
|
-
#
|
|
1
|
+
# blockflow-bridge
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Native messaging host for the [BlockFlow](https://github.com/akibh-dev/blockflow) browser extension. It lets local programs (the
|
|
4
|
+
`blockflow-mcp` MCP server, the `blockflow` CLI, your own scripts) validate, import and run workflows in
|
|
5
|
+
your browser.
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
your program ──local socket (NDJSON, token)──▶ blockflow-bridge ──native messaging──▶ BlockFlow extension
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
1. In BlockFlow, open **Settings** and copy the extension id.
|
|
14
|
+
2. Install the host for your browsers:
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
npx blockflow-bridge install --extension-id <id> # Chrome, Chromium, Brave, Edge
|
|
18
|
+
npx blockflow-bridge install --browser firefox # Firefox (fixed id, no --extension-id)
|
|
19
|
+
npx blockflow-bridge install --extension-id <id> --browser brave --browser firefox
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
This writes a small launcher (it runs this package's `host.mjs` with the current Node) and a
|
|
23
|
+
`dev.akibh.blockflow.json` manifest where each browser looks for it (registry keys on Windows).
|
|
24
|
+
3. Switch on **Allow outside control** in BlockFlow Settings. The browser starts the host; it listens on
|
|
25
|
+
`$XDG_RUNTIME_DIR/blockflow.sock` (or `~/.config/blockflow/blockflow.sock`; `\\.\pipe\blockflow-<user>` on
|
|
26
|
+
Windows) and the token is in `~/.config/blockflow/token`.
|
|
27
|
+
|
|
28
|
+
`npx blockflow-bridge status` shows the manifests found and whether the bridge answers.
|
|
29
|
+
`npx blockflow-bridge uninstall` removes everything again. `--dir <folder>` installs into one folder instead
|
|
30
|
+
(for example `<chromium profile>/NativeMessagingHosts`).
|
|
31
|
+
|
|
32
|
+
## Use it from Node
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
import { connectBridge } from 'blockflow-bridge/client';
|
|
36
|
+
|
|
37
|
+
const bridge = await connectBridge({ client: 'my-script' });
|
|
38
|
+
const { ok, issues } = await bridge.call('validate', { source: scriptText });
|
|
39
|
+
const result = await bridge.call('run', { source: scriptText }, { timeoutMs: 0, onNotification: (n) => console.log(n.method) });
|
|
40
|
+
bridge.close();
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Errors are `BridgeError` with `.code` (JSON-RPC code, see `blockflow-bridge/protocol`) and `.data`.
|
|
44
|
+
The methods and their parameters are in the extension's
|
|
45
|
+
[`src/core/bridgeProtocol.ts`](https://github.com/akibh-dev/blockflow/blob/main/src/core/bridgeProtocol.ts).
|
|
46
|
+
|
|
47
|
+
Environment: `BLOCKFLOW_SOCKET` and `BLOCKFLOW_TOKEN_FILE` override the paths (set them on the browser and on
|
|
48
|
+
the client alike).
|
|
49
|
+
|
|
50
|
+
Internals: [Bridge wiki](https://github.com/akibh-dev/blockflow/wiki/Bridge).
|
package/cli.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function main(argv: string[], io?: { out?: (text: string) => void; err?: (text: string) => void; env?: Record<string, string | undefined> }): Promise<number>;
|
package/cli.mjs
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// blockflow-bridge install | uninstall | status | host
|
|
3
|
+
import { realpathSync } from 'node:fs';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { parseArgs } from 'node:util';
|
|
6
|
+
import { BridgeError, connectBridge } from './client.mjs';
|
|
7
|
+
import { runHost } from './host.mjs';
|
|
8
|
+
import { BROWSERS, findManifests, installHost, uninstallHost } from './install.mjs';
|
|
9
|
+
import { socketPath, tokenFile } from './paths.mjs';
|
|
10
|
+
|
|
11
|
+
const USAGE = `Usage:
|
|
12
|
+
blockflow-bridge install --extension-id <id> [--extension-id <id>...] [--browser chrome|chromium|brave|brave-origin|edge|firefox|all]... [--dir <folder>]...
|
|
13
|
+
blockflow-bridge uninstall [--browser <name>]... [--dir <folder>]...
|
|
14
|
+
blockflow-bridge status
|
|
15
|
+
blockflow-bridge host (what the browser runs; speaks native messaging on stdin/stdout)
|
|
16
|
+
|
|
17
|
+
The extension id is shown in BlockFlow > Settings. --dir writes the manifest (and the launcher) into the given
|
|
18
|
+
folder instead of the browsers' own folders, e.g. <profile>/NativeMessagingHosts for one Chromium profile.`;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Runs one command. Returns the exit code (0 ok, 1 failure, 2 usage).
|
|
22
|
+
* @param {string[]} argv arguments after the program name
|
|
23
|
+
* @param {{ out?: (text: string) => void, err?: (text: string) => void, env?: Record<string, string | undefined> }} [io]
|
|
24
|
+
*/
|
|
25
|
+
export async function main(argv, io = {}) {
|
|
26
|
+
const out = io.out ?? ((text) => process.stdout.write(`${text}\n`));
|
|
27
|
+
const err = io.err ?? ((text) => process.stderr.write(`${text}\n`));
|
|
28
|
+
const env = io.env ?? process.env;
|
|
29
|
+
const [command, ...rest] = argv;
|
|
30
|
+
// Chromium starts the launcher with the caller's origin as the first argument; the launcher runs host.mjs,
|
|
31
|
+
// but a hand-written launcher may call `cli.mjs host` too.
|
|
32
|
+
if (command === 'host' || command?.startsWith('chrome-extension://')) {
|
|
33
|
+
return runHost({ stdin: process.stdin, stdout: process.stdout, env });
|
|
34
|
+
}
|
|
35
|
+
let values;
|
|
36
|
+
try {
|
|
37
|
+
({ values } = parseArgs({
|
|
38
|
+
args: rest,
|
|
39
|
+
options: {
|
|
40
|
+
'extension-id': { type: 'string', multiple: true },
|
|
41
|
+
browser: { type: 'string', multiple: true },
|
|
42
|
+
dir: { type: 'string', multiple: true },
|
|
43
|
+
help: { type: 'boolean', short: 'h' },
|
|
44
|
+
},
|
|
45
|
+
}));
|
|
46
|
+
} catch (error) {
|
|
47
|
+
err(`${/** @type {Error} */ (error).message}\n\n${USAGE}`);
|
|
48
|
+
return 2;
|
|
49
|
+
}
|
|
50
|
+
if (values.help || !command || command === 'help' || command === '--help' || command === '-h') {
|
|
51
|
+
out(USAGE);
|
|
52
|
+
return command ? 0 : 2;
|
|
53
|
+
}
|
|
54
|
+
/** @type {any[] | undefined} */
|
|
55
|
+
let browsers;
|
|
56
|
+
try {
|
|
57
|
+
browsers = parseBrowsers(values.browser);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
err(/** @type {Error} */ (error).message);
|
|
60
|
+
return 2;
|
|
61
|
+
}
|
|
62
|
+
const extensionIds = (values['extension-id'] ?? []).flatMap((value) => value.split(',')).map((id) => id.trim()).filter(Boolean);
|
|
63
|
+
const dirs = values.dir;
|
|
64
|
+
|
|
65
|
+
if (command === 'install') {
|
|
66
|
+
try {
|
|
67
|
+
const firefox = browsers ? browsers.includes('firefox') : false;
|
|
68
|
+
const chosen = browsers ?? (extensionIds.length ? undefined : []);
|
|
69
|
+
const result = installHost({ extensionIds, firefox, browsers: chosen, dirs });
|
|
70
|
+
out(`Launcher: ${result.launcher}`);
|
|
71
|
+
for (const file of result.manifests) out(`Manifest: ${file}`);
|
|
72
|
+
for (const entry of result.registry) out(`Registry: ${entry.key} -> ${entry.manifest}`);
|
|
73
|
+
out('Done. Switch on "Allow outside control" in BlockFlow > Settings (or switch it off and on again).');
|
|
74
|
+
return 0;
|
|
75
|
+
} catch (error) {
|
|
76
|
+
err(`Install failed: ${/** @type {Error} */ (error).message}`);
|
|
77
|
+
return /could not|need|Nothing to install|not a Chromium/.test(String(error)) ? 2 : 1;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (command === 'uninstall') {
|
|
81
|
+
const result = uninstallHost({ browsers, dirs });
|
|
82
|
+
if (!result.removed.length && !result.registry.length) out('Nothing to remove.');
|
|
83
|
+
for (const file of result.removed) out(`Removed: ${file}`);
|
|
84
|
+
for (const key of result.registry) out(`Removed registry key: ${key}`);
|
|
85
|
+
return 0;
|
|
86
|
+
}
|
|
87
|
+
if (command === 'status') {
|
|
88
|
+
const manifests = findManifests();
|
|
89
|
+
if (!manifests.length) out('Manifests: none found (run blockflow-bridge install --extension-id <id>)');
|
|
90
|
+
for (const { browser, file } of manifests) out(`Manifest (${browser}): ${file}`);
|
|
91
|
+
out(`Socket: ${socketPath(env)}`);
|
|
92
|
+
out(`Token file: ${tokenFile(env)}`);
|
|
93
|
+
try {
|
|
94
|
+
const bridge = await connectBridge({ env, client: 'blockflow-bridge status', timeoutMs: 5000 });
|
|
95
|
+
out(`Bridge: reachable, extension ${bridge.extensionConnected ? 'connected' : 'not connected'}`);
|
|
96
|
+
bridge.close();
|
|
97
|
+
return 0;
|
|
98
|
+
} catch (error) {
|
|
99
|
+
out(`Bridge: ${error instanceof BridgeError ? error.message : String(error)}`);
|
|
100
|
+
return 1;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
err(`Unknown command "${command}".\n\n${USAGE}`);
|
|
104
|
+
return 2;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** @param {string[] | undefined} values */
|
|
108
|
+
function parseBrowsers(values) {
|
|
109
|
+
if (!values?.length) return undefined;
|
|
110
|
+
const names = values.flatMap((value) => value.split(',')).map((name) => name.trim().toLowerCase()).filter(Boolean);
|
|
111
|
+
if (names.includes('all')) return [...BROWSERS];
|
|
112
|
+
for (const name of names) if (!BROWSERS.includes(name)) throw new Error(`Unknown browser "${name}" (use ${BROWSERS.join(', ')} or all)`);
|
|
113
|
+
return names;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const invokedAs = (() => {
|
|
117
|
+
try {
|
|
118
|
+
return realpathSync(process.argv[1] ?? '');
|
|
119
|
+
} catch {
|
|
120
|
+
return process.argv[1];
|
|
121
|
+
}
|
|
122
|
+
})();
|
|
123
|
+
if (invokedAs === fileURLToPath(import.meta.url)) {
|
|
124
|
+
main(process.argv.slice(2)).then((code) => {
|
|
125
|
+
process.stdout.write('', () => process.exit(code));
|
|
126
|
+
});
|
|
127
|
+
}
|
package/client.d.mts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export declare const NOT_REACHABLE: string;
|
|
2
|
+
export declare class BridgeError extends Error {
|
|
3
|
+
constructor(code: number, message: string, data?: { code?: string; [key: string]: unknown });
|
|
4
|
+
/** JSON-RPC error code (RPC_ERRORS). */
|
|
5
|
+
code: number;
|
|
6
|
+
data?: { code?: string; [key: string]: unknown };
|
|
7
|
+
}
|
|
8
|
+
export type Notification = { jsonrpc: '2.0'; method: string; params: any };
|
|
9
|
+
export type CallOptions = { onNotification?: (notification: Notification) => void; timeoutMs?: number };
|
|
10
|
+
export type BridgeConnection = {
|
|
11
|
+
call(method: string, params?: unknown, options?: CallOptions): Promise<any>;
|
|
12
|
+
close(): void;
|
|
13
|
+
extensionConnected: boolean;
|
|
14
|
+
/** Resolves when the socket closes. */
|
|
15
|
+
closed: Promise<void>;
|
|
16
|
+
};
|
|
17
|
+
export declare function connectBridge(options?: {
|
|
18
|
+
socketPath?: string;
|
|
19
|
+
tokenFile?: string;
|
|
20
|
+
client?: string;
|
|
21
|
+
timeoutMs?: number;
|
|
22
|
+
env?: Record<string, string | undefined>;
|
|
23
|
+
}): Promise<BridgeConnection>;
|
package/client.mjs
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// Client for the bridge socket, used by the MCP server and the CLI:
|
|
2
|
+
//
|
|
3
|
+
// const bridge = await connectBridge({ client: 'blockflow-mcp' });
|
|
4
|
+
// const { run } = await bridge.call('run', { source }, { onNotification: (n) => console.error(n.method) });
|
|
5
|
+
// bridge.close();
|
|
6
|
+
//
|
|
7
|
+
// Every failure is a BridgeError with the JSON-RPC `.code` (RPC_ERRORS) and `.data`.
|
|
8
|
+
import net from 'node:net';
|
|
9
|
+
import { createLineSplitter, encodeLine } from './framing.mjs';
|
|
10
|
+
import { readToken, socketPath as defaultSocketPath, tokenFile as defaultTokenFile } from './paths.mjs';
|
|
11
|
+
import { BRIDGE_PROTOCOL_VERSION, MAX_MESSAGE_BYTES, RPC_ERRORS } from './protocol.mjs';
|
|
12
|
+
|
|
13
|
+
export const NOT_REACHABLE = 'BlockFlow is not reachable: is the browser open with Allow outside control on, and the bridge installed?';
|
|
14
|
+
|
|
15
|
+
export class BridgeError extends Error {
|
|
16
|
+
/**
|
|
17
|
+
* @param {number} code JSON-RPC error code (see RPC_ERRORS)
|
|
18
|
+
* @param {string} message
|
|
19
|
+
* @param {{ code?: string, [key: string]: unknown }} [data]
|
|
20
|
+
*/
|
|
21
|
+
constructor(code, message, data) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.name = 'BridgeError';
|
|
24
|
+
this.code = code;
|
|
25
|
+
this.data = data;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @typedef {{ jsonrpc: '2.0', method: string, params: any }} Notification
|
|
31
|
+
* @typedef {{ onNotification?: (notification: Notification) => void, timeoutMs?: number }} CallOptions
|
|
32
|
+
* @typedef {{
|
|
33
|
+
* call: (method: string, params?: unknown, options?: CallOptions) => Promise<any>,
|
|
34
|
+
* close: () => void,
|
|
35
|
+
* extensionConnected: boolean,
|
|
36
|
+
* closed: Promise<void>,
|
|
37
|
+
* }} BridgeConnection
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Connects and authenticates. `timeoutMs` (default 120 s) covers connecting and is the default for each
|
|
42
|
+
* `call`; pass `timeoutMs: 0` to a call to wait as long as it takes (a long `run`).
|
|
43
|
+
* @param {{ socketPath?: string, tokenFile?: string, client?: string, timeoutMs?: number, env?: Record<string, string | undefined> }} [options]
|
|
44
|
+
* @returns {Promise<BridgeConnection>}
|
|
45
|
+
*/
|
|
46
|
+
export async function connectBridge(options = {}) {
|
|
47
|
+
const env = options.env ?? process.env;
|
|
48
|
+
const where = options.socketPath ?? defaultSocketPath(env);
|
|
49
|
+
const tokenPath = options.tokenFile ?? defaultTokenFile(env);
|
|
50
|
+
const defaultTimeout = options.timeoutMs ?? 120_000;
|
|
51
|
+
|
|
52
|
+
let token;
|
|
53
|
+
try {
|
|
54
|
+
token = readToken(tokenPath);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
const code = /** @type {NodeJS.ErrnoException} */ (error).code;
|
|
57
|
+
if (code === 'ENOENT') throw new BridgeError(RPC_ERRORS.notConnected, NOT_REACHABLE, { code: 'ENOENT', path: tokenPath });
|
|
58
|
+
throw new BridgeError(RPC_ERRORS.internal, `Cannot read the bridge token ${tokenPath}: ${/** @type {Error} */ (error).message}`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const socket = await new Promise((resolve, reject) => {
|
|
62
|
+
const candidate = net.createConnection(where);
|
|
63
|
+
const timer = defaultTimeout > 0 ? setTimeout(() => {
|
|
64
|
+
candidate.destroy();
|
|
65
|
+
reject(new BridgeError(RPC_ERRORS.notConnected, `${NOT_REACHABLE} (connecting to ${where} timed out)`, { code: 'TIMEOUT', path: where }));
|
|
66
|
+
}, defaultTimeout) : undefined;
|
|
67
|
+
candidate.once('connect', () => {
|
|
68
|
+
clearTimeout(timer);
|
|
69
|
+
candidate.off('error', onError);
|
|
70
|
+
resolve(candidate);
|
|
71
|
+
});
|
|
72
|
+
const onError = (/** @type {NodeJS.ErrnoException} */ error) => {
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
if (error.code === 'ENOENT' || error.code === 'ECONNREFUSED') reject(new BridgeError(RPC_ERRORS.notConnected, NOT_REACHABLE, { code: error.code, path: where }));
|
|
75
|
+
else reject(new BridgeError(RPC_ERRORS.notConnected, `${NOT_REACHABLE} (${error.message})`, { code: error.code, path: where }));
|
|
76
|
+
};
|
|
77
|
+
candidate.once('error', onError);
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
let nextId = 1;
|
|
81
|
+
let isClosed = false;
|
|
82
|
+
/** @type {Map<number, { resolve: (value: any) => void, reject: (error: Error) => void, onNotification?: (n: Notification) => void, timer?: NodeJS.Timeout }>} */
|
|
83
|
+
const waiting = new Map();
|
|
84
|
+
/** @type {() => void} */
|
|
85
|
+
let markClosed = () => {};
|
|
86
|
+
const closed = new Promise((resolve) => (markClosed = () => resolve(undefined)));
|
|
87
|
+
/** Why the host hung up, when it said so (bridge.disabled etc. arrive as errors on pending calls). */
|
|
88
|
+
let closeReason = 'The BlockFlow bridge closed the connection (the browser closed, or outside control was switched off).';
|
|
89
|
+
|
|
90
|
+
const splitter = createLineSplitter({
|
|
91
|
+
maxBytes: MAX_MESSAGE_BYTES + 64 * 1024,
|
|
92
|
+
onLine: (line) => {
|
|
93
|
+
/** @type {any} */
|
|
94
|
+
let message;
|
|
95
|
+
try {
|
|
96
|
+
message = JSON.parse(line);
|
|
97
|
+
} catch {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (message && typeof message.method === 'string' && message.id === undefined) {
|
|
101
|
+
const entry = waiting.get(Number(message.params?.requestId));
|
|
102
|
+
entry?.onNotification?.(message);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (message?.id === null && message.error) {
|
|
106
|
+
// The host rejected something it could not tie to a request (e.g. a line over the limit).
|
|
107
|
+
closeReason = message.error.message;
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const entry = waiting.get(Number(message?.id));
|
|
111
|
+
if (!entry) return;
|
|
112
|
+
waiting.delete(Number(message.id));
|
|
113
|
+
clearTimeout(entry.timer);
|
|
114
|
+
if (message.error) entry.reject(new BridgeError(message.error.code, message.error.message, message.error.data));
|
|
115
|
+
else entry.resolve(message.result);
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
socket.on('data', (chunk) => splitter.push(chunk));
|
|
119
|
+
socket.on('error', () => {});
|
|
120
|
+
socket.on('close', () => {
|
|
121
|
+
isClosed = true;
|
|
122
|
+
for (const [id, entry] of waiting) {
|
|
123
|
+
waiting.delete(id);
|
|
124
|
+
clearTimeout(entry.timer);
|
|
125
|
+
entry.reject(new BridgeError(RPC_ERRORS.notConnected, closeReason));
|
|
126
|
+
}
|
|
127
|
+
markClosed();
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
/** @type {BridgeConnection['call']} */
|
|
131
|
+
function call(method, params = {}, callOptions = {}) {
|
|
132
|
+
if (isClosed) return Promise.reject(new BridgeError(RPC_ERRORS.notConnected, closeReason));
|
|
133
|
+
const id = nextId++;
|
|
134
|
+
const timeoutMs = callOptions.timeoutMs ?? defaultTimeout;
|
|
135
|
+
return new Promise((resolve, reject) => {
|
|
136
|
+
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
137
|
+
waiting.delete(id);
|
|
138
|
+
reject(new BridgeError(RPC_ERRORS.internal, `BlockFlow did not answer ${method} within ${Math.round(timeoutMs / 100) / 10} s`, { code: 'TIMEOUT', method }));
|
|
139
|
+
}, timeoutMs) : undefined;
|
|
140
|
+
waiting.set(id, { resolve, reject, onNotification: callOptions.onNotification, timer });
|
|
141
|
+
socket.write(encodeLine({ jsonrpc: '2.0', id, method, params }));
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function close() {
|
|
146
|
+
socket.end();
|
|
147
|
+
setTimeout(() => socket.destroy(), 500).unref();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
let auth;
|
|
151
|
+
try {
|
|
152
|
+
auth = await call('auth', { token, protocol: BRIDGE_PROTOCOL_VERSION, ...(options.client ? { client: options.client } : {}) });
|
|
153
|
+
} catch (error) {
|
|
154
|
+
socket.destroy();
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
return { call, close, extensionConnected: Boolean(auth?.extensionConnected), closed };
|
|
158
|
+
}
|
package/framing.d.mts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare class FrameTooLargeError extends Error {
|
|
2
|
+
constructor(size: number, limit: number);
|
|
3
|
+
size: number;
|
|
4
|
+
limit: number;
|
|
5
|
+
}
|
|
6
|
+
export declare function encodeNative(message: unknown, maxBytes?: number): Buffer;
|
|
7
|
+
export declare function createNativeDecoder(handlers: {
|
|
8
|
+
onMessage: (message: unknown) => void;
|
|
9
|
+
onError?: (error: Error) => void;
|
|
10
|
+
maxBytes?: number;
|
|
11
|
+
}): { push(chunk: Buffer | Uint8Array | string): void; readonly pending: number };
|
|
12
|
+
export declare function encodeLine(message: unknown): string;
|
|
13
|
+
export declare function createLineSplitter(handlers: {
|
|
14
|
+
onLine: (line: string) => void;
|
|
15
|
+
onError?: (error: Error) => void;
|
|
16
|
+
maxBytes?: number;
|
|
17
|
+
}): { push(chunk: Buffer | Uint8Array | string): void };
|
package/framing.mjs
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// The two wire formats of the bridge.
|
|
2
|
+
//
|
|
3
|
+
// Native messaging (host <-> browser, on stdin/stdout): every message is a 4-byte little-endian length
|
|
4
|
+
// followed by that many bytes of UTF-8 JSON. Chunks from a pipe can hold part of a frame or several.
|
|
5
|
+
// NDJSON (client <-> host, on the local socket): one JSON message per line.
|
|
6
|
+
import { MAX_MESSAGE_BYTES } from './protocol.mjs';
|
|
7
|
+
|
|
8
|
+
/** Thrown (or passed to `onError`) when a message is over the size limit. */
|
|
9
|
+
export class FrameTooLargeError extends Error {
|
|
10
|
+
/** @param {number} size @param {number} limit */
|
|
11
|
+
constructor(size, limit) {
|
|
12
|
+
super(`Message of ${size} bytes is over the ${limit} byte limit`);
|
|
13
|
+
this.name = 'FrameTooLargeError';
|
|
14
|
+
this.size = size;
|
|
15
|
+
this.limit = limit;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* One native message: length prefix + UTF-8 JSON.
|
|
21
|
+
* @param {unknown} message
|
|
22
|
+
* @param {number} [maxBytes]
|
|
23
|
+
* @returns {Buffer}
|
|
24
|
+
*/
|
|
25
|
+
export function encodeNative(message, maxBytes = MAX_MESSAGE_BYTES) {
|
|
26
|
+
const body = Buffer.from(JSON.stringify(message), 'utf8');
|
|
27
|
+
if (body.length > maxBytes) throw new FrameTooLargeError(body.length, maxBytes);
|
|
28
|
+
const frame = Buffer.allocUnsafe(4 + body.length);
|
|
29
|
+
frame.writeUInt32LE(body.length, 0);
|
|
30
|
+
body.copy(frame, 4);
|
|
31
|
+
return frame;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Stream parser for native messages. Feed it chunks with `push`; it calls `onMessage` once per complete
|
|
36
|
+
* frame. A frame over `maxBytes` is skipped (its bytes are still consumed, so the stream stays in step) and
|
|
37
|
+
* reported to `onError`; a frame that is not JSON is reported too.
|
|
38
|
+
* @param {{ onMessage: (message: unknown) => void, onError?: (error: Error) => void, maxBytes?: number }} handlers
|
|
39
|
+
*/
|
|
40
|
+
export function createNativeDecoder({ onMessage, onError = () => {}, maxBytes = MAX_MESSAGE_BYTES }) {
|
|
41
|
+
/** @type {Buffer} */
|
|
42
|
+
let buffered = Buffer.alloc(0);
|
|
43
|
+
/** Bytes of an oversize frame still to throw away. */
|
|
44
|
+
let skipping = 0;
|
|
45
|
+
return {
|
|
46
|
+
/** @param {Buffer | Uint8Array | string} chunk */
|
|
47
|
+
push(chunk) {
|
|
48
|
+
let data = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : Buffer.from(chunk);
|
|
49
|
+
if (skipping > 0) {
|
|
50
|
+
const dropped = Math.min(skipping, data.length);
|
|
51
|
+
skipping -= dropped;
|
|
52
|
+
data = data.subarray(dropped);
|
|
53
|
+
}
|
|
54
|
+
buffered = buffered.length ? Buffer.concat([buffered, data]) : data;
|
|
55
|
+
while (buffered.length >= 4) {
|
|
56
|
+
const size = buffered.readUInt32LE(0);
|
|
57
|
+
if (size > maxBytes) {
|
|
58
|
+
const available = buffered.length - 4;
|
|
59
|
+
skipping = Math.max(0, size - available);
|
|
60
|
+
buffered = buffered.subarray(4 + Math.min(size, available));
|
|
61
|
+
onError(new FrameTooLargeError(size, maxBytes));
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (buffered.length < 4 + size) break;
|
|
65
|
+
const body = buffered.subarray(4, 4 + size).toString('utf8');
|
|
66
|
+
buffered = buffered.subarray(4 + size);
|
|
67
|
+
let message;
|
|
68
|
+
try {
|
|
69
|
+
message = JSON.parse(body);
|
|
70
|
+
} catch (error) {
|
|
71
|
+
onError(new Error(`Native message is not JSON: ${/** @type {Error} */ (error).message}`));
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
onMessage(message);
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
/** Bytes held while waiting for the rest of a frame. */
|
|
78
|
+
get pending() {
|
|
79
|
+
return buffered.length;
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* One NDJSON line (JSON + "\n").
|
|
86
|
+
* @param {unknown} message
|
|
87
|
+
*/
|
|
88
|
+
export function encodeLine(message) {
|
|
89
|
+
return `${JSON.stringify(message)}\n`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Splits a byte stream into lines (UTF-8 safe across chunk boundaries; `\r\n` accepted; blank lines
|
|
94
|
+
* skipped). A line longer than `maxBytes` is dropped up to its newline and reported to `onError`.
|
|
95
|
+
* @param {{ onLine: (line: string) => void, onError?: (error: Error) => void, maxBytes?: number }} handlers
|
|
96
|
+
*/
|
|
97
|
+
export function createLineSplitter({ onLine, onError = () => {}, maxBytes = MAX_MESSAGE_BYTES }) {
|
|
98
|
+
/** @type {Buffer[]} */
|
|
99
|
+
let parts = [];
|
|
100
|
+
let size = 0;
|
|
101
|
+
let discarding = false;
|
|
102
|
+
return {
|
|
103
|
+
/** @param {Buffer | Uint8Array | string} chunk */
|
|
104
|
+
push(chunk) {
|
|
105
|
+
let data = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : Buffer.from(chunk);
|
|
106
|
+
while (data.length) {
|
|
107
|
+
const newline = data.indexOf(0x0a);
|
|
108
|
+
const piece = newline === -1 ? data : data.subarray(0, newline);
|
|
109
|
+
if (!discarding) {
|
|
110
|
+
parts.push(piece);
|
|
111
|
+
size += piece.length;
|
|
112
|
+
if (size > maxBytes) {
|
|
113
|
+
onError(new FrameTooLargeError(size, maxBytes));
|
|
114
|
+
parts = [];
|
|
115
|
+
size = 0;
|
|
116
|
+
discarding = true;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (newline === -1) break;
|
|
120
|
+
if (!discarding) {
|
|
121
|
+
let line = Buffer.concat(parts).toString('utf8');
|
|
122
|
+
if (line.endsWith('\r')) line = line.slice(0, -1);
|
|
123
|
+
if (line.trim()) onLine(line);
|
|
124
|
+
}
|
|
125
|
+
parts = [];
|
|
126
|
+
size = 0;
|
|
127
|
+
discarding = false;
|
|
128
|
+
data = data.subarray(newline + 1);
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
}
|
package/host.d.mts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare const EXIT: Readonly<{ ok: 0; error: 1; socketInUse: 3 }>;
|
|
2
|
+
export type HostOptions = {
|
|
3
|
+
stdin: NodeJS.ReadableStream;
|
|
4
|
+
stdout: NodeJS.WritableStream;
|
|
5
|
+
stderr?: { write(chunk: string | Uint8Array): boolean };
|
|
6
|
+
env?: Record<string, string | undefined>;
|
|
7
|
+
/** Close socket clients that have not sent `auth` within this time (default 10 s). */
|
|
8
|
+
authTimeoutMs?: number;
|
|
9
|
+
onReady?: (info: { socketPath: string; tokenFile: string }) => void;
|
|
10
|
+
};
|
|
11
|
+
/** Resolves with the exit code: 0 normal end, 1 could not listen, 3 socket served by another live host. */
|
|
12
|
+
export declare function runHost(options: HostOptions): Promise<number>;
|
|
13
|
+
export declare function isLive(socketPath: string): Promise<boolean>;
|