dsh-project-mcp 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/src/write.ts ADDED
@@ -0,0 +1,447 @@
1
+ /**
2
+ * Write half of the entry editor: every decision one save makes, plus the
3
+ * atomic document write those decisions guard.
4
+ *
5
+ * The host and the browser half agree on the outcome through the contract
6
+ * (`docs/design/contracts/write-path.md`): a save replaces `mcpServers[<server>]`
7
+ * wholesale, keeps every other key of the document, normalizes the formatting
8
+ * (two spaces, trailing newline) and never writes a value the editor could not
9
+ * see. Everything here is pure except {@link writeDocument}, so the rules are
10
+ * testable without a filesystem.
11
+ *
12
+ * @module dsh-project-mcp/write
13
+ */
14
+
15
+ import { createHash, randomUUID } from 'node:crypto'
16
+ import { copyFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
17
+ import { basename, dirname, join, resolve } from 'node:path'
18
+ import { DEFAULT_LOCAL_FILES } from './discovery.ts'
19
+ import { hasReference } from './parse.ts'
20
+ import type { EntryField, EntrySnapshot, WriteScope } from './types.ts'
21
+
22
+ /** Characters of the SHA-256 digest published as a document revision. */
23
+ const REVISION_LENGTH = 16
24
+
25
+ /**
26
+ * Key names whose literal value is treated as a credential. The document is the
27
+ * only place such a value exists, so the host shows the key and withholds the
28
+ * value; a save keeps whatever the document declares for it.
29
+ */
30
+ const SECRET_KEY_PATTERN =
31
+ /(?:^|[^a-z0-9])(?:password|passwd|secret|token|credential|credentials|apikey|api[_-]?key|private[_-]?key|access[_-]?key|auth)/i
32
+
33
+ /**
34
+ * Keys the editor presents, whatever the transport.
35
+ */
36
+ const COMMON_KEYS = ['type', 'transport', 'enabled', 'disabled', 'connectTimeoutMs'] as const
37
+
38
+ /** Keys that belong to one transport alone; the other section is not modelled. */
39
+ const SECTION_KEYS: Record<'stdio' | 'streamable-http', readonly string[]> = {
40
+ stdio: ['command', 'args', 'cwd', 'env'],
41
+ 'streamable-http': ['url', 'headers'],
42
+ }
43
+
44
+ /** Every presented key, whichever transport an entry declares. */
45
+ const PRESENTED_KEYS = new Set([...COMMON_KEYS, ...SECTION_KEYS.stdio, ...SECTION_KEYS['streamable-http']])
46
+
47
+ /**
48
+ * Opaque content revision of one document.
49
+ *
50
+ * A save carries the revision the editor was built from, so a document changed
51
+ * underneath the form is refused instead of merged. The value is a prefix of a
52
+ * SHA-256 digest: stable for identical bytes, different for any change, and
53
+ * carrying nothing about the content.
54
+ * @param text - exact document bytes as read from disk.
55
+ * @returns a short hexadecimal digest of the content.
56
+ */
57
+ export function documentRevision(text: string): string {
58
+ return createHash('sha256').update(text, 'utf8').digest('hex').slice(0, REVISION_LENGTH)
59
+ }
60
+
61
+ /** How one declaring document may be written, and why not when it may not. */
62
+ export interface WriteScopeInfo {
63
+ /** Tier of the declaring document. */
64
+ readonly scope: WriteScope
65
+ /** One line saying why a write is unavailable, when one is. */
66
+ readonly reason?: string
67
+ /**
68
+ * Stable wire code of `reason` (`projectMcp.host` namespace), for
69
+ * client-side translation; the prose `reason` keeps its byte-identical
70
+ * English and stays the fallback.
71
+ */
72
+ readonly blockedCode?: string
73
+ /** Flat params of {@link blockedCode}. */
74
+ readonly blockedParams?: Record<string, string>
75
+ }
76
+
77
+ /**
78
+ * Which tier one declaring document belongs to.
79
+ *
80
+ * The two lists are the deployment's own: `projectDocuments` — the project
81
+ * documents it reads (`localFiles`) — are always writable, and `globalDocuments`
82
+ * — the ones its `globalFiles` names — are writable only with an explicit
83
+ * per-write consent and a deployment that enables `allowGlobalWrite`. Anything
84
+ * else (a profile document, a bundled one, an in-memory pseudo-path) is never
85
+ * written.
86
+ * @param document - absolute path of the declaring document.
87
+ * @param projectRoot - project root the row belongs to.
88
+ * @param options - the deployment's document lists and the `allowGlobalWrite` switch.
89
+ * @returns the tier plus the blocking sentence, when there is one.
90
+ */
91
+ export function writeScopeFor(
92
+ document: string,
93
+ projectRoot: string,
94
+ options: {
95
+ projectDocuments?: readonly string[]
96
+ globalDocuments?: readonly string[]
97
+ allowGlobalWrite?: boolean
98
+ } = {},
99
+ ): WriteScopeInfo {
100
+ const target = resolve(document)
101
+ const projectDocuments = (options.projectDocuments ?? DEFAULT_LOCAL_FILES).map((path) =>
102
+ resolve(projectRoot, path),
103
+ )
104
+ if (projectDocuments.includes(target)) return { scope: 'project' }
105
+ const globalDocuments = (options.globalDocuments ?? []).map((path) => resolve(path))
106
+ if (!globalDocuments.includes(target)) {
107
+ const writable = [...projectDocuments, ...globalDocuments]
108
+ // The prose is the fallback and never changes by a character; the code
109
+ // and its flat params are the additive companions the client translates
110
+ // (`projectMcp.host` namespace).
111
+ const notConfigured = writable.length === 0
112
+ return {
113
+ scope: 'readonly',
114
+ reason: notConfigured
115
+ ? `${document} is not a document this deployment reads, and it configures none to write`
116
+ : `${document} is not one of this deployment's MCP documents; only ${writable.join(', ')} can be written`,
117
+ blockedCode: notConfigured ? 'write.blocked.notConfigured' : 'write.blocked.notWritable',
118
+ blockedParams: notConfigured ? { document } : { document, writable: writable.join(', ') },
119
+ }
120
+ }
121
+ if (options.allowGlobalWrite === true) return { scope: 'global' }
122
+ return {
123
+ scope: 'global',
124
+ reason: `writing the global tier is disabled by this deployment (allowGlobalWrite: false); ${document} stays read-only here`,
125
+ blockedCode: 'write.blocked.globalDisabled',
126
+ blockedParams: { document },
127
+ }
128
+ }
129
+
130
+ /** Raw `env`/`headers` keys whose declared value is answered outside the document. */
131
+ export interface CredentialKeys {
132
+ /** Keys of the entry's `env` object. */
133
+ readonly env?: ReadonlySet<string>
134
+ /** Keys of the entry's `headers` object. */
135
+ readonly headers?: ReadonlySet<string>
136
+ }
137
+
138
+ /** Mutable local view of {@link EntrySnapshot}, so the builder can assign fields. */
139
+ interface MutableEntry {
140
+ transport: 'stdio' | 'streamable-http'
141
+ command?: string
142
+ args?: string[]
143
+ cwd?: string
144
+ env?: EntryField[]
145
+ url?: string
146
+ headers?: EntryField[]
147
+ enabled?: boolean
148
+ connectTimeoutMs?: number
149
+ extra?: Record<string, unknown>
150
+ }
151
+
152
+ /**
153
+ * Parse one declared entry into the body the editor is given.
154
+ *
155
+ * Every field is what the document declares: a resolved default (the project
156
+ * root folded into `cwd`, for example) is never copied in, because a save
157
+ * replaces the declaration, not the runtime config. A `env`/`headers` value is
158
+ * handed over only when the document really holds it as a literal and the key
159
+ * is not credential-shaped — otherwise the key is published with `masked` (and
160
+ * `fromCredentials` when the project `.env` or the credentials file answered it)
161
+ * and the value stays on the host.
162
+ * @param declared - raw `mcpServers[<server>]` value as parsed from the document.
163
+ * @param transport - transport of the parsed config, which decides the shape used.
164
+ * @param credentials - key names per section that are answered outside the document.
165
+ * @returns the entry body for the snapshot.
166
+ */
167
+ export function buildEntrySnapshot(
168
+ declared: unknown,
169
+ transport: 'stdio' | 'streamable-http',
170
+ credentials: CredentialKeys = {},
171
+ ): EntrySnapshot {
172
+ const record = isRecord(declared) ? declared : {}
173
+ const snapshot: MutableEntry = { transport }
174
+ if (transport === 'stdio') {
175
+ if (typeof record.command === 'string') snapshot.command = record.command
176
+ const args = record.args
177
+ if (Array.isArray(args) && args.every((item) => typeof item === 'string')) {
178
+ snapshot.args = [...(args as string[])]
179
+ }
180
+ if (typeof record.cwd === 'string') snapshot.cwd = record.cwd
181
+ const env = entryFields(record.env, credentials.env)
182
+ if (env !== undefined) snapshot.env = env
183
+ } else {
184
+ if (typeof record.url === 'string') snapshot.url = visibleUrl(record.url)
185
+ const headers = entryFields(record.headers, credentials.headers)
186
+ if (headers !== undefined) snapshot.headers = headers
187
+ }
188
+ if (record.enabled === false || record.disabled === true) snapshot.enabled = false
189
+ if (typeof record.connectTimeoutMs === 'number') {
190
+ snapshot.connectTimeoutMs = record.connectTimeoutMs
191
+ }
192
+ const extra: Record<string, unknown> = {}
193
+ for (const [key, value] of Object.entries(record)) {
194
+ // A key of the other transport is neither shown nor carried in `extra`:
195
+ // {@link entryToDeclaration} keeps it from the declaration itself, so a
196
+ // value the editor never saw cannot travel through the payload.
197
+ if (PRESENTED_KEYS.has(key)) continue
198
+ extra[key] = value
199
+ }
200
+ if (Object.keys(extra).length > 0) snapshot.extra = extra
201
+ return snapshot
202
+ }
203
+
204
+ /**
205
+ * Build the JSON object a save writes for one server.
206
+ *
207
+ * The declaration starts from the raw document entry, so keys the editor never
208
+ * showed survive verbatim — including the other transport's section, which the
209
+ * editor of the declared transport does not model and a switch drops on
210
+ * purpose. `type`/`transport` keeps its declared spelling while the transport is
211
+ * unchanged. `env`/`headers` follow the contract's three-way rule per key: a
212
+ * masked key submitted without a `value` keeps the declared one, a key with a
213
+ * `value` writes that value, and a declared key the submission omits is removed.
214
+ * A key marked `fromCredentials` never writes the submitted value: the declared
215
+ * text (usually a `${input:NAME}` reference) stays exactly as it is, so a
216
+ * resolved secret can never reach the document.
217
+ * @param entry - the entry body the panel submitted.
218
+ * @param declared - raw `mcpServers[<server>]` value as parsed from the document.
219
+ * @returns the declaration object to write in its place.
220
+ */
221
+ export function entryToDeclaration(entry: EntrySnapshot, declared: unknown): Record<string, unknown> {
222
+ const base: Record<string, unknown> = isRecord(declared) ? { ...declared } : {}
223
+ const declaredUrl = typeof base.url === 'string' ? base.url : undefined
224
+ const declaredEnv = stringRecord(base.env) ?? {}
225
+ const declaredHeaders = stringRecord(base.headers) ?? {}
226
+ const declaredTypeKey =
227
+ typeof base.type === 'string' ? 'type' : typeof base.transport === 'string' ? 'transport' : undefined
228
+ const declaredTypeValue = declaredTypeKey === undefined ? undefined : base[declaredTypeKey]
229
+ const declaredType = declaredTransport(base)
230
+ const sameTransport = declaredType === entry.transport
231
+
232
+ for (const key of COMMON_KEYS) delete base[key]
233
+ for (const key of SECTION_KEYS[entry.transport]) delete base[key]
234
+ // A switched transport drops the other transport's keys with it; an unchanged
235
+ // one keeps them, because the editor of this transport never modelled them.
236
+ if (!sameTransport) {
237
+ for (const key of [...SECTION_KEYS.stdio, ...SECTION_KEYS['streamable-http']]) delete base[key]
238
+ }
239
+
240
+ if (entry.extra !== undefined) {
241
+ for (const [key, value] of Object.entries(entry.extra)) {
242
+ if (PRESENTED_KEYS.has(key)) continue
243
+ base[key] = value
244
+ }
245
+ }
246
+ // `type`/`transport` is a presented key, but its declared spelling is kept
247
+ // while the transport is unchanged (`sse`, for example, would otherwise be
248
+ // rewritten as `streamable-http`).
249
+ if (declaredTypeKey !== undefined && sameTransport) base[declaredTypeKey] = declaredTypeValue
250
+
251
+ if (entry.transport === 'stdio') {
252
+ if (entry.command !== undefined) base.command = entry.command
253
+ if (entry.args !== undefined) base.args = [...entry.args]
254
+ if (entry.cwd !== undefined) base.cwd = entry.cwd
255
+ if (entry.env !== undefined) base.env = fieldsToRecord(entry.env, declaredEnv)
256
+ } else {
257
+ if (entry.url !== undefined) base.url = urlToWrite(entry.url, declaredUrl)
258
+ if (entry.headers !== undefined) base.headers = fieldsToRecord(entry.headers, declaredHeaders)
259
+ }
260
+ if (entry.enabled === false) base.enabled = false
261
+ if (entry.connectTimeoutMs !== undefined) base.connectTimeoutMs = entry.connectTimeoutMs
262
+ return base
263
+ }
264
+
265
+ /**
266
+ * A refusal {@link applyEntry} throws: the English message, byte-identical to
267
+ * what the site threw before codes existed, plus the `projectMcp.host` wire
268
+ * code and its flat params beside it (F-48). The save path catches it and
269
+ * reuses the companions as its own `messageCode`/`messageParams`, so the
270
+ * client translates the refusal instead of wrapping raw English.
271
+ */
272
+ export class WriteDocError extends Error {
273
+ constructor(
274
+ message: string,
275
+ /** The dotted wire code, into the client's `projectMcp.host` namespace. */
276
+ readonly code: string,
277
+ /** Flat params of the code, when it has any. */
278
+ readonly params?: Record<string, string>,
279
+ ) {
280
+ super(message)
281
+ this.name = 'WriteDocError'
282
+ }
283
+ }
284
+
285
+ /**
286
+ * Replace one entry in a document's text.
287
+ *
288
+ * Only `mcpServers[server]` changes: the rest of the server map and every other
289
+ * key of the document are serialized back as they were, with two-space
290
+ * indentation and a trailing newline.
291
+ * @param documentText - current document bytes.
292
+ * @param server - key inside `mcpServers` to replace.
293
+ * @param declaration - object to write in its place.
294
+ * @returns the full new document text.
295
+ * @throws {@link WriteDocError} when the text is not valid JSON or holds no
296
+ * `mcpServers` object.
297
+ */
298
+ export function applyEntry(
299
+ documentText: string,
300
+ server: string,
301
+ declaration: Record<string, unknown>,
302
+ ): string {
303
+ let root: unknown
304
+ try {
305
+ root = JSON.parse(documentText) as unknown
306
+ } catch (error) {
307
+ throw new WriteDocError(`the document is not valid JSON: ${errorText(error)}`, 'write.doc.invalidJson', {
308
+ error: errorText(error),
309
+ })
310
+ }
311
+ if (!isRecord(root)) throw new WriteDocError('the document is not a JSON object', 'write.doc.notObject')
312
+ const servers = root.mcpServers
313
+ if (!isRecord(servers)) throw new WriteDocError('the document has no "mcpServers" object', 'write.doc.noMcpServers')
314
+ const next = { ...servers, [server]: declaration }
315
+ return `${JSON.stringify({ ...root, mcpServers: next }, null, 2)}\n`
316
+ }
317
+
318
+ /**
319
+ * Write one document so that a failure at any step leaves it exactly as it was.
320
+ *
321
+ * Order: a `<document>.bak` copy of the current bytes first, then the new text
322
+ * into a temporary file in the same directory, then a `rename` over the
323
+ * document. The `rename` is the only operation that touches the original path,
324
+ * so a failure while copying or while writing the temporary file cannot leave
325
+ * half a document behind; a failed write drops the temporary file and rethrows.
326
+ * @param document - absolute path of the document to replace.
327
+ * @param text - the full new content.
328
+ * @throws when the backup, the temporary write or the rename fails.
329
+ */
330
+ export function writeDocument(document: string, text: string): void {
331
+ copyFileSync(document, `${document}.bak`)
332
+ const temporary = join(dirname(document), `.${basename(document)}.${randomUUID()}.tmp`)
333
+ try {
334
+ writeFileSync(temporary, text, 'utf8')
335
+ renameSync(temporary, document)
336
+ } catch (error) {
337
+ try {
338
+ unlinkSync(temporary)
339
+ } catch {
340
+ // The temporary file was never created, or is already gone.
341
+ }
342
+ throw error
343
+ }
344
+ }
345
+
346
+ /**
347
+ * URL as the editor sees it: a query string or fragment can carry a credential
348
+ * (`?token=…`), so it is dropped from the panel. A save that leaves the visible
349
+ * URL untouched keeps the declared one, query included.
350
+ * @param url - declared or submitted endpoint.
351
+ * @returns the endpoint without its query string or fragment.
352
+ */
353
+ export function visibleUrl(url: string): string {
354
+ const index = url.search(/[?#]/)
355
+ return index === -1 ? url : url.slice(0, index)
356
+ }
357
+
358
+ /** The URL a declaration writes: keep the declared query when unchanged. */
359
+ function urlToWrite(submitted: string, declaredUrl: string | undefined): string {
360
+ if (declaredUrl !== undefined && visibleUrl(declaredUrl) === submitted) return declaredUrl
361
+ return submitted
362
+ }
363
+
364
+ /** The three-way rule of one `env`/`headers` section, applied to one record. */
365
+ function fieldsToRecord(
366
+ fields: readonly EntryField[],
367
+ declared: Record<string, string>,
368
+ ): Record<string, string> {
369
+ const result: Record<string, string> = {}
370
+ for (const field of fields) {
371
+ const declaredValue = declared[field.key]
372
+ if (field.fromCredentials === true) {
373
+ // Never write an externally answered value: the declared text stays.
374
+ if (declaredValue !== undefined) result[field.key] = declaredValue
375
+ continue
376
+ }
377
+ if (field.value !== undefined) {
378
+ result[field.key] = field.value
379
+ continue
380
+ }
381
+ // No value at all: a masked key keeps what the document declares, so an
382
+ // editor that cannot see a secret can never erase or replace it. A shape
383
+ // with neither `value` nor `masked` has nothing to contribute either, and
384
+ // is kept for the same reason — removal is expressed by omitting the key.
385
+ if (declaredValue !== undefined) result[field.key] = declaredValue
386
+ }
387
+ return result
388
+ }
389
+
390
+ /** One `env`/`headers` section as entry fields, values masked where needed. */
391
+ function entryFields(
392
+ record: unknown,
393
+ credentials: ReadonlySet<string> | undefined,
394
+ ): EntryField[] | undefined {
395
+ if (!isRecord(record)) return undefined
396
+ const fields: EntryField[] = []
397
+ for (const [key, value] of Object.entries(record)) {
398
+ if (typeof value !== 'string') return undefined
399
+ if (credentials?.has(key) === true) {
400
+ fields.push({ key, masked: true, fromCredentials: true })
401
+ continue
402
+ }
403
+ // A `${...}` reference is resolved on the host and is not a literal the
404
+ // document holds, so its value is withheld as well.
405
+ if (SECRET_KEY_PATTERN.test(key) || hasReference(value)) {
406
+ fields.push({ key, masked: true })
407
+ continue
408
+ }
409
+ fields.push({ key, value })
410
+ }
411
+ return fields
412
+ }
413
+
414
+ /**
415
+ * Transport a declaration names, normalized the way `parse.ts` reads it: an
416
+ * explicit `type`/`transport` wins, otherwise the presence of `url` decides.
417
+ */
418
+ function declaredTransport(record: Record<string, unknown>): 'stdio' | 'streamable-http' {
419
+ const raw = record.type ?? record.transport
420
+ if (typeof raw === 'string') {
421
+ const normalized = raw.toLowerCase()
422
+ if (normalized === 'stdio') return 'stdio'
423
+ if (normalized === 'http' || normalized === 'streamable-http' || normalized === 'sse') {
424
+ return 'streamable-http'
425
+ }
426
+ }
427
+ return record.url !== undefined ? 'streamable-http' : 'stdio'
428
+ }
429
+
430
+ /** Flat string map, or `undefined` when the value is not one. */
431
+ function stringRecord(value: unknown): Record<string, string> | undefined {
432
+ if (!isRecord(value)) return undefined
433
+ const result: Record<string, string> = {}
434
+ for (const [key, item] of Object.entries(value)) {
435
+ if (typeof item !== 'string') return undefined
436
+ result[key] = item
437
+ }
438
+ return result
439
+ }
440
+
441
+ function isRecord(value: unknown): value is Record<string, unknown> {
442
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
443
+ }
444
+
445
+ function errorText(error: unknown): string {
446
+ return error instanceof Error ? error.message : String(error)
447
+ }