@mysterycode-liwen/dsh-credential-vault 1.4.3 → 1.5.1

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.js CHANGED
@@ -1,411 +1,412 @@
1
- /**
2
- * Host half of the dsh-credential-vault bundle.
3
- *
4
- * The browser (client.js) owns the vault data in localStorage. This half
5
- * exposes it to the Harness through two things:
6
- * 1. a loopback-only HTTP surface the browser POSTs its entries to, and
7
- * 2. an agent tool (`dsh_credential_vault_read`) the model calls to read them.
8
- *
9
- * SECURITY MODEL (hardened):
10
- * - The browser sends a METADATA-ONLY envelope. Secret fields (password /
11
- * apiKey / content) never reach this Host process; plaintext stays in the
12
- * browser's localStorage. Even a malicious full payload is sanitized here.
13
- * - Nothing is persisted to disk. The snapshot lives only in memory and is
14
- * re-synced by the browser on mount / change, so a restart simply starts
15
- * empty until the browser reconnects.
16
- * - Every tool access is recorded in a bounded, in-memory audit log that
17
- * contains no plaintext (GET /audit, same-origin + loopback only).
18
- *
19
- * @module dsh-credential-vault
20
- */
21
-
22
- /** Cordis plugin name. */
23
- export const name = 'dsh-credential-vault'
24
-
25
- /** The web server is the only hard dependency. */
26
- export const inject = ['webServer']
27
-
28
- /** Route prefix owned by this plugin. */
29
- const PREFIX = '/dsh-credential-vault'
30
-
31
- /** Cap the synced payload so a stray client cannot blow up the Host. Raised for large vaults. */
32
- const MAX_BODY_BYTES = 16 * 1024 * 1024
33
-
34
- /** Max entries mirrored from the browser; beyond this the tool output would be unwieldy. */
35
- const MAX_ENTRIES = 20000
36
-
37
- /** Fields that hold secrets; masked by default in tool output. */
38
- const SECRET_FIELDS = ['password', 'apiKey', 'content']
39
- const MASK = '••••••••'
40
-
41
- /** Pagination defaults / limits for the read tool. */
42
- const DEFAULT_LIMIT = 20
43
- const MAX_LIMIT = 200
44
-
45
- /** Fields kept in the compact "summary" projection. */
46
- const SUMMARY_FIELDS = ['id', 'title', 'category', 'username', 'provider', 'expiry', 'updatedAt']
47
-
48
- /** Current plugin version. Keep in sync with package.json when releasing. */
49
- const CURRENT_VERSION = '1.4.3'
50
-
51
- /** Where update checks read the latest published version from (GitHub Releases latest). */
52
- const RELEASES_API = 'https://api.github.com/repos/mysterycode-liwen/dsh-credential-vault/releases/latest'
53
- const RELEASES_URL = 'https://github.com/mysterycode-liwen/dsh-credential-vault/releases/latest'
54
- const UPDATE_CHECK_TIMEOUT_MS = 8000
55
- const UPDATE_CACHE_MS = 10 * 60 * 1000
56
- let updateCache = { at: 0, result: null }
57
-
58
- /** Last metadata-only snapshot received from the browser (never contains secrets). */
59
- let snapshot = { entries: [], updatedAt: 0 }
60
-
61
- /**
62
- * Fields mirrored from the browser. Everything else (especially SECRET_FIELDS)
63
- * is dropped, so the Host can never hold a plaintext password / key / body.
64
- */
65
- const META_FIELDS = ['id', 'title', 'category', 'username', 'provider', 'url', 'endpoint', 'expiry', 'notes', 'createdAt', 'updatedAt']
66
-
67
- /**
68
- * Force every incoming entry into a metadata-only shape. Applied defensively on
69
- * POST /entries, so even a buggy or hostile client cannot smuggle a secret into
70
- * the Host, the tool output, or the audit log.
71
- */
72
- function sanitizeEnvelope(entry) {
73
- const out = {}
74
- for (const key of META_FIELDS) {
75
- const value = entry[key]
76
- if (typeof value === 'string' || typeof value === 'number') out[key] = value
77
- }
78
- // Keep the masked placeholders so the UI shape stays stable for the model.
79
- for (const key of SECRET_FIELDS) {
80
- if (typeof entry[key] === 'string' && entry[key] !== '') out[key] = MASK
81
- }
82
- return out
83
- }
84
-
85
- // --- in-memory access audit (no plaintext, bounded) ------------------------
86
-
87
- const MAX_AUDIT = 200
88
- /** @type {{at:string, tool:string, action:string, entryId?:string, query?:string, count?:number}[]} */
89
- const auditLog = []
90
- function recordAudit(event) {
91
- auditLog.push(Object.assign({ at: new Date().toISOString() }, event))
92
- if (auditLog.length > MAX_AUDIT) auditLog.splice(0, auditLog.length - MAX_AUDIT)
93
- }
94
-
95
- // --- tiny HTTP helpers (self-contained so the bundle stays 7 files) --------
96
-
97
- function isLoopback(req) {
98
- const address = req && req.socket ? req.socket.remoteAddress : undefined
99
- if (address === undefined) return true
100
- return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1' || address.startsWith('127.')
101
- }
102
-
103
- function isSameOrigin(req) {
104
- const origin = req && req.headers ? req.headers.origin : undefined
105
- if (typeof origin !== 'string' || origin === '') return true
106
- const host = req && req.headers ? req.headers.host : undefined
107
- if (typeof host !== 'string' || host === '') return false
108
- try {
109
- return new URL(origin).host === host
110
- } catch {
111
- return false
112
- }
113
- }
114
-
115
- function sendJson(res, status, payload) {
116
- if (!res || res.writableEnded || res.destroyed) return
117
- const body = JSON.stringify(payload)
118
- res.writeHead(status, {
119
- 'content-type': 'application/json; charset=utf-8',
120
- 'cache-control': 'no-store',
121
- 'content-length': Buffer.byteLength(body),
122
- })
123
- res.end(body)
124
- }
125
-
126
- function fail(res, status, code, message) {
127
- sendJson(res, status, { ok: false, error: { code, ...(message === undefined ? {} : { message }) } })
128
- }
129
-
130
- function readJson(req, cap = MAX_BODY_BYTES) {
131
- return new Promise((resolve, reject) => {
132
- const chunks = []
133
- let size = 0
134
- req.on('data', (chunk) => {
135
- size += chunk.length
136
- if (size > cap) {
137
- reject(new Error('body too large'))
138
- req.destroy()
139
- return
140
- }
141
- chunks.push(chunk)
142
- })
143
- req.on('end', () => {
144
- try {
145
- resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
146
- } catch {
147
- reject(new Error('invalid json'))
148
- }
149
- })
150
- req.on('error', reject)
151
- })
152
- }
153
-
154
- // --- update check helpers --------------------------------------------------
155
-
156
- /** Parse a semver-ish tag into comparable parts. Returns null when unparseable. */
157
- function parseSemver(value) {
158
- if (typeof value !== 'string') return null
159
- const m = value.trim().replace(/^v/i, '').match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/)
160
- if (!m) return null
161
- return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]), prerelease: m[4] || '' }
162
- }
163
-
164
- /** Compare two parsed semvers: -1 (left older), 0 (equal), 1 (left newer). */
165
- function compareSemver(l, r) {
166
- const parts = ['major', 'minor', 'patch']
167
- for (const key of parts) {
168
- if (l[key] !== r[key]) return l[key] < r[key] ? -1 : 1
169
- }
170
- if (!l.prerelease && !r.prerelease) return 0
171
- if (!l.prerelease) return 1
172
- if (!r.prerelease) return -1
173
- return l.prerelease < r.prerelease ? -1 : l.prerelease > r.prerelease ? 1 : 0
174
- }
175
-
176
- /** Fetch the latest Release tag from GitHub, with a timeout and short cache. */
177
- async function checkForUpdate() {
178
- if (updateCache.result && Date.now() - updateCache.at < UPDATE_CACHE_MS) {
179
- return Object.assign({}, updateCache.result, { cached: true })
180
- }
181
- const fetchImpl = typeof globalThis.fetch === 'function' ? globalThis.fetch.bind(globalThis) : undefined
182
- if (!fetchImpl) throw new Error('fetch is not available on this Node runtime')
183
- let signal
184
- try { signal = AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) } catch { /* no timeout support */ }
185
- const response = await fetchImpl(RELEASES_API, {
186
- headers: { accept: 'application/vnd.github+json', 'user-agent': 'dsh-credential-vault-update-check' },
187
- ...(signal ? { signal } : {}),
188
- })
189
- if (!response.ok) throw new Error('GitHub API returned ' + response.status)
190
- const body = await response.json()
191
- const tag = body && typeof body.tag_name === 'string' ? body.tag_name : ''
192
- const latest = parseSemver(tag)
193
- if (!latest) throw new Error('Latest release tag is not a valid version: ' + tag)
194
- const current = parseSemver(CURRENT_VERSION) || { major: 0, minor: 0, patch: 0, prerelease: '' }
195
- const result = {
196
- ok: true,
197
- currentVersion: CURRENT_VERSION,
198
- latestVersion: tag.replace(/^v/i, ''),
199
- updateAvailable: compareSemver(current, latest) < 0,
200
- releaseUrl: RELEASES_URL,
201
- checkedAt: new Date().toISOString(),
202
- cached: false,
203
- }
204
- updateCache = { at: Date.now(), result }
205
- return result
206
- }
207
-
208
- // --- HTTP surface ----------------------------------------------------------
209
-
210
- async function handle(req, res) {
211
- try {
212
- if (!isLoopback(req)) return fail(res, 403, 'NOT_LOOPBACK')
213
- if (!isSameOrigin(req)) return fail(res, 403, 'BAD_ORIGIN')
214
-
215
- let pathname = (req.url || '/').split('?')[0]
216
- if (pathname.startsWith(PREFIX)) pathname = pathname.slice(PREFIX.length) || '/'
217
- const method = (req.method || 'GET').toUpperCase()
218
-
219
- // Browser -> Host: replace the snapshot with the browser's current vault.
220
- // Every entry is forced through sanitizeEnvelope(), so secrets never enter
221
- // this process even if the browser sends a full (legacy) payload.
222
- if (pathname === '/entries' && method === 'POST') {
223
- let body
224
- try {
225
- body = await readJson(req)
226
- } catch (error) {
227
- return fail(res, 400, 'BAD_JSON', String(error && error.message ? error.message : error))
228
- }
229
- const list = body && Array.isArray(body.entries) ? body.entries : null
230
- if (!list) return fail(res, 400, 'BAD_ENTRIES', 'expected { entries: [] }')
231
- // Keep only plain objects, cap the count, then strip all secret fields.
232
- const entries = list
233
- .filter((e) => e !== null && typeof e === 'object' && !Array.isArray(e))
234
- .slice(0, MAX_ENTRIES)
235
- .map(sanitizeEnvelope)
236
- snapshot = { entries, updatedAt: Date.now() }
237
- return sendJson(res, 200, { ok: true, count: entries.length, truncated: list.length > entries.length })
238
- }
239
-
240
- // Debug / inspection endpoint removed: it used to return a page of the raw
241
- // snapshot. It is not needed by the browser and only widened the read
242
- // surface. The dsh_credential_vault_read tool is the sanctioned read path.
243
- if (pathname === '/entries' && method === 'GET') {
244
- return fail(res, 404, 'NOT_FOUND')
245
- }
246
-
247
- // In-memory access audit (same-origin + loopback already enforced above).
248
- // Contains no plaintext — only tool names, actions, ids and counts.
249
- if (pathname === '/audit' && method === 'GET') {
250
- return sendJson(res, 200, { ok: true, total: auditLog.length, events: auditLog.slice() })
251
- }
252
-
253
- // Check GitHub Releases latest for a newer plugin version.
254
- if (pathname === '/update-check' && method === 'GET') {
255
- try {
256
- return sendJson(res, 200, await checkForUpdate())
257
- } catch (error) {
258
- return sendJson(res, 200, {
259
- ok: false,
260
- currentVersion: CURRENT_VERSION,
261
- error: String(error && error.message ? error.message : error),
262
- checkedAt: new Date().toISOString(),
263
- })
264
- }
265
- }
266
-
267
- return fail(res, 404, 'NOT_FOUND')
268
- } catch (error) {
269
- return fail(res, 500, 'INTERNAL', String(error && error.message ? error.message : error))
270
- }
271
- }
272
-
273
- // --- tool projection helpers ----------------------------------------------
274
-
275
- function projectEntry(entry, mode) {
276
- const keys = mode === 'summary' ? SUMMARY_FIELDS : Object.keys(entry)
277
- const out = {}
278
- for (const key of keys) {
279
- const value = entry[key]
280
- if (value === null || value === undefined || value === '') continue
281
- // Secret fields in the snapshot are already MASK placeholders (the Host
282
- // never receives plaintext). Guard here too, defense-in-depth.
283
- out[key] = SECRET_FIELDS.includes(key) ? MASK : value
284
- }
285
- return out
286
- }
287
-
288
- function matches(entry, query, category) {
289
- if (category && category !== 'all' && entry.category !== category) return false
290
- if (!query) return true
291
- const q = query.toLowerCase()
292
- const haystack = [entry.title, entry.username, entry.provider, entry.url, entry.endpoint, entry.notes]
293
- .filter((v) => typeof v === 'string')
294
- .join(' ')
295
- .toLowerCase()
296
- return haystack.includes(q)
297
- }
298
-
299
- /**
300
- * @param {import('@deepseek-ai/cordis').Context} ctx
301
- */
302
- export function apply(ctx) {
303
- ctx.effect(() => {
304
- const dispose = ctx.webServer.register({
305
- kind: 'prefix',
306
- path: PREFIX,
307
- handler: (req, res) => handle(req, res),
308
- })
309
- return () => {
310
- if (typeof dispose === 'function') dispose()
311
- }
312
- })
313
-
314
- // Tools / systemPrompt are optional services: read them defensively so the
315
- // plugin still loads where they are unavailable.
316
- const tools = typeof ctx.get === 'function' ? ctx.get('tools') : undefined
317
- if (tools !== undefined && tools !== null && typeof tools.register === 'function') {
318
- ctx.effect(() => {
319
- const dispose = tools.register(
320
- {
321
- name: 'dsh_credential_vault_read',
322
- description:
323
- 'Read metadata about credentials in the user\'s local vault (accounts, API keys, other entries stored in the sidebar vault panel). Results are paginated: use limit/offset to page through large vaults, or mode="summary" for a lightweight id/title/category list first. Secret values (passwords / API keys / text bodies) are ALWAYS masked — plaintext never leaves the browser and cannot be returned by this tool; the revealSecrets parameter is accepted for compatibility but has no effect. Use this to discover which credentials exist; to actually use a secret, ask the user to open the vault panel and copy it.',
324
- parameters: {
325
- type: 'object',
326
- properties: {
327
- query: {
328
- type: 'string',
329
- description: 'Optional text to filter by title, account, provider, URL or notes (case-insensitive substring).',
330
- },
331
- category: {
332
- type: 'string',
333
- enum: ['all', 'account', 'apikey', 'other'],
334
- description: 'Only return entries of this category. Defaults to all.',
335
- },
336
- mode: {
337
- type: 'string',
338
- enum: ['summary', 'full'],
339
- description: 'summary = only id/title/category/account/provider/expiry (lightweight, recommended for browsing); full = all metadata fields (secrets always masked). Defaults to full.',
340
- },
341
- limit: {
342
- type: 'number',
343
- description: 'Page size, 1-200. Defaults to 20. Use with offset to page through large vaults.',
344
- },
345
- offset: {
346
- type: 'number',
347
- description: 'How many matching entries to skip. Defaults to 0. Increase by limit to get the next page.',
348
- },
349
- revealSecrets: {
350
- type: 'boolean',
351
- description: 'Deprecated / no-op. Secret values are always masked and are never returned by this tool. Accepted only so older tool calls keep working.',
352
- },
353
- },
354
- additionalProperties: false,
355
- },
356
- output: {
357
- schema: {
358
- type: 'object',
359
- properties: {
360
- total: { type: 'number' },
361
- returned: { type: 'number' },
362
- hasMore: { type: 'boolean' },
363
- entries: { type: 'array', items: { type: 'object' } },
364
- },
365
- additionalProperties: true,
366
- },
367
- render: () => [{ type: 'text', text: 'dsh_credential_vault_read' }],
368
- },
369
- async execute(args) {
370
- const a = args !== null && typeof args === 'object' ? args : {}
371
- const query = typeof a.query === 'string' ? a.query : ''
372
- const category = typeof a.category === 'string' ? a.category : 'all'
373
- const mode = a.mode === 'summary' ? 'summary' : 'full'
374
- // revealSecrets is intentionally ignored: plaintext never reaches
375
- // the Host, so there is nothing to reveal. Kept for compatibility.
376
- const limit = Math.max(1, Math.min(MAX_LIMIT, Number.isFinite(a.limit) ? Math.floor(a.limit) : DEFAULT_LIMIT))
377
- const offset = Math.max(0, Number.isFinite(a.offset) ? Math.floor(a.offset) : 0)
378
- const all = Array.isArray(snapshot.entries) ? snapshot.entries : []
379
- const filtered = all.filter((e) => matches(e, query, category))
380
- const page = filtered.slice(offset, offset + limit)
381
- recordAudit({ tool: 'dsh_credential_vault_read', action: 'read', category, query: query || undefined, count: page.length })
382
- return {
383
- total: filtered.length,
384
- returned: page.length,
385
- offset,
386
- limit,
387
- hasMore: offset + page.length < filtered.length,
388
- updatedAt: snapshot.updatedAt,
389
- entries: page.map((e) => projectEntry(e, mode)),
390
- }
391
- },
392
- },
393
- {},
394
- )
395
- return typeof dispose === 'function' ? dispose : () => {}
396
- }, 'dsh-credential-vault-read-tool')
397
- }
398
-
399
- const systemPrompt = typeof ctx.get === 'function' ? ctx.get('systemPrompt') : undefined
400
- if (systemPrompt !== undefined && systemPrompt !== null && typeof systemPrompt.section === 'function') {
401
- ctx.effect(() => {
402
- systemPrompt.section({
403
- name: 'tool:dsh-credential-vault',
404
- order: 118,
405
- text:
406
- '凭据保险箱:用户把账号密码、API Key、恢复码等保存在侧边栏「凭据保险箱」里。需要知道有哪些凭据时用 dsh_credential_vault_read 工具(按 query / category 过滤;数据多时先用 mode="summary" 看标题清单,再用 limit/offset 翻页)。出于安全,该工具只返回元数据——密码 / API Key / 文本正文一律显示为 ••••••••,明文只留在浏览器内、不会进入模型上下文,revealSecrets 参数已失效。不要向用户索要明文密钥;需要用到具体密钥时,请让用户自行在侧边栏面板中查看或复制。',
407
- })
408
- return () => {}
409
- }, 'dsh-credential-vault-prompt')
410
- }
411
- }
1
+ /**
2
+ * Host half of the dsh-credential-vault bundle.
3
+ *
4
+ * The browser (client.js) owns the vault data in localStorage. This half
5
+ * exposes it to the Harness through two things:
6
+ * 1. a loopback-only HTTP surface the browser POSTs its entries to, and
7
+ * 2. an agent tool (`dsh_credential_vault_read`) the model calls to read them.
8
+ *
9
+ * SECURITY MODEL (hardened):
10
+ * - The browser sends a METADATA-ONLY envelope. Secret fields (password /
11
+ * apiKey / content) never reach this Host process; plaintext stays in the
12
+ * browser's localStorage. Even a malicious full payload is sanitized here.
13
+ * - Nothing is persisted to disk. The snapshot lives only in memory and is
14
+ * re-synced by the browser on mount / change, so a restart simply starts
15
+ * empty until the browser reconnects.
16
+ * - Every tool access is recorded in a bounded, in-memory audit log that
17
+ * contains no plaintext (GET /audit, same-origin + loopback only).
18
+ *
19
+ * @module dsh-credential-vault
20
+ */
21
+
22
+ /** Cordis plugin name. */
23
+ export const name = 'dsh-credential-vault'
24
+
25
+ /** The web server is the only hard dependency. */
26
+ export const inject = ['webServer']
27
+
28
+ /** Route prefix owned by this plugin. */
29
+ const PREFIX = '/dsh-credential-vault'
30
+
31
+ /** Cap the synced payload so a stray client cannot blow up the Host. Raised for large vaults. */
32
+ const MAX_BODY_BYTES = 16 * 1024 * 1024
33
+
34
+ /** Max entries mirrored from the browser; beyond this the tool output would be unwieldy. */
35
+ const MAX_ENTRIES = 20000
36
+
37
+ /** Fields that hold secrets; masked by default in tool output. */
38
+ const SECRET_FIELDS = ['password', 'apiKey', 'content', 'appSecret', 'token', 'encodingAesKey', 'uploadKey', 'keyValue']
39
+ const MASK = '••••••••'
40
+
41
+ /** Pagination defaults / limits for the read tool. */
42
+ const DEFAULT_LIMIT = 20
43
+ const MAX_LIMIT = 200
44
+
45
+ /** Fields kept in the compact "summary" projection. */
46
+ const SUMMARY_FIELDS = ['id', 'title', 'category', 'username', 'provider', 'expiry', 'updatedAt']
47
+
48
+ /** Current plugin version. Keep in sync with package.json when releasing. */
49
+ const CURRENT_VERSION = '1.5.1'
50
+
51
+ /** Where update checks read the latest published version from (GitHub Releases latest). */
52
+ const RELEASES_API = 'https://api.github.com/repos/mysterycode-liwen/dsh-credential-vault/releases/latest'
53
+ const RELEASES_URL = 'https://github.com/mysterycode-liwen/dsh-credential-vault/releases/latest'
54
+ const UPDATE_CHECK_TIMEOUT_MS = 8000
55
+ const UPDATE_CACHE_MS = 10 * 60 * 1000
56
+ let updateCache = { at: 0, result: null }
57
+
58
+ /** Last metadata-only snapshot received from the browser (never contains secrets). */
59
+ let snapshot = { entries: [], updatedAt: 0 }
60
+
61
+ /**
62
+ * Fields mirrored from the browser. Everything else (especially SECRET_FIELDS)
63
+ * is dropped, so the Host can never hold a plaintext password / key / body.
64
+ */
65
+ const META_FIELDS = ['id', 'title', 'category', 'username', 'provider', 'keyName', 'url', 'endpoint', 'expiry',
66
+ 'appId', 'serverUrl', 'domains', 'notes', 'createdAt', 'updatedAt']
67
+
68
+ /**
69
+ * Force every incoming entry into a metadata-only shape. Applied defensively on
70
+ * POST /entries, so even a buggy or hostile client cannot smuggle a secret into
71
+ * the Host, the tool output, or the audit log.
72
+ */
73
+ function sanitizeEnvelope(entry) {
74
+ const out = {}
75
+ for (const key of META_FIELDS) {
76
+ const value = entry[key]
77
+ if (typeof value === 'string' || typeof value === 'number') out[key] = value
78
+ }
79
+ // Keep the masked placeholders so the UI shape stays stable for the model.
80
+ for (const key of SECRET_FIELDS) {
81
+ if (typeof entry[key] === 'string' && entry[key] !== '') out[key] = MASK
82
+ }
83
+ return out
84
+ }
85
+
86
+ // --- in-memory access audit (no plaintext, bounded) ------------------------
87
+
88
+ const MAX_AUDIT = 200
89
+ /** @type {{at:string, tool:string, action:string, entryId?:string, query?:string, count?:number}[]} */
90
+ const auditLog = []
91
+ function recordAudit(event) {
92
+ auditLog.push(Object.assign({ at: new Date().toISOString() }, event))
93
+ if (auditLog.length > MAX_AUDIT) auditLog.splice(0, auditLog.length - MAX_AUDIT)
94
+ }
95
+
96
+ // --- tiny HTTP helpers (self-contained so the bundle stays 7 files) --------
97
+
98
+ function isLoopback(req) {
99
+ const address = req && req.socket ? req.socket.remoteAddress : undefined
100
+ if (address === undefined) return true
101
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1' || address.startsWith('127.')
102
+ }
103
+
104
+ function isSameOrigin(req) {
105
+ const origin = req && req.headers ? req.headers.origin : undefined
106
+ if (typeof origin !== 'string' || origin === '') return true
107
+ const host = req && req.headers ? req.headers.host : undefined
108
+ if (typeof host !== 'string' || host === '') return false
109
+ try {
110
+ return new URL(origin).host === host
111
+ } catch {
112
+ return false
113
+ }
114
+ }
115
+
116
+ function sendJson(res, status, payload) {
117
+ if (!res || res.writableEnded || res.destroyed) return
118
+ const body = JSON.stringify(payload)
119
+ res.writeHead(status, {
120
+ 'content-type': 'application/json; charset=utf-8',
121
+ 'cache-control': 'no-store',
122
+ 'content-length': Buffer.byteLength(body),
123
+ })
124
+ res.end(body)
125
+ }
126
+
127
+ function fail(res, status, code, message) {
128
+ sendJson(res, status, { ok: false, error: { code, ...(message === undefined ? {} : { message }) } })
129
+ }
130
+
131
+ function readJson(req, cap = MAX_BODY_BYTES) {
132
+ return new Promise((resolve, reject) => {
133
+ const chunks = []
134
+ let size = 0
135
+ req.on('data', (chunk) => {
136
+ size += chunk.length
137
+ if (size > cap) {
138
+ reject(new Error('body too large'))
139
+ req.destroy()
140
+ return
141
+ }
142
+ chunks.push(chunk)
143
+ })
144
+ req.on('end', () => {
145
+ try {
146
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
147
+ } catch {
148
+ reject(new Error('invalid json'))
149
+ }
150
+ })
151
+ req.on('error', reject)
152
+ })
153
+ }
154
+
155
+ // --- update check helpers --------------------------------------------------
156
+
157
+ /** Parse a semver-ish tag into comparable parts. Returns null when unparseable. */
158
+ function parseSemver(value) {
159
+ if (typeof value !== 'string') return null
160
+ const m = value.trim().replace(/^v/i, '').match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/)
161
+ if (!m) return null
162
+ return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]), prerelease: m[4] || '' }
163
+ }
164
+
165
+ /** Compare two parsed semvers: -1 (left older), 0 (equal), 1 (left newer). */
166
+ function compareSemver(l, r) {
167
+ const parts = ['major', 'minor', 'patch']
168
+ for (const key of parts) {
169
+ if (l[key] !== r[key]) return l[key] < r[key] ? -1 : 1
170
+ }
171
+ if (!l.prerelease && !r.prerelease) return 0
172
+ if (!l.prerelease) return 1
173
+ if (!r.prerelease) return -1
174
+ return l.prerelease < r.prerelease ? -1 : l.prerelease > r.prerelease ? 1 : 0
175
+ }
176
+
177
+ /** Fetch the latest Release tag from GitHub, with a timeout and short cache. */
178
+ async function checkForUpdate() {
179
+ if (updateCache.result && Date.now() - updateCache.at < UPDATE_CACHE_MS) {
180
+ return Object.assign({}, updateCache.result, { cached: true })
181
+ }
182
+ const fetchImpl = typeof globalThis.fetch === 'function' ? globalThis.fetch.bind(globalThis) : undefined
183
+ if (!fetchImpl) throw new Error('fetch is not available on this Node runtime')
184
+ let signal
185
+ try { signal = AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) } catch { /* no timeout support */ }
186
+ const response = await fetchImpl(RELEASES_API, {
187
+ headers: { accept: 'application/vnd.github+json', 'user-agent': 'dsh-credential-vault-update-check' },
188
+ ...(signal ? { signal } : {}),
189
+ })
190
+ if (!response.ok) throw new Error('GitHub API returned ' + response.status)
191
+ const body = await response.json()
192
+ const tag = body && typeof body.tag_name === 'string' ? body.tag_name : ''
193
+ const latest = parseSemver(tag)
194
+ if (!latest) throw new Error('Latest release tag is not a valid version: ' + tag)
195
+ const current = parseSemver(CURRENT_VERSION) || { major: 0, minor: 0, patch: 0, prerelease: '' }
196
+ const result = {
197
+ ok: true,
198
+ currentVersion: CURRENT_VERSION,
199
+ latestVersion: tag.replace(/^v/i, ''),
200
+ updateAvailable: compareSemver(current, latest) < 0,
201
+ releaseUrl: RELEASES_URL,
202
+ checkedAt: new Date().toISOString(),
203
+ cached: false,
204
+ }
205
+ updateCache = { at: Date.now(), result }
206
+ return result
207
+ }
208
+
209
+ // --- HTTP surface ----------------------------------------------------------
210
+
211
+ async function handle(req, res) {
212
+ try {
213
+ if (!isLoopback(req)) return fail(res, 403, 'NOT_LOOPBACK')
214
+ if (!isSameOrigin(req)) return fail(res, 403, 'BAD_ORIGIN')
215
+
216
+ let pathname = (req.url || '/').split('?')[0]
217
+ if (pathname.startsWith(PREFIX)) pathname = pathname.slice(PREFIX.length) || '/'
218
+ const method = (req.method || 'GET').toUpperCase()
219
+
220
+ // Browser -> Host: replace the snapshot with the browser's current vault.
221
+ // Every entry is forced through sanitizeEnvelope(), so secrets never enter
222
+ // this process even if the browser sends a full (legacy) payload.
223
+ if (pathname === '/entries' && method === 'POST') {
224
+ let body
225
+ try {
226
+ body = await readJson(req)
227
+ } catch (error) {
228
+ return fail(res, 400, 'BAD_JSON', String(error && error.message ? error.message : error))
229
+ }
230
+ const list = body && Array.isArray(body.entries) ? body.entries : null
231
+ if (!list) return fail(res, 400, 'BAD_ENTRIES', 'expected { entries: [] }')
232
+ // Keep only plain objects, cap the count, then strip all secret fields.
233
+ const entries = list
234
+ .filter((e) => e !== null && typeof e === 'object' && !Array.isArray(e))
235
+ .slice(0, MAX_ENTRIES)
236
+ .map(sanitizeEnvelope)
237
+ snapshot = { entries, updatedAt: Date.now() }
238
+ return sendJson(res, 200, { ok: true, count: entries.length, truncated: list.length > entries.length })
239
+ }
240
+
241
+ // Debug / inspection endpoint removed: it used to return a page of the raw
242
+ // snapshot. It is not needed by the browser and only widened the read
243
+ // surface. The dsh_credential_vault_read tool is the sanctioned read path.
244
+ if (pathname === '/entries' && method === 'GET') {
245
+ return fail(res, 404, 'NOT_FOUND')
246
+ }
247
+
248
+ // In-memory access audit (same-origin + loopback already enforced above).
249
+ // Contains no plaintext — only tool names, actions, ids and counts.
250
+ if (pathname === '/audit' && method === 'GET') {
251
+ return sendJson(res, 200, { ok: true, total: auditLog.length, events: auditLog.slice() })
252
+ }
253
+
254
+ // Check GitHub Releases latest for a newer plugin version.
255
+ if (pathname === '/update-check' && method === 'GET') {
256
+ try {
257
+ return sendJson(res, 200, await checkForUpdate())
258
+ } catch (error) {
259
+ return sendJson(res, 200, {
260
+ ok: false,
261
+ currentVersion: CURRENT_VERSION,
262
+ error: String(error && error.message ? error.message : error),
263
+ checkedAt: new Date().toISOString(),
264
+ })
265
+ }
266
+ }
267
+
268
+ return fail(res, 404, 'NOT_FOUND')
269
+ } catch (error) {
270
+ return fail(res, 500, 'INTERNAL', String(error && error.message ? error.message : error))
271
+ }
272
+ }
273
+
274
+ // --- tool projection helpers ----------------------------------------------
275
+
276
+ function projectEntry(entry, mode) {
277
+ const keys = mode === 'summary' ? SUMMARY_FIELDS : Object.keys(entry)
278
+ const out = {}
279
+ for (const key of keys) {
280
+ const value = entry[key]
281
+ if (value === null || value === undefined || value === '') continue
282
+ // Secret fields in the snapshot are already MASK placeholders (the Host
283
+ // never receives plaintext). Guard here too, defense-in-depth.
284
+ out[key] = SECRET_FIELDS.includes(key) ? MASK : value
285
+ }
286
+ return out
287
+ }
288
+
289
+ function matches(entry, query, category) {
290
+ if (category && category !== 'all' && entry.category !== category) return false
291
+ if (!query) return true
292
+ const q = query.toLowerCase()
293
+ const haystack = [entry.title, entry.username, entry.provider, entry.url, entry.endpoint, entry.notes]
294
+ .filter((v) => typeof v === 'string')
295
+ .join(' ')
296
+ .toLowerCase()
297
+ return haystack.includes(q)
298
+ }
299
+
300
+ /**
301
+ * @param {import('@deepseek-ai/cordis').Context} ctx
302
+ */
303
+ export function apply(ctx) {
304
+ ctx.effect(() => {
305
+ const dispose = ctx.webServer.register({
306
+ kind: 'prefix',
307
+ path: PREFIX,
308
+ handler: (req, res) => handle(req, res),
309
+ })
310
+ return () => {
311
+ if (typeof dispose === 'function') dispose()
312
+ }
313
+ })
314
+
315
+ // Tools / systemPrompt are optional services: read them defensively so the
316
+ // plugin still loads where they are unavailable.
317
+ const tools = typeof ctx.get === 'function' ? ctx.get('tools') : undefined
318
+ if (tools !== undefined && tools !== null && typeof tools.register === 'function') {
319
+ ctx.effect(() => {
320
+ const dispose = tools.register(
321
+ {
322
+ name: 'dsh_credential_vault_read',
323
+ description:
324
+ 'Read metadata about credentials in the user\'s local vault (accounts, API keys, other entries stored in the sidebar vault panel). Results are paginated: use limit/offset to page through large vaults, or mode="summary" for a lightweight id/title/category list first. Secret values (passwords / API keys / text bodies) are ALWAYS masked — plaintext never leaves the browser and cannot be returned by this tool; the revealSecrets parameter is accepted for compatibility but has no effect. Use this to discover which credentials exist; to actually use a secret, ask the user to open the vault panel and copy it.',
325
+ parameters: {
326
+ type: 'object',
327
+ properties: {
328
+ query: {
329
+ type: 'string',
330
+ description: 'Optional text to filter by title, account, provider, URL or notes (case-insensitive substring).',
331
+ },
332
+ category: {
333
+ type: 'string',
334
+ enum: ['all', 'account', 'apikey', 'secretKey', 'other', 'wechatMp', 'wechatMini'],
335
+ description: 'Only return entries of this category. Defaults to all.',
336
+ },
337
+ mode: {
338
+ type: 'string',
339
+ enum: ['summary', 'full'],
340
+ description: 'summary = only id/title/category/account/provider/expiry (lightweight, recommended for browsing); full = all metadata fields (secrets always masked). Defaults to full.',
341
+ },
342
+ limit: {
343
+ type: 'number',
344
+ description: 'Page size, 1-200. Defaults to 20. Use with offset to page through large vaults.',
345
+ },
346
+ offset: {
347
+ type: 'number',
348
+ description: 'How many matching entries to skip. Defaults to 0. Increase by limit to get the next page.',
349
+ },
350
+ revealSecrets: {
351
+ type: 'boolean',
352
+ description: 'Deprecated / no-op. Secret values are always masked and are never returned by this tool. Accepted only so older tool calls keep working.',
353
+ },
354
+ },
355
+ additionalProperties: false,
356
+ },
357
+ output: {
358
+ schema: {
359
+ type: 'object',
360
+ properties: {
361
+ total: { type: 'number' },
362
+ returned: { type: 'number' },
363
+ hasMore: { type: 'boolean' },
364
+ entries: { type: 'array', items: { type: 'object' } },
365
+ },
366
+ additionalProperties: true,
367
+ },
368
+ render: () => [{ type: 'text', text: 'dsh_credential_vault_read' }],
369
+ },
370
+ async execute(args) {
371
+ const a = args !== null && typeof args === 'object' ? args : {}
372
+ const query = typeof a.query === 'string' ? a.query : ''
373
+ const category = typeof a.category === 'string' ? a.category : 'all'
374
+ const mode = a.mode === 'summary' ? 'summary' : 'full'
375
+ // revealSecrets is intentionally ignored: plaintext never reaches
376
+ // the Host, so there is nothing to reveal. Kept for compatibility.
377
+ const limit = Math.max(1, Math.min(MAX_LIMIT, Number.isFinite(a.limit) ? Math.floor(a.limit) : DEFAULT_LIMIT))
378
+ const offset = Math.max(0, Number.isFinite(a.offset) ? Math.floor(a.offset) : 0)
379
+ const all = Array.isArray(snapshot.entries) ? snapshot.entries : []
380
+ const filtered = all.filter((e) => matches(e, query, category))
381
+ const page = filtered.slice(offset, offset + limit)
382
+ recordAudit({ tool: 'dsh_credential_vault_read', action: 'read', category, query: query || undefined, count: page.length })
383
+ return {
384
+ total: filtered.length,
385
+ returned: page.length,
386
+ offset,
387
+ limit,
388
+ hasMore: offset + page.length < filtered.length,
389
+ updatedAt: snapshot.updatedAt,
390
+ entries: page.map((e) => projectEntry(e, mode)),
391
+ }
392
+ },
393
+ },
394
+ {},
395
+ )
396
+ return typeof dispose === 'function' ? dispose : () => {}
397
+ }, 'dsh-credential-vault-read-tool')
398
+ }
399
+
400
+ const systemPrompt = typeof ctx.get === 'function' ? ctx.get('systemPrompt') : undefined
401
+ if (systemPrompt !== undefined && systemPrompt !== null && typeof systemPrompt.section === 'function') {
402
+ ctx.effect(() => {
403
+ systemPrompt.section({
404
+ name: 'tool:dsh-credential-vault',
405
+ order: 118,
406
+ text:
407
+ '凭据保险箱:用户把账号密码、API Key、微信公众号 / 小程序开发信息、通用密钥、恢复码等保存在侧边栏「凭据保险箱」里。需要知道有哪些凭据时用 dsh_credential_vault_read 工具(按 query / category 过滤,category 可选 account / apikey / secretKey / other / wechatMp / wechatMini;数据多时先用 mode="summary" 看标题清单,再用 limit/offset 翻页)。出于安全,该工具只返回元数据——密码 / API Key / 密钥值 / AppSecret / Token / 上传密钥等一律显示为 ••••••••,明文只留在浏览器内、不会进入模型上下文,revealSecrets 参数已失效。不要向用户索要明文密钥;需要用到具体密钥时,请让用户自行在侧边栏面板中查看或复制。',
408
+ })
409
+ return () => {}
410
+ }, 'dsh-credential-vault-prompt')
411
+ }
412
+ }