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 CHANGED
@@ -16,7 +16,8 @@ Once you switch it on, an MCP client (Claude Code, Claude Desktop, Codex, Cursor
16
16
  - **MCP server**: Streamable HTTP at `/dsh-control-mcp/mcp`, plus a bundled stdio bridge (`npx -y dsh-control-mcp`).
17
17
  - **HTTP API**: JSON and Server-Sent Events at `/dsh-control-mcp/api/v1`.
18
18
  - **Off by default.** Turn each surface on in **Plugins → dsh-control-mcp**; changes apply at once.
19
- - **One bearer token** for both, kept in the DSH credential store. Show, copy and rotate it on the plugin page.
19
+ - **Multiple API keys**, one per client, each with its own token, name, MCP/API switches and optional expiry. Disable, rotate or delete any key without touching the others.
20
+ - **Scoped keys** reach only the workspaces and chats you pick, read only or read and prompt. Everything else is invisible to them, in every list and every call (DSH 0.2.1+).
20
21
  - **Read-only mode** and **blocked endpoint patterns** limit what clients may do.
21
22
 
22
23
  ## Supported DSH versions
@@ -44,6 +45,8 @@ What differs between versions:
44
45
  | `dsh_send_prompt` with `wait` | ✅ polls `session/list` | ✅ polls `session/list` | ✅ native `session/wait` |
45
46
  | Calls run as a dedicated peer that never answers approvals | — (runs as the operator) | ✅ | ✅ |
46
47
  | Long detail page under Plugins | README only | README only | ✅ |
48
+ | Full-access API keys | ✅ | ✅ | ✅ |
49
+ | Scoped API keys (chosen workspaces and chats) | ❌ refused | ✅ | ✅ |
47
50
 
48
51
  Each harness version exposes its own set of endpoints; `dsh_list_endpoints` always shows what *your* DSH offers.
49
52
 
@@ -59,6 +62,43 @@ Or open **Plugins → Add plugin** in the GUI and enter `dsh-control-mcp`. Resta
59
62
 
60
63
  See [Supported DSH versions](#supported-dsh-versions).
61
64
 
65
+ ## API keys and scopes
66
+
67
+ Open **Plugins → dsh-control-mcp → API keys → New key**. Each key has:
68
+
69
+ | Setting | Choices |
70
+ |---|---|
71
+ | Name | Any label, e.g. "Claude on my phone" |
72
+ | Surfaces | MCP, HTTP API, or both |
73
+ | Access | **Only chosen workspaces and chats**, or **Full access to this harness** |
74
+ | Inside its chats | **Read only** (history, state, replies), or **Read and prompt** (also send messages, stop, rename, start chats in its workspaces) |
75
+ | Workspaces | Each chosen workspace includes its current chats **and chats added to it later** |
76
+ | Chats | Individual chats, from any workspace |
77
+ | Expires | Optional date |
78
+
79
+ The token is shown **once** when you create or rotate a key; the harness stores only its SHA-256 fingerprint. Changes to a key (narrowing its scope, disabling it, expiry) apply to the very next request.
80
+
81
+ ### How scoping is enforced
82
+
83
+ A scoped key does not run as you. It runs as its own principal (`dsh-control-key`), and DSH's own remote-access engine, the one that confines Liveshare viewers, decides every call. Every session and workspace endpoint names the resource it touches, and DSH checks it before the call runs. List and stream endpoints (`session/list`, `session/search`, `session/control`, `workspace/follow`) filter each item, so a scoped key never even learns that other chats exist. The plugin adds a second, earlier check with clear error messages, and it never offers a scoped key a tool it cannot use.
84
+
85
+ What a scoped key can reach:
86
+
87
+ | | Read only | Read and prompt |
88
+ |---|---|---|
89
+ | Model and provider catalogs, agent presets | ✅ | ✅ |
90
+ | Its chats: list, history, state, wait, follow, goals, commands, skills, terminal list | ✅ | ✅ |
91
+ | Its chats: send prompts, steer, stop, rename, choose model, edit queue, upload attachments | — | ✅ |
92
+ | Start new chats inside its workspaces | — | ✅ |
93
+ | Other chats and workspaces | ❌ invisible | ❌ invisible |
94
+ | Plugins, settings, credentials, accounts, schedules, jobs, terminals (create), workspace create/delete | ❌ | ❌ |
95
+
96
+ Use a full-access key for harness-wide administration. On DSH 0.2.0, which has no remote-access engine, scoped keys are refused with a clear error and full-access keys keep working.
97
+
98
+ ### Owner token
99
+
100
+ The plugin page also shows a built-in **owner token** with full access, the token from version 0.1. It keeps working; prefer named keys so you can scope and revoke each client.
101
+
62
102
  ## Turn it on
63
103
 
64
104
  1. Open **Plugins → dsh-control-mcp**.
@@ -127,7 +167,7 @@ In read-only mode, write tools are hidden and write calls are refused.
127
167
 
128
168
  ## HTTP API
129
169
 
130
- Every request needs `Authorization: Bearer <token>`. Responses are `{"ok": true, "value": …}` or `{"ok": false, "error": {"code", "message"}}` with a matching HTTP status.
170
+ Every request needs `Authorization: Bearer <token>`: an API key enabled for the HTTP API, or the owner token. Responses are `{"ok": true, "value": …}` or `{"ok": false, "error": {"code", "message"}}` with a matching HTTP status.
131
171
 
132
172
  | Method and path | Purpose |
133
173
  |---|---|
@@ -156,7 +196,8 @@ Endpoint arguments are named exactly as the harness declares them. Check `GET
156
196
 
157
197
  - **Full control means full control.** A prompt can run tools and shell commands. Anyone with the token, and network access to DSH, can do what you can do in the GUI. Treat the token like a password, rotate it if it leaks, and prefer read-only mode when a client only needs to look.
158
198
  - Both surfaces are off until you turn them on, and turning one off takes effect on the next request.
159
- - Tokens are 256-bit random values compared in constant time. The plugin page reads the token through an owner-only route that accepts only your signed-in DSH browser session from the same origin.
199
+ - Tokens are 256-bit random values. Key tokens are stored only as SHA-256 fingerprints and shown once; the owner token is compared in constant time. Key management and the owner token are served only to your signed-in DSH browser session from the same origin; bearer tokens, even full-access ones, cannot create or list keys.
200
+ - Scoped keys are confined by DSH's remote-access engine, not only by this plugin. They run as their own principal, never as the owner.
160
201
  - Requests with a cross-site `Origin` are refused, so a web page you visit cannot use the API even if it guesses the URL.
161
202
  - Calls run as a dedicated in-process owner peer that **never answers approvals or questions**; those still appear in the GUI. (`userQuestions/answer` remains callable explicitly.)
162
203
  - DSH binds to loopback by default. For remote clients use an SSH tunnel or DSH's own `trustedHosts`/TLS options. Do not expose it publicly without TLS.
@@ -171,7 +212,8 @@ The Host plugin (`index.mjs`) registers one prefix route, `/dsh-control-mcp`, on
171
212
  | npm package, bundle, Loader entry id/name, Host plugin name | `dsh-control-mcp` |
172
213
  | Client module id and `plugins.bundle.config` key | `dsh-control-mcp` |
173
214
  | Web route prefix | `/dsh-control-mcp` |
174
- | Credential record | `dsh-control-mcp/access-token` (grant) |
215
+ | Credential records | `dsh-control-mcp/access-token` (owner token), `dsh-control-mcp/api-keys` (key fingerprints and scopes) |
216
+ | Remote-access principal | `dsh-control-key` (scoped keys), roles `dsh-control-mcp:*` |
175
217
  | Config fields (all volatile) | `mcpEnabled`, `apiEnabled`, `readOnly`, `exposeAllEndpoints`, `blockedEndpoints`, `maxResultBytes` |
176
218
  | Log prefix | `dsh-control-mcp:` |
177
219
  | Injected Host services | `typert`, `typertGateway`, `connection`, `webServer`; optional `credentials`, `connection.authentication` (DSH 0.2.3+) |
@@ -183,7 +225,8 @@ The Host plugin (`index.mjs`) registers one prefix route, `/dsh-control-mcp`, on
183
225
  |---|---|
184
226
  | `index.mjs` | Host entry: Config, token store, gateway bridge, route registration. |
185
227
  | `lib/core.mjs` | Transport-independent catalog, policy, curated tools and MCP JSON-RPC. |
186
- | `lib/http.mjs` | HTTP routing, auth, MCP Streamable HTTP, REST and SSE. |
228
+ | `lib/http.mjs` | HTTP routing, auth, MCP Streamable HTTP, REST and SSE, key management routes. |
229
+ | `lib/access.mjs` | API key registry, scoped roles and the remote-access policy. |
187
230
  | `client/index.mjs` | Plugin page source (source of truth). |
188
231
  | `lib/client.js` | **Generated** by `npm run build` from `client/index.mjs`. Do not edit. |
189
232
  | `bin/dsh-control-mcp.mjs` | stdio bridge. |
@@ -193,7 +236,7 @@ The Host plugin (`index.mjs`) registers one prefix route, `/dsh-control-mcp`, on
193
236
  ```sh
194
237
  npm run verify # build client bundle, unit tests, release gate (metadata, identities, packed files)
195
238
  npm pack --dry-run
196
- scripts/version-matrix.sh ./dsh-control-mcp-0.1.0.tgz /path/to/dsh/bin [port] # one DSH version, end to end
239
+ scripts/version-matrix.sh ./dsh-control-mcp-X.Y.Z.tgz /path/to/dsh/bin [port] # one DSH version: page, live and scope-isolation tests
197
240
  ```
198
241
 
199
242
  `LOCAL-SETUP.md` covers testing against a disposable DSH profile, including the live MCP/API smoke test (`npm run test:live`) and the headless-Chrome page test (`npm run test:e2e`).
package/client/index.mjs CHANGED
@@ -66,6 +66,38 @@ export function createClientPlugin(require) {
66
66
  return body.value.token;
67
67
  }
68
68
 
69
+ /** Owner-only management call to this plugin's own same-origin routes. */
70
+ async function manage(path, method = 'GET', body) {
71
+ const response = await fetch(`${ROUTE}${path}`, {
72
+ method, credentials: 'same-origin',
73
+ headers: { accept: 'application/json', ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
74
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
75
+ });
76
+ const json = await response.json().catch(() => undefined);
77
+ if (!response.ok || json?.ok !== true) throw new Error(typeof json?.error?.message === 'string' ? json.error.message : 'The request failed.');
78
+ return json.value;
79
+ }
80
+
81
+ function scopeSummary(key, options) {
82
+ if (key.mode === 'full') return 'Full access';
83
+ const ws = key.workspaces.map(id => options.workspaces.find(w => w.id === id)?.title ?? 'missing workspace');
84
+ const ss = key.sessions.length;
85
+ const parts = [];
86
+ if (ws.length) parts.push(`${ws.length === 1 ? 'Workspace' : `${ws.length} workspaces`}: ${ws.slice(0, 2).join(', ')}${ws.length > 2 ? '…' : ''}`);
87
+ if (ss) parts.push(`${ss} chat${ss === 1 ? '' : 's'}`);
88
+ return `${key.access === 'prompt' ? 'Read and prompt' : 'Read only'} · ${parts.join(' · ') || 'nothing selected'}`;
89
+ }
90
+
91
+ function relativeTime(iso) {
92
+ if (!iso) return 'never';
93
+ const diff = Date.now() - Date.parse(iso);
94
+ if (!Number.isFinite(diff)) return 'never';
95
+ if (diff < 60000) return 'just now';
96
+ if (diff < 3600000) return `${Math.round(diff / 60000)} min ago`;
97
+ if (diff < 86400000) return `${Math.round(diff / 3600000)} h ago`;
98
+ return `${Math.round(diff / 86400000)} d ago`;
99
+ }
100
+
69
101
  const styles = {
70
102
  page: { display: 'flex', flexDirection: 'column', gap: '16px', minWidth: 0, fontSize: '13px', lineHeight: '20px', color: 'var(--dsw-alias-label-primary)' },
71
103
  head: { display: 'flex', flexDirection: 'column', gap: '4px' },
@@ -91,6 +123,15 @@ export function createClientPlugin(require) {
91
123
  primary: { background: 'var(--dsw-alias-brand-primary)', borderColor: 'transparent', color: 'var(--dsw-alias-label-on-brand, #fff)' },
92
124
  disabled: { opacity: 0.5, cursor: 'not-allowed' },
93
125
  tabs: { display: 'flex', gap: '6px', flexWrap: 'wrap' },
126
+ keyRow: { display: 'flex', alignItems: 'center', gap: '12px', padding: '10px 14px', borderBottom: '.5px solid var(--dsw-alias-border-l2)', minWidth: 0 },
127
+ keyMain: { display: 'flex', flexDirection: 'column', gap: '2px', minWidth: 0, flex: 1 },
128
+ 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)' },
129
+ 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)' },
130
+ fieldRow: { display: 'flex', flexDirection: 'column', gap: '4px' },
131
+ radioRow: { display: 'flex', gap: '16px', flexWrap: 'wrap' },
132
+ 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' },
133
+ pickItem: { display: 'flex', alignItems: 'flex-start', gap: '8px', padding: '5px 8px', borderRadius: '6px', cursor: 'pointer', minWidth: 0 },
134
+ 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%' },
94
135
  };
95
136
 
96
137
  function buttonStyle(primary, disabled) {
@@ -167,8 +208,8 @@ export function createClientPlugin(require) {
167
208
  const snippets = snippetsFor(token);
168
209
  const displayed = snippetsFor(shown);
169
210
  return h('div', { style: styles.section },
170
- h('h5', { style: styles.sectionTitle }, 'Access token'),
171
- h('p', { style: styles.hint }, 'MCP and API clients send this as "Authorization: Bearer <token>". It grants full control of this harness (or read access in read-only mode). Keep it secret.'),
211
+ h('h5', { style: styles.sectionTitle }, 'Owner token'),
212
+ 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.'),
172
213
  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,
173
214
  h('div', { style: styles.inline },
174
215
  h('input', { readOnly: true, value: state === 'loading' && !token ? 'Loading…' : shown, style: styles.input, 'aria-label': 'Access token', onFocus: event => event.target.select() }),
@@ -185,6 +226,147 @@ export function createClientPlugin(require) {
185
226
  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.`));
