@mysterycode-liwen/dsh-credential-vault 1.4.2 → 1.5.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.js CHANGED
@@ -1,436 +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
- * The in-memory snapshot is intentionally tiny: the browser re-syncs on every
10
- * change and on mount, so it is always the source of truth; the Host just
11
- * mirrors the last payload.
12
- *
13
- * @module dsh-credential-vault
14
- */
15
-
16
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
17
- import { homedir } from 'node:os'
18
- import { join, resolve } from 'node:path'
19
-
20
- /** Cordis plugin name. */
21
- export const name = 'dsh-credential-vault'
22
-
23
- /** The web server is the only hard dependency. */
24
- export const inject = ['webServer']
25
-
26
- /** Route prefix owned by this plugin. */
27
- const PREFIX = '/dsh-credential-vault'
28
-
29
- /** Cap the synced payload so a stray client cannot blow up the Host. Raised for large vaults. */
30
- const MAX_BODY_BYTES = 16 * 1024 * 1024
31
-
32
- /** Max entries mirrored from the browser; beyond this the tool output would be unwieldy. */
33
- const MAX_ENTRIES = 20000
34
-
35
- /** Fields that hold secrets; masked by default in tool output. */
36
- const SECRET_FIELDS = ['password', 'apiKey', 'content']
37
- const MASK = '••••••••'
38
-
39
- /** Pagination defaults / limits for the read tool. */
40
- const DEFAULT_LIMIT = 20
41
- const MAX_LIMIT = 200
42
-
43
- /** Fields kept in the compact "summary" projection. */
44
- const SUMMARY_FIELDS = ['id', 'title', 'category', 'username', 'provider', 'expiry', 'updatedAt']
45
-
46
- /** Current plugin version. Keep in sync with package.json when releasing. */
47
- const CURRENT_VERSION = '1.2.0'
48
-
49
- /** Where update checks read the latest published version from (GitHub Releases latest). */
50
- const RELEASES_API = 'https://api.github.com/repos/mysterycode-liwen/dsh-credential-vault/releases/latest'
51
- const RELEASES_URL = 'https://github.com/mysterycode-liwen/dsh-credential-vault/releases/latest'
52
- const UPDATE_CHECK_TIMEOUT_MS = 8000
53
- const UPDATE_CACHE_MS = 10 * 60 * 1000
54
- let updateCache = { at: 0, result: null }
55
-
56
- /** Last snapshot received from the browser. */
57
- let snapshot = { entries: [], updatedAt: 0 }
58
-
59
- /** Resolve DSH home the same way the Harness does: config > $DSH_HOME > ~/.dsh. */
60
- function resolveHome(configured, env) {
61
- const fromEnv = typeof env.DSH_HOME === 'string' && env.DSH_HOME.trim() !== '' ? env.DSH_HOME : undefined
62
- const raw = configured !== undefined && configured !== null && configured !== '' ? configured : (fromEnv || join(homedir(), '.dsh'))
63
- const expanded = typeof raw === 'string' && raw === '~' ? homedir()
64
- : typeof raw === 'string' && (raw.startsWith('~/') || raw.startsWith('~\\')) ? join(homedir(), raw.slice(2))
65
- : raw
66
- return resolve(expanded)
67
- }
68
-
69
- /** Durable store for the mirrored vault, so the tool still works after restart. */
70
- function createStore(home) {
71
- const dir = join(home, 'dsh-credential-vault')
72
- const legacyDir = join(home, 'credential-vault')
73
- const file = join(dir, 'vault.json')
74
- const legacyFile = join(legacyDir, 'vault.json')
75
- return {
76
- async restore() {
77
- try {
78
- const parsed = JSON.parse(await readFile(file, 'utf8'))
79
- if (parsed && Array.isArray(parsed.entries)) {
80
- snapshot = { entries: parsed.entries, updatedAt: Number(parsed.updatedAt) || 0 }
81
- return
82
- }
83
- } catch {
84
- // No file at the renamed location yet: fall through to the legacy path.
85
- }
86
- // One-time migration from the pre-rename store location.
87
- try {
88
- const parsed = JSON.parse(await readFile(legacyFile, 'utf8'))
89
- if (parsed && Array.isArray(parsed.entries)) {
90
- snapshot = { entries: parsed.entries, updatedAt: Number(parsed.updatedAt) || 0 }
91
- try {
92
- await mkdir(dir, { recursive: true })
93
- await writeFile(file, JSON.stringify(snapshot), 'utf8')
94
- } catch {
95
- // Migration write is best-effort; the in-memory snapshot still works.
96
- }
97
- }
98
- } catch {
99
- // Nothing to restore: start with an empty snapshot.
100
- }
101
- },
102
- async persist(next) {
103
- try {
104
- await mkdir(dir, { recursive: true })
105
- const tmp = file + '.tmp'
106
- await writeFile(tmp, JSON.stringify(next), 'utf8')
107
- await rename(tmp, file)
108
- } catch {
109
- // Persistence is best-effort; the in-memory snapshot still works.
110
- }
111
- },
112
- }
113
- }
114
-
115
- // --- tiny HTTP helpers (self-contained so the bundle stays 7 files) --------
116
-
117
- function isLoopback(req) {
118
- const address = req && req.socket ? req.socket.remoteAddress : undefined
119
- if (address === undefined) return true
120
- return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1' || address.startsWith('127.')
121
- }
122
-
123
- function isSameOrigin(req) {
124
- const origin = req && req.headers ? req.headers.origin : undefined
125
- if (typeof origin !== 'string' || origin === '') return true
126
- const host = req && req.headers ? req.headers.host : undefined
127
- if (typeof host !== 'string' || host === '') return false
128
- try {
129
- return new URL(origin).host === host
130
- } catch {
131
- return false
132
- }
133
- }
134
-
135
- function sendJson(res, status, payload) {
136
- if (!res || res.writableEnded || res.destroyed) return
137
- const body = JSON.stringify(payload)
138
- res.writeHead(status, {
139
- 'content-type': 'application/json; charset=utf-8',
140
- 'cache-control': 'no-store',
141
- 'content-length': Buffer.byteLength(body),
142
- })
143
- res.end(body)
144
- }
145
-
146
- function fail(res, status, code, message) {
147
- sendJson(res, status, { ok: false, error: { code, ...(message === undefined ? {} : { message }) } })
148
- }
149
-
150
- function readJson(req, cap = MAX_BODY_BYTES) {
151
- return new Promise((resolve, reject) => {
152
- const chunks = []
153
- let size = 0
154
- req.on('data', (chunk) => {
155
- size += chunk.length
156
- if (size > cap) {
157
- reject(new Error('body too large'))
158
- req.destroy()
159
- return
160
- }
161
- chunks.push(chunk)
162
- })
163
- req.on('end', () => {
164
- try {
165
- resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
166
- } catch {
167
- reject(new Error('invalid json'))
168
- }
169
- })
170
- req.on('error', reject)
171
- })
172
- }
173
-
174
- // --- update check helpers --------------------------------------------------
175
-
176
- /** Parse a semver-ish tag into comparable parts. Returns null when unparseable. */
177
- function parseSemver(value) {
178
- if (typeof value !== 'string') return null
179
- const m = value.trim().replace(/^v/i, '').match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/)
180
- if (!m) return null
181
- return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]), prerelease: m[4] || '' }
182
- }
183
-
184
- /** Compare two parsed semvers: -1 (left older), 0 (equal), 1 (left newer). */
185
- function compareSemver(l, r) {
186
- const parts = ['major', 'minor', 'patch']
187
- for (const key of parts) {
188
- if (l[key] !== r[key]) return l[key] < r[key] ? -1 : 1
189
- }
190
- if (!l.prerelease && !r.prerelease) return 0
191
- if (!l.prerelease) return 1
192
- if (!r.prerelease) return -1
193
- return l.prerelease < r.prerelease ? -1 : l.prerelease > r.prerelease ? 1 : 0
194
- }
195
-
196
- /** Fetch the latest Release tag from GitHub, with a timeout and short cache. */
197
- async function checkForUpdate() {
198
- if (updateCache.result && Date.now() - updateCache.at < UPDATE_CACHE_MS) {
199
- return Object.assign({}, updateCache.result, { cached: true })
200
- }
201
- const fetchImpl = typeof globalThis.fetch === 'function' ? globalThis.fetch.bind(globalThis) : undefined
202
- if (!fetchImpl) throw new Error('fetch is not available on this Node runtime')
203
- let signal
204
- try { signal = AbortSignal.timeout(UPDATE_CHECK_TIMEOUT_MS) } catch { /* no timeout support */ }
205
- const response = await fetchImpl(RELEASES_API, {
206
- headers: { accept: 'application/vnd.github+json', 'user-agent': 'dsh-credential-vault-update-check' },
207
- ...(signal ? { signal } : {}),
208
- })
209
- if (!response.ok) throw new Error('GitHub API returned ' + response.status)
210
- const body = await response.json()
211
- const tag = body && typeof body.tag_name === 'string' ? body.tag_name : ''
212
- const latest = parseSemver(tag)
213
- if (!latest) throw new Error('Latest release tag is not a valid version: ' + tag)
214
- const current = parseSemver(CURRENT_VERSION) || { major: 0, minor: 0, patch: 0, prerelease: '' }
215
- const result = {
216
- ok: true,
217
- currentVersion: CURRENT_VERSION,
218
- latestVersion: tag.replace(/^v/i, ''),
219
- updateAvailable: compareSemver(current, latest) < 0,
220
- releaseUrl: RELEASES_URL,
221
- checkedAt: new Date().toISOString(),
222
- cached: false,
223
- }
224
- updateCache = { at: Date.now(), result }
225
- return result
226
- }
227
-
228
- // --- HTTP surface ----------------------------------------------------------
229
-
230
- async function handle(req, res, store) {
231
- try {
232
- if (!isLoopback(req)) return fail(res, 403, 'NOT_LOOPBACK')
233
- if (!isSameOrigin(req)) return fail(res, 403, 'BAD_ORIGIN')
234
-
235
- let pathname = (req.url || '/').split('?')[0]
236
- if (pathname.startsWith(PREFIX)) pathname = pathname.slice(PREFIX.length) || '/'
237
- const method = (req.method || 'GET').toUpperCase()
238
-
239
- // Browser -> Host: replace the snapshot with the browser's current vault.
240
- if (pathname === '/entries' && method === 'POST') {
241
- let body
242
- try {
243
- body = await readJson(req)
244
- } catch (error) {
245
- return fail(res, 400, 'BAD_JSON', String(error && error.message ? error.message : error))
246
- }
247
- const list = body && Array.isArray(body.entries) ? body.entries : null
248
- if (!list) return fail(res, 400, 'BAD_ENTRIES', 'expected { entries: [] }')
249
- // Keep only plain objects, and cap the count defensively.
250
- const entries = list.filter((e) => e !== null && typeof e === 'object' && !Array.isArray(e)).slice(0, MAX_ENTRIES)
251
- snapshot = { entries, updatedAt: Date.now() }
252
- await store.persist(snapshot)
253
- return sendJson(res, 200, { ok: true, count: entries.length, truncated: list.length > entries.length })
254
- }
255
-
256
- // Debug / inspection: return a bounded page of the current snapshot.
257
- if (pathname === '/entries' && method === 'GET') {
258
- const url = new URL(req.url || '/', 'http://localhost')
259
- const limit = Math.max(1, Math.min(MAX_LIMIT, Number(url.searchParams.get('limit')) || DEFAULT_LIMIT))
260
- const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0)
261
- const page = snapshot.entries.slice(offset, offset + limit)
262
- return sendJson(res, 200, {
263
- ok: true,
264
- total: snapshot.entries.length,
265
- returned: page.length,
266
- offset,
267
- limit,
268
- entries: page,
269
- updatedAt: snapshot.updatedAt,
270
- })
271
- }
272
-
273
- // Check GitHub Releases latest for a newer plugin version.
274
- if (pathname === '/update-check' && method === 'GET') {
275
- try {
276
- return sendJson(res, 200, await checkForUpdate())
277
- } catch (error) {
278
- return sendJson(res, 200, {
279
- ok: false,
280
- currentVersion: CURRENT_VERSION,
281
- error: String(error && error.message ? error.message : error),
282
- checkedAt: new Date().toISOString(),
283
- })
284
- }
285
- }
286
-
287
- return fail(res, 404, 'NOT_FOUND')
288
- } catch (error) {
289
- return fail(res, 500, 'INTERNAL', String(error && error.message ? error.message : error))
290
- }
291
- }
292
-
293
- // --- tool projection helpers ----------------------------------------------
294
-
295
- function projectEntry(entry, revealSecrets, mode) {
296
- const keys = mode === 'summary' ? SUMMARY_FIELDS : Object.keys(entry)
297
- const out = {}
298
- for (const key of keys) {
299
- const value = entry[key]
300
- if (value === null || value === undefined || value === '') continue
301
- if (SECRET_FIELDS.includes(key)) {
302
- // Secrets never appear in summary mode, whatever revealSecrets says.
303
- out[key] = (revealSecrets && mode !== 'summary') ? value : MASK
304
- } else {
305
- out[key] = value
306
- }
307
- }
308
- return out
309
- }
310
-
311
- function matches(entry, query, category) {
312
- if (category && category !== 'all' && entry.category !== category) return false
313
- if (!query) return true
314
- const q = query.toLowerCase()
315
- const haystack = [entry.title, entry.username, entry.provider, entry.url, entry.endpoint, entry.notes]
316
- .filter((v) => typeof v === 'string')
317
- .join(' ')
318
- .toLowerCase()
319
- return haystack.includes(q)
320
- }
321
-
322
- /**
323
- * @param {import('@deepseek-ai/cordis').Context} ctx
324
- */
325
- export function apply(ctx, rawConfig) {
326
- const config = rawConfig !== null && typeof rawConfig === 'object' ? rawConfig : {}
327
- const store = createStore(resolveHome(config.dshHome, process.env))
328
- void store.restore()
329
-
330
- ctx.effect(() => {
331
- const dispose = ctx.webServer.register({
332
- kind: 'prefix',
333
- path: PREFIX,
334
- handler: (req, res) => handle(req, res, store),
335
- })
336
- return () => {
337
- if (typeof dispose === 'function') dispose()
338
- }
339
- })
340
-
341
- // Tools / systemPrompt are optional services: read them defensively so the
342
- // plugin still loads where they are unavailable.
343
- const tools = typeof ctx.get === 'function' ? ctx.get('tools') : undefined
344
- if (tools !== undefined && tools !== null && typeof tools.register === 'function') {
345
- ctx.effect(() => {
346
- const dispose = tools.register(
347
- {
348
- name: 'dsh_credential_vault_read',
349
- description:
350
- 'Read the contents of the user\'s local credential vault (accounts, passwords, API keys, other secrets 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. By default secret values are masked; set revealSecrets to true (with mode="full") to include the actual passwords / API keys. Use this when the user asks you to look up, list, or use a credential saved in the vault.',
351
- parameters: {
352
- type: 'object',
353
- properties: {
354
- query: {
355
- type: 'string',
356
- description: 'Optional text to filter by title, account, provider, URL or notes (case-insensitive substring).',
357
- },
358
- category: {
359
- type: 'string',
360
- enum: ['all', 'account', 'apikey', 'other'],
361
- description: 'Only return entries of this category. Defaults to all.',
362
- },
363
- mode: {
364
- type: 'string',
365
- enum: ['summary', 'full'],
366
- description: 'summary = only id/title/category/account/provider/expiry (lightweight, recommended for browsing); full = all fields with secrets masked unless revealSecrets. Defaults to full.',
367
- },
368
- limit: {
369
- type: 'number',
370
- description: 'Page size, 1-200. Defaults to 20. Use with offset to page through large vaults.',
371
- },
372
- offset: {
373
- type: 'number',
374
- description: 'How many matching entries to skip. Defaults to 0. Increase by limit to get the next page.',
375
- },
376
- revealSecrets: {
377
- type: 'boolean',
378
- description: 'If true (and mode="full"), include the real password / API key / secret values instead of a masked placeholder. Defaults to false. Ignored in summary mode.',
379
- },
380
- },
381
- additionalProperties: false,
382
- },
383
- output: {
384
- schema: {
385
- type: 'object',
386
- properties: {
387
- total: { type: 'number' },
388
- returned: { type: 'number' },
389
- hasMore: { type: 'boolean' },
390
- entries: { type: 'array', items: { type: 'object' } },
391
- },
392
- additionalProperties: true,
393
- },
394
- render: () => [{ type: 'text', text: 'dsh_credential_vault_read' }],
395
- },
396
- async execute(args) {
397
- const a = args !== null && typeof args === 'object' ? args : {}
398
- const query = typeof a.query === 'string' ? a.query : ''
399
- const category = typeof a.category === 'string' ? a.category : 'all'
400
- const mode = a.mode === 'summary' ? 'summary' : 'full'
401
- const revealSecrets = a.revealSecrets === true
402
- const limit = Math.max(1, Math.min(MAX_LIMIT, Number.isFinite(a.limit) ? Math.floor(a.limit) : DEFAULT_LIMIT))
403
- const offset = Math.max(0, Number.isFinite(a.offset) ? Math.floor(a.offset) : 0)
404
- const all = Array.isArray(snapshot.entries) ? snapshot.entries : []
405
- const filtered = all.filter((e) => matches(e, query, category))
406
- const page = filtered.slice(offset, offset + limit)
407
- return {
408
- total: filtered.length,
409
- returned: page.length,
410
- offset,
411
- limit,
412
- hasMore: offset + page.length < filtered.length,
413
- updatedAt: snapshot.updatedAt,
414
- entries: page.map((e) => projectEntry(e, revealSecrets, mode)),
415
- }
416
- },
417
- },
418
- {},
419
- )
420
- return typeof dispose === 'function' ? dispose : () => {}
421
- }, 'dsh-credential-vault-read-tool')
422
- }
423
-
424
- const systemPrompt = typeof ctx.get === 'function' ? ctx.get('systemPrompt') : undefined
425
- if (systemPrompt !== undefined && systemPrompt !== null && typeof systemPrompt.section === 'function') {
426
- ctx.effect(() => {
427
- systemPrompt.section({
428
- name: 'tool:dsh-credential-vault',
429
- order: 118,
430
- text:
431
- '凭据保险箱:用户把账号密码、API Key、恢复码等保存在侧边栏「凭据保险箱」里。需要查询这些凭据时用 dsh_credential_vault_read 工具(按 query / category 过滤;数据多时先用 mode="summary" 看标题清单,再用 limit/offset 翻页;默认隐藏密钥,mode="full" 且 revealSecrets:true 才返回明文)。',
432
- })
433
- return () => {}
434
- }, 'dsh-credential-vault-prompt')
435
- }
436
- }
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']
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.0'
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',
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', '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 / other / wechatMp / wechatMini;数据多时先用 mode="summary" 看标题清单,再用 limit/offset 翻页)。出于安全,该工具只返回元数据——密码 / API Key / AppSecret / Token / 上传密钥等一律显示为 ••••••••,明文只留在浏览器内、不会进入模型上下文,revealSecrets 参数已失效。不要向用户索要明文密钥;需要用到具体密钥时,请让用户自行在侧边栏面板中查看或复制。',
408
+ })
409
+ return () => {}
410
+ }, 'dsh-credential-vault-prompt')
411
+ }
412
+ }