dsh-dragonbyte-client 0.0.0-stage → 0.4.2
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 +158 -2
- package/client.js +201 -0
- package/cordis.patch.yml +3 -0
- package/package.json +58 -4
- package/src/desktop.mjs +421 -0
- package/src/host-main.mjs +275 -0
- package/src/host.mjs +325 -0
- package/src/protocol.v1.json +72 -0
- package/src/schema.mjs +118 -0
- package/src/wire.mjs +129 -0
package/src/desktop.mjs
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
// The DSH Desktop half: a Settings section, and the bridge it drives.
|
|
2
|
+
//
|
|
3
|
+
// ⚠ THIS IS A CORDIS PLUGIN, NOT A SCRIPT. It installs into whatever DSH the
|
|
4
|
+
// person uses — today a desktop shell with its own local Host — and contributes
|
|
5
|
+
// two things that must run inside that Host, not beside it: the routes the
|
|
6
|
+
// Settings section calls, and the MCP bridge that must stay alive as long as the
|
|
7
|
+
// app does. A `bin` script cannot do either.
|
|
8
|
+
//
|
|
9
|
+
// ⚠ NOTHING HERE NEEDS AN EDGE01 SESSION. The machine holds a device token and
|
|
10
|
+
// nothing else. Pairing happens in a browser on edge01; this side only opens it,
|
|
11
|
+
// receives a one-time code on loopback, and trades the code for a token.
|
|
12
|
+
//
|
|
13
|
+
// ⚠ IT DEGRADES RATHER THAN REFUSING TO LOAD. No credential, no saved servers,
|
|
14
|
+
// no reachable bridge — each is a status the Settings section shows. Loading
|
|
15
|
+
// must never depend on the network, or an offline laptop loses its own settings
|
|
16
|
+
// UI.
|
|
17
|
+
|
|
18
|
+
import { randomBytes } from 'node:crypto';
|
|
19
|
+
import { createInterface } from 'node:readline/promises';
|
|
20
|
+
import { spawn } from 'node:child_process';
|
|
21
|
+
import { hostname } from 'node:os';
|
|
22
|
+
|
|
23
|
+
import { connectServers, serveBridge } from './host.mjs';
|
|
24
|
+
import { credentialPath, loadCredential, saveCredential, parseServerLine } from './host-main.mjs';
|
|
25
|
+
|
|
26
|
+
export const name = 'dragonbyte';
|
|
27
|
+
export const inject = ['webServer'];
|
|
28
|
+
|
|
29
|
+
const DEFAULT_BRIDGE = 'wss://edge01.snapai.app/dragonbyte/ws';
|
|
30
|
+
// The bridge holds the waiting request this long. Matched on the bridge's own
|
|
31
|
+
// window, with a margin so this side is not what gives up first.
|
|
32
|
+
const WAIT_TTL_MS = 5 * 60 * 1000;
|
|
33
|
+
|
|
34
|
+
const json = (res, status, payload) => {
|
|
35
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
|
|
36
|
+
res.end(JSON.stringify(payload));
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const readBody = (req, limit = 256 * 1024) => new Promise((resolve, reject) => {
|
|
40
|
+
let size = 0;
|
|
41
|
+
const chunks = [];
|
|
42
|
+
req.on('data', (chunk) => {
|
|
43
|
+
size += chunk.length;
|
|
44
|
+
if (size > limit) { reject(Object.assign(new Error('request body is too large'), { status: 413 })); req.destroy(); return; }
|
|
45
|
+
chunks.push(chunk);
|
|
46
|
+
});
|
|
47
|
+
req.on('end', () => {
|
|
48
|
+
try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : null); }
|
|
49
|
+
catch { reject(Object.assign(new Error('invalid JSON'), { status: 400 })); }
|
|
50
|
+
});
|
|
51
|
+
req.on('error', reject);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
export function bridgeUrlOf(env = process.env) {
|
|
55
|
+
return env.DSH_DRAGONBYTE_BRIDGE || DEFAULT_BRIDGE;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The plain HTTP origin the bridge's REST routes live on.
|
|
60
|
+
*
|
|
61
|
+
* ⚠ THE SOCKET URL'S PATH IS NOT A BASE. `DEFAULT_BRIDGE` ends in `/dragonbyte/ws`,
|
|
62
|
+
* which is where the WebSocket route is mounted, so appending `/dragonbyte/pair/…`
|
|
63
|
+
* to it produced `/dragonbyte/ws/dragonbyte/pair/…` — answered 401 by the gateway,
|
|
64
|
+
* which reads exactly like the machine never signed in.
|
|
65
|
+
*/
|
|
66
|
+
function httpBaseOf(bridgeUrl) {
|
|
67
|
+
const url = new URL(bridgeUrl);
|
|
68
|
+
url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:';
|
|
69
|
+
return url.origin;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* What this machine calls itself in the tenant's Settings.
|
|
74
|
+
*
|
|
75
|
+
* ⚠ THE OS HOSTNAME, NOT A PROMPT. Pairing is a browser round trip and asking a
|
|
76
|
+
* person to type a name there would add a step to the flow that most needs to
|
|
77
|
+
* be one click. `DSH_DRAGONBYTE_LABEL` overrides it for a person who runs two
|
|
78
|
+
* machines whose hostnames look alike.
|
|
79
|
+
*/
|
|
80
|
+
export function labelOf(env = process.env) {
|
|
81
|
+
const configured = String(env.DSH_DRAGONBYTE_LABEL ?? '').trim();
|
|
82
|
+
if (configured) return configured.slice(0, 80);
|
|
83
|
+
try { return String(hostname() || '').slice(0, 80); }
|
|
84
|
+
catch { return ''; }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Ask the bridge for a short-lived editor code, or `''` when it cannot answer.
|
|
89
|
+
*
|
|
90
|
+
* ⚠ THE CODE IS NOT KEPT, BECAUSE IT CANNOT BE. The bridge holds it in memory
|
|
91
|
+
* for an hour; a copy saved beside the credential would be dead by the time a
|
|
92
|
+
* person used it. The device token is signed and can always ask again.
|
|
93
|
+
*/
|
|
94
|
+
async function editorCodeOf({ bridgeUrl, token, mcpServers }) {
|
|
95
|
+
if (!token) return '';
|
|
96
|
+
const response = await fetch(`${httpBaseOf(bridgeUrl)}/dragonbyte/pair/servers`, {
|
|
97
|
+
method: 'POST',
|
|
98
|
+
headers: { 'content-type': 'application/json' },
|
|
99
|
+
body: JSON.stringify(mcpServers === undefined ? { token } : { token, mcpServers }),
|
|
100
|
+
});
|
|
101
|
+
if (!response.ok) {
|
|
102
|
+
const body = await response.json().catch(() => null);
|
|
103
|
+
throw badRequest(body?.error || 'the bridge refused that server list');
|
|
104
|
+
}
|
|
105
|
+
const body = await response.json();
|
|
106
|
+
return typeof body?.code === 'string' ? body.code : '';
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function pairPageUrl({ bridgeUrl, code = '', handle = '', tenantId = '', callback = '' }) {
|
|
110
|
+
const url = new URL('/dragonbyte/pair/start', httpBaseOf(bridgeUrl));
|
|
111
|
+
// ⚠ ONLY THE PARAMETERS THAT EXIST. An empty `tenant` would be sent as a
|
|
112
|
+
// tenant named "", which reads as a choice nobody made.
|
|
113
|
+
if (tenantId) url.searchParams.set('tenant', tenantId);
|
|
114
|
+
// ⚠ THE CODE IS THE PAGE'S SUBJECT, NOT A RESUME TOKEN. It is what the person
|
|
115
|
+
// signs in to spend; the page shows it back so a different machine can be
|
|
116
|
+
// paired from the same browser session.
|
|
117
|
+
if (code) url.searchParams.set('code', code);
|
|
118
|
+
// ⚠ THE HANDLE IS HOW THE PAGE FINDS THE MACHINE WAITING FOR IT. Without it
|
|
119
|
+
// the sign-in completes in the browser and nothing on this side hears about it.
|
|
120
|
+
if (handle) url.searchParams.set('handle', handle);
|
|
121
|
+
if (callback) url.searchParams.set('callback', callback);
|
|
122
|
+
return url.toString();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const badRequest = (message) => Object.assign(new Error(message), { status: 400 });
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Typed lines -> the spec objects `connectServers` and the bridge both take.
|
|
129
|
+
*
|
|
130
|
+
* ⚠ ONE LINE, ONE SERVER, AND THE COMMAND IS NOT RUN THROUGH A SHELL. The parse
|
|
131
|
+
* is `parseServerLine`, the same one the headless prompt uses, so a line means
|
|
132
|
+
* the same thing here, there, and on a Windows machine.
|
|
133
|
+
*/
|
|
134
|
+
export function parseServerLines(text) {
|
|
135
|
+
const specs = [];
|
|
136
|
+
const seen = new Set();
|
|
137
|
+
String(text ?? '').split('\n').forEach((raw, index) => {
|
|
138
|
+
const line = raw.trim();
|
|
139
|
+
if (!line || line.startsWith('#')) return;
|
|
140
|
+
const at = line.indexOf(':');
|
|
141
|
+
if (at < 1) throw badRequest(`line ${index + 1}: write "name: command" or "name: https://url"`);
|
|
142
|
+
const name = line.slice(0, at).trim();
|
|
143
|
+
if (seen.has(name)) throw badRequest(`line ${index + 1}: ${name} is listed twice`);
|
|
144
|
+
seen.add(name);
|
|
145
|
+
try { specs.push(parseServerLine(name, line.slice(at + 1))); }
|
|
146
|
+
catch (error) { throw badRequest(`line ${index + 1}: ${error.message}`); }
|
|
147
|
+
});
|
|
148
|
+
return specs;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** One spec -> the line this panel shows and a person edits. */
|
|
152
|
+
export function serverLine(spec) {
|
|
153
|
+
if (!spec || typeof spec !== 'object') return '';
|
|
154
|
+
if (spec.transport === 'http') return `${spec.name}: ${spec.url}`;
|
|
155
|
+
return `${spec.name}: ${[spec.command, ...(spec.args ?? [])].join(' ')}`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function openBrowser(url) {
|
|
159
|
+
const [command, args] = process.platform === 'darwin' ? ['open', [url]]
|
|
160
|
+
: process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]]
|
|
161
|
+
: ['xdg-open', [url]];
|
|
162
|
+
try {
|
|
163
|
+
const child = spawn(command, args, { detached: true, stdio: 'ignore' });
|
|
164
|
+
child.on('error', () => {});
|
|
165
|
+
child.unref();
|
|
166
|
+
} catch { /* the URL is printed in the status; the person can open it */ }
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function apply(ctx, config = {}) {
|
|
170
|
+
const bridgeUrl = config.bridgeUrl || bridgeUrlOf();
|
|
171
|
+
const state = {
|
|
172
|
+
credential: null,
|
|
173
|
+
catalog: null,
|
|
174
|
+
session: null,
|
|
175
|
+
status: 'idle',
|
|
176
|
+
error: '',
|
|
177
|
+
connecting: null,
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
async function load() {
|
|
181
|
+
try { state.credential = await loadCredential(); }
|
|
182
|
+
catch (error) { state.error = error?.message || String(error); state.status = 'error'; }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Stop the MCP clients and the socket. Safe to call repeatedly. */
|
|
186
|
+
async function stop() {
|
|
187
|
+
state.session?.close?.();
|
|
188
|
+
state.session = null;
|
|
189
|
+
if (state.catalog) { await state.catalog.close?.().catch(() => {}); state.catalog = null; }
|
|
190
|
+
state.status = 'idle';
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function start() {
|
|
194
|
+
if (state.connecting) return state.connecting;
|
|
195
|
+
state.connecting = (async () => {
|
|
196
|
+
await stop();
|
|
197
|
+
if (!state.credential?.token) { state.status = 'idle'; return; }
|
|
198
|
+
// ⚠ ONE FORM, WRITTEN WHERE THE LIST IS EDITED AND READ HERE UNCHANGED.
|
|
199
|
+
// The credential holds the spec objects `connectServers` takes, so
|
|
200
|
+
// re-parsing them as a `{command|url}` config would read a stdio spec as
|
|
201
|
+
// a server that "needs either command or url".
|
|
202
|
+
// ⚠ THE LIST IS READ FROM THE EDITOR BEFORE EACH CONNECT. A list saved on
|
|
203
|
+
// the bridge after this machine last ran is what the person meant; the
|
|
204
|
+
// copy in the credential is a cache for an offline start.
|
|
205
|
+
try {
|
|
206
|
+
const code = await editorCodeOf({ bridgeUrl, token: state.credential.token });
|
|
207
|
+
if (code) {
|
|
208
|
+
const url = `${httpBaseOf(bridgeUrl)}/dragonbyte/pair/servers?code=${encodeURIComponent(code)}`;
|
|
209
|
+
const response = await fetch(url, { cache: 'no-store' });
|
|
210
|
+
if (response.ok) {
|
|
211
|
+
const body = await response.json();
|
|
212
|
+
// ⚠ AN EMPTY LIST IS AN ANSWER, NOT A MISS. A person who deletes
|
|
213
|
+
// every server means to share none; keeping the cached copy would
|
|
214
|
+
// publish a list they just removed.
|
|
215
|
+
if (Array.isArray(body?.mcpServers)) {
|
|
216
|
+
state.credential.mcpServers = body.mcpServers;
|
|
217
|
+
await saveCredential(state.credential);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
} catch { /* offline: keep the cached list, which is what lets it start */ }
|
|
222
|
+
const specs = Array.isArray(state.credential.mcpServers) ? state.credential.mcpServers : [];
|
|
223
|
+
// ⚠ AN EMPTY CATALOG IS NOT PUBLISHED. Binding a tenant to a host that can
|
|
224
|
+
// do nothing is worse than being offline, so a machine with no servers
|
|
225
|
+
// stays "configured but not connected" and says so.
|
|
226
|
+
if (!specs.length) { state.status = 'no-servers'; return; }
|
|
227
|
+
state.status = 'connecting';
|
|
228
|
+
const catalog = await connectServers(specs, { log: () => {} });
|
|
229
|
+
state.catalog = catalog;
|
|
230
|
+
if (!catalog.catalog.servers.length) { state.status = 'no-servers'; await catalog.close(); state.catalog = null; return; }
|
|
231
|
+
state.session = serveBridge({
|
|
232
|
+
url: bridgeUrl,
|
|
233
|
+
token: state.credential.token,
|
|
234
|
+
refreshToken: state.credential.refreshToken ?? '',
|
|
235
|
+
expiresAt: state.credential.expiresAt ?? 0,
|
|
236
|
+
tenantId: state.credential.tenantId || '',
|
|
237
|
+
catalog: catalog.catalog,
|
|
238
|
+
call: catalog.call,
|
|
239
|
+
// ⚠ `connect` IS AN INJECTED DEPENDENCY, NOT A REFERENCE TO GLOBAL
|
|
240
|
+
// WebSocket — `serveBridge` defaults it to `undefined` so a test can
|
|
241
|
+
// drive the protocol without a socket. Omitting it here made `open()`
|
|
242
|
+
// throw `connect is not a function` on every start, so the machine
|
|
243
|
+
// held an open MCP connection, showed nothing, and never dialed the
|
|
244
|
+
// bridge. `host-main.mjs` has always passed this line.
|
|
245
|
+
connect: (url, { headers }) => new WebSocket(url, { headers }),
|
|
246
|
+
onServers: (servers) => { state.credential.mcpServers = servers; },
|
|
247
|
+
});
|
|
248
|
+
state.status = 'connected';
|
|
249
|
+
state.error = '';
|
|
250
|
+
})().catch((error) => {
|
|
251
|
+
state.status = 'error';
|
|
252
|
+
state.error = error?.message || String(error);
|
|
253
|
+
}).finally(() => { state.connecting = null; });
|
|
254
|
+
return state.connecting;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Open the pairing page and wait for the bridge to hand this machine a code.
|
|
259
|
+
*
|
|
260
|
+
* ⚠ THE CODE COMES FROM THE BRIDGE, NOT FROM THE PAGE. It is minted in the
|
|
261
|
+
* browser's own copy of the page, so fetching that page from here returns
|
|
262
|
+
* markup with no code in it and can only ever time out. The sign-in ends on
|
|
263
|
+
* the bridge, and the bridge answers this request with the code directly.
|
|
264
|
+
*/
|
|
265
|
+
async function pair({ tenantId }) {
|
|
266
|
+
// ⚠ AN EMPTY TENANT IS THE NORMAL FIRST PAIRING, AND THE PAGE NAMES NONE.
|
|
267
|
+
// The device is scoped to the account, so there is nothing to choose; the
|
|
268
|
+
// bridge checks ownership from the registry on every catalog it publishes.
|
|
269
|
+
const handle = randomBytes(16).toString('base64url');
|
|
270
|
+
const issued = waitForPairing(handle);
|
|
271
|
+
openBrowser(pairPageUrl({ bridgeUrl, handle, tenantId }));
|
|
272
|
+
return redeem((await issued).code);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Hold this request until the browser finishes signing in, then take the code.
|
|
277
|
+
*
|
|
278
|
+
* ⚠ THE HANDLE IS THIS MACHINE'S CLAIM ON THE RESULT, AND IT IS THE ONLY
|
|
279
|
+
* ONE. It is 16 random bytes, never shown to anyone, and the bridge keeps it
|
|
280
|
+
* until it either hands over a code or the window closes.
|
|
281
|
+
*/
|
|
282
|
+
async function waitForPairing(handle) {
|
|
283
|
+
const response = await fetch(`${httpBaseOf(bridgeUrl)}/dragonbyte/pair/wait?handle=${encodeURIComponent(handle)}`,
|
|
284
|
+
{ cache: 'no-store', signal: AbortSignal.timeout(WAIT_TTL_MS + 30_000) }).catch(() => null);
|
|
285
|
+
if (!response) throw new Error('the bridge could not be reached while pairing');
|
|
286
|
+
const body = await response.json().catch(() => null);
|
|
287
|
+
if (!response.ok) throw new Error(body?.error || 'the bridge refused to register this machine');
|
|
288
|
+
if (typeof body?.code !== 'string' || !body.code) throw new Error('sign-in did not finish on the bridge');
|
|
289
|
+
return body;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Adopt a device token typed into Settings.
|
|
294
|
+
*
|
|
295
|
+
* ⚠ THIS IS THE PATH THAT DOES NOT NEED A BROWSER OR A CODE. A token minted in
|
|
296
|
+
* the tenant's own Settings -> DragonByte proves the same thing a pairing code
|
|
297
|
+
* does, and this machine already knows how to hold one: the headless host has
|
|
298
|
+
* taken a pasted token since it existed. Refusing it here only meant a desktop
|
|
299
|
+
* had to route the same proof through a page instead.
|
|
300
|
+
*
|
|
301
|
+
* ⚠ THE PREFIX IS CHECKED BEFORE ANYTHING IS SAVED. A pasted line that is not
|
|
302
|
+
* a device token is a paste mistake, not a credential — writing it would make
|
|
303
|
+
* "paired" true and every call fail afterwards.
|
|
304
|
+
*/
|
|
305
|
+
async function adoptToken(text) {
|
|
306
|
+
const token = String(text ?? '').trim();
|
|
307
|
+
if (!token) throw badRequest('a device token is required');
|
|
308
|
+
if (!/^dbt1[.A-Za-z0-9_-]+$/.test(token)) throw badRequest('that is not a device token (it should start with dbt1)');
|
|
309
|
+
state.credential = { token, refreshToken: '', expiresAt: 0, tenantId: '', mcpServers: state.credential?.mcpServers ?? [] };
|
|
310
|
+
await saveCredential(state.credential);
|
|
311
|
+
await start();
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function redeem(code) {
|
|
315
|
+
const response = await fetch(`${httpBaseOf(bridgeUrl)}/dragonbyte/pair/redeem`, {
|
|
316
|
+
method: 'POST',
|
|
317
|
+
headers: { 'content-type': 'application/json' },
|
|
318
|
+
// ⚠ THE NAME IS SENT HERE, BY THE ONLY CALLER THAT KNOWS IT. The browser
|
|
319
|
+
// signs in and hands over a code; it never learns what this machine is
|
|
320
|
+
// called, so naming it there would mean asking a person mid-flow.
|
|
321
|
+
body: JSON.stringify({ code, label: labelOf() }),
|
|
322
|
+
});
|
|
323
|
+
const credential = await response.json().catch(() => null);
|
|
324
|
+
if (!response.ok) throw new Error(credential?.error || 'the pairing code was refused');
|
|
325
|
+
state.credential = {
|
|
326
|
+
token: credential.token,
|
|
327
|
+
refreshToken: credential.refreshToken,
|
|
328
|
+
expiresAt: credential.expiresAt,
|
|
329
|
+
tenantId: credential.tenantId,
|
|
330
|
+
mcpServers: state.credential?.mcpServers ?? [],
|
|
331
|
+
};
|
|
332
|
+
await saveCredential(state.credential);
|
|
333
|
+
await start();
|
|
334
|
+
return { tenantId: state.credential.tenantId };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Save the list the panel holds, then reconnect with it.
|
|
339
|
+
*
|
|
340
|
+
* ⚠ THE BRIDGE IS WRITTEN FIRST, AND THE CREDENTIAL ONLY AFTER IT AGREES. The
|
|
341
|
+
* bridge re-reads this list on the machine's next start, so a save that never
|
|
342
|
+
* reached it must not look saved here. The credential copy is what lets an
|
|
343
|
+
* offline start publish the list the person last confirmed.
|
|
344
|
+
*
|
|
345
|
+
* ⚠ AN EMPTY LIST IS SAVED, NOT SKIPPED. Deleting every server is how a
|
|
346
|
+
* machine stops sharing; `start()` then publishes nothing and says so.
|
|
347
|
+
*/
|
|
348
|
+
async function saveServers(text) {
|
|
349
|
+
const specs = parseServerLines(text);
|
|
350
|
+
await editorCodeOf({ bridgeUrl, token: state.credential?.token, mcpServers: specs });
|
|
351
|
+
state.credential = { ...(state.credential ?? {}), mcpServers: specs };
|
|
352
|
+
await saveCredential(state.credential);
|
|
353
|
+
await start();
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const publicStatus = () => ({
|
|
357
|
+
status: state.status,
|
|
358
|
+
...(state.error ? { error: state.error } : {}),
|
|
359
|
+
tenantId: state.credential?.tenantId || '',
|
|
360
|
+
paired: Boolean(state.credential?.token),
|
|
361
|
+
// ⚠ THE NAME THE TENANT SAW AT PAIRING, SHOWN BACK HERE. It is the same
|
|
362
|
+
// `labelOf()` sent to the bridge in `pair`, so Settings names this machine
|
|
363
|
+
// exactly as the tenant's device list does. A person running two machines
|
|
364
|
+
// with alike hostnames sets `DSH_DRAGONBYTE_LABEL` to tell them apart.
|
|
365
|
+
label: labelOf(),
|
|
366
|
+
// The list as text, because this panel is where it is typed. The credential
|
|
367
|
+
// holds specs; the panel holds one line per server.
|
|
368
|
+
servers: (state.credential?.mcpServers ?? []).map(serverLine).join('\n'),
|
|
369
|
+
credentialPath: credentialPath(),
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
const routes = [
|
|
374
|
+
ctx.webServer.register({
|
|
375
|
+
kind: 'prefix', path: '/dragonbyte',
|
|
376
|
+
handler: async (req, res) => {
|
|
377
|
+
const url = new URL(req.url || '/', 'http://host.invalid');
|
|
378
|
+
try {
|
|
379
|
+
if (url.pathname === '/dragonbyte/status' && req.method === 'GET') return json(res, 200, publicStatus());
|
|
380
|
+
if (url.pathname === '/dragonbyte/pair' && req.method === 'POST') {
|
|
381
|
+
const body = await readBody(req);
|
|
382
|
+
await pair({ tenantId: typeof body?.tenantId === 'string' ? body.tenantId : '' });
|
|
383
|
+
return json(res, 200, publicStatus());
|
|
384
|
+
}
|
|
385
|
+
if (url.pathname === '/dragonbyte/token' && req.method === 'PUT') {
|
|
386
|
+
const body = await readBody(req);
|
|
387
|
+
await adoptToken(body?.token);
|
|
388
|
+
return json(res, 200, publicStatus());
|
|
389
|
+
}
|
|
390
|
+
if (url.pathname === '/dragonbyte/servers' && req.method === 'PUT') {
|
|
391
|
+
const body = await readBody(req);
|
|
392
|
+
await saveServers(typeof body?.text === 'string' ? body.text : '');
|
|
393
|
+
return json(res, 200, publicStatus());
|
|
394
|
+
}
|
|
395
|
+
if (url.pathname === '/dragonbyte/credential' && req.method === 'DELETE') {
|
|
396
|
+
state.credential = { token: '', refreshToken: '', expiresAt: 0, tenantId: '', mcpServers: state.credential?.mcpServers ?? [] };
|
|
397
|
+
await saveCredential(state.credential);
|
|
398
|
+
await stop();
|
|
399
|
+
return json(res, 200, publicStatus());
|
|
400
|
+
}
|
|
401
|
+
if (url.pathname === '/dragonbyte/reconnect' && req.method === 'POST') {
|
|
402
|
+
await start();
|
|
403
|
+
return json(res, 200, publicStatus());
|
|
404
|
+
}
|
|
405
|
+
return json(res, 404, { error: 'not found' });
|
|
406
|
+
} catch (error) {
|
|
407
|
+
return json(res, Number.isInteger(error?.status) ? error.status : 500, { error: error?.message || 'dragonbyte failed' });
|
|
408
|
+
}
|
|
409
|
+
},
|
|
410
|
+
}),
|
|
411
|
+
];
|
|
412
|
+
|
|
413
|
+
ctx.effect(() => () => {
|
|
414
|
+
for (const dispose of routes) dispose();
|
|
415
|
+
void stop();
|
|
416
|
+
}, 'dragonbyte: routes and bridge');
|
|
417
|
+
|
|
418
|
+
void load().then(() => start()).catch(() => {});
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
export { apply };
|