186
227
  }
187
228
 
229
+ function Picker({ label, items, selected, onToggle, empty, describe }) {
230
+ const [query, setQuery] = useState('');
231
+ const needle = query.trim().toLowerCase();
232
+ const shown = needle ? items.filter(item => `${item.title} ${describe(item)}`.toLowerCase().includes(needle)) : items;
233
+ return h('div', { style: styles.fieldRow },
234
+ h('span', { style: styles.label }, `${label} (${selected.length} selected)`),
235
+ 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,
236
+ h('div', { style: styles.pick, role: 'group', 'aria-label': label },
237
+ items.length === 0 ? h('p', { style: { ...styles.hint, padding: '6px 8px' } }, empty) : null,
238
+ shown.map(item => h('label', { key: item.id, style: styles.pickItem },
239
+ h('input', { type: 'checkbox', checked: selected.includes(item.id), onChange: () => onToggle(item.id), style: { marginTop: '3px', flex: 'none' } }),
240
+ h('span', { style: { display: 'flex', flexDirection: 'column', minWidth: 0 } },
241
+ h('span', { style: { overflowWrap: 'anywhere' } }, item.title),
242
+ h('span', { style: { ...styles.hint, overflowWrap: 'anywhere' } }, describe(item)))))));
243
+ }
244
+
245
+ const EMPTY_KEY = { name: '', mode: 'scoped', access: 'read', workspaces: [], sessions: [], mcp: true, api: true, expiresAt: null, disabled: false };
246
+
247
+ function KeyEditor({ initial, options, scopedSupported, onCancel, onSave, busy }) {
248
+ const [draft, setDraft] = useState(() => ({ ...EMPTY_KEY, ...initial, expiresAt: initial?.expiresAt ? initial.expiresAt.slice(0, 10) : '' }));
249
+ const set = patch => setDraft(previous => ({ ...previous, ...patch }));
250
+ const toggle = (field, id) => set({ [field]: draft[field].includes(id) ? draft[field].filter(item => item !== id) : [...draft[field], id] });
251
+ const workspaceTitle = id => options.workspaces.find(w => w.id === id)?.title;
252
+ const coveredByWorkspace = session => options.workspaces.some(w => draft.workspaces.includes(w.id) && w.sessionIds.includes(session.id));
253
+ const problems = [];
254
+ if (draft.name.trim() === '') problems.push('Give the key a name.');
255
+ if (!draft.mcp && !draft.api) problems.push('Enable MCP, the HTTP API, or both.');
256
+ 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.');
257
+ if (draft.mode === 'scoped' && !scopedSupported) problems.push('Scoped keys need DSH 0.2.1 or later.');
258
+ const submit = () => onSave({
259
+ name: draft.name.trim(), mode: draft.mode, access: draft.access, mcp: draft.mcp, api: draft.api,
260
+ workspaces: draft.mode === 'scoped' ? draft.workspaces : [], sessions: draft.mode === 'scoped' ? draft.sessions : [],
261
+ expiresAt: draft.expiresAt ? new Date(`${draft.expiresAt}T23:59:59`).toISOString() : null,
262
+ });
263
+ return h('div', { style: styles.editor, 'data-dsh-control-mcp-key-editor': '' },
264
+ h('div', { style: styles.fieldRow },
265
+ h('label', { htmlFor: 'dsh-control-mcp-key-name', style: styles.label }, 'Name'),
266
+ 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 }) })),
267
+ h('div', { style: styles.radioRow },
268
+ h('label', { style: styles.inline }, h('input', { type: 'checkbox', checked: draft.mcp, onChange: event => set({ mcp: event.target.checked }) }), 'MCP'),
269
+ h('label', { style: styles.inline }, h('input', { type: 'checkbox', checked: draft.api, onChange: event => set({ api: event.target.checked }) }), 'HTTP API')),
270
+ h('div', { style: styles.fieldRow, role: 'radiogroup', 'aria-label': 'Access' },
271
+ h('span', { style: styles.label }, 'Access'),
272
+ 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'),
273
+ 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'),
274
+ draft.mode === 'full' ? h('p', { style: styles.warn }, 'A full-access key can do anything you can: every chat, plugins, settings and installs.') : null),
275
+ draft.mode === 'scoped' ? h(React.Fragment, null,
276
+ h('div', { style: styles.fieldRow, role: 'radiogroup', 'aria-label': 'Inside its chats' },
277
+ h('span', { style: styles.label }, 'Inside its chats'),
278
+ 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'),
279
+ 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')),
280
+ h(Picker, {
281
+ label: 'Workspaces', items: options.workspaces, selected: draft.workspaces, onToggle: id => toggle('workspaces', id),
282
+ empty: 'No workspaces yet.', describe: w => `${w.path} · ${w.sessionIds.length} chat${w.sessionIds.length === 1 ? '' : 's'} · includes chats added later`,
283
+ }),
284
+ h(Picker, {
285
+ label: 'Chats', items: options.sessions, selected: draft.sessions, onToggle: id => toggle('sessions', id),
286
+ empty: 'No chats yet.',
287
+ 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(' · '),
288
+ })) : null,
289
+ h('div', { style: styles.fieldRow },
290
+ h('label', { htmlFor: 'dsh-control-mcp-key-expiry', style: styles.label }, 'Expires (optional)'),
291
+ 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 }) })),
292
+ problems.length ? h('p', { role: 'alert', style: styles.error }, problems[0]) : null,
293
+ h('div', { style: styles.inline },
294
+ 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'),
295
+ h('button', { type: 'button', style: buttonStyle(false, busy), disabled: busy, onClick: onCancel }, 'Cancel')));
296
+ }
297
+
298
+ function NewToken({ reveal, onDone }) {
299
+ const [tab, setTab] = useState('http');
300
+ const mcpUrl = originUrl(`${ROUTE}/mcp`);
301
+ const apiUrl = originUrl(`${ROUTE}/api/v1`);
302
+ const snippets = {
303
+ http: { label: 'MCP over HTTP', text: mcpJsonConfig(mcpUrl, reveal.token) },
304
+ stdio: { label: 'MCP over stdio', text: stdioConfig(mcpUrl, reveal.token) },
305
+ 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` },
306
+ };
307
+ return h('div', { style: { ...styles.editor, borderColor: 'var(--dsw-alias-brand-primary)' }, role: 'status', 'data-dsh-control-mcp-new-token': '' },
308
+ h('span', { style: styles.label }, `Token for "${reveal.key.name}"`),
309
+ 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.'),
310
+ h('div', { style: styles.inline },
311
+ h('input', { readOnly: true, value: reveal.token, style: styles.input, 'aria-label': 'New key token', onFocus: event => event.target.select() }),
312
+ h(CopyButton, { text: reveal.token })),
313
+ 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))),
314
+ h('pre', { style: styles.code }, snippets[tab].text),
315
+ 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')));
316
+ }
317
+
318
+ function KeysSection({ enabled }) {
319
+ const [state, setState] = useState({ status: 'loading', keys: [], options: { workspaces: [], sessions: [] }, scopedSupported: true, error: '' });
320
+ const [editing, setEditing] = useState(undefined);
321
+ const [reveal, setReveal] = useState(undefined);
322
+ const [busy, setBusy] = useState(false);
323
+ const [failure, setFailure] = useState('');
324
+ const mounted = useRef(true);
325
+ useEffect(() => () => { mounted.current = false; }, []);
326
+
327
+ const load = useCallback(async () => {
328
+ try {
329
+ const [list, options] = await Promise.all([manage('/keys'), manage('/scope-options')]);
330
+ if (mounted.current) setState({ status: 'ready', keys: list.keys, options: { workspaces: options.workspaces, sessions: options.sessions }, scopedSupported: list.scopedSupported !== false, error: '' });
331
+ } catch (error) {
332
+ if (mounted.current) setState(previous => ({ ...previous, status: 'error', error: error.message }));
333
+ }
334
+ }, []);
335
+ useEffect(() => { void load(); }, [load]);
336
+
337
+ const run = async (action, after) => {
338
+ setBusy(true); setFailure('');
339
+ 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); }
340
+ };
341
+ const save = fields => run(
342
+ () => (editing?.id ? manage(`/keys/${editing.id}`, 'PATCH', fields) : manage('/keys', 'POST', fields)),
343
+ value => { setEditing(undefined); if (value?.token) setReveal(value); },
344
+ );
345
+
346
+ return h('div', { style: styles.section, 'data-dsh-control-mcp-keys': '' },
347
+ h('h5', { style: styles.sectionTitle }, 'API keys'),
348
+ 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.'),
349
+ !enabled ? h('p', { style: styles.status }, 'Keys work once the MCP server or the HTTP API is on.') : null,
350
+ !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,
351
+ 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,
352
+ failure ? h('p', { role: 'alert', style: styles.error }, failure) : null,
353
+ reveal ? h(NewToken, { reveal, onDone: () => setReveal(undefined) }) : null,
354
+ state.status === 'loading' ? h('p', { style: styles.status }, 'Loading keys…') : null,
355
+ state.status === 'ready' && state.keys.length === 0 && editing === undefined ? h('p', { style: styles.status }, 'No keys yet.') : null,
356
+ 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 },
357
+ h('div', { style: styles.keyMain },
358
+ h('span', { style: { ...styles.label, overflowWrap: 'anywhere' } }, key.name),
359
+ 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)}` : ''}`)),
360
+ key.disabled ? h('span', { style: styles.badgeMuted }, 'Disabled') : key.expired ? h('span', { style: styles.badgeMuted }, 'Expired') : null,
361
+ h('button', { type: 'button', style: buttonStyle(false, busy), disabled: busy, onClick: () => { setReveal(undefined); setEditing(key); } }, 'Edit'),
362
+ h('button', { type: 'button', style: buttonStyle(false, busy), disabled: busy, onClick: () => run(() => manage(`/keys/${key.id}`, 'PATCH', { disabled: !key.disabled })) }, key.disabled ? 'Enable' : 'Disable'),
363
+ 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'),
364
+ 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,
365
+ editing !== undefined
366
+ ? h(KeyEditor, { key: editing?.id ?? 'new', initial: editing, options: state.options, scopedSupported: state.scopedSupported, busy, onCancel: () => setEditing(undefined), onSave: save })
367
+ : 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')));
368
+ }
369
+
188
370
  function ControlPage({ source }) {
189
371
  const mirrorSnapshot = useStore(source.describe, emptyMirror);
190
372
  const namespaces = mirrorSnapshot?.view?.namespaces ?? [];
@@ -256,6 +438,7 @@ export function createClientPlugin(require) {
256
438
  onClick: () => { void write('blockedEndpoints', blocked.items); },
257
439
  }, pending === 'blockedEndpoints' ? 'Saving…' : 'Save'),
258
440
  blockedDraft !== undefined ? h('button', { type: 'button', style: buttonStyle(false, false), onClick: () => setBlockedDraft(undefined) }, 'Discard') : null)),
441
+ h(KeysSection, { enabled: anyEnabled }),
259
442
  h(TokenSection, { enabled: anyEnabled }));
260
443
  }
261
444
 
@@ -280,5 +463,5 @@ export function createClientPlugin(require) {
280
463
  });
281
464
  }
282
465
 
283
- return { inject, apply, findEntryNamespace, parseBlocked, mcpJsonConfig, stdioConfig };
466
+ return { inject, apply, findEntryNamespace, parseBlocked, mcpJsonConfig, stdioConfig, scopeSummary };
284
467
  }
package/docs/DETAIL.md CHANGED
@@ -22,6 +22,15 @@ Lets MCP clients and other programs drive this DeepSeek Harness through the same
22
22
 
23
23
  Every call needs `Authorization: Bearer <token>`. **Rotate** issues a new token and invalidates the old one.
24
24
 
25
+ ## API keys and scopes
26
+
27
+ Create one key per client under **API keys → New key**. A key has a name, MCP and/or HTTP API access, an optional expiry, and either:
28
+
29
+ - **Full access** to this harness, or
30
+ - **Only chosen workspaces and chats**: a workspace includes its current chats and chats added later. Pick **Read only** or **Read and prompt**.
31
+
32
+ A scoped key cannot see, list or touch any other chat, and cannot reach plugins, settings, credentials or other harness-wide actions. DSH's own access control enforces this (DSH 0.2.1 or later). The token is shown once; disable, rotate or delete a key at any time.
33
+
25
34
  ## Limit what clients may do
26
35
 
27
36
  - **Read-only mode** refuses every call that changes harness state.
package/index.mjs CHANGED
@@ -20,12 +20,14 @@ import { dirname, join } from 'node:path';
20
20
  import { pathToFileURL } from 'node:url';
21
21
  import { DEFAULT_MAX_RESULT_BYTES } from './lib/core.mjs';
22
22
  import { createHttpHandler, ROUTE_PREFIX } from './lib/http.mjs';
23
+ import { KEY_PRINCIPAL, createKeyRegistry, createScopedPolicy, keyPrincipal, scopedPreCheck } from './lib/access.mjs';
23
24
 
24
25
  export const name = 'dsh-control-mcp';
25
26
  export const inject = ['typert', 'typertGateway', 'connection', 'webServer'];
26
27
  const LOG_PREFIX = 'dsh-control-mcp:';
27
28
  export const TOKEN_SCOPE = 'dsh-control-mcp';
28
29
  export const TOKEN_ID = 'access-token';
30
+ export const KEYS_ID = 'api-keys';
29
31
  export const SUPPORTED_DSH_RANGE = Object.freeze({ min: '0.2.0-0', below: '0.3.0-0' });
30
32
 
31
33
  const PLUGIN_VERSION = (() => {
@@ -105,6 +107,31 @@ export function newToken() {
105
107
  return `dshc_${randomBytes(32).toString('base64url')}`;
106
108
  }
107
109
 
110
+ /** Read and write one grant record of this plugin in the harness credential store. */
111
+ export function createGrantRecord(ctx, id) {
112
+ let key;
113
+ const store = () => ctx.get?.('credentials');
114
+ const keyOf = async () => {
115
+ if (key !== undefined) return key;
116
+ const { credentialKey } = await import(pathToFileURL(createRequire(join(harness.dir, 'package.json')).resolve('@deepseek-ai/dsh-credentials')).href);
117
+ key = credentialKey(TOKEN_SCOPE, id);
118
+ return key;
119
+ };
120
+ return {
121
+ available: () => store() !== undefined && harness !== undefined,
122
+ async read() {
123
+ if (store() === undefined || harness === undefined) return undefined;
124
+ const record = await store().readRecord(await keyOf());
125
+ return record?.kind === 'grant' ? record.payload : undefined;
126
+ },
127
+ async write(payload) {
128
+ if (store() === undefined || harness === undefined) return false;
129
+ await store().modifyRecord(await keyOf(), async () => ({ kind: 'grant', payload }));
130
+ return true;
131
+ },
132
+ };
133
+ }
134
+
108
135
  /** Token persistence in the harness credential store, with an in-memory fallback. */
109
136
  export function createTokenStore(ctx, logger) {
110
137
  let token;
@@ -149,10 +176,12 @@ export function createTokenStore(ctx, logger) {
149
176
  }
150
177
 
151
178
  /** The bridge lib/core.mjs works on, over the live gateway. */
152
- export function createBridge(ctx, config, peer) {
179
+ export function createBridge(ctx, config, peer, { caller, precheck } = {}) {
153
180
  // DSH 0.2.0 has no Peer API; its gateway runs calls without a peer as the operator (owner).
154
181
  const withPeer = peer === undefined ? {} : { peer };
155
182
  return {
183
+ ...(caller ? { caller } : {}),
184
+ ...(precheck ? { precheck } : {}),
156
185
  list: () => ctx.typert.local.list(),
157
186
  invoke: (namespace, method, args, signal) => ctx.typertGateway.invoke({ namespace, method, args, ...withPeer, ...(signal ? { signal } : {}) }),
158
187
  stream: (namespace, method, args, signal) => ctx.typertGateway.stream({ namespace, method, args, ...withPeer, ...(signal ? { signal } : {}) }),
@@ -176,6 +205,81 @@ export async function apply(ctx, config = {}) {
176
205
  const tokens = createTokenStore(ctx, logger);
177
206
  await tokens.load();
178
207
 
208
+ // ── API keys ──
209
+ const keyRecord = createGrantRecord(ctx, KEYS_ID);
210
+ const keyPeers = new Map();
211
+ /** DSH 0.2.1+ ships the remote-access engine that confines scoped keys. */
212
+ const remoteAccess = () => ctx.get?.('remoteAccess');
213
+ const scopedSupported = () => typeof ctx.connection.createPeer === 'function' && typeof remoteAccess()?.registerPolicy === 'function';
214
+ const keys = createKeyRegistry({
215
+ persist: async list => {
216
+ if (!(await keyRecord.write({ version: 1, keys: list }))) logger.warn(`${LOG_PREFIX} no credential store; API keys last until restart`);
217
+ },
218
+ onChange: () => {
219
+ // Drop Peers of keys that changed mode or vanished, and recompute access.
220
+ for (const [id, entry] of keyPeers) {
221
+ const current = keys?.get(id);
222
+ if (current === undefined || current.mode !== entry.mode) { keyPeers.delete(id); entry.peer?.dispose?.(); }
223
+ }
224
+ try { remoteAccess()?.invalidate?.(); } catch { /* recomputed on the next decision anyway */ }
225
+ },
226
+ });
227
+ try {
228
+ keys.load(await keyRecord.read());
229
+ } catch (error) {
230
+ logger.warn(`${LOG_PREFIX} could not read stored API keys: ${error?.message ?? error}`);
231
+ }
232
+ if (typeof ctx.inject === 'function') {
233
+ // Scoped keys ride DSH's remote-access engine (0.2.1+), like Liveshare viewers.
234
+ ctx.inject(['remoteAccess', 'workspaceRegistry'], inner => {
235
+ const policy = createScopedPolicy(keys, () => inner.workspaceRegistry.list().map(workspace => ({ id: workspace.id, sessionIds: [...(workspace.sessionIds ?? [])] })));
236
+ // DSH reads bindings() afresh on every decision, so sessions that join a
237
+ // scoped workspace later are covered from their first call on.
238
+ inner.remoteAccess.registerPolicy(KEY_PRINCIPAL, policy);
239
+ });
240
+ }
241
+ /** A Peer per key: owner principal for full keys, the key principal for scoped ones. */
242
+ const peerFor = key => {
243
+ if (typeof ctx.connection.createPeer !== 'function') return undefined;
244
+ let entry = keyPeers.get(key.id);
245
+ if (entry === undefined || entry.peer?.signal?.aborted) {
246
+ const principal = key.mode === 'scoped' ? keyPrincipal(key) : { kind: 'owner' };
247
+ entry = { mode: key.mode, peer: ctx.connection.createPeer({ principal, interactions: 'none' }) };
248
+ keyPeers.set(key.id, entry);
249
+ }
250
+ return entry.peer;
251
+ };
252
+ ctx.effect(() => () => { for (const entry of keyPeers.values()) entry.peer?.dispose?.(); keyPeers.clear(); }, 'dsh-control-mcp: key peers');
253
+ const bridgeFor = caller => {
254
+ const key = keys.get(caller.keyId);
255
+ if (key === undefined) throw new Error('key vanished');
256
+ return createBridge(ctx, config, peerFor(key), {
257
+ caller: { keyName: caller.keyName, mode: caller.mode, access: caller.access },
258
+ precheck: endpoint => scopedPreCheck(keys.get(caller.keyId), endpoint),
259
+ });
260
+ };
261
+ /** Workspaces and sessions the key editor offers, read as the owner. */
262
+ const scopeOptions = async () => {
263
+ const out = { workspaces: [], sessions: [] };
264
+ try {
265
+ for (const workspace of ctx.get?.('workspaceRegistry')?.list?.() ?? []) {
266
+ out.workspaces.push({ id: workspace.id, title: workspace.title, path: workspace.path, sessionIds: [...(workspace.sessionIds ?? [])] });
267
+ }
268
+ } catch { /* registry unavailable */ }
269
+ try {
270
+ const value = await bridge.invoke('session', 'list', { _request: {} });
271
+ const rows = Array.isArray(value) ? value : value?.items ?? [];
272
+ for (const row of rows) {
273
+ // Subagent children belong to their parent chat; blank sessions stay
274
+ // selectable (a key may be prepared for a chat before its first prompt).
275
+ if (row.origin === 'subagent') continue;
276
+ const title = row.projections?.values?.title;
277
+ out.sessions.push({ id: row.sessionId, title: typeof title === 'string' && title.trim() ? title.trim() : 'Untitled session', cwd: row.cwd, updatedAt: row.updatedAt, running: row.running === true, blank: row.blank === true });
278
+ }
279
+ } catch { /* listed empty */ }
280
+ return out;
281
+ };
282
+
179
283
  /**
180
284
  * True for a request DSH itself admits as the owner: the signed-in browser
181
285
  * session, or an owner API cookie from /connect. Either already has full
@@ -206,6 +310,10 @@ export async function apply(ctx, config = {}) {
206
310
  };
207
311
  const handler = createHttpHandler({
208
312
  bridge,
313
+ bridgeFor,
314
+ keys,
315
+ scopeOptions,
316
+ scopedSupported,
209
317
  getToken: tokens.get,
210
318
  rotateToken: tokens.rotate,
211
319
  isOwnerBrowser,