dsh-chat-background 0.0.0-stage → 1.0.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/CHANGELOG.md +24 -0
- package/LICENSE +21 -0
- package/README.en.md +128 -0
- package/README.md +124 -2
- package/assets/screenshots/main-ui.png +0 -0
- package/assets/screenshots/settings-page.png +0 -0
- package/client.js +3229 -0
- package/cordis.patch.yml +4 -0
- package/docs/ARCHITECTURE.md +225 -0
- package/docs/CONVENTIONS.md +181 -0
- package/docs/DEVELOPMENT.md +127 -0
- package/docs/PUBLISHING.md +105 -0
- package/docs/TESTING.md +127 -0
- package/docs/TROUBLESHOOTING.md +121 -0
- package/host/constants.js +87 -0
- package/host/media.js +153 -0
- package/host/paths.js +43 -0
- package/host/routes.js +504 -0
- package/host/token-usage.js +171 -0
- package/icon.svg +27 -0
- package/index.js +132 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +88 -4
package/host/routes.js
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP handlers for the four routes this plugin owns.
|
|
3
|
+
*
|
|
4
|
+
* The Web server hands the raw Node `request`/`response` pair over, so this
|
|
5
|
+
* module owns status codes, headers, bodies and failure text. Only `node:`
|
|
6
|
+
* builtins are imported: a profile-installed package cannot resolve the
|
|
7
|
+
* installation's `@deepseek-ai/*` packages.
|
|
8
|
+
*
|
|
9
|
+
* Security model (`SEC-01`, `SEC-02`, `SEC-04`, `SEC-06`):
|
|
10
|
+
* - the routes are same-origin resources on a local, unauthenticated server,
|
|
11
|
+
* so every request passes the same kind of fence the Host `/api` route
|
|
12
|
+
* implements: a loopback/known `Host`, no `Sec-Fetch-Site: cross-site`, and
|
|
13
|
+
* an `Origin`, when present, equal to the request authority;
|
|
14
|
+
* - the image manifest is the only set of names the file route serves;
|
|
15
|
+
* - every response carries nosniff/CORP/referrer headers, and SVG (the only
|
|
16
|
+
* accepted format browsers can execute when opened top-level) also carries
|
|
17
|
+
* a sandboxing CSP.
|
|
18
|
+
*/
|
|
19
|
+
import { spawn } from 'node:child_process'
|
|
20
|
+
import { constants as fsConstants } from 'node:fs'
|
|
21
|
+
import { mkdir, open } from 'node:fs/promises'
|
|
22
|
+
import { homedir } from 'node:os'
|
|
23
|
+
import { join, relative } from 'node:path'
|
|
24
|
+
import {
|
|
25
|
+
FILE_PREFIX,
|
|
26
|
+
FOLDER_HEADER,
|
|
27
|
+
FOLDER_HEADER_VALUE,
|
|
28
|
+
IMAGE_CACHE_CONTROL,
|
|
29
|
+
IMAGE_DOCUMENT_CSP,
|
|
30
|
+
MANIFEST_CACHE_MS,
|
|
31
|
+
MAX_IMAGE_BYTES,
|
|
32
|
+
MAX_MANIFEST_ENTRIES,
|
|
33
|
+
SECURITY_HEADERS,
|
|
34
|
+
TOKEN_CACHE_MS
|
|
35
|
+
} from './constants.js'
|
|
36
|
+
import {
|
|
37
|
+
ACCEPTED_EXTENSIONS,
|
|
38
|
+
findManifestEntry,
|
|
39
|
+
mediaTypeFor,
|
|
40
|
+
readImageManifestDetailed,
|
|
41
|
+
safeImageName
|
|
42
|
+
} from './media.js'
|
|
43
|
+
import { missingTotalsPayload, readTokenTotals } from './token-usage.js'
|
|
44
|
+
|
|
45
|
+
/** How long the folder-open child may take to report success before failing. */
|
|
46
|
+
const SPAWN_TIMEOUT_MS = 2_500
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Open flags for image reads. POSIX gets O_NOFOLLOW, so a file swapped for a
|
|
50
|
+
* symlink after the manifest check cannot be followed outside the folder
|
|
51
|
+
* (SEC-05); Windows has no equivalent final-component guarantee and uses a
|
|
52
|
+
* plain read.
|
|
53
|
+
*/
|
|
54
|
+
const IMAGE_OPEN_FLAGS = process.platform === 'win32' ? 'r' : fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Merge the headers every response carries.
|
|
58
|
+
* @param extra - route-specific headers.
|
|
59
|
+
*/
|
|
60
|
+
function withSecurityHeaders(extra = {}) {
|
|
61
|
+
return { ...SECURITY_HEADERS, ...extra }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Write a JSON body.
|
|
66
|
+
* @param response - Node response.
|
|
67
|
+
* @param status - HTTP status code.
|
|
68
|
+
* @param value - JSON-serialisable payload.
|
|
69
|
+
* @param options - `head` for a HEAD answer, plus extra headers.
|
|
70
|
+
*/
|
|
71
|
+
function sendJson(response, status, value, options = {}) {
|
|
72
|
+
const body = Buffer.from(`${JSON.stringify(value)}\n`, 'utf8')
|
|
73
|
+
response.writeHead(
|
|
74
|
+
status,
|
|
75
|
+
withSecurityHeaders({
|
|
76
|
+
'content-type': 'application/json; charset=utf-8',
|
|
77
|
+
'content-length': String(body.byteLength),
|
|
78
|
+
'cache-control': 'no-store',
|
|
79
|
+
...(options.headers ?? {})
|
|
80
|
+
})
|
|
81
|
+
)
|
|
82
|
+
response.end(options.head === true ? undefined : body)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Write a plain-text failure; the browser half surfaces the message verbatim.
|
|
87
|
+
* @param response - Node response.
|
|
88
|
+
* @param status - HTTP status code.
|
|
89
|
+
* @param message - one line of human-readable text.
|
|
90
|
+
* @param options - `head` for a HEAD answer, plus extra headers.
|
|
91
|
+
*/
|
|
92
|
+
function sendError(response, status, message, options = {}) {
|
|
93
|
+
const body = Buffer.from(`${message}\n`, 'utf8')
|
|
94
|
+
response.writeHead(
|
|
95
|
+
status,
|
|
96
|
+
withSecurityHeaders({
|
|
97
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
98
|
+
'content-length': String(body.byteLength),
|
|
99
|
+
'cache-control': 'no-store',
|
|
100
|
+
...(options.headers ?? {})
|
|
101
|
+
})
|
|
102
|
+
)
|
|
103
|
+
response.end(options.head === true ? undefined : body)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Log a caught value without assuming it is an `Error`.
|
|
108
|
+
* @param logger - host logger.
|
|
109
|
+
* @param error - caught value.
|
|
110
|
+
*/
|
|
111
|
+
function logFailure(logger, error) {
|
|
112
|
+
logger?.warn?.(error instanceof Error ? error : new Error(String(error)))
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The request method, defaulting to GET when absent. */
|
|
116
|
+
function methodOf(request) {
|
|
117
|
+
return (request.method ?? 'GET').toUpperCase()
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Reject a method the route does not answer.
|
|
122
|
+
* @returns whether the caller may continue.
|
|
123
|
+
*/
|
|
124
|
+
function allowMethod(request, response, methods) {
|
|
125
|
+
const method = methodOf(request)
|
|
126
|
+
if (methods.includes(method)) return true
|
|
127
|
+
sendError(response, 405, 'method not allowed', { headers: { allow: methods.join(', ') } })
|
|
128
|
+
return false
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The request pathname, or null when the URL cannot be parsed.
|
|
133
|
+
* @param request - Node request.
|
|
134
|
+
*/
|
|
135
|
+
function requestPath(request) {
|
|
136
|
+
try {
|
|
137
|
+
return new URL(request.url ?? '/', 'http://localhost').pathname
|
|
138
|
+
} catch {
|
|
139
|
+
return null
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Whether an `If-None-Match` header names the given entity tag. Weak prefixes
|
|
145
|
+
* and comma-separated lists are accepted, per RFC 9110.
|
|
146
|
+
* @param request - Node request.
|
|
147
|
+
* @param etag - strong entity tag, quotes included.
|
|
148
|
+
*/
|
|
149
|
+
function isNotModified(request, etag) {
|
|
150
|
+
const header = request.headers['if-none-match']
|
|
151
|
+
if (typeof header !== 'string' || header === '') return false
|
|
152
|
+
return header
|
|
153
|
+
.split(',')
|
|
154
|
+
.map((tag) => tag.trim())
|
|
155
|
+
.some((tag) => tag.replace(/^W\//iu, '') === etag)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* The requester's `Host`, parsed. The browser always sends it from the URL,
|
|
160
|
+
* which is why it is the anchor of the DNS-rebinding fence (`SEC-02`).
|
|
161
|
+
* @param request - Node request.
|
|
162
|
+
* @returns the parsed authority, or null when missing/malformed.
|
|
163
|
+
*/
|
|
164
|
+
function requestAuthority(request) {
|
|
165
|
+
const raw = request.headers.host
|
|
166
|
+
if (typeof raw !== 'string' || raw === '') return null
|
|
167
|
+
try {
|
|
168
|
+
const url = new URL(`http://${raw}`)
|
|
169
|
+
return { host: url.host, hostname: url.hostname.toLowerCase() }
|
|
170
|
+
} catch {
|
|
171
|
+
return null
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Whether a browser request is marked as same-origin (or as no-cors `none`,
|
|
177
|
+
* which a direct address-bar navigation sends). Requests without the header are
|
|
178
|
+
* accepted so older clients keep working; the header is defence in depth on top
|
|
179
|
+
* of the Host/Origin fence.
|
|
180
|
+
* @param request - Node request.
|
|
181
|
+
* @returns whether the Fetch metadata allows the side effect.
|
|
182
|
+
*/
|
|
183
|
+
function hasSameOriginFetch(request) {
|
|
184
|
+
const site = request.headers['sec-fetch-site']
|
|
185
|
+
return typeof site !== 'string' || site === 'same-origin' || site === 'none'
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Whether the request comes from the application's own browser context.
|
|
190
|
+
* @param request - Node request.
|
|
191
|
+
* @param trustedHosts - accepted host names, or null to disable the host check.
|
|
192
|
+
*/
|
|
193
|
+
function isTrustedRequest(request, trustedHosts) {
|
|
194
|
+
const authority = requestAuthority(request)
|
|
195
|
+
if (authority === null) return false
|
|
196
|
+
if (trustedHosts !== null && !trustedHosts.has(authority.hostname)) return false
|
|
197
|
+
if (request.headers['sec-fetch-site'] === 'cross-site') return false
|
|
198
|
+
const origin = request.headers.origin
|
|
199
|
+
if (typeof origin === 'string' && origin !== '') {
|
|
200
|
+
if (origin === 'null') return false
|
|
201
|
+
try {
|
|
202
|
+
if (new URL(origin).host !== authority.host) return false
|
|
203
|
+
} catch {
|
|
204
|
+
return false
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return true
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* The folder path as shown to the user: the home directory is abbreviated, so
|
|
212
|
+
* responses do not leak the OS user name and full directory layout (`SEC-03`).
|
|
213
|
+
* @param folder - absolute folder path.
|
|
214
|
+
*/
|
|
215
|
+
function displayFolder(folder) {
|
|
216
|
+
const home = homedir()
|
|
217
|
+
if (folder === home) return '~'
|
|
218
|
+
const separator = process.platform === 'win32' ? '\\' : '/'
|
|
219
|
+
if (folder.startsWith(`${home}${separator}`)) return `~${folder.slice(home.length)}`
|
|
220
|
+
return folder
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Reveal a directory in the platform file manager.
|
|
225
|
+
*
|
|
226
|
+
* Resolves once the file manager process actually spawned (or after a short
|
|
227
|
+
* grace period on platforms that report no spawn event) and rejects when it
|
|
228
|
+
* cannot start, so the route can answer honestly (`SEC-07`).
|
|
229
|
+
* @param dir - absolute directory path.
|
|
230
|
+
* @param logger - host logger.
|
|
231
|
+
*/
|
|
232
|
+
function openInFileManager(dir, logger) {
|
|
233
|
+
const command = process.platform === 'win32' ? 'explorer.exe' : process.platform === 'darwin' ? 'open' : 'xdg-open'
|
|
234
|
+
return new Promise((resolve, reject) => {
|
|
235
|
+
let child
|
|
236
|
+
try {
|
|
237
|
+
child = spawn(command, [dir], { detached: true, stdio: 'ignore' })
|
|
238
|
+
} catch (error) {
|
|
239
|
+
reject(error)
|
|
240
|
+
return
|
|
241
|
+
}
|
|
242
|
+
let settled = false
|
|
243
|
+
/** @param {Error | undefined} error */
|
|
244
|
+
const finish = (error) => {
|
|
245
|
+
if (settled) return
|
|
246
|
+
settled = true
|
|
247
|
+
clearTimeout(timer)
|
|
248
|
+
if (error !== undefined) reject(error)
|
|
249
|
+
else resolve()
|
|
250
|
+
}
|
|
251
|
+
const timer = setTimeout(() => {
|
|
252
|
+
child.kill()
|
|
253
|
+
finish(new Error(`file manager did not succeed: ${command}`))
|
|
254
|
+
}, SPAWN_TIMEOUT_MS)
|
|
255
|
+
child.once('error', (error) => {
|
|
256
|
+
logFailure(logger, error)
|
|
257
|
+
finish(error)
|
|
258
|
+
})
|
|
259
|
+
if (process.platform === 'win32') {
|
|
260
|
+
/* explorer.exe keeps running; a successful spawn is the best signal. */
|
|
261
|
+
child.once('spawn', () => {
|
|
262
|
+
child.unref()
|
|
263
|
+
finish()
|
|
264
|
+
})
|
|
265
|
+
} else {
|
|
266
|
+
/* open / xdg-open exit quickly and report failure through the exit code. */
|
|
267
|
+
child.once('exit', (code) => {
|
|
268
|
+
if (code === 0) finish()
|
|
269
|
+
else finish(new Error(`file manager exited with code ${String(code)}: ${command}`))
|
|
270
|
+
})
|
|
271
|
+
}
|
|
272
|
+
})
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Build the shared route handlers for one folder.
|
|
277
|
+
* @param options - resolved folder, logger, token provider, request fence and limits.
|
|
278
|
+
* @returns the route handlers keyed by route.
|
|
279
|
+
*/
|
|
280
|
+
export function createHandlers({
|
|
281
|
+
folder,
|
|
282
|
+
logger,
|
|
283
|
+
tokenDirectory,
|
|
284
|
+
tokenProvider = null,
|
|
285
|
+
tokenCacheMs = TOKEN_CACHE_MS,
|
|
286
|
+
manifestCacheMs = MANIFEST_CACHE_MS,
|
|
287
|
+
trustedHosts = null,
|
|
288
|
+
maxImageBytes = MAX_IMAGE_BYTES,
|
|
289
|
+
version = 'unknown'
|
|
290
|
+
}) {
|
|
291
|
+
const readTokenPayload = tokenProvider ?? (async () => readTokenTotals(tokenDirectory))
|
|
292
|
+
|
|
293
|
+
/* The scan reads every session's projection, so its result is reused for a
|
|
294
|
+
* short window while the browser polls. A missing cache is cached as a zero
|
|
295
|
+
* payload too, so an early page load does not rescan on every request. */
|
|
296
|
+
let tokenCache = { at: 0, payload: null }
|
|
297
|
+
|
|
298
|
+
/* `list` and `files` share one short-lived directory listing: the manifest is
|
|
299
|
+
* the file route's allow-list, and the settings row asks for it right before
|
|
300
|
+
* the browser fetches the chosen image. */
|
|
301
|
+
let manifestCache = { at: 0, entries: [], truncated: false }
|
|
302
|
+
|
|
303
|
+
async function listManifest() {
|
|
304
|
+
if (manifestCache.at !== 0 && Date.now() - manifestCache.at <= manifestCacheMs) return manifestCache
|
|
305
|
+
const { entries, truncated } = await readImageManifestDetailed(folder)
|
|
306
|
+
manifestCache = { at: Date.now(), entries, truncated }
|
|
307
|
+
return manifestCache
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Apply the request fence.
|
|
312
|
+
* @returns whether the handler may continue.
|
|
313
|
+
*/
|
|
314
|
+
function guard(request, response, head = false) {
|
|
315
|
+
if (isTrustedRequest(request, trustedHosts)) return true
|
|
316
|
+
sendError(response, 403, 'untrusted request origin', { head })
|
|
317
|
+
return false
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
async function list(request, response) {
|
|
321
|
+
const head = methodOf(request) === 'HEAD'
|
|
322
|
+
if (!guard(request, response, head)) return
|
|
323
|
+
if (!allowMethod(request, response, ['GET', 'HEAD'])) return
|
|
324
|
+
try {
|
|
325
|
+
await mkdir(folder, { recursive: true })
|
|
326
|
+
const manifest = await listManifest()
|
|
327
|
+
sendJson(
|
|
328
|
+
response,
|
|
329
|
+
200,
|
|
330
|
+
{
|
|
331
|
+
folder: displayFolder(folder),
|
|
332
|
+
accepted: ACCEPTED_EXTENSIONS,
|
|
333
|
+
images: manifest.entries,
|
|
334
|
+
truncated: manifest.truncated
|
|
335
|
+
},
|
|
336
|
+
{ head }
|
|
337
|
+
)
|
|
338
|
+
} catch (error) {
|
|
339
|
+
logFailure(logger, error)
|
|
340
|
+
sendError(response, 500, 'background folder could not be read', { head })
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
async function tokenTotal(request, response) {
|
|
345
|
+
const head = methodOf(request) === 'HEAD'
|
|
346
|
+
if (!guard(request, response, head)) return
|
|
347
|
+
if (!allowMethod(request, response, ['GET', 'HEAD'])) return
|
|
348
|
+
try {
|
|
349
|
+
const fresh = tokenCache.payload !== null && Date.now() - tokenCache.at <= tokenCacheMs
|
|
350
|
+
if (!fresh) {
|
|
351
|
+
const value = await readTokenPayload()
|
|
352
|
+
tokenCache = { at: Date.now(), payload: value ?? missingTotalsPayload() }
|
|
353
|
+
}
|
|
354
|
+
sendJson(response, 200, tokenCache.payload, { head })
|
|
355
|
+
} catch (error) {
|
|
356
|
+
logFailure(logger, error)
|
|
357
|
+
sendError(response, 500, 'token usage could not be read', { head })
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
async function health(request, response) {
|
|
362
|
+
const head = methodOf(request) === 'HEAD'
|
|
363
|
+
if (!guard(request, response, head)) return
|
|
364
|
+
if (!allowMethod(request, response, ['GET', 'HEAD'])) return
|
|
365
|
+
sendJson(
|
|
366
|
+
response,
|
|
367
|
+
200,
|
|
368
|
+
{
|
|
369
|
+
ok: true,
|
|
370
|
+
version,
|
|
371
|
+
folder: displayFolder(folder),
|
|
372
|
+
accepted: ACCEPTED_EXTENSIONS,
|
|
373
|
+
limits: { maxImageBytes, maxManifestEntries: MAX_MANIFEST_ENTRIES, manifestCacheMs, tokenCacheMs },
|
|
374
|
+
fence: trustedHosts === null ? 'off' : 'on'
|
|
375
|
+
},
|
|
376
|
+
{ head }
|
|
377
|
+
)
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
async function file(request, response) {
|
|
381
|
+
const head = methodOf(request) === 'HEAD'
|
|
382
|
+
if (!guard(request, response, head)) return
|
|
383
|
+
if (!allowMethod(request, response, ['GET', 'HEAD'])) return
|
|
384
|
+
const pathname = requestPath(request)
|
|
385
|
+
const wanted =
|
|
386
|
+
pathname !== null && pathname.startsWith(`${FILE_PREFIX}/`) ? pathname.slice(FILE_PREFIX.length + 1) : ''
|
|
387
|
+
let name
|
|
388
|
+
try {
|
|
389
|
+
name = safeImageName(decodeURIComponent(wanted))
|
|
390
|
+
} catch {
|
|
391
|
+
/* A malformed percent-encoding is just an unknown image. */
|
|
392
|
+
name = undefined
|
|
393
|
+
}
|
|
394
|
+
if (name === undefined) {
|
|
395
|
+
sendError(response, 404, 'unknown background image', { head })
|
|
396
|
+
return
|
|
397
|
+
}
|
|
398
|
+
let entry
|
|
399
|
+
try {
|
|
400
|
+
entry = findManifestEntry((await listManifest()).entries, name)
|
|
401
|
+
} catch (error) {
|
|
402
|
+
logFailure(logger, error)
|
|
403
|
+
sendError(response, 500, 'background folder could not be read', { head })
|
|
404
|
+
return
|
|
405
|
+
}
|
|
406
|
+
if (entry === undefined) {
|
|
407
|
+
/* The manifest is the access-control list: unlisted names, including
|
|
408
|
+
* Windows 8.3 aliases and hidden files, are not served (`SEC-04`). */
|
|
409
|
+
sendError(response, 404, 'unknown background image', { head })
|
|
410
|
+
return
|
|
411
|
+
}
|
|
412
|
+
const target = join(folder, entry.name)
|
|
413
|
+
/* `entry.name` is a listed single segment; keep the containment assertion
|
|
414
|
+
* explicit because this is the only path-shaped input. */
|
|
415
|
+
if (relative(folder, target) !== entry.name) {
|
|
416
|
+
sendError(response, 404, 'unknown background image', { head })
|
|
417
|
+
return
|
|
418
|
+
}
|
|
419
|
+
let handle
|
|
420
|
+
try {
|
|
421
|
+
handle = await open(target, IMAGE_OPEN_FLAGS)
|
|
422
|
+
} catch {
|
|
423
|
+
sendError(response, 404, 'unknown background image', { head })
|
|
424
|
+
return
|
|
425
|
+
}
|
|
426
|
+
let info
|
|
427
|
+
try {
|
|
428
|
+
info = await handle.stat()
|
|
429
|
+
} catch (error) {
|
|
430
|
+
await handle.close().catch(() => {})
|
|
431
|
+
logFailure(logger, error)
|
|
432
|
+
sendError(response, 404, 'unknown background image', { head })
|
|
433
|
+
return
|
|
434
|
+
}
|
|
435
|
+
if (!info.isFile()) {
|
|
436
|
+
await handle.close().catch(() => {})
|
|
437
|
+
sendError(response, 404, 'unknown background image', { head })
|
|
438
|
+
return
|
|
439
|
+
}
|
|
440
|
+
if (info.size > maxImageBytes) {
|
|
441
|
+
await handle.close().catch(() => {})
|
|
442
|
+
sendError(response, 413, 'background image is too large', { head })
|
|
443
|
+
return
|
|
444
|
+
}
|
|
445
|
+
const mediaType = mediaTypeFor(entry.name)
|
|
446
|
+
const etag = `"${info.size.toString(36)}-${Math.floor(info.mtimeMs).toString(36)}"`
|
|
447
|
+
const headers = withSecurityHeaders({
|
|
448
|
+
'content-type': mediaType,
|
|
449
|
+
'content-length': String(info.size),
|
|
450
|
+
etag,
|
|
451
|
+
'cache-control': IMAGE_CACHE_CONTROL
|
|
452
|
+
})
|
|
453
|
+
if (mediaType === 'image/svg+xml') headers['content-security-policy'] = IMAGE_DOCUMENT_CSP
|
|
454
|
+
if (isNotModified(request, etag)) {
|
|
455
|
+
await handle.close().catch(() => {})
|
|
456
|
+
response.writeHead(304, headers)
|
|
457
|
+
response.end()
|
|
458
|
+
return
|
|
459
|
+
}
|
|
460
|
+
if (head) {
|
|
461
|
+
await handle.close().catch(() => {})
|
|
462
|
+
response.writeHead(200, headers)
|
|
463
|
+
response.end()
|
|
464
|
+
return
|
|
465
|
+
}
|
|
466
|
+
response.writeHead(200, headers)
|
|
467
|
+
const stream = handle.createReadStream()
|
|
468
|
+
stream.once('error', (error) => {
|
|
469
|
+
logFailure(logger, error)
|
|
470
|
+
response.destroy()
|
|
471
|
+
})
|
|
472
|
+
/* A browser that navigates away mid-download leaves the read stream open
|
|
473
|
+
* unless the response close is forwarded to it. */
|
|
474
|
+
response.once('close', () => stream.destroy())
|
|
475
|
+
stream.pipe(response)
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
async function revealFolder(request, response) {
|
|
479
|
+
if (!guard(request, response)) return
|
|
480
|
+
if (!allowMethod(request, response, ['POST'])) return
|
|
481
|
+
/* The route is public and has a visible side effect; a cross-site request
|
|
482
|
+
* cannot attach this header without a CORS preflight, which this server
|
|
483
|
+
* does not answer (`BG-10`), and same-origin browser requests additionally
|
|
484
|
+
* carry `Sec-Fetch-Site` (`SEC-02`). */
|
|
485
|
+
if (request.headers[FOLDER_HEADER] !== FOLDER_HEADER_VALUE) {
|
|
486
|
+
sendError(response, 403, 'missing chat-background request header')
|
|
487
|
+
return
|
|
488
|
+
}
|
|
489
|
+
if (!hasSameOriginFetch(request)) {
|
|
490
|
+
sendError(response, 403, 'untrusted request origin')
|
|
491
|
+
return
|
|
492
|
+
}
|
|
493
|
+
try {
|
|
494
|
+
await mkdir(folder, { recursive: true })
|
|
495
|
+
await openInFileManager(folder, logger)
|
|
496
|
+
sendJson(response, 200, { folder: displayFolder(folder), opened: true })
|
|
497
|
+
} catch (error) {
|
|
498
|
+
logFailure(logger, error)
|
|
499
|
+
sendError(response, 500, 'background folder could not be opened')
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
return { list, file, revealFolder, tokenTotal, health }
|
|
504
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* All-sessions token aggregation.
|
|
3
|
+
*
|
|
4
|
+
* Two data sources, preferred first:
|
|
5
|
+
*
|
|
6
|
+
* 1. the documented Host services `sessionPersistence.list()` plus
|
|
7
|
+
* `sessionProjectionCache.cachedSnapshot(header, ['tokenUsage'])`. They
|
|
8
|
+
* return the cached `tokenUsage` projection value directly, are independent
|
|
9
|
+
* of the projection cache's on-disk layout, and work with any storage
|
|
10
|
+
* backend (`SEC` / implementation review: the disk layout is an
|
|
11
|
+
* implementation detail and may change between DSH versions);
|
|
12
|
+
* 2. the original straight scan of
|
|
13
|
+
* `<dsh home>/storages/session_projcache/sessions/*.json`, used when those
|
|
14
|
+
* services are not mounted (older composition, headless profile).
|
|
15
|
+
*
|
|
16
|
+
* The browser half cannot read the host, so it asks through
|
|
17
|
+
* `/chat-backgrounds/token-total`.
|
|
18
|
+
*/
|
|
19
|
+
import { readdir, readFile, stat } from 'node:fs/promises'
|
|
20
|
+
import { join } from 'node:path'
|
|
21
|
+
import { MAX_TOKEN_FILES } from './constants.js'
|
|
22
|
+
|
|
23
|
+
/** The four token buckets every provider records, in display order. */
|
|
24
|
+
export const TOKEN_KEYS = ['uncachedInputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens']
|
|
25
|
+
|
|
26
|
+
/** The projection key the token meter registers. */
|
|
27
|
+
const TOKEN_PROJECTION_KEY = 'tokenUsage'
|
|
28
|
+
|
|
29
|
+
/** One projection file is expected to stay small; skip anything pathological. */
|
|
30
|
+
export const MAX_PROJECTION_BYTES = 8 * 1024 * 1024
|
|
31
|
+
|
|
32
|
+
/** Parallel file reads; enough to keep the scan quick without a file-handle storm. */
|
|
33
|
+
const READ_CONCURRENCY = 8
|
|
34
|
+
|
|
35
|
+
/** Zero-filled bucket object. */
|
|
36
|
+
export function emptyTotals() {
|
|
37
|
+
return Object.fromEntries(TOKEN_KEYS.map((key) => [key, 0]))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Run an async worker over a list with a fixed concurrency.
|
|
42
|
+
* @param items - input values.
|
|
43
|
+
* @param limit - maximum concurrent workers.
|
|
44
|
+
* @param worker - async mapper.
|
|
45
|
+
* @returns results in input order.
|
|
46
|
+
*/
|
|
47
|
+
async function mapWithConcurrency(items, limit, worker) {
|
|
48
|
+
const results = new Array(items.length)
|
|
49
|
+
let cursor = 0
|
|
50
|
+
const run = async () => {
|
|
51
|
+
while (cursor < items.length) {
|
|
52
|
+
const index = cursor
|
|
53
|
+
cursor += 1
|
|
54
|
+
results[index] = await worker(items[index])
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, run))
|
|
58
|
+
return results
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Fold one projection value into the accumulator.
|
|
63
|
+
* @param value - `tokenUsage` projection value (the four buckets) or an unknown.
|
|
64
|
+
* @param totals - accumulator mutated in place.
|
|
65
|
+
* @returns whether any bucket contributed.
|
|
66
|
+
*/
|
|
67
|
+
function foldTokenValue(value, totals) {
|
|
68
|
+
if (value === null || typeof value !== 'object') return false
|
|
69
|
+
let contributed = false
|
|
70
|
+
for (const key of TOKEN_KEYS) {
|
|
71
|
+
const amount = Number(value[key])
|
|
72
|
+
if (Number.isFinite(amount) && amount > 0) {
|
|
73
|
+
totals[key] += amount
|
|
74
|
+
contributed = true
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return contributed
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Sum token usage through the documented Host services.
|
|
82
|
+
*
|
|
83
|
+
* `cachedSnapshot` is documented as "as stale as the last durable checkpoint but
|
|
84
|
+
* never wrong", which matches what the on-disk scan would see.
|
|
85
|
+
* @param options - the two Host services.
|
|
86
|
+
* @returns the summed buckets plus session counts, or null when nothing is readable.
|
|
87
|
+
*/
|
|
88
|
+
export async function readTokenTotalsFromServices({ persistence, projectionCache }) {
|
|
89
|
+
const sessions = await persistence.list()
|
|
90
|
+
if (!Array.isArray(sessions)) return null
|
|
91
|
+
const totals = emptyTotals()
|
|
92
|
+
let countedSessions = 0
|
|
93
|
+
for (const session of sessions) {
|
|
94
|
+
let snapshot
|
|
95
|
+
try {
|
|
96
|
+
snapshot = projectionCache.cachedSnapshot(session?.header, [TOKEN_PROJECTION_KEY])
|
|
97
|
+
} catch {
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
100
|
+
const value = snapshot?.values?.[TOKEN_PROJECTION_KEY]
|
|
101
|
+
if (foldTokenValue(value, totals)) countedSessions += 1
|
|
102
|
+
}
|
|
103
|
+
const total = TOKEN_KEYS.reduce((sum, key) => sum + totals[key], 0)
|
|
104
|
+
return { total, ...totals, sessions: sessions.length, countedSessions, scannedAt: Date.now(), source: 'services' }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Read one projection file and return its token contribution.
|
|
109
|
+
* @param directory - projection-cache directory.
|
|
110
|
+
* @param name - file name.
|
|
111
|
+
* @returns the four buckets when the file contributes, otherwise null.
|
|
112
|
+
*/
|
|
113
|
+
async function readProjectionContribution(directory, name) {
|
|
114
|
+
try {
|
|
115
|
+
const info = await stat(join(directory, name))
|
|
116
|
+
if (!info.isFile() || info.size > MAX_PROJECTION_BYTES) return null
|
|
117
|
+
const parsed = JSON.parse(await readFile(join(directory, name), 'utf8'))
|
|
118
|
+
const value = parsed?.record?.rows?.tokenUsage?.val?.totals
|
|
119
|
+
const contribution = emptyTotals()
|
|
120
|
+
return foldTokenValue(value, contribution) ? contribution : null
|
|
121
|
+
} catch {
|
|
122
|
+
/* A half-written or foreign file simply does not contribute. */
|
|
123
|
+
return null
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Sum token usage by scanning the cached projection files directly. This is the
|
|
129
|
+
* fallback for compositions without the two Host services; the file count is
|
|
130
|
+
* capped so a pathological cache cannot stall the request (`SEC-08`).
|
|
131
|
+
* @param directory - absolute projection-cache directory.
|
|
132
|
+
* @returns the summed buckets plus session counts, or null when the cache is absent.
|
|
133
|
+
*/
|
|
134
|
+
export async function readTokenTotals(directory) {
|
|
135
|
+
let names
|
|
136
|
+
try {
|
|
137
|
+
names = await readdir(directory)
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (error?.code === 'ENOENT') return null
|
|
140
|
+
throw error
|
|
141
|
+
}
|
|
142
|
+
const projections = names.filter((name) => name.endsWith('.json')).slice(0, MAX_TOKEN_FILES)
|
|
143
|
+
const contributions = await mapWithConcurrency(projections, READ_CONCURRENCY, (name) =>
|
|
144
|
+
readProjectionContribution(directory, name)
|
|
145
|
+
)
|
|
146
|
+
const totals = emptyTotals()
|
|
147
|
+
let countedSessions = 0
|
|
148
|
+
for (const contribution of contributions) {
|
|
149
|
+
if (contribution === null) continue
|
|
150
|
+
countedSessions += 1
|
|
151
|
+
for (const key of TOKEN_KEYS) totals[key] += contribution[key]
|
|
152
|
+
}
|
|
153
|
+
const total = TOKEN_KEYS.reduce((sum, key) => sum + totals[key], 0)
|
|
154
|
+
return { total, ...totals, sessions: projections.length, countedSessions, scannedAt: Date.now(), source: 'files' }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The payload served while no projection cache exists yet.
|
|
159
|
+
* @returns an all-zero payload flagged `missing`.
|
|
160
|
+
*/
|
|
161
|
+
export function missingTotalsPayload() {
|
|
162
|
+
return {
|
|
163
|
+
total: 0,
|
|
164
|
+
...emptyTotals(),
|
|
165
|
+
sessions: 0,
|
|
166
|
+
countedSessions: 0,
|
|
167
|
+
scannedAt: Date.now(),
|
|
168
|
+
missing: true,
|
|
169
|
+
source: 'none'
|
|
170
|
+
}
|
|
171
|
+
}
|
package/icon.svg
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256" role="img" aria-label="dsh-chat-background icon">
|
|
2
|
+
<defs>
|
|
3
|
+
<linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
|
|
4
|
+
<stop offset="0" stop-color="#7aa9ff"/>
|
|
5
|
+
<stop offset="1" stop-color="#3e6fe0"/>
|
|
6
|
+
</linearGradient>
|
|
7
|
+
<linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
|
|
8
|
+
<stop offset="0" stop-color="#ffffff"/>
|
|
9
|
+
<stop offset="1" stop-color="#e8f0ff"/>
|
|
10
|
+
</linearGradient>
|
|
11
|
+
<clipPath id="photo">
|
|
12
|
+
<rect x="52" y="44" width="152" height="118" rx="18"/>
|
|
13
|
+
</clipPath>
|
|
14
|
+
</defs>
|
|
15
|
+
<rect width="256" height="256" rx="56" fill="url(#tile)"/>
|
|
16
|
+
<rect x="52" y="44" width="152" height="118" rx="18" fill="url(#sky)"/>
|
|
17
|
+
<g clip-path="url(#photo)">
|
|
18
|
+
<circle cx="166" cy="80" r="14" fill="#ffd166"/>
|
|
19
|
+
<path d="M52 150 L104 96 L134 128 L156 108 L204 150 L204 162 L52 162 Z" fill="#8faee4"/>
|
|
20
|
+
<path d="M52 158 L92 120 L122 150 L146 132 L204 162 L204 162 L52 162 Z" fill="#5f84c9"/>
|
|
21
|
+
</g>
|
|
22
|
+
<rect x="96" y="138" width="112" height="62" rx="20" fill="#ffffff" opacity="0.97"/>
|
|
23
|
+
<path d="M118 198 L110 216 L138 200 Z" fill="#ffffff" opacity="0.97"/>
|
|
24
|
+
<circle cx="133" cy="169" r="6" fill="#3e6fe0"/>
|
|
25
|
+
<circle cx="152" cy="169" r="6" fill="#3e6fe0"/>
|
|
26
|
+
<circle cx="171" cy="169" r="6" fill="#3e6fe0"/>
|
|
27
|
+
</svg>
|