dsh-control-mcp 0.0.0-stage → 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/index.mjs ADDED
@@ -0,0 +1,332 @@
1
+ /**
2
+ * dsh-control-mcp Host entry.
3
+ *
4
+ * Exposes the running DeepSeek Harness's own Remote API (the API the Web UI
5
+ * uses: sessions, prompts, workspaces, models, plugins, schedules, goals,
6
+ * terminals, settings, …) as
7
+ * - an MCP server (Streamable HTTP, plus the bundled stdio bridge), and
8
+ * - an opt-in JSON/SSE HTTP API,
9
+ * both under `/dsh-control-mcp` on the DSH web server, both off by default,
10
+ * and both behind one bearer token kept in the harness credential store.
11
+ *
12
+ * Calls go through `ctx.typertGateway.invoke()/stream()` with an in-process
13
+ * owner Peer, so they get exactly the argument validation, lookups and
14
+ * business rules a Web UI call gets.
15
+ */
16
+ import { randomBytes } from 'node:crypto';
17
+ import { createRequire } from 'node:module';
18
+ import { readFileSync, realpathSync } from 'node:fs';
19
+ import { dirname, join } from 'node:path';
20
+ import { pathToFileURL } from 'node:url';
21
+ import { DEFAULT_MAX_RESULT_BYTES } from './lib/core.mjs';
22
+ import { createHttpHandler, ROUTE_PREFIX } from './lib/http.mjs';
23
+ import { KEY_PRINCIPAL, createKeyRegistry, createScopedPolicy, keyPrincipal, scopedPreCheck } from './lib/access.mjs';
24
+
25
+ export const name = 'dsh-control-mcp';
26
+ export const inject = ['typert', 'typertGateway', 'connection', 'webServer'];
27
+ const LOG_PREFIX = 'dsh-control-mcp:';
28
+ export const TOKEN_SCOPE = 'dsh-control-mcp';
29
+ export const TOKEN_ID = 'access-token';
30
+ export const KEYS_ID = 'api-keys';
31
+ export const SUPPORTED_DSH_RANGE = Object.freeze({ min: '0.2.0-0', below: '0.3.0-0' });
32
+
33
+ const PLUGIN_VERSION = (() => {
34
+ try {
35
+ return JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version;
36
+ } catch {
37
+ return undefined;
38
+ }
39
+ })();
40
+
41
+ /** Volatile so the plugin page applies changes without a restart. */
42
+ export function createConfig(z) {
43
+ return z.object({
44
+ mcpEnabled: z.boolean().default(false).volatile()
45
+ .description('Serve the MCP endpoint at /dsh-control-mcp/mcp.'),
46
+ apiEnabled: z.boolean().default(false).volatile()
47
+ .description('Serve the JSON/SSE HTTP API at /dsh-control-mcp/api/v1.'),
48
+ readOnly: z.boolean().default(false).volatile()
49
+ .description('Refuse every endpoint that changes harness state.'),
50
+ exposeAllEndpoints: z.boolean().default(false).volatile()
51
+ .description('List one MCP tool per harness endpoint in addition to the curated tools.'),
52
+ blockedEndpoints: z.array(z.string()).default([]).volatile()
53
+ .description('Endpoint patterns never callable through this plugin, e.g. "account/*".'),
54
+ maxResultBytes: z.natural().min(4096).max(16777216).default(DEFAULT_MAX_RESULT_BYTES).volatile()
55
+ .description('Largest MCP tool result text, in bytes.'),
56
+ });
57
+ }
58
+
59
+ function harnessPackageRoot(entry = process.argv[1]) {
60
+ try {
61
+ let dir = dirname(realpathSync(entry));
62
+ for (let i = 0; i < 8; i += 1) {
63
+ try {
64
+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
65
+ if (pkg.name === '@deepseek-ai/dsh') return { dir, version: pkg.version };
66
+ } catch { /* keep walking */ }
67
+ const parent = dirname(dir);
68
+ if (parent === dir) break;
69
+ dir = parent;
70
+ }
71
+ } catch { /* not running under dsh */ }
72
+ return undefined;
73
+ }
74
+
75
+ // Build Config with the running harness's own schemastery, never a second copy.
76
+ const harness = harnessPackageRoot();
77
+ const harnessSchemastery = (() => {
78
+ try {
79
+ return harness && pathToFileURL(createRequire(join(harness.dir, 'package.json')).resolve('@deepseek-ai/schemastery')).href;
80
+ } catch {
81
+ return undefined;
82
+ }
83
+ })();
84
+ export const Config = harnessSchemastery === undefined ? undefined : createConfig((await import(harnessSchemastery)).default);
85
+
86
+ function read(config, field, fallback) {
87
+ const value = config?.[field];
88
+ const current = value !== null && typeof value === 'object' && typeof value.get === 'function' ? value.get() : value;
89
+ return current === undefined ? fallback : current;
90
+ }
91
+
92
+ /** Live settings snapshot, read on every request so volatile edits apply at once. */
93
+ export function settingsFrom(config) {
94
+ const blocked = read(config, 'blockedEndpoints', []);
95
+ const maxResultBytes = Number(read(config, 'maxResultBytes', DEFAULT_MAX_RESULT_BYTES));
96
+ return {
97
+ mcpEnabled: read(config, 'mcpEnabled', false) === true,
98
+ apiEnabled: read(config, 'apiEnabled', false) === true,
99
+ readOnly: read(config, 'readOnly', false) === true,
100
+ exposeAllEndpoints: read(config, 'exposeAllEndpoints', false) === true,
101
+ blockedEndpoints: Array.isArray(blocked) ? blocked.filter(item => typeof item === 'string' && item.trim() !== '') : [],
102
+ maxResultBytes: Number.isFinite(maxResultBytes) && maxResultBytes >= 4096 ? maxResultBytes : DEFAULT_MAX_RESULT_BYTES,
103
+ };
104
+ }
105
+
106
+ export function newToken() {
107
+ return `dshc_${randomBytes(32).toString('base64url')}`;
108
+ }
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
+
135
+ /** Token persistence in the harness credential store, with an in-memory fallback. */
136
+ export function createTokenStore(ctx, logger) {
137
+ let token;
138
+ let key;
139
+ const credentials = () => ctx.get?.('credentials');
140
+ const keyOf = async () => {
141
+ if (key !== undefined) return key;
142
+ const { credentialKey } = await import(pathToFileURL(createRequire(join(harness.dir, 'package.json')).resolve('@deepseek-ai/dsh-credentials')).href);
143
+ key = credentialKey(TOKEN_SCOPE, TOKEN_ID);
144
+ return key;
145
+ };
146
+ const persist = async value => {
147
+ const store = credentials();
148
+ if (store === undefined || harness === undefined) { logger.warn(`${LOG_PREFIX} no credential store; the access token lasts until restart`); return; }
149
+ await store.modifyRecord(await keyOf(), async () => ({ kind: 'grant', payload: { token: value, createdAt: new Date().toISOString() } }));
150
+ };
151
+ return {
152
+ get: () => token,
153
+ async load() {
154
+ const store = credentials();
155
+ if (store !== undefined && harness !== undefined) {
156
+ try {
157
+ const record = await store.readRecord(await keyOf());
158
+ const stored = record?.kind === 'grant' ? record.payload?.token : undefined;
159
+ if (typeof stored === 'string' && stored.length >= 32) { token = stored; return token; }
160
+ } catch (error) {
161
+ logger.warn(`${LOG_PREFIX} could not read the stored access token: ${error?.message ?? error}`);
162
+ }
163
+ }
164
+ token = newToken();
165
+ try { await persist(token); } catch (error) { logger.warn(`${LOG_PREFIX} could not store the access token: ${error?.message ?? error}`); }
166
+ return token;
167
+ },
168
+ async rotate() {
169
+ const next = newToken();
170
+ await persist(next);
171
+ token = next;
172
+ logger.info(`${LOG_PREFIX} access token rotated; update your MCP and API clients`);
173
+ return next;
174
+ },
175
+ };
176
+ }
177
+
178
+ /** The bridge lib/core.mjs works on, over the live gateway. */
179
+ export function createBridge(ctx, config, peer, { caller, precheck } = {}) {
180
+ // DSH 0.2.0 has no Peer API; its gateway runs calls without a peer as the operator (owner).
181
+ const withPeer = peer === undefined ? {} : { peer };
182
+ return {
183
+ ...(caller ? { caller } : {}),
184
+ ...(precheck ? { precheck } : {}),
185
+ list: () => ctx.typert.local.list(),
186
+ invoke: (namespace, method, args, signal) => ctx.typertGateway.invoke({ namespace, method, args, ...withPeer, ...(signal ? { signal } : {}) }),
187
+ stream: (namespace, method, args, signal) => ctx.typertGateway.stream({ namespace, method, args, ...withPeer, ...(signal ? { signal } : {}) }),
188
+ settings: () => settingsFrom(config),
189
+ info: () => ({ plugin: name, pluginVersion: PLUGIN_VERSION, dshVersion: harness?.version }),
190
+ };
191
+ }
192
+
193
+ export async function apply(ctx, config = {}) {
194
+ const logger = ctx.logger ?? console;
195
+ if (typeof ctx.typertGateway?.invoke !== 'function' || typeof ctx.typert?.local?.list !== 'function') {
196
+ throw new Error(`${LOG_PREFIX} this dsh has no Typert gateway; DSH ${SUPPORTED_DSH_RANGE.min} or later is required`);
197
+ }
198
+ // One owner Peer for every call this plugin makes; disposed with the plugin.
199
+ // `interactions: 'none'`: it never answers forwarded approvals or questions.
200
+ // DSH 0.2.1+: a dedicated owner Peer. DSH 0.2.0: no Peer API, calls run as the operator.
201
+ const peer = typeof ctx.connection.createPeer === 'function'
202
+ ? ctx.connection.createPeer({ principal: { kind: 'owner' }, interactions: 'none' })
203
+ : undefined;
204
+ const bridge = createBridge(ctx, config, peer);
205
+ const tokens = createTokenStore(ctx, logger);
206
+ await tokens.load();
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
+
283
+ /**
284
+ * True for a request DSH itself admits as the owner: the signed-in browser
285
+ * session, or an owner API cookie from /connect. Either already has full
286
+ * control of this harness, so it may read this plugin's token.
287
+ * (0.2.0 admits the operator; 0.2.1/0.2.2 the shared browserPeer; 0.2.3+
288
+ * the authentication provider's owner Peer.)
289
+ */
290
+ // DSH 0.2.3+ splits authentication into `connection.authentication`, and
291
+ // `connection.admit` only works from a context that injects it. Older
292
+ // releases have no such service, so `admitCtx` stays the plugin context.
293
+ let admitCtx = ctx;
294
+ if (typeof ctx.inject === 'function') {
295
+ ctx.inject(['connection', 'connection.authentication'], inner => {
296
+ admitCtx = inner;
297
+ inner.effect(() => () => { admitCtx = ctx; }, 'dsh-control-mcp: owner admission');
298
+ });
299
+ }
300
+ const isOwnerBrowser = req => {
301
+ try {
302
+ const admission = admitCtx.connection.admit(req);
303
+ if (!('peer' in admission) || admission.peer === undefined) return false;
304
+ const admitted = admission.peer;
305
+ if (admitted === ctx.connection.browserPeer || admitted === ctx.connection.operator) return true;
306
+ return admitted.principal?.kind === 'owner' && admitted.signal?.aborted !== true;
307
+ } catch {
308
+ return false;
309
+ }
310
+ };
311
+ const handler = createHttpHandler({
312
+ bridge,
313
+ bridgeFor,
314
+ keys,
315
+ scopeOptions,
316
+ scopedSupported,
317
+ getToken: tokens.get,
318
+ rotateToken: tokens.rotate,
319
+ isOwnerBrowser,
320
+ warn: message => logger.warn(`${LOG_PREFIX} ${message}`),
321
+ });
322
+ // `auth: 'anonymous'`: DSH 0.2.3+ otherwise requires a browser session for every
323
+ // route. This plugin authenticates each request itself (bearer token, or the
324
+ // owner browser session for the token routes). Earlier releases ignore the field.
325
+ ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: ROUTE_PREFIX, handler, auth: 'anonymous' }), 'dsh-control-mcp: HTTP routes');
326
+ if (peer !== undefined) ctx.effect(() => () => peer.dispose?.(), 'dsh-control-mcp: owner peer');
327
+
328
+ const s = settingsFrom(config);
329
+ let origin = '';
330
+ try { origin = ctx.webServer.getOrigin?.() ?? ''; } catch { /* port not bound yet */ }
331
+ logger.info(`${LOG_PREFIX} ready at ${origin}${ROUTE_PREFIX} (mcp ${s.mcpEnabled ? 'on' : 'off'}, api ${s.apiEnabled ? 'on' : 'off'}${s.readOnly ? ', read-only' : ''}); Plugins → dsh-control-mcp`);
332
+ }
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
+ }