dsh-control-mcp 0.1.0 → 0.2.0
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/README.md +49 -6
- package/client/index.mjs +186 -3
- package/docs/DETAIL.md +9 -0
- package/index.mjs +109 -1
- package/lib/access.mjs +324 -0
- package/lib/client.js +186 -3
- package/lib/core.mjs +34 -7
- package/lib/http.mjs +80 -8
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +5 -3
package/lib/access.mjs
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* API keys and their scopes.
|
|
3
|
+
*
|
|
4
|
+
* A key is either
|
|
5
|
+
* - full: speaks as the harness owner, like the original single token;
|
|
6
|
+
* - scoped: speaks as a `dsh-control-key` principal whose permissions DSH's
|
|
7
|
+
* own remote-access engine decides through the policy below.
|
|
8
|
+
*
|
|
9
|
+
* Scoping rides the same engine that confines Liveshare viewers: every Remote
|
|
10
|
+
* call names the session/workspace resources it touches, the gateway asks the
|
|
11
|
+
* policy before running it, and list methods (session/list, session/search,
|
|
12
|
+
* workspace/follow, session/control, …) filter their items per resource. So a
|
|
13
|
+
* scoped key never sees a chat outside its scope, in any endpoint.
|
|
14
|
+
*
|
|
15
|
+
* Stored records (credential store, one grant record):
|
|
16
|
+
* { version: 1, keys: [{ id, name, hash, prefix, createdAt, expiresAt?,
|
|
17
|
+
* lastUsedAt?, disabled?, mcp, api, mode: 'full' | 'scoped',
|
|
18
|
+
* access: 'read' | 'prompt', workspaces: [...], sessions: [...] }] }
|
|
19
|
+
* Tokens are never stored, only their SHA-256.
|
|
20
|
+
*/
|
|
21
|
+
import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
22
|
+
import { ControlError, isRecord } from './core.mjs';
|
|
23
|
+
|
|
24
|
+
export const KEY_PRINCIPAL = 'dsh-control-key';
|
|
25
|
+
export const KEY_STORE_VERSION = 1;
|
|
26
|
+
export const MAX_KEYS = 100;
|
|
27
|
+
export const MAX_SCOPE_ITEMS = 1000;
|
|
28
|
+
const TOKEN_PREFIX = 'dshc_';
|
|
29
|
+
|
|
30
|
+
// ── roles: the actions DSH lets a scoped key take ────────────────────────────
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Global reads a scoped key needs to find its way around. Every one either
|
|
34
|
+
* names no private resource (model and provider catalogs, presets, command
|
|
35
|
+
* descriptors) or filters its items through `remoteAccess.allows()` per
|
|
36
|
+
* session/workspace (session/list, session/search, session/control,
|
|
37
|
+
* workspace/follow). Nothing here mutates.
|
|
38
|
+
*/
|
|
39
|
+
export const SCOPED_GLOBAL_ACTIONS = Object.freeze([
|
|
40
|
+
'agentPresets/list',
|
|
41
|
+
'llm/listProviders',
|
|
42
|
+
'permissionPresets/catalog',
|
|
43
|
+
'session/canOpenWorkspacePath',
|
|
44
|
+
'session/control',
|
|
45
|
+
'session/list',
|
|
46
|
+
'session/modelCatalog',
|
|
47
|
+
'session/search',
|
|
48
|
+
'workspace/follow',
|
|
49
|
+
// Owner-side Remote events that carry a session the key may see.
|
|
50
|
+
'event:api-session/activity',
|
|
51
|
+
'event:api-session/added',
|
|
52
|
+
'event:api-session/error',
|
|
53
|
+
'event:api-session/removed',
|
|
54
|
+
'event:api-session/status',
|
|
55
|
+
]);
|
|
56
|
+
|
|
57
|
+
/** Reading one allowed session. */
|
|
58
|
+
export const SESSION_READ_ACTIONS = Object.freeze([
|
|
59
|
+
'commands/list',
|
|
60
|
+
'goals/get',
|
|
61
|
+
'session/attachment',
|
|
62
|
+
'session/control',
|
|
63
|
+
'session/events',
|
|
64
|
+
'session/follow',
|
|
65
|
+
'session/list',
|
|
66
|
+
'session/observeEvent',
|
|
67
|
+
'session/observeProjections',
|
|
68
|
+
'session/observeState',
|
|
69
|
+
'session/page',
|
|
70
|
+
'session/projections',
|
|
71
|
+
'session/search',
|
|
72
|
+
'session/state',
|
|
73
|
+
'session/wait',
|
|
74
|
+
'skills/list',
|
|
75
|
+
'terminal/list',
|
|
76
|
+
'terminal/watch',
|
|
77
|
+
'toolResults/watch',
|
|
78
|
+
'workspace/follow',
|
|
79
|
+
'event:api-session/activity',
|
|
80
|
+
'event:api-session/added',
|
|
81
|
+
'event:api-session/error',
|
|
82
|
+
'event:api-session/removed',
|
|
83
|
+
'event:api-session/status',
|
|
84
|
+
]);
|
|
85
|
+
|
|
86
|
+
/** Driving one allowed session, on top of reading it. */
|
|
87
|
+
export const SESSION_PROMPT_ACTIONS = Object.freeze([
|
|
88
|
+
'session/prompt',
|
|
89
|
+
'session/cancel',
|
|
90
|
+
'session/rename',
|
|
91
|
+
'session/selectModel',
|
|
92
|
+
'session/updateQueue',
|
|
93
|
+
'fileUploads/upload',
|
|
94
|
+
]);
|
|
95
|
+
|
|
96
|
+
/** Seeing one allowed workspace. */
|
|
97
|
+
export const WORKSPACE_READ_ACTIONS = Object.freeze(['workspace/follow']);
|
|
98
|
+
|
|
99
|
+
/** Starting new chats inside one allowed workspace (prompt access only). */
|
|
100
|
+
export const WORKSPACE_PROMPT_ACTIONS = Object.freeze(['session/create']);
|
|
101
|
+
|
|
102
|
+
/** Every action some scoped role grants: anything else is refused before it runs. */
|
|
103
|
+
export const SCOPED_ACTIONS = Object.freeze([...new Set([
|
|
104
|
+
...SCOPED_GLOBAL_ACTIONS, ...SESSION_READ_ACTIONS, ...SESSION_PROMPT_ACTIONS, ...WORKSPACE_READ_ACTIONS, ...WORKSPACE_PROMPT_ACTIONS,
|
|
105
|
+
])].sort());
|
|
106
|
+
|
|
107
|
+
const role = (name, resource, actions) => Object.freeze({ name, resource, actions: Object.freeze([...actions]) });
|
|
108
|
+
export const ROLES = Object.freeze({
|
|
109
|
+
global: role('dsh-control-mcp:scoped-global', 'global', SCOPED_GLOBAL_ACTIONS),
|
|
110
|
+
sessionRead: role('dsh-control-mcp:session-read', 'session', SESSION_READ_ACTIONS),
|
|
111
|
+
sessionPrompt: role('dsh-control-mcp:session-prompt', 'session', SESSION_PROMPT_ACTIONS),
|
|
112
|
+
workspaceRead: role('dsh-control-mcp:workspace-read', 'workspace', WORKSPACE_READ_ACTIONS),
|
|
113
|
+
workspacePrompt: role('dsh-control-mcp:workspace-prompt', 'workspace', WORKSPACE_PROMPT_ACTIONS),
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
// ── key records ─────────────────────────────────────────────────────────────
|
|
117
|
+
|
|
118
|
+
export function hashToken(token) {
|
|
119
|
+
return createHash('sha256').update(String(token)).digest('hex');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function newKeyToken() {
|
|
123
|
+
return `${TOKEN_PREFIX}${randomBytes(32).toString('base64url')}`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const NAME_MAX = 80;
|
|
127
|
+
const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;
|
|
128
|
+
|
|
129
|
+
function cleanIds(values, label) {
|
|
130
|
+
if (values === undefined) return [];
|
|
131
|
+
if (!Array.isArray(values)) throw new ControlError('dsh-control/key-invalid', `${label} must be a list of ids.`, 400);
|
|
132
|
+
const out = [...new Set(values.map(value => String(value).trim()).filter(Boolean))];
|
|
133
|
+
if (out.length > MAX_SCOPE_ITEMS) throw new ControlError('dsh-control/key-invalid', `${label} may list at most ${MAX_SCOPE_ITEMS} ids.`, 400);
|
|
134
|
+
const bad = out.find(value => !ID_RE.test(value));
|
|
135
|
+
if (bad !== undefined) throw new ControlError('dsh-control/key-invalid', `${label} contains an invalid id: ${bad.slice(0, 60)}`, 400);
|
|
136
|
+
return out;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Validate the editable fields of a key. `previous` supplies values the patch
|
|
141
|
+
* omits, so the same function serves create and update.
|
|
142
|
+
*/
|
|
143
|
+
export function normalizeKeyFields(input, previous = {}) {
|
|
144
|
+
if (!isRecord(input)) throw new ControlError('dsh-control/key-invalid', 'Key fields must be an object.', 400);
|
|
145
|
+
const pick = (field, fallback) => (input[field] === undefined ? (previous[field] ?? fallback) : input[field]);
|
|
146
|
+
const name = String(pick('name', '')).trim();
|
|
147
|
+
if (name === '' || name.length > NAME_MAX) throw new ControlError('dsh-control/key-invalid', `A key needs a name of 1 to ${NAME_MAX} characters.`, 400);
|
|
148
|
+
const mode = pick('mode', 'scoped');
|
|
149
|
+
if (mode !== 'full' && mode !== 'scoped') throw new ControlError('dsh-control/key-invalid', 'mode is "full" or "scoped".', 400);
|
|
150
|
+
const access = pick('access', 'read');
|
|
151
|
+
if (access !== 'read' && access !== 'prompt') throw new ControlError('dsh-control/key-invalid', 'access is "read" or "prompt".', 400);
|
|
152
|
+
const workspaces = cleanIds(pick('workspaces', []), 'workspaces');
|
|
153
|
+
const sessions = cleanIds(pick('sessions', []), 'sessions');
|
|
154
|
+
let expiresAt = pick('expiresAt', null);
|
|
155
|
+
if (expiresAt !== null && expiresAt !== '') {
|
|
156
|
+
const time = Date.parse(expiresAt);
|
|
157
|
+
if (!Number.isFinite(time)) throw new ControlError('dsh-control/key-invalid', 'expiresAt must be an ISO date or null.', 400);
|
|
158
|
+
expiresAt = new Date(time).toISOString();
|
|
159
|
+
} else expiresAt = null;
|
|
160
|
+
const flag = (field, fallback) => { const value = pick(field, fallback); if (typeof value !== 'boolean') throw new ControlError('dsh-control/key-invalid', `${field} must be true or false.`, 400); return value; };
|
|
161
|
+
return { name, mode, access, workspaces, sessions, expiresAt, mcp: flag('mcp', true), api: flag('api', true), disabled: flag('disabled', false) };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Public view of a key: never the hash. */
|
|
165
|
+
export function publicKey(record) {
|
|
166
|
+
const { hash, ...rest } = record;
|
|
167
|
+
void hash;
|
|
168
|
+
return { ...rest, expired: isExpired(record) };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function isExpired(record, now = Date.now()) {
|
|
172
|
+
return typeof record.expiresAt === 'string' && Date.parse(record.expiresAt) <= now;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function parseStore(payload) {
|
|
176
|
+
const keys = isRecord(payload) && Array.isArray(payload.keys) ? payload.keys : [];
|
|
177
|
+
return keys.filter(key => isRecord(key) && typeof key.id === 'string' && typeof key.hash === 'string' && /^[0-9a-f]{64}$/.test(key.hash)).map(key => {
|
|
178
|
+
try {
|
|
179
|
+
return { id: key.id, hash: key.hash, prefix: String(key.prefix ?? ''), createdAt: String(key.createdAt ?? ''), lastUsedAt: key.lastUsedAt ?? null, ...normalizeKeyFields(key) };
|
|
180
|
+
} catch {
|
|
181
|
+
return { id: key.id, hash: key.hash, prefix: String(key.prefix ?? ''), createdAt: String(key.createdAt ?? ''), lastUsedAt: null, name: String(key.name ?? 'invalid key').slice(0, NAME_MAX) || 'invalid key', mode: 'scoped', access: 'read', workspaces: [], sessions: [], expiresAt: null, mcp: false, api: false, disabled: true };
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* In-memory key registry. `persist(keys)` saves the full list; `onChange`
|
|
188
|
+
* tells the access policy to recompute. Authentication is a hash lookup
|
|
189
|
+
* followed by a constant-time compare.
|
|
190
|
+
*/
|
|
191
|
+
export function createKeyRegistry({ persist = async () => {}, onChange = () => {}, now = () => Date.now() } = {}) {
|
|
192
|
+
let keys = [];
|
|
193
|
+
const byHash = () => new Map(keys.map(key => [key.hash, key]));
|
|
194
|
+
let index = byHash();
|
|
195
|
+
const commit = async next => {
|
|
196
|
+
const previous = keys;
|
|
197
|
+
keys = next;
|
|
198
|
+
index = byHash();
|
|
199
|
+
try {
|
|
200
|
+
await persist(keys);
|
|
201
|
+
} catch (error) {
|
|
202
|
+
keys = previous;
|
|
203
|
+
index = byHash();
|
|
204
|
+
throw error;
|
|
205
|
+
}
|
|
206
|
+
onChange();
|
|
207
|
+
};
|
|
208
|
+
return {
|
|
209
|
+
load(stored) { keys = parseStore(stored); index = byHash(); onChange(); },
|
|
210
|
+
list: () => keys.map(publicKey),
|
|
211
|
+
get: id => keys.find(key => key.id === id),
|
|
212
|
+
count: () => keys.length,
|
|
213
|
+
/** The live key for a presented token, or undefined. Never throws. */
|
|
214
|
+
authenticate(token) {
|
|
215
|
+
if (typeof token !== 'string' || !token.startsWith(TOKEN_PREFIX) || token.length < 40) return undefined;
|
|
216
|
+
const hash = hashToken(token);
|
|
217
|
+
const key = index.get(hash);
|
|
218
|
+
if (key === undefined) return undefined;
|
|
219
|
+
if (!timingSafeEqual(Buffer.from(key.hash, 'hex'), Buffer.from(hash, 'hex'))) return undefined;
|
|
220
|
+
if (key.disabled || isExpired(key, now())) return undefined;
|
|
221
|
+
return key;
|
|
222
|
+
},
|
|
223
|
+
async create(fields) {
|
|
224
|
+
if (keys.length >= MAX_KEYS) throw new ControlError('dsh-control/key-limit', `At most ${MAX_KEYS} keys.`, 409);
|
|
225
|
+
const token = newKeyToken();
|
|
226
|
+
const record = { id: randomUUID(), hash: hashToken(token), prefix: token.slice(0, 9), createdAt: new Date(now()).toISOString(), lastUsedAt: null, ...normalizeKeyFields(fields) };
|
|
227
|
+
await commit([...keys, record]);
|
|
228
|
+
return { key: publicKey(record), token };
|
|
229
|
+
},
|
|
230
|
+
async update(id, patch) {
|
|
231
|
+
const current = keys.find(key => key.id === id);
|
|
232
|
+
if (current === undefined) throw new ControlError('dsh-control/key-unknown', 'No such key.', 404);
|
|
233
|
+
const record = { ...current, ...normalizeKeyFields(patch, current) };
|
|
234
|
+
await commit(keys.map(key => (key.id === id ? record : key)));
|
|
235
|
+
return publicKey(record);
|
|
236
|
+
},
|
|
237
|
+
async rotate(id) {
|
|
238
|
+
const current = keys.find(key => key.id === id);
|
|
239
|
+
if (current === undefined) throw new ControlError('dsh-control/key-unknown', 'No such key.', 404);
|
|
240
|
+
const token = newKeyToken();
|
|
241
|
+
const record = { ...current, hash: hashToken(token), prefix: token.slice(0, 9) };
|
|
242
|
+
await commit(keys.map(key => (key.id === id ? record : key)));
|
|
243
|
+
return { key: publicKey(record), token };
|
|
244
|
+
},
|
|
245
|
+
async remove(id) {
|
|
246
|
+
if (!keys.some(key => key.id === id)) throw new ControlError('dsh-control/key-unknown', 'No such key.', 404);
|
|
247
|
+
await commit(keys.filter(key => key.id !== id));
|
|
248
|
+
},
|
|
249
|
+
/** Best-effort usage stamp, persisted at most once a minute per key. */
|
|
250
|
+
touch(key) {
|
|
251
|
+
const stamp = now();
|
|
252
|
+
if (key.lastUsedAt && stamp - Date.parse(key.lastUsedAt) < 60000) return;
|
|
253
|
+
key.lastUsedAt = new Date(stamp).toISOString();
|
|
254
|
+
persist(keys).catch(() => {});
|
|
255
|
+
},
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// ── DSH remote-access policy ────────────────────────────────────────────────
|
|
260
|
+
|
|
261
|
+
export function keyPrincipal(key) {
|
|
262
|
+
return Object.freeze({ kind: KEY_PRINCIPAL, keyId: key.id });
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* The remote-access policy for scoped keys.
|
|
267
|
+
* @param registry - key registry (reads the live record on every decision).
|
|
268
|
+
* @param workspaces - `() => [{ id, sessionIds }]`, the live workspace registry.
|
|
269
|
+
*/
|
|
270
|
+
export function createScopedPolicy(registry, workspaces) {
|
|
271
|
+
return {
|
|
272
|
+
bindings(principal) {
|
|
273
|
+
const key = registry.get(principal?.keyId);
|
|
274
|
+
if (key === undefined || key.mode !== 'scoped' || key.disabled || isExpired(key)) return [];
|
|
275
|
+
const prompt = key.access === 'prompt';
|
|
276
|
+
const bindings = [{ role: ROLES.global, resource: { kind: 'global' } }];
|
|
277
|
+
const sessionIds = new Set(key.sessions);
|
|
278
|
+
const workspaceIds = new Set(key.workspaces);
|
|
279
|
+
let registered = [];
|
|
280
|
+
try { registered = workspaces(); } catch { registered = []; }
|
|
281
|
+
for (const workspace of registered) {
|
|
282
|
+
if (workspaceIds.has(workspace.id)) {
|
|
283
|
+
// Follow the workspace: its current and future sessions.
|
|
284
|
+
for (const id of workspace.sessionIds ?? []) sessionIds.add(id);
|
|
285
|
+
} else if ((workspace.sessionIds ?? []).some(id => key.sessions.includes(id))) {
|
|
286
|
+
// A workspace that holds an individually allowed session stays visible (filtered to that session).
|
|
287
|
+
bindings.push({ role: ROLES.workspaceRead, resource: { kind: 'workspace', id: workspace.id } });
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
for (const id of workspaceIds) {
|
|
291
|
+
bindings.push({ role: ROLES.workspaceRead, resource: { kind: 'workspace', id } });
|
|
292
|
+
if (prompt) bindings.push({ role: ROLES.workspacePrompt, resource: { kind: 'workspace', id } });
|
|
293
|
+
}
|
|
294
|
+
for (const id of sessionIds) {
|
|
295
|
+
bindings.push({ role: ROLES.sessionRead, resource: { kind: 'session', id } });
|
|
296
|
+
if (prompt) bindings.push({ role: ROLES.sessionPrompt, resource: { kind: 'session', id } });
|
|
297
|
+
}
|
|
298
|
+
return bindings;
|
|
299
|
+
},
|
|
300
|
+
/** Refusal reason string; DSH wraps it into `remote-access/denied` details. */
|
|
301
|
+
explain(request) {
|
|
302
|
+
const key = registry.get(request?.principal?.keyId);
|
|
303
|
+
if (key === undefined || key.disabled || isExpired(key)) return 'dsh-control-key-inactive';
|
|
304
|
+
if (!SCOPED_ACTIONS.includes(request.action)) return 'dsh-control-key-action-not-allowed';
|
|
305
|
+
if (key.access === 'read' && [...SESSION_PROMPT_ACTIONS, ...WORKSPACE_PROMPT_ACTIONS].includes(request.action)) return 'dsh-control-key-read-only';
|
|
306
|
+
return 'dsh-control-key-out-of-scope';
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Plugin-side pre-check for scoped keys, before a call reaches the gateway.
|
|
313
|
+
* DSH's policy is the real gate; this only turns the common refusals into
|
|
314
|
+
* clear messages and blocks endpoints no scoped role names.
|
|
315
|
+
*/
|
|
316
|
+
export function scopedPreCheck(key, endpoint) {
|
|
317
|
+
if (key?.mode !== 'scoped') return;
|
|
318
|
+
if (!SCOPED_ACTIONS.includes(endpoint)) {
|
|
319
|
+
throw new ControlError('dsh-control/key-scope', `${endpoint} is not available to a scoped key. Scoped keys reach sessions, workspaces and model catalogs only; use a full-access key for this.`, 403);
|
|
320
|
+
}
|
|
321
|
+
if (key.access === 'read' && [...SESSION_PROMPT_ACTIONS, ...WORKSPACE_PROMPT_ACTIONS].includes(endpoint)) {
|
|
322
|
+
throw new ControlError('dsh-control/key-read-only', `${endpoint} changes a session, and this key has read-only access.`, 403);
|
|
323
|
+
}
|
|
324
|
+
}
|
package/lib/client.js
CHANGED
|
@@ -58,6 +58,38 @@ window.__ModuleLoader__.load({
|
|
|
58
58
|
return body.value.token;
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
/** Owner-only management call to this plugin's own same-origin routes. */
|
|
62
|
+
async function manage(path, method = 'GET', body) {
|
|
63
|
+
const response = await fetch(`${ROUTE}${path}`, {
|
|
64
|
+
method, credentials: 'same-origin',
|
|
65
|
+
headers: { accept: 'application/json', ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
|
|
66
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
67
|
+
});
|
|
68
|
+
const json = await response.json().catch(() => undefined);
|
|
69
|
+
if (!response.ok || json?.ok !== true) throw new Error(typeof json?.error?.message === 'string' ? json.error.message : 'The request failed.');
|
|
70
|
+
return json.value;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function scopeSummary(key, options) {
|
|
74
|
+
if (key.mode === 'full') return 'Full access';
|
|
75
|
+
const ws = key.workspaces.map(id => options.workspaces.find(w => w.id === id)?.title ?? 'missing workspace');
|
|
76
|
+
const ss = key.sessions.length;
|
|
77
|
+
const parts = [];
|
|
78
|
+
if (ws.length) parts.push(`${ws.length === 1 ? 'Workspace' : `${ws.length} workspaces`}: ${ws.slice(0, 2).join(', ')}${ws.length > 2 ? '…' : ''}`);
|
|
79
|
+
if (ss) parts.push(`${ss} chat${ss === 1 ? '' : 's'}`);
|
|
80
|
+
return `${key.access === 'prompt' ? 'Read and prompt' : 'Read only'} · ${parts.join(' · ') || 'nothing selected'}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function relativeTime(iso) {
|
|
84
|
+
if (!iso) return 'never';
|
|
85
|
+
const diff = Date.now() - Date.parse(iso);
|
|
86
|
+
if (!Number.isFinite(diff)) return 'never';
|
|
87
|
+
if (diff < 60000) return 'just now';
|
|
88
|
+
if (diff < 3600000) return `${Math.round(diff / 60000)} min ago`;
|
|
89
|
+
if (diff < 86400000) return `${Math.round(diff / 3600000)} h ago`;
|
|
90
|
+
return `${Math.round(diff / 86400000)} d ago`;
|
|
91
|
+
}
|
|
92
|
+
|
|
61
93
|
const styles = {
|
|
62
94
|
page: { display: 'flex', flexDirection: 'column', gap: '16px', minWidth: 0, fontSize: '13px', lineHeight: '20px', color: 'var(--dsw-alias-label-primary)' },
|
|
63
95
|
head: { display: 'flex', flexDirection: 'column', gap: '4px' },
|
|
@@ -83,6 +115,15 @@ window.__ModuleLoader__.load({
|
|
|
83
115
|
primary: { background: 'var(--dsw-alias-brand-primary)', borderColor: 'transparent', color: 'var(--dsw-alias-label-on-brand, #fff)' },
|
|
84
116
|
disabled: { opacity: 0.5, cursor: 'not-allowed' },
|
|
85
117
|
tabs: { display: 'flex', gap: '6px', flexWrap: 'wrap' },
|
|
118
|
+
keyRow: { display: 'flex', alignItems: 'center', gap: '12px', padding: '10px 14px', borderBottom: '.5px solid var(--dsw-alias-border-l2)', minWidth: 0 },
|
|
119
|
+
keyMain: { display: 'flex', flexDirection: 'column', gap: '2px', minWidth: 0, flex: 1 },
|
|
120
|
+
badgeMuted: { flex: 'none', padding: '0 8px', borderRadius: '999px', fontSize: '11px', lineHeight: '18px', background: 'var(--dsw-alias-bg-layer-3)', color: 'var(--dsw-alias-label-secondary)', border: '.5px solid var(--dsw-alias-border-l3)' },
|
|
121
|
+
editor: { display: 'flex', flexDirection: 'column', gap: '12px', padding: '14px', borderRadius: 'var(--dsw-radius-md, 8px)', border: '.5px solid var(--dsw-alias-border-l3)', background: 'var(--dsw-alias-bg-layer-1)' },
|
|
122
|
+
fieldRow: { display: 'flex', flexDirection: 'column', gap: '4px' },
|
|
123
|
+
radioRow: { display: 'flex', gap: '16px', flexWrap: 'wrap' },
|
|
124
|
+
pick: { display: 'flex', flexDirection: 'column', maxHeight: '220px', overflow: 'auto', border: '.5px solid var(--dsw-alias-border-l3)', borderRadius: 'var(--dsw-radius-md, 8px)', padding: '4px' },
|
|
125
|
+
pickItem: { display: 'flex', alignItems: 'flex-start', gap: '8px', padding: '5px 8px', borderRadius: '6px', cursor: 'pointer', minWidth: 0 },
|
|
126
|
+
textInput: { height: '30px', padding: '0 10px', boxSizing: 'border-box', borderRadius: 'var(--dsw-radius-md, 8px)', border: '.5px solid var(--dsw-alias-border-l4)', background: 'var(--dsw-alias-bg-layer-3)', color: 'inherit', font: 'inherit', fontSize: '12.5px', width: '100%' },
|
|
86
127
|
};
|
|
87
128
|
|
|
88
129
|
function buttonStyle(primary, disabled) {
|
|
@@ -159,8 +200,8 @@ window.__ModuleLoader__.load({
|
|
|
159
200
|
const snippets = snippetsFor(token);
|
|
160
201
|
const displayed = snippetsFor(shown);
|
|
161
202
|
return h('div', { style: styles.section },
|
|
162
|
-
h('h5', { style: styles.sectionTitle }, '
|
|
163
|
-
h('p', { style: styles.hint }, '
|
|
203
|
+
h('h5', { style: styles.sectionTitle }, 'Owner token'),
|
|
204
|
+
h('p', { style: styles.hint }, 'The built-in full-access token, sent as "Authorization: Bearer <token>". It controls the whole harness (or reads it in read-only mode). Prefer a named API key per client above, so you can scope and revoke each one.'),
|
|
164
205
|
state === 'error' ? h('p', { role: 'alert', style: styles.error }, 'Could not read the token. Reload this page from the DSH web GUI you are signed in to.') : null,
|
|
165
206
|
h('div', { style: styles.inline },
|
|
166
207
|
h('input', { readOnly: true, value: state === 'loading' && !token ? 'Loading…' : shown, style: styles.input, 'aria-label': 'Access token', onFocus: event => event.target.select() }),
|
|
@@ -177,6 +218,147 @@ window.__ModuleLoader__.load({
|
|
|
177
218
|
h('p', { style: styles.hint }, `MCP endpoint: ${mcpUrl} · API base: ${apiUrl}. DSH listens on this machine only unless you started it with a trusted host; remote clients need a tunnel or a trusted host.`));
|
|
178
219
|
}
|
|
179
220
|
|
|
221
|
+
function Picker({ label, items, selected, onToggle, empty, describe }) {
|
|
222
|
+
const [query, setQuery] = useState('');
|
|
223
|
+
const needle = query.trim().toLowerCase();
|
|
224
|
+
const shown = needle ? items.filter(item => `${item.title} ${describe(item)}`.toLowerCase().includes(needle)) : items;
|
|
225
|
+
return h('div', { style: styles.fieldRow },
|
|
226
|
+
h('span', { style: styles.label }, `${label} (${selected.length} selected)`),
|
|
227
|
+
items.length > 6 ? h('input', { type: 'search', placeholder: `Search ${label.toLowerCase()}…`, value: query, style: styles.textInput, 'aria-label': `Search ${label.toLowerCase()}`, onChange: event => setQuery(event.target.value) }) : null,
|
|
228
|
+
h('div', { style: styles.pick, role: 'group', 'aria-label': label },
|
|
229
|
+
items.length === 0 ? h('p', { style: { ...styles.hint, padding: '6px 8px' } }, empty) : null,
|
|
230
|
+
shown.map(item => h('label', { key: item.id, style: styles.pickItem },
|
|
231
|
+
h('input', { type: 'checkbox', checked: selected.includes(item.id), onChange: () => onToggle(item.id), style: { marginTop: '3px', flex: 'none' } }),
|
|
232
|
+
h('span', { style: { display: 'flex', flexDirection: 'column', minWidth: 0 } },
|
|
233
|
+
h('span', { style: { overflowWrap: 'anywhere' } }, item.title),
|
|
234
|
+
h('span', { style: { ...styles.hint, overflowWrap: 'anywhere' } }, describe(item)))))));
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const EMPTY_KEY = { name: '', mode: 'scoped', access: 'read', workspaces: [], sessions: [], mcp: true, api: true, expiresAt: null, disabled: false };
|
|
238
|
+
|
|
239
|
+
function KeyEditor({ initial, options, scopedSupported, onCancel, onSave, busy }) {
|
|
240
|
+
const [draft, setDraft] = useState(() => ({ ...EMPTY_KEY, ...initial, expiresAt: initial?.expiresAt ? initial.expiresAt.slice(0, 10) : '' }));
|
|
241
|
+
const set = patch => setDraft(previous => ({ ...previous, ...patch }));
|
|
242
|
+
const toggle = (field, id) => set({ [field]: draft[field].includes(id) ? draft[field].filter(item => item !== id) : [...draft[field], id] });
|
|
243
|
+
const workspaceTitle = id => options.workspaces.find(w => w.id === id)?.title;
|
|
244
|
+
const coveredByWorkspace = session => options.workspaces.some(w => draft.workspaces.includes(w.id) && w.sessionIds.includes(session.id));
|
|
245
|
+
const problems = [];
|
|
246
|
+
if (draft.name.trim() === '') problems.push('Give the key a name.');
|
|
247
|
+
if (!draft.mcp && !draft.api) problems.push('Enable MCP, the HTTP API, or both.');
|
|
248
|
+
if (draft.mode === 'scoped' && draft.workspaces.length === 0 && draft.sessions.length === 0) problems.push('Choose at least one workspace or chat, or make it a full-access key.');
|
|
249
|
+
if (draft.mode === 'scoped' && !scopedSupported) problems.push('Scoped keys need DSH 0.2.1 or later.');
|
|
250
|
+
const submit = () => onSave({
|
|
251
|
+
name: draft.name.trim(), mode: draft.mode, access: draft.access, mcp: draft.mcp, api: draft.api,
|
|
252
|
+
workspaces: draft.mode === 'scoped' ? draft.workspaces : [], sessions: draft.mode === 'scoped' ? draft.sessions : [],
|
|
253
|
+
expiresAt: draft.expiresAt ? new Date(`${draft.expiresAt}T23:59:59`).toISOString() : null,
|
|
254
|
+
});
|
|
255
|
+
return h('div', { style: styles.editor, 'data-dsh-control-mcp-key-editor': '' },
|
|
256
|
+
h('div', { style: styles.fieldRow },
|
|
257
|
+
h('label', { htmlFor: 'dsh-control-mcp-key-name', style: styles.label }, 'Name'),
|
|
258
|
+
h('input', { id: 'dsh-control-mcp-key-name', style: styles.textInput, maxLength: 80, value: draft.name, placeholder: 'e.g. Claude on my phone, CI bot, Release notes chat', onChange: event => set({ name: event.target.value }) })),
|
|
259
|
+
h('div', { style: styles.radioRow },
|
|
260
|
+
h('label', { style: styles.inline }, h('input', { type: 'checkbox', checked: draft.mcp, onChange: event => set({ mcp: event.target.checked }) }), 'MCP'),
|
|
261
|
+
h('label', { style: styles.inline }, h('input', { type: 'checkbox', checked: draft.api, onChange: event => set({ api: event.target.checked }) }), 'HTTP API')),
|
|
262
|
+
h('div', { style: styles.fieldRow, role: 'radiogroup', 'aria-label': 'Access' },
|
|
263
|
+
h('span', { style: styles.label }, 'Access'),
|
|
264
|
+
h('label', { style: styles.inline }, h('input', { type: 'radio', name: 'dsh-control-mcp-mode', checked: draft.mode === 'scoped', onChange: () => set({ mode: 'scoped' }) }), 'Only chosen workspaces and chats'),
|
|
265
|
+
h('label', { style: styles.inline }, h('input', { type: 'radio', name: 'dsh-control-mcp-mode', checked: draft.mode === 'full', onChange: () => set({ mode: 'full' }) }), 'Full access to this harness'),
|
|
266
|
+
draft.mode === 'full' ? h('p', { style: styles.warn }, 'A full-access key can do anything you can: every chat, plugins, settings and installs.') : null),
|
|
267
|
+
draft.mode === 'scoped' ? h(React.Fragment, null,
|
|
268
|
+
h('div', { style: styles.fieldRow, role: 'radiogroup', 'aria-label': 'Inside its chats' },
|
|
269
|
+
h('span', { style: styles.label }, 'Inside its chats'),
|
|
270
|
+
h('label', { style: styles.inline }, h('input', { type: 'radio', name: 'dsh-control-mcp-access', checked: draft.access === 'read', onChange: () => set({ access: 'read' }) }), 'Read only: history, state and replies'),
|
|
271
|
+
h('label', { style: styles.inline }, h('input', { type: 'radio', name: 'dsh-control-mcp-access', checked: draft.access === 'prompt', onChange: () => set({ access: 'prompt' }) }), 'Read and prompt: also send messages, stop, rename, and start chats in its workspaces')),
|
|
272
|
+
h(Picker, {
|
|
273
|
+
label: 'Workspaces', items: options.workspaces, selected: draft.workspaces, onToggle: id => toggle('workspaces', id),
|
|
274
|
+
empty: 'No workspaces yet.', describe: w => `${w.path} · ${w.sessionIds.length} chat${w.sessionIds.length === 1 ? '' : 's'} · includes chats added later`,
|
|
275
|
+
}),
|
|
276
|
+
h(Picker, {
|
|
277
|
+
label: 'Chats', items: options.sessions, selected: draft.sessions, onToggle: id => toggle('sessions', id),
|
|
278
|
+
empty: 'No chats yet.',
|
|
279
|
+
describe: session => [coveredByWorkspace(session) ? 'already covered by a chosen workspace' : null, options.workspaces.find(w => w.sessionIds.includes(session.id)) ? `in ${workspaceTitle(options.workspaces.find(w => w.sessionIds.includes(session.id)).id)}` : session.cwd, session.blank ? 'not started' : session.running ? 'running' : null].filter(Boolean).join(' · '),
|
|
280
|
+
})) : null,
|
|
281
|
+
h('div', { style: styles.fieldRow },
|
|
282
|
+
h('label', { htmlFor: 'dsh-control-mcp-key-expiry', style: styles.label }, 'Expires (optional)'),
|
|
283
|
+
h('input', { id: 'dsh-control-mcp-key-expiry', type: 'date', style: { ...styles.textInput, width: '180px' }, value: draft.expiresAt, onChange: event => set({ expiresAt: event.target.value }) })),
|
|
284
|
+
problems.length ? h('p', { role: 'alert', style: styles.error }, problems[0]) : null,
|
|
285
|
+
h('div', { style: styles.inline },
|
|
286
|
+
h('button', { type: 'button', style: buttonStyle(true, busy || problems.length > 0), disabled: busy || problems.length > 0, onClick: submit }, busy ? 'Saving…' : initial?.id ? 'Save key' : 'Create key'),
|
|
287
|
+
h('button', { type: 'button', style: buttonStyle(false, busy), disabled: busy, onClick: onCancel }, 'Cancel')));
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function NewToken({ reveal, onDone }) {
|
|
291
|
+
const [tab, setTab] = useState('http');
|
|
292
|
+
const mcpUrl = originUrl(`${ROUTE}/mcp`);
|
|
293
|
+
const apiUrl = originUrl(`${ROUTE}/api/v1`);
|
|
294
|
+
const snippets = {
|
|
295
|
+
http: { label: 'MCP over HTTP', text: mcpJsonConfig(mcpUrl, reveal.token) },
|
|
296
|
+
stdio: { label: 'MCP over stdio', text: stdioConfig(mcpUrl, reveal.token) },
|
|
297
|
+
curl: { label: 'HTTP API', text: `curl -s -X POST -H 'Authorization: Bearer ${reveal.token}' -H 'content-type: application/json' \\\n -d '{"_request":{}}' ${apiUrl}/call/session/list` },
|
|
298
|
+
};
|
|
299
|
+
return h('div', { style: { ...styles.editor, borderColor: 'var(--dsw-alias-brand-primary)' }, role: 'status', 'data-dsh-control-mcp-new-token': '' },
|
|
300
|
+
h('span', { style: styles.label }, `Token for "${reveal.key.name}"`),
|
|
301
|
+
h('p', { style: styles.warn }, 'Copy it now. It is shown only once; the harness keeps only a fingerprint. Rotate the key if you lose it.'),
|
|
302
|
+
h('div', { style: styles.inline },
|
|
303
|
+
h('input', { readOnly: true, value: reveal.token, style: styles.input, 'aria-label': 'New key token', onFocus: event => event.target.select() }),
|
|
304
|
+
h(CopyButton, { text: reveal.token })),
|
|
305
|
+
h('div', { style: styles.tabs, role: 'tablist' }, Object.entries(snippets).map(([key, snippet]) => h('button', { key, type: 'button', role: 'tab', 'aria-selected': tab === key, style: buttonStyle(tab === key, false), onClick: () => setTab(key) }, snippet.label))),
|
|
306
|
+
h('pre', { style: styles.code }, snippets[tab].text),
|
|
307
|
+
h('div', { style: styles.inline }, h(CopyButton, { text: snippets[tab].text, label: 'Copy configuration' }), h('button', { type: 'button', style: buttonStyle(false, false), onClick: onDone }, 'Done')));
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function KeysSection({ enabled }) {
|
|
311
|
+
const [state, setState] = useState({ status: 'loading', keys: [], options: { workspaces: [], sessions: [] }, scopedSupported: true, error: '' });
|
|
312
|
+
const [editing, setEditing] = useState(undefined);
|
|
313
|
+
const [reveal, setReveal] = useState(undefined);
|
|
314
|
+
const [busy, setBusy] = useState(false);
|
|
315
|
+
const [failure, setFailure] = useState('');
|
|
316
|
+
const mounted = useRef(true);
|
|
317
|
+
useEffect(() => () => { mounted.current = false; }, []);
|
|
318
|
+
|
|
319
|
+
const load = useCallback(async () => {
|
|
320
|
+
try {
|
|
321
|
+
const [list, options] = await Promise.all([manage('/keys'), manage('/scope-options')]);
|
|
322
|
+
if (mounted.current) setState({ status: 'ready', keys: list.keys, options: { workspaces: options.workspaces, sessions: options.sessions }, scopedSupported: list.scopedSupported !== false, error: '' });
|
|
323
|
+
} catch (error) {
|
|
324
|
+
if (mounted.current) setState(previous => ({ ...previous, status: 'error', error: error.message }));
|
|
325
|
+
}
|
|
326
|
+
}, []);
|
|
327
|
+
useEffect(() => { void load(); }, [load]);
|
|
328
|
+
|
|
329
|
+
const run = async (action, after) => {
|
|
330
|
+
setBusy(true); setFailure('');
|
|
331
|
+
try { const value = await action(); after?.(value); await load(); } catch (error) { setFailure(error.message || 'The change was not saved.'); } finally { if (mounted.current) setBusy(false); }
|
|
332
|
+
};
|
|
333
|
+
const save = fields => run(
|
|
334
|
+
() => (editing?.id ? manage(`/keys/${editing.id}`, 'PATCH', fields) : manage('/keys', 'POST', fields)),
|
|
335
|
+
value => { setEditing(undefined); if (value?.token) setReveal(value); },
|
|
336
|
+
);
|
|
337
|
+
|
|
338
|
+
return h('div', { style: styles.section, 'data-dsh-control-mcp-keys': '' },
|
|
339
|
+
h('h5', { style: styles.sectionTitle }, 'API keys'),
|
|
340
|
+
h('p', { style: styles.hint }, 'Give each client its own key. A key can reach the whole harness, or only the workspaces and chats you choose: everything else stays invisible to it, in every list and every call.'),
|
|
341
|
+
!enabled ? h('p', { style: styles.status }, 'Keys work once the MCP server or the HTTP API is on.') : null,
|
|
342
|
+
!state.scopedSupported ? h('p', { style: styles.warn }, 'This DSH version cannot confine keys; scoped keys need DSH 0.2.1 or later. Full-access keys work.') : null,
|
|
343
|
+
state.status === 'error' ? h('div', { style: styles.inline }, h('p', { role: 'alert', style: styles.error }, `Could not load keys: ${state.error}`), h('button', { type: 'button', style: buttonStyle(false, false), onClick: () => { void load(); } }, 'Retry')) : null,
|
|
344
|
+
failure ? h('p', { role: 'alert', style: styles.error }, failure) : null,
|
|
345
|
+
reveal ? h(NewToken, { reveal, onDone: () => setReveal(undefined) }) : null,
|
|
346
|
+
state.status === 'loading' ? h('p', { style: styles.status }, 'Loading keys…') : null,
|
|
347
|
+
state.status === 'ready' && state.keys.length === 0 && editing === undefined ? h('p', { style: styles.status }, 'No keys yet.') : null,
|
|
348
|
+
state.keys.length > 0 ? h('div', { style: styles.card, role: 'list', 'aria-label': 'API keys' }, state.keys.map((key, index) => h('div', { key: key.id, role: 'listitem', style: { ...styles.keyRow, ...index === state.keys.length - 1 ? styles.rowLast : {} }, 'data-key-name': key.name },
|
|
349
|
+
h('div', { style: styles.keyMain },
|
|
350
|
+
h('span', { style: { ...styles.label, overflowWrap: 'anywhere' } }, key.name),
|
|
351
|
+
h('span', { style: { ...styles.hint, overflowWrap: 'anywhere' } }, `${scopeSummary(key, state.options)} · ${[key.mcp ? 'MCP' : null, key.api ? 'API' : null].filter(Boolean).join(' + ')} · ${key.prefix}… · used ${relativeTime(key.lastUsedAt)}${key.expiresAt ? ` · expires ${key.expiresAt.slice(0, 10)}` : ''}`)),
|
|
352
|
+
key.disabled ? h('span', { style: styles.badgeMuted }, 'Disabled') : key.expired ? h('span', { style: styles.badgeMuted }, 'Expired') : null,
|
|
353
|
+
h('button', { type: 'button', style: buttonStyle(false, busy), disabled: busy, onClick: () => { setReveal(undefined); setEditing(key); } }, 'Edit'),
|
|
354
|
+
h('button', { type: 'button', style: buttonStyle(false, busy), disabled: busy, onClick: () => run(() => manage(`/keys/${key.id}`, 'PATCH', { disabled: !key.disabled })) }, key.disabled ? 'Enable' : 'Disable'),
|
|
355
|
+
h('button', { type: 'button', style: buttonStyle(false, busy), disabled: busy, onClick: () => { if (window.confirm(`Rotate "${key.name}"? Clients using its current token stop working.`)) void run(() => manage(`/keys/${key.id}/rotate`, 'POST'), value => setReveal(value)); } }, 'Rotate'),
|
|
356
|
+
h('button', { type: 'button', style: buttonStyle(false, busy), disabled: busy, onClick: () => { if (window.confirm(`Delete "${key.name}"? Clients using it stop working at once.`)) void run(() => manage(`/keys/${key.id}`, 'DELETE')); } }, 'Delete')))) : null,
|
|
357
|
+
editing !== undefined
|
|
358
|
+
? h(KeyEditor, { key: editing?.id ?? 'new', initial: editing, options: state.options, scopedSupported: state.scopedSupported, busy, onCancel: () => setEditing(undefined), onSave: save })
|
|
359
|
+
: h('div', { style: styles.inline }, h('button', { type: 'button', style: buttonStyle(true, busy || state.status !== 'ready'), disabled: busy || state.status !== 'ready', onClick: () => { setReveal(undefined); setEditing(null); } }, 'New key'), h('button', { type: 'button', style: buttonStyle(false, false), onClick: () => { void load(); } }, 'Refresh chats')));
|
|
360
|
+
}
|
|
361
|
+
|
|
180
362
|
function ControlPage({ source }) {
|
|
181
363
|
const mirrorSnapshot = useStore(source.describe, emptyMirror);
|
|
182
364
|
const namespaces = mirrorSnapshot?.view?.namespaces ?? [];
|
|
@@ -248,6 +430,7 @@ window.__ModuleLoader__.load({
|
|
|
248
430
|
onClick: () => { void write('blockedEndpoints', blocked.items); },
|
|
249
431
|
}, pending === 'blockedEndpoints' ? 'Saving…' : 'Save'),
|
|
250
432
|
blockedDraft !== undefined ? h('button', { type: 'button', style: buttonStyle(false, false), onClick: () => setBlockedDraft(undefined) }, 'Discard') : null)),
|
|
433
|
+
h(KeysSection, { enabled: anyEnabled }),
|
|
251
434
|
h(TokenSection, { enabled: anyEnabled }));
|
|
252
435
|
}
|
|
253
436
|
|
|
@@ -272,6 +455,6 @@ window.__ModuleLoader__.load({
|
|
|
272
455
|
});
|
|
273
456
|
}
|
|
274
457
|
|
|
275
|
-
return { inject, apply, findEntryNamespace, parseBlocked, mcpJsonConfig, stdioConfig };
|
|
458
|
+
return { inject, apply, findEntryNamespace, parseBlocked, mcpJsonConfig, stdioConfig, scopeSummary };
|
|
276
459
|
})
|
|
277
460
|
});
|