dsh-dragonbyte-client 0.0.0-stage → 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.
@@ -0,0 +1,275 @@
1
+ #!/usr/bin/env node
2
+ // `dsh-dragonbyte-host` — run on the machine that holds the MCP servers.
3
+ //
4
+ // DSH_DRAGONBYTE_TOKEN=... dsh-dragonbyte-host --email you@example.com
5
+ //
6
+ // With no `--mcp`, the servers are typed in one at a time. To reuse the config
7
+ // every MCP client already has, pass that file instead:
8
+ //
9
+ // dsh-dragonbyte-host --email you@example.com --mcp ./mcp.json
10
+ //
11
+ // { "mcpServers": {
12
+ // "fs": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/me"] },
13
+ // "docs": { "url": "https://mcp.example.com/mcp", "headers": { "authorization": "Bearer ..." } } } }
14
+
15
+ import { readFileSync, realpathSync } from 'node:fs';
16
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
17
+ import { homedir } from 'node:os';
18
+ import { dirname, join } from 'node:path';
19
+ import { pathToFileURL } from 'node:url';
20
+ import process from 'node:process';
21
+ import { createInterface } from 'node:readline/promises';
22
+
23
+ import { connectServers, fetchServers, serveBridge } from './host.mjs';
24
+
25
+ /**
26
+ * Where the credential lives, and why it is a file rather than a flag.
27
+ *
28
+ * ⚠ 0600 IN THE USER'S OWN CONFIG DIRECTORY, NEVER IN THE PROJECT. This file is
29
+ * a bearer credential for one person's DSH; a copy in a repository is a leaked
30
+ * credential, and a default umask would make it group-readable on a shared
31
+ * machine. `XDG_CONFIG_HOME` is honoured because that is where a desktop user
32
+ * looks when they need to revoke something by hand.
33
+ */
34
+ export function credentialPath(env = process.env) {
35
+ const base = env.DSH_DRAGONBYTE_CONFIG_DIR || join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'dsh-dragonbyte');
36
+ return join(base, 'credential.json');
37
+ }
38
+
39
+ /** `null` when nothing is saved — a first run, not an error. */
40
+ export async function loadCredential(env = process.env, io = {}) {
41
+ const read = io.readFile ?? readFile;
42
+ try {
43
+ const value = JSON.parse(await read(credentialPath(env), 'utf8'));
44
+ return value !== null && typeof value === 'object' && typeof value.token === 'string' ? value : null;
45
+ } catch (error) {
46
+ if (error?.code === 'ENOENT') return null;
47
+ // ⚠ AN UNREADABLE FILE IS NOT "NO CREDENTIAL". Silently prompting again would
48
+ // mint a second device for a machine that already has one, and the user
49
+ // would never learn their file is corrupt. Say so and let them fix it.
50
+ throw new Error(`could not read ${credentialPath(env)}: ${error?.message || error}`);
51
+ }
52
+ }
53
+
54
+ /** Write atomically: a crash mid-write must not leave a truncated credential. */
55
+ export async function saveCredential(value, env = process.env, io = {}) {
56
+ const write = io.writeFile ?? writeFile;
57
+ const renameFile = io.rename ?? rename;
58
+ const file = credentialPath(env);
59
+ const temporary = `${file}.${process.pid}.tmp`;
60
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
61
+ await write(temporary, `${JSON.stringify(value, null, 1)}\n`, { mode: 0o600 });
62
+ await renameFile(temporary, file);
63
+ }
64
+
65
+ function readlineAsk() {
66
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
67
+ return async (question) => (await rl.question(question)).trim();
68
+ }
69
+
70
+ function parseArgs(argv) {
71
+ const args = { bridge: '', mcp: '', tenant: '' };
72
+ for (let index = 0; index < argv.length; index += 1) {
73
+ const flag = argv[index];
74
+ const value = argv[index + 1];
75
+ // ⚠ `--email` IS STILL ACCEPTED AND STILL IGNORED. An operator's stored
76
+ // command line predates the credential and carries it; failing on an unknown
77
+ // flag would break a working setup for a value the device token now supplies.
78
+ if (flag === '--email') { index += 1; }
79
+ else if (flag === '--bridge') { args.bridge = value ?? ''; index += 1; }
80
+ else if (flag === '--mcp') { args.mcp = value ?? ''; index += 1; }
81
+ else if (flag === '--tenant') { args.tenant = value ?? ''; index += 1; }
82
+ else if (flag === '--help' || flag === '-h') args.help = true;
83
+ }
84
+ return args;
85
+ }
86
+
87
+ const SERVER_NAME = /^[a-z][a-z0-9-]{0,31}$/;
88
+
89
+ /** `{mcpServers:{...}}` -> the array `connectServers` takes, with names checked. */
90
+ export function serverSpecs(file) {
91
+ return specList(JSON.parse(readFileSync(file, 'utf8'))?.mcpServers, 'config');
92
+ }
93
+
94
+ /** The same conversion for a config object already in hand. */
95
+ export function specsFromConfig(config) {
96
+ return specList(config?.mcpServers, 'config');
97
+ }
98
+
99
+ function specList(servers, source) {
100
+ if (!servers || typeof servers !== 'object') throw new Error(`${source} must contain an "mcpServers" object`);
101
+ return Object.entries(servers).map(([name, spec]) => {
102
+ if (!SERVER_NAME.test(name)) throw new Error(`server name "${name}" must match [a-z][a-z0-9-]{0,31}`);
103
+ if (spec?.command) return { name, label: spec.label, transport: 'stdio', command: spec.command, args: spec.args ?? [], env: spec.env ?? {} };
104
+ if (spec?.url) return { name, label: spec.label, transport: 'http', url: spec.url, headers: spec.headers ?? {} };
105
+ throw new Error(`server "${name}" needs either "command" (stdio) or "url" (HTTP)`);
106
+ });
107
+ }
108
+
109
+ /**
110
+ * Split a typed command line into `{command, args}`, honouring double and single
111
+ * quotes so a path or an argument with a space survives.
112
+ *
113
+ * ⚠ NOT run through a shell. The user is typing a command for their own machine,
114
+ * but this parser is why the same line behaves identically on Windows and on
115
+ * macOS, and why nothing here can expand `$HOME` or a glob into something the
116
+ * user did not see.
117
+ */
118
+ export function splitCommand(line) {
119
+ const out = [];
120
+ let current = '';
121
+ let quote = '';
122
+ let started = false;
123
+ for (const char of String(line ?? '')) {
124
+ if (quote) {
125
+ if (char === quote) quote = '';
126
+ else current += char;
127
+ continue;
128
+ }
129
+ if (char === '"' || char === "'") { quote = char; started = true; continue; }
130
+ if (/\s/.test(char)) {
131
+ if (started) { out.push(current); current = ''; started = false; }
132
+ continue;
133
+ }
134
+ current += char;
135
+ started = true;
136
+ }
137
+ if (quote) throw new Error('unbalanced quote in the command');
138
+ if (started) out.push(current);
139
+ if (!out.length) throw new Error('empty command');
140
+ return { command: out[0], args: out.slice(1) };
141
+ }
142
+
143
+ /** One typed line -> one server spec. `url` or `command`, decided by the line. */
144
+ export function parseServerLine(name, line) {
145
+ if (!SERVER_NAME.test(name)) throw new Error(`name "${name}" must match [a-z][a-z0-9-]{0,31}`);
146
+ const trimmed = String(line ?? '').trim();
147
+ if (!trimmed) throw new Error('a server needs a command line or a URL');
148
+ if (/^https?:\/\//.test(trimmed)) return { name, transport: 'http', url: trimmed, headers: {} };
149
+ const { command, args } = splitCommand(trimmed);
150
+ return { name, transport: 'stdio', command, args, env: {} };
151
+ }
152
+
153
+ /**
154
+ * Ask for servers one at a time until the user submits an empty name.
155
+ *
156
+ * `ask` is injected so this is testable without a terminal: it is called with a
157
+ * question and must return the typed line.
158
+ */
159
+ export async function promptServers(ask, log = console.log) {
160
+ const servers = {};
161
+ log('Add the MCP servers you want to share. Press Enter on an empty name when done.');
162
+ for (;;) {
163
+ const name = (await ask('server name (e.g. fs): ')).trim();
164
+ if (!name) break;
165
+ let line;
166
+ for (;;) {
167
+ line = await ask(` ${name} command or URL (e.g. npx -y @modelcontextprotocol/server-filesystem ~/docs): `);
168
+ try {
169
+ servers[name] = parseServerLine(name, line);
170
+ break;
171
+ } catch (error) {
172
+ log(` ${error.message}`);
173
+ }
174
+ }
175
+ log(` added ${name}`);
176
+ }
177
+ if (!Object.keys(servers).length) throw new Error('no MCP server was entered');
178
+ return specsFromConfig({ mcpServers: servers });
179
+ }
180
+
181
+ export async function main(argv = process.argv.slice(2), env = process.env, io = {}) {
182
+ const args = parseArgs(argv);
183
+ if (args.help) {
184
+ console.log('usage: dsh-dragonbyte-host [--bridge <wss url>] [--mcp <mcp.json>]');
185
+ console.log('Nothing else is needed after the first run: the credential Settings gave you is');
186
+ console.log('saved in ~/.config/dsh-dragonbyte and renewed by itself.');
187
+ return 0;
188
+ }
189
+ const bridge = args.bridge || env.DSH_DRAGONBYTE_BRIDGE || 'wss://edge01.snapai.app/dragonbyte/ws';
190
+ if (!/^wss?:\/\//.test(bridge)) throw new Error('--bridge must be a ws:// or wss:// URL');
191
+
192
+ // ⚠ CREATED HERE, NOT AT THE TOP OF `main`. An open readline holds the event
193
+ // loop, so a run that never prompts — `--help` above all — prints its line and
194
+ // then never exits. Measured: `--help` with a silent pipe on stdin hung until
195
+ // the interface moved below the early returns.
196
+ const ask = io.ask ?? readlineAsk();
197
+
198
+ // ⚠ THE SAVED CREDENTIAL IS THE DEFAULT, AND THE INTERACTIVE PATH EXISTS ONLY
199
+ // FOR THE FIRST RUN. A machine that has connected once should never prompt
200
+ // again — that is the whole meaning of "authorize once". The file is read
201
+ // before any server is spawned, so a missing credential fails in a second
202
+ // rather than after connecting MCP servers it cannot publish.
203
+ const saved = await loadCredential(env, io);
204
+ let credential = saved;
205
+ let mcpServers = args.mcp ? null : (saved?.mcpServers ?? null);
206
+ if (!credential?.token) {
207
+ const pasted = env.DSH_DRAGONBYTE_TOKEN || await ask('device token from Settings → Dragonbyte: ');
208
+ if (!pasted) throw new Error('a device token is required');
209
+ credential = { token: pasted.trim(), refreshToken: '', expiresAt: 0, tenantId: args.tenant || env.DSH_DRAGONBYTE_TENANT || '' };
210
+ mcpServers = null;
211
+ }
212
+
213
+ // ⚠ THE NODE CHECK COMES BEFORE THE SOCKET, because `WebSocket` only exists
214
+ // globally from 22 and the fetch below would otherwise fail as a network error.
215
+ const [major, minor] = process.versions.node.split('.').map(Number);
216
+ if (major < 22 || (major === 22 && minor < 5)) throw new Error(`Node >= 22.5 is required (found ${process.versions.node})`);
217
+ const connect = (url, { headers }) => new WebSocket(url, { headers });
218
+
219
+ // ⚠ SETTINGS IS THE SOURCE OF TRUTH, AND IT LIVES ON THE GATEWAY. The host
220
+ // holds a device token, not the browser's session cookie, so it asks the
221
+ // bridge — which reads the document the gateway wrote — rather than the
222
+ // browser route. `--mcp` and the saved credential remain fallbacks, so an old
223
+ // bridge that does not answer `config` still starts a working host.
224
+ if (!args.mcp && !mcpServers?.length && credential.refreshToken !== undefined) {
225
+ const fetched = await fetchServers({ url: bridge, token: credential.token, connect });
226
+ if (fetched?.length) {
227
+ mcpServers = fetched;
228
+ console.log(`dsh-dragonbyte-host: using the ${fetched.length} server(s) saved in Settings`);
229
+ }
230
+ }
231
+
232
+ const specs = mcpServers?.length
233
+ ? specsFromConfig({ mcpServers: Object.fromEntries(mcpServers.map((entry) => [entry.name, entry])) })
234
+ : args.mcp ? serverSpecs(args.mcp) : await promptServers(ask);
235
+ const { catalog, call, close } = await connectServers(specs, { log: (line) => console.log(line) });
236
+ if (!catalog.servers.length) {
237
+ await close();
238
+ throw new Error('no configured MCP server connected; nothing to publish');
239
+ }
240
+
241
+ const session = serveBridge({
242
+ url: bridge,
243
+ token: credential.token,
244
+ refreshToken: credential.refreshToken ?? '',
245
+ expiresAt: credential.expiresAt ?? 0,
246
+ tenantId: credential.tenantId || args.tenant || '',
247
+ catalog,
248
+ call,
249
+ connect,
250
+ log: (line) => console.log(line),
251
+ });
252
+ // The refreshed token replaces only the credential; the tenant and the refresh
253
+ // token stay as they were, so a renewal never loses the binding.
254
+ session.onRefresh(({ token, expiresAt }) => {
255
+ void saveCredential({ ...credential, token, expiresAt }, env, io);
256
+ });
257
+
258
+ const shutdown = async () => { session.close(); await close(); process.exit(0); };
259
+ for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, shutdown);
260
+ // The caller owns the lifetime: `main` resolves once the bridge is serving, so
261
+ // a test can drive it without a process that never exits.
262
+ return session;
263
+ }
264
+
265
+ // ⚠ BOTH SIDES ARE RESOLVED, AND `import.meta.url` IS ALREADY ONE. Node
266
+ // realpaths the module it loads, so `import.meta.url` is the real file while
267
+ // `process.argv[1]` is whatever the caller typed — a relative path, or the
268
+ // `node_modules/.bin` symlink that an installed `bin` always is. Comparing the
269
+ // two raw is therefore false for every installed run, and the entrypoint
270
+ // silently does nothing: `--help` printed no usage and exited 0. Resolving the
271
+ // argv side to its real path is what makes an install behave like a direct run.
272
+ const entry = process.argv[1] ? realpathSync(process.argv[1]) : '';
273
+ if (entry && import.meta.url === pathToFileURL(entry).href) {
274
+ main().then(() => { /* stays alive on the socket */ }).catch((error) => { console.error(`dsh-dragonbyte-host: ${error?.message || error}`); process.exit(1); });
275
+ }
package/src/host.mjs ADDED
@@ -0,0 +1,325 @@
1
+ // The half that runs on the end user's machine.
2
+ //
3
+ // It is an MCP *client*, not a server: it connects to whichever MCP servers the
4
+ // user already has (stdio or Streamable HTTP), and publishes their catalog
5
+ // upward over one outbound WebSocket. Nothing dials in. That direction is what
6
+ // makes "any DSH, outside edge01" possible — the user's laptop needs no public
7
+ // name, no certificate and no inbound port, only egress to edge01.snapai.app.
8
+ //
9
+ // ⚠ THE HOST DOES NOT TRUST THE TENANT SIDE EITHER. A tool call arrives as
10
+ // `{server, tool, args}` and is dispatched only to a server named in the
11
+ // catalog this host published; an unknown pair is a refusal in the reply body,
12
+ // never a throw, because a throw crosses the socket as a protocol error and
13
+ // loses the correlation.
14
+
15
+ import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
16
+ import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
17
+
18
+ import { MAX_FRAME_BYTES, WIRE_VERSION, assertFrame, validateArgs, validateCatalog, validateResult } from './wire.mjs';
19
+
20
+ const CALL_TIMEOUT_MS = 60_000;
21
+ const PING_INTERVAL_MS = 30_000;
22
+ const RECONNECT_MIN_MS = 1_000;
23
+ const RECONNECT_MAX_MS = 30_000;
24
+ // Refresh this long before expiry: longer than one ping interval, so a live
25
+ // socket renews on its next tick rather than after the bridge has started
26
+ // refusing the token it is holding.
27
+ const REFRESH_MARGIN_SECONDS = 300;
28
+
29
+ function createTransport(spec) {
30
+ if (spec.transport === 'stdio') {
31
+ return new StdioClientTransport({
32
+ command: spec.command,
33
+ args: spec.args ?? [],
34
+ env: { ...process.env, ...(spec.env ?? {}) },
35
+ stderr: 'inherit',
36
+ });
37
+ }
38
+ return new StreamableHTTPClientTransport(new URL(spec.url), {
39
+ requestInit: { headers: spec.headers ?? {} },
40
+ });
41
+ }
42
+
43
+ /**
44
+ * Connect every configured MCP server and return the catalog plus a dispatcher.
45
+ *
46
+ * A server that fails to connect is reported and skipped rather than failing
47
+ * the whole host: one broken server on the user's machine must not take the
48
+ * others' tools away from their agent.
49
+ */
50
+ export async function connectServers(specs, { log = () => {} } = {}) {
51
+ const clients = new Map();
52
+ const tools = new Map();
53
+ const published = [];
54
+
55
+ for (const spec of specs) {
56
+ try {
57
+ const client = new Client({ name: 'dsh-dragonbyte-host', version: '0.1.0' }, { capabilities: {} });
58
+ await client.connect(createTransport(spec));
59
+ const listed = await client.listTools(undefined, { cacheMode: 'refresh' });
60
+ const entries = [];
61
+ for (const tool of listed.tools || []) {
62
+ entries.push({ name: tool.name, description: tool.description || '', inputSchema: tool.inputSchema ?? { type: 'object' } });
63
+ tools.set(`${spec.name}\0${tool.name}`, { client, rawName: tool.name });
64
+ }
65
+ if (!entries.length) {
66
+ await client.close();
67
+ log(`dragonbyte-host: ${spec.name} exposes no tools; not published`);
68
+ continue;
69
+ }
70
+ clients.set(spec.name, client);
71
+ published.push({ name: spec.name, label: spec.label, tools: entries });
72
+ log(`dragonbyte-host: ${spec.name} exposes ${entries.length} tool(s)`);
73
+ } catch (error) {
74
+ log(`dragonbyte-host: ${spec.name} did not connect (${error?.message || error})`);
75
+ }
76
+ }
77
+
78
+ // ⚠ AN EMPTY CATALOG IS VALID HERE AND INVALID ON THE WIRE. The host must be
79
+ // able to start, report "nothing connected", and keep retrying — crashing on
80
+ // a config whose servers are temporarily down would make the user restart it
81
+ // by hand for no reason. What must not happen is publishing it: the wire
82
+ // validator refuses a tool-less catalog, so the socket stays closed until
83
+ // there is something real to send.
84
+ const catalog = published.length
85
+ ? validateCatalog({ servers: published })
86
+ : { servers: [] };
87
+
88
+ return {
89
+ catalog,
90
+ clients,
91
+ /** One `tools/call` on a published pair. Errors come back as `isError` results. */
92
+ async call(server, tool, args) {
93
+ const target = tools.get(`${server}\0${tool}`);
94
+ if (!target) return { content: [{ type: 'text', text: `unknown tool ${server}/${tool}` }], isError: true };
95
+ try {
96
+ const result = await target.client.callTool(
97
+ { name: target.rawName, arguments: validateArgs(args) },
98
+ { timeout: CALL_TIMEOUT_MS },
99
+ );
100
+ return validateResult(result);
101
+ } catch (error) {
102
+ // ⚠ A THROWN CALL MAY ALREADY HAVE HAPPENED on the far side. The tool
103
+ // result says so and the bridge never retries, because a local MCP tool
104
+ // is an arbitrary side effect rather than a read.
105
+ return { content: [{ type: 'text', text: `tool ${server}/${tool} failed: ${error?.message || error}` }], isError: true };
106
+ }
107
+ },
108
+ async close() {
109
+ await Promise.allSettled([...clients.values()].map((client) => client.close()));
110
+ clients.clear();
111
+ tools.clear();
112
+ },
113
+ };
114
+ }
115
+
116
+ /**
117
+ * Keep one outbound WebSocket to the bridge open for as long as the process
118
+ * lives, republishing the catalog on every (re)connect.
119
+ *
120
+ * ⚠ THE TOKEN IS A CREDENTIAL, NOT A CONFIG VALUE. `token` is a `device` token
121
+ * minted by the gateway for this machine and this tenant; it carries the uid,
122
+ * the address and the tenant id, so this function never needs to be told who it
123
+ * speaks for. A `refreshToken`, when present, is exchanged over the live socket
124
+ * before the device token expires — see `refresh`: it replaces the credential
125
+ * without touching the socket, so a refresh never drops an in-flight call.
126
+ *
127
+ * `connect` is injected so a test can drive the protocol without a socket.
128
+ */
129
+ export function serveBridge({ url, token, refreshToken = '', expiresAt = 0, tenantId = '', catalog, call, connect, log = () => {},
130
+ onServers = () => {} }) {
131
+ // Publishing a tool-less catalog would bind a tenant to a host that can do
132
+ // nothing; the caller is expected to have found something to send.
133
+ if (!catalog?.servers?.length) throw new Error('refusing to bridge an empty catalog');
134
+ let socket = null;
135
+ let currentToken = token;
136
+ let currentExpiry = expiresAt;
137
+ let boundTenant = tenantId;
138
+ let closedByUs = false;
139
+ let attempt = 0;
140
+ let reconnecting = null;
141
+ /** Persist a rotated credential. Called on every refresh; a no-op in tests. */
142
+ let persist = () => {};
143
+
144
+ const send = (message) => {
145
+ if (socket && socket.readyState === 1) socket.send(JSON.stringify(message));
146
+ };
147
+
148
+ const publishCatalog = () => {
149
+ send({ v: WIRE_VERSION, type: 'catalog', ...(boundTenant ? { tenantId: boundTenant } : {}), catalog });
150
+ };
151
+
152
+ /**
153
+ * Exchange the refresh token for a new device token, over the open socket.
154
+ *
155
+ * ⚠ RENEWS ONCE PER LIFETIME, NOT ON A TIMER THAT CAN FIRE TWICE. A token that
156
+ * is already fresh when this runs (a second call raced with the first, or the
157
+ * process just started inside the window) is not sent again: the bridge mints
158
+ * every time it is asked, and an unnecessary mint is a credential the user's
159
+ * disk no longer needs to hold.
160
+ */
161
+ function refresh() {
162
+ if (!refreshToken) return;
163
+ const secondsLeft = currentExpiry - Math.floor(Date.now() / 1000);
164
+ if (currentExpiry && secondsLeft > REFRESH_MARGIN_SECONDS) return;
165
+ send({ v: WIRE_VERSION, type: 'refresh', token: refreshToken });
166
+ }
167
+
168
+ const scheduleReconnect = () => {
169
+ if (closedByUs || reconnecting) return;
170
+ const delay = Math.min(RECONNECT_MAX_MS, RECONNECT_MIN_MS * 2 ** attempt);
171
+ attempt += 1;
172
+ log(`dragonbyte-host: reconnecting in ${delay}ms`);
173
+ const timer = setTimeout(() => { reconnecting = null; open(); }, delay);
174
+ timer.unref?.();
175
+ reconnecting = timer;
176
+ };
177
+
178
+ function open() {
179
+ if (closedByUs) return;
180
+ socket = connect(url, {
181
+ headers: { authorization: `Bearer ${currentToken}` },
182
+ });
183
+ socket.addEventListener('open', () => {
184
+ attempt = 0;
185
+ publishCatalog();
186
+ refresh();
187
+ // Ask for the servers Settings saved. The bridge answers over this socket
188
+ // because a laptop holds a device token, not the browser's session cookie.
189
+ send({ v: WIRE_VERSION, type: 'config' });
190
+ });
191
+ socket.addEventListener('message', async (event) => {
192
+ let message;
193
+ try { message = JSON.parse(String(event.data)); } catch { return; }
194
+ // ⚠ THE BRIDGE'S FRAMES ARE VALIDATED, NOT ASSUMED. A newer bridge may
195
+ // send a frame this host does not know; without this check it would be
196
+ // silently ignored, which reads as a host that stopped answering calls.
197
+ try {
198
+ if (typeof message?.type === 'string') assertFrame(message, 'bridge-to-host', message.type);
199
+ } catch (error) {
200
+ log(`dragonbyte-host: ignoring a frame from the bridge: ${error.message}`);
201
+ return;
202
+ }
203
+ if (message.type === 'refreshed') {
204
+ currentToken = message.token;
205
+ currentExpiry = message.expiresAt;
206
+ // ⚠ PERSIST, THEN LOG. The new token is the only live credential until
207
+ // this process exits, and a crash before the next write would leave the
208
+ // disk holding one the bridge is about to refuse. Writing first means
209
+ // the failure mode is an unused fresh token, not a dead one.
210
+ try { persist({ token: currentToken, expiresAt: currentExpiry }); }
211
+ catch (error) { log(`dragonbyte-host: could not save the refreshed token (${error?.message || error})`); }
212
+ log('dragonbyte-host: device token refreshed');
213
+ return;
214
+ }
215
+ if (message.type === 'tenants') {
216
+ // ⚠ THIS FRAME IS LEGACY, AND THE REFUSAL IS GONE WITH IT. An older
217
+ // bridge answers a tenant-less catalog by listing what the address
218
+ // owns; that listing used to force a choice and then give up. A current
219
+ // bridge publishes to every owned tenant on the catalog itself, so all
220
+ // this has to do is republish and let the bridge decide.
221
+ const owned = Array.isArray(message.tenants) ? message.tenants.filter((id) => typeof id === 'string') : [];
222
+ if (!boundTenant && owned.length === 1) {
223
+ boundTenant = owned[0];
224
+ log(`dragonbyte-host: this address owns one tenant; serving ${boundTenant}`);
225
+ }
226
+ if (!boundTenant && owned.length > 1) {
227
+ log(`dragonbyte-host: this address owns ${owned.length} tenants; serving all of them`);
228
+ }
229
+ publishCatalog();
230
+ return;
231
+ }
232
+ if (message.type === 'servers') {
233
+ // The list Settings saved for this machine. It is advisory: a machine
234
+ // that has never been configured gets an empty list and keeps whatever
235
+ // its credential already names, so this cannot fail a start.
236
+ const servers = Array.isArray(message.servers) ? message.servers : [];
237
+ try { onServers(servers); }
238
+ catch (error) { log(`dragonbyte-host: could not apply the saved servers (${error?.message || error})`); }
239
+ return;
240
+ }
241
+ if (message.type === 'error') {
242
+ log(`dragonbyte-host: bridge refused: ${message.error || 'unknown error'}`);
243
+ return;
244
+ }
245
+ // `call`: the schema already required `id`, `server` and `tool`.
246
+ const result = await call(message.server, message.tool, message.args ?? {});
247
+ send({ v: WIRE_VERSION, type: 'reply', id: message.id, result });
248
+ });
249
+ socket.addEventListener('close', () => { socket = null; scheduleReconnect(); });
250
+ socket.addEventListener('error', () => { /* `close` always follows */ });
251
+ }
252
+
253
+ open();
254
+ // ⚠ THE REFRESH TICKER IS THE SAFETY NET, NOT THE MECHANISM. `open()` refreshes
255
+ // on connect, which covers a restart inside the window; this covers a socket
256
+ // that stays up for longer than a token lives, which is the ordinary case for
257
+ // a laptop left running. It fires on the same ping interval, so no second timer.
258
+ const ping = setInterval(() => {
259
+ if (socket?.readyState === 1) socket.send(JSON.stringify({ v: WIRE_VERSION, type: 'ping' }));
260
+ refresh();
261
+ }, PING_INTERVAL_MS);
262
+ ping.unref?.();
263
+
264
+ return {
265
+ close() {
266
+ closedByUs = true;
267
+ clearInterval(ping);
268
+ if (reconnecting) clearTimeout(reconnecting);
269
+ socket?.close();
270
+ socket = null;
271
+ },
272
+ /** Let the caller persist a rotated credential; called before it is used. */
273
+ onRefresh(fn) { persist = typeof fn === 'function' ? fn : () => {}; },
274
+ };
275
+ }
276
+
277
+ export { MAX_FRAME_BYTES };
278
+
279
+ /**
280
+ * Ask the bridge what Settings saved for this machine, before any MCP server is
281
+ * spawned, and close the socket again.
282
+ *
283
+ * ⚠ A SEPARATE SHORT CONNECTION, NOT A PHASE OF `serveBridge`. The catalog must
284
+ * be published on the first connect, and the catalog comes from the servers,
285
+ * which come from this answer — so the list has to be in hand before serving
286
+ * starts. Reusing the serving socket would mean either publishing a catalog it
287
+ * does not have yet or holding the socket open with nothing to send.
288
+ *
289
+ * Resolves to `null` — not an error — whenever the answer is anything but a
290
+ * usable list: an older bridge that does not know `config` will answer with an
291
+ * error frame, and a machine with nothing saved gets an empty array. Both mean
292
+ * "fall back to what the credential already names".
293
+ */
294
+ export function fetchServers({ url, token, connect, timeoutMs = 10000 }) {
295
+ return new Promise((resolve) => {
296
+ let socket;
297
+ let settled = false;
298
+ const finish = (value) => {
299
+ if (settled) return;
300
+ settled = true;
301
+ clearTimeout(timer);
302
+ try { socket?.close(); } catch {}
303
+ resolve(value);
304
+ };
305
+ const timer = setTimeout(() => finish(null), timeoutMs);
306
+ timer.unref?.();
307
+ try {
308
+ socket = connect(url, { headers: { authorization: `Bearer ${token}` } });
309
+ } catch { return finish(null); }
310
+ socket.addEventListener('open', () => {
311
+ try { socket.send(JSON.stringify({ v: WIRE_VERSION, type: 'config' })); } catch { finish(null); }
312
+ });
313
+ socket.addEventListener('message', (event) => {
314
+ let message;
315
+ try { message = JSON.parse(String(event.data)); } catch { return; }
316
+ if (message?.type === 'servers') {
317
+ finish(Array.isArray(message.servers) && message.servers.length ? message.servers : null);
318
+ } else if (message?.type === 'error') {
319
+ finish(null);
320
+ }
321
+ });
322
+ socket.addEventListener('error', () => finish(null));
323
+ socket.addEventListener('close', () => finish(null));
324
+ });
325
+ }
@@ -0,0 +1,72 @@
1
+ {
2
+ "$id": "dsh-dragonbyte/protocol.v1",
3
+ "title": "DSH Dragonbyte protocol, version 1",
4
+ "description": "The frames of all three hops, in one artifact so a host, a bridge and a tenant cannot disagree about them. ⚠ additionalProperties IS ABSENT AND MUST STAY ABSENT, for the reason dsh-wire's envelope gives: the three halves deploy independently -- a laptop can run an old host against a new bridge, and a tenant's bundle is an immutable archive -- so version skew is a certainty. A strict frame turns an additive field on the newer side into a total outage on the older one. ⚠ `v` IS `minimum: 1`, NOT `const: 1`. The explicit version check runs FIRST and answers `unsupported wire version`; a const here would make that check unreachable and report skew as corruption.",
5
+ "type": "object",
6
+ "required": ["v", "type"],
7
+ "properties": {
8
+ "v": { "type": "integer", "minimum": 1, "description": "Protocol version. A breaking change is a new v, never a mutated field." },
9
+ "type": {
10
+ "type": "string",
11
+ "enum": ["catalog", "tenants", "call", "reply", "ping", "error", "refresh", "refreshed", "config", "servers"],
12
+ "description": "Which frame this is. The set is closed: an unknown type is refused by the receiver rather than ignored, because a silently dropped frame looks like a slow peer."
13
+ },
14
+ "token": { "type": "string", "minLength": 32, "maxLength": 4096, "description": "A refresh token, exchanged for a new device token. ⚠ CARRIED ON ITS OWN FRAME, not in an Authorization header: the socket is already open under the expiring device token, and re-opening it would drop every in-flight call." },
15
+ "expiresAt": { "type": "integer", "minimum": 1, "description": "Unix seconds at which the issued device token stops being accepted. Persisted by the host so it can refresh before, not after, the bridge refuses it." },
16
+ "email": { "type": "string", "pattern": "^[^\\s@]{1,64}@[^\\s@]{1,190}$" },
17
+ "tenantId": { "type": "string", "pattern": "^[A-Za-z0-9._:-]{1,128}$" },
18
+ "tenants": { "type": "array", "maxItems": 32, "items": { "type": "string", "pattern": "^[A-Za-z0-9._:-]{1,128}$" } },
19
+ "catalog": { "type": "object" },
20
+ "servers": {
21
+ "type": "array",
22
+ "maxItems": 16,
23
+ "description": "The MCP servers Settings saved for this machine. ⚠ THE HOST ASKS FOR THESE INSTEAD OF THE GATEWAY. It holds a device token, not a browser session, so the browser's `/dragonbyte/mcp` route is unreachable to it; the bridge reads the same document the gateway wrote and answers over the socket the host already has open.",
24
+ "items": {
25
+ "type": "object",
26
+ "required": ["name", "transport"],
27
+ "properties": {
28
+ "name": { "type": "string", "pattern": "^[a-z][a-z0-9-]{0,31}$" },
29
+ "label": { "type": "string", "maxLength": 64 },
30
+ "transport": { "type": "string", "enum": ["stdio", "http"] },
31
+ "command": { "type": "string", "maxLength": 512 },
32
+ "args": { "type": "array", "maxItems": 64, "items": { "type": "string", "maxLength": 2048 } },
33
+ "env": { "type": "object" },
34
+ "url": { "type": "string", "maxLength": 2048 },
35
+ "headers": { "type": "object" }
36
+ }
37
+ }
38
+ },
39
+ "id": { "type": "string", "pattern": "^[A-Za-z0-9_-]{8,128}$" },
40
+ "server": { "type": "string", "pattern": "^[a-z][a-z0-9-]{0,31}$" },
41
+ "tool": { "type": "string", "pattern": "^[A-Za-z0-9_.-]{1,64}$" },
42
+ "args": { "type": "object" },
43
+ "result": { "type": "object" },
44
+ "error": { "type": "string", "maxLength": 512 },
45
+ "requestId": { "type": "string", "pattern": "^dragonbyte-[0-9]{1,9}$", "description": "The sidecar's correlation token. Its shape is fixed by the shim so a bridge cannot answer an id the shim would never mint." },
46
+ "path": { "type": "string", "pattern": "^/[a-z0-9/_-]{1,120}$", "description": "The bridge route a shim request names. ⚠ A PATTERN, NOT AN `enum` OF THE TWO KNOWN ROUTES. An enum would make the bridge's own `not found` answer unreachable — every unknown path would fail here as a 400 and the 404 branch would be dead code that no test could exercise. dsh-wire's envelope makes the same choice for `kind`, and its `v` is `minimum` rather than `const` for the same reason." },
47
+ "status": { "type": "integer", "minimum": 200, "maximum": 599 },
48
+ "body": { "type": "object" }
49
+ },
50
+ "frames": {
51
+ "host-to-bridge": {
52
+ "catalog": { "required": ["catalog"], "properties": ["v", "type", "email", "tenantId", "catalog"] },
53
+ "ping": { "required": [], "properties": ["v", "type"] },
54
+ "reply": { "required": ["id", "result"], "properties": ["v", "type", "id", "result"] },
55
+ "refresh": { "required": ["token"], "properties": ["v", "type", "token"] },
56
+ "config": { "required": [], "properties": ["v", "type"] }
57
+ },
58
+ "bridge-to-host": {
59
+ "call": { "required": ["id", "server", "tool"], "properties": ["v", "type", "id", "server", "tool", "args"] },
60
+ "tenants": { "required": ["tenants"], "properties": ["v", "type", "email", "tenants"] },
61
+ "error": { "required": ["error"], "properties": ["v", "type", "error"] },
62
+ "refreshed": { "required": ["token", "expiresAt"], "properties": ["v", "type", "token", "expiresAt"] },
63
+ "servers": { "required": ["servers"], "properties": ["v", "type", "servers"] }
64
+ },
65
+ "shim-to-bridge": {
66
+ "request": { "required": ["requestId", "path"], "properties": ["requestId", "path", "body"] }
67
+ },
68
+ "bridge-to-shim": {
69
+ "result": { "required": ["requestId", "status", "body"], "properties": ["requestId", "status", "body"] }
70
+ }
71
+ }
72
+ }