cvc-catalog-sync-plugin 1.0.0 → 2.0.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/CHANGELOG.md +203 -0
- package/README.md +297 -203
- package/README.ru.md +380 -0
- package/SECURITY.md +234 -34
- package/client.js +2428 -553
- package/cordis.patch.yml +13 -8
- package/docs/ARCHITECTURE.md +965 -0
- package/docs/COMPATIBILITY.md +260 -0
- package/docs/DETAIL.md +3 -0
- package/docs/UPGRADING.md +357 -0
- package/docs/preview.svg +99 -0
- package/icon.svg +76 -8
- package/index.js +243 -1312
- package/lib/CONTRACT.js +63 -0
- package/lib/balance.js +412 -0
- package/lib/cache.js +114 -0
- package/lib/catalog-build.js +391 -0
- package/lib/catalog-sync.js +856 -0
- package/lib/coefficients.js +308 -0
- package/lib/config.js +558 -0
- package/lib/cvc-api.js +372 -0
- package/lib/http.js +269 -0
- package/lib/providers.js +210 -0
- package/lib/state.js +233 -0
- package/locale/en.json +4 -3
- package/locale/ru.json +4 -3
- package/package.json +32 -10
package/lib/cvc-api.js
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP-клиент CheapVibeCode: каталог моделей, баланс ключа, карта уровней.
|
|
3
|
+
*
|
|
4
|
+
* Только глобальный `fetch` — никакого `ctx.shell`: сеть разрешена хосту, а
|
|
5
|
+
* таймаут и отмена ограничивают один запрос. Ключ никогда не попадает в текст
|
|
6
|
+
* ошибки, лог или ответ маршрута.
|
|
7
|
+
*
|
|
8
|
+
* @module cvc-catalog-sync-plugin/lib/cvc-api
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Таймаут одного запроса по умолчанию. */
|
|
12
|
+
export const DEFAULT_TIMEOUT_MS = 20000
|
|
13
|
+
|
|
14
|
+
/** Верхняя граница того, что читается из тела ошибки апстрима. */
|
|
15
|
+
const ERROR_BODY_LIMIT = 300
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Ошибка обращения к CheapVibeCode с машинным кодом.
|
|
19
|
+
*
|
|
20
|
+
* Коды: `no-key`, `invalid-base-url`, `timeout`, `aborted`, `network`,
|
|
21
|
+
* `unauthorized`, `http`, `invalid-json`, `invalid-payload`, `levels-unavailable`.
|
|
22
|
+
*/
|
|
23
|
+
export class CvcApiError extends Error {
|
|
24
|
+
/**
|
|
25
|
+
* @param {string} code
|
|
26
|
+
* @param {string} message
|
|
27
|
+
* @param {{ status?: number, cause?: unknown }} [details]
|
|
28
|
+
*/
|
|
29
|
+
constructor(code, message, details = {}) {
|
|
30
|
+
super(message)
|
|
31
|
+
this.name = 'CvcApiError'
|
|
32
|
+
this.code = code
|
|
33
|
+
if (details.status !== undefined) this.status = details.status
|
|
34
|
+
if (details.cause !== undefined) this.cause = details.cause
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Обычный объект, не массив и не null. */
|
|
39
|
+
function isPlainObject(value) {
|
|
40
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Снять хвостовые слэши без регулярки: значение приходит из конфигурации. */
|
|
44
|
+
function stripTrailingSlashes(value) {
|
|
45
|
+
let end = value.length
|
|
46
|
+
while (end > 0 && value[end - 1] === '/') end -= 1
|
|
47
|
+
return value.slice(0, end)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Корень API: база провайдера задана как OpenAI-совместимый `.../v1`,
|
|
52
|
+
* а `/v1/balance` живёт уровнем выше.
|
|
53
|
+
* @param {unknown} baseURL
|
|
54
|
+
* @returns {string}
|
|
55
|
+
*/
|
|
56
|
+
export function apiRoot(baseURL) {
|
|
57
|
+
const trimmed = stripTrailingSlashes(String(baseURL ?? '').trim())
|
|
58
|
+
return trimmed.endsWith('/v1') ? trimmed.slice(0, -3) : trimmed
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Адрес каталога моделей.
|
|
63
|
+
* @param {unknown} baseURL
|
|
64
|
+
* @returns {string}
|
|
65
|
+
*/
|
|
66
|
+
export function modelsUrl(baseURL) {
|
|
67
|
+
return `${stripTrailingSlashes(String(baseURL ?? '').trim())}/models`
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Адрес баланса ключа.
|
|
72
|
+
* @param {unknown} baseURL
|
|
73
|
+
* @returns {string}
|
|
74
|
+
*/
|
|
75
|
+
export function balanceUrl(baseURL) {
|
|
76
|
+
return `${apiRoot(baseURL)}/v1/balance`
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Убрать секрет из произвольного текста.
|
|
81
|
+
* @param {string} text
|
|
82
|
+
* @param {string} secret
|
|
83
|
+
* @returns {string}
|
|
84
|
+
*/
|
|
85
|
+
export function redact(text, secret) {
|
|
86
|
+
const line = typeof text === 'string' ? text : String(text ?? '')
|
|
87
|
+
if (typeof secret !== 'string' || secret.length === 0) return line
|
|
88
|
+
return line.split(secret).join('***')
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Проверить `baseURL` перед запросом.
|
|
93
|
+
* @param {unknown} baseURL
|
|
94
|
+
* @returns {string}
|
|
95
|
+
*/
|
|
96
|
+
function requireBaseURL(baseURL) {
|
|
97
|
+
if (typeof baseURL !== 'string' || baseURL.trim().length === 0) {
|
|
98
|
+
throw new CvcApiError('invalid-base-url', 'baseURL is not configured')
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
const url = new URL(baseURL.trim())
|
|
102
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
|
|
103
|
+
throw new CvcApiError('invalid-base-url', 'baseURL must be an http(s) URL')
|
|
104
|
+
}
|
|
105
|
+
} catch (error) {
|
|
106
|
+
if (error instanceof CvcApiError) throw error
|
|
107
|
+
throw new CvcApiError('invalid-base-url', 'baseURL must be an http(s) URL')
|
|
108
|
+
}
|
|
109
|
+
return baseURL.trim()
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Проверить ключ: без него запрос не имеет смысла. */
|
|
113
|
+
function requireKey(key) {
|
|
114
|
+
if (typeof key !== 'string' || key.trim().length === 0) {
|
|
115
|
+
throw new CvcApiError('no-key', 'API key is not configured for this provider')
|
|
116
|
+
}
|
|
117
|
+
return key.trim()
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Сигнал запроса: таймаут плюс внешняя отмена, если она есть.
|
|
122
|
+
* @param {AbortSignal | undefined} signal
|
|
123
|
+
* @param {number} timeoutMs
|
|
124
|
+
* @returns {AbortSignal}
|
|
125
|
+
*/
|
|
126
|
+
function requestSignal(signal, timeoutMs) {
|
|
127
|
+
const timeout = AbortSignal.timeout(timeoutMs)
|
|
128
|
+
return signal instanceof AbortSignal ? AbortSignal.any([signal, timeout]) : timeout
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Таймаут из конфига: конечное число не меньше секунды. */
|
|
132
|
+
function timeoutOr(value) {
|
|
133
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 1) return DEFAULT_TIMEOUT_MS
|
|
134
|
+
return Math.min(Math.round(value), 2147483647)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Тело ошибки апстрима — коротко и без секретов.
|
|
139
|
+
* @param {Response} response
|
|
140
|
+
* @param {string} key
|
|
141
|
+
* @returns {Promise<string>}
|
|
142
|
+
*/
|
|
143
|
+
async function errorDetail(response, key) {
|
|
144
|
+
try {
|
|
145
|
+
const text = await response.text()
|
|
146
|
+
const trimmed = text.slice(0, ERROR_BODY_LIMIT)
|
|
147
|
+
try {
|
|
148
|
+
const body = JSON.parse(trimmed)
|
|
149
|
+
const message = isPlainObject(body) && isPlainObject(body.error) && typeof body.error.message === 'string'
|
|
150
|
+
? body.error.message
|
|
151
|
+
: isPlainObject(body) && typeof body.message === 'string'
|
|
152
|
+
? body.message
|
|
153
|
+
: ''
|
|
154
|
+
if (message.length > 0) return `: ${redact(message, key)}`
|
|
155
|
+
} catch {
|
|
156
|
+
// Не-JSON тело ничего полезного не несёт.
|
|
157
|
+
}
|
|
158
|
+
return ''
|
|
159
|
+
} catch {
|
|
160
|
+
return ''
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Один JSON-запрос с таймаутом.
|
|
166
|
+
* @param {string} url
|
|
167
|
+
* @param {{ key: string, timeoutMs?: number, fetchImpl?: typeof fetch, signal?: AbortSignal, label: string }} options
|
|
168
|
+
* @returns {Promise<{ status: number, payload: unknown }>}
|
|
169
|
+
*/
|
|
170
|
+
async function requestJson(url, options) {
|
|
171
|
+
const { key } = options
|
|
172
|
+
const fetchImpl = typeof options.fetchImpl === 'function' ? options.fetchImpl : fetch
|
|
173
|
+
const timeoutMs = timeoutOr(options.timeoutMs)
|
|
174
|
+
let response
|
|
175
|
+
try {
|
|
176
|
+
response = await fetchImpl(url, {
|
|
177
|
+
method: 'GET',
|
|
178
|
+
headers: { Authorization: `Bearer ${key}`, accept: 'application/json' },
|
|
179
|
+
signal: requestSignal(options.signal, timeoutMs),
|
|
180
|
+
})
|
|
181
|
+
} catch (error) {
|
|
182
|
+
const name = error instanceof Error ? error.name : ''
|
|
183
|
+
if (name === 'TimeoutError') {
|
|
184
|
+
throw new CvcApiError('timeout', `${options.label}: request timed out after ${timeoutMs} ms`, { cause: error })
|
|
185
|
+
}
|
|
186
|
+
if (name === 'AbortError') {
|
|
187
|
+
throw new CvcApiError('aborted', `${options.label}: request was aborted`, { cause: error })
|
|
188
|
+
}
|
|
189
|
+
throw new CvcApiError(
|
|
190
|
+
'network',
|
|
191
|
+
`${options.label}: network error${error instanceof Error && error.message ? `: ${redact(error.message, key)}` : ''}`,
|
|
192
|
+
{ cause: error },
|
|
193
|
+
)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (response.status === 401 || response.status === 403) {
|
|
197
|
+
const detail = await errorDetail(response, key)
|
|
198
|
+
throw new CvcApiError(
|
|
199
|
+
'unauthorized',
|
|
200
|
+
`${options.label}: HTTP ${response.status}${detail}`,
|
|
201
|
+
{ status: response.status },
|
|
202
|
+
)
|
|
203
|
+
}
|
|
204
|
+
if (!response.ok) {
|
|
205
|
+
const detail = await errorDetail(response, key)
|
|
206
|
+
throw new CvcApiError('http', `${options.label}: HTTP ${response.status}${detail}`, { status: response.status })
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
try {
|
|
210
|
+
return { status: response.status, payload: await response.json() }
|
|
211
|
+
} catch (error) {
|
|
212
|
+
throw new CvcApiError(
|
|
213
|
+
'invalid-json',
|
|
214
|
+
`${options.label}: response is not valid JSON${error instanceof Error ? `: ${redact(error.message, key)}` : ''}`,
|
|
215
|
+
{ cause: error },
|
|
216
|
+
)
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Разобрать ответ `GET /v1/models` или `null`, если форма не та.
|
|
222
|
+
*
|
|
223
|
+
* Принимается OpenAI-форма `{ data: [...] }` и голый массив; записи без
|
|
224
|
+
* строкового `id` отбрасываются — без идентификатора модель в патч не лежит.
|
|
225
|
+
* @param {unknown} payload
|
|
226
|
+
* @returns {Array<Record<string, unknown>> | null}
|
|
227
|
+
*/
|
|
228
|
+
export function parseCatalogPayload(payload) {
|
|
229
|
+
const rows = Array.isArray(payload)
|
|
230
|
+
? payload
|
|
231
|
+
: isPlainObject(payload) && Array.isArray(payload.data)
|
|
232
|
+
? payload.data
|
|
233
|
+
: null
|
|
234
|
+
if (rows === null) return null
|
|
235
|
+
const items = []
|
|
236
|
+
for (const row of rows) {
|
|
237
|
+
if (!isPlainObject(row)) continue
|
|
238
|
+
const id = typeof row.id === 'string' ? row.id.trim() : ''
|
|
239
|
+
if (id.length === 0) continue
|
|
240
|
+
items.push(row)
|
|
241
|
+
}
|
|
242
|
+
return items
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Забрать каталог моделей провайдера.
|
|
247
|
+
* @param {{ baseURL?: string, key?: string, timeoutMs?: number, fetchImpl?: typeof fetch, signal?: AbortSignal }} [options]
|
|
248
|
+
* @returns {Promise<Array<Record<string, unknown>>>}
|
|
249
|
+
*/
|
|
250
|
+
export async function fetchModels(options = {}) {
|
|
251
|
+
const baseURL = requireBaseURL(options.baseURL)
|
|
252
|
+
const key = requireKey(options.key)
|
|
253
|
+
const { payload } = await requestJson(modelsUrl(baseURL), {
|
|
254
|
+
key,
|
|
255
|
+
timeoutMs: options.timeoutMs,
|
|
256
|
+
fetchImpl: options.fetchImpl,
|
|
257
|
+
signal: options.signal,
|
|
258
|
+
label: 'GET /models',
|
|
259
|
+
})
|
|
260
|
+
const models = parseCatalogPayload(payload)
|
|
261
|
+
if (models === null) {
|
|
262
|
+
throw new CvcApiError('invalid-payload', 'GET /models: response has no model list')
|
|
263
|
+
}
|
|
264
|
+
return models
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Забрать баланс ключа.
|
|
269
|
+
* @param {{ baseURL?: string, key?: string, timeoutMs?: number, fetchImpl?: typeof fetch, signal?: AbortSignal }} [options]
|
|
270
|
+
* @returns {Promise<{ units: number }>}
|
|
271
|
+
*/
|
|
272
|
+
export async function fetchBalance(options = {}) {
|
|
273
|
+
const baseURL = requireBaseURL(options.baseURL)
|
|
274
|
+
const key = requireKey(options.key)
|
|
275
|
+
const { payload } = await requestJson(balanceUrl(baseURL), {
|
|
276
|
+
key,
|
|
277
|
+
timeoutMs: options.timeoutMs,
|
|
278
|
+
fetchImpl: options.fetchImpl,
|
|
279
|
+
signal: options.signal,
|
|
280
|
+
label: 'GET /balance',
|
|
281
|
+
})
|
|
282
|
+
const units = isPlainObject(payload) ? payload.token_balance : undefined
|
|
283
|
+
if (typeof units !== 'number' || !Number.isFinite(units)) {
|
|
284
|
+
throw new CvcApiError('invalid-payload', 'GET /balance: response has no token_balance')
|
|
285
|
+
}
|
|
286
|
+
return { units }
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Вытащить карту `reasoningLevels` из текста официального установщика.
|
|
291
|
+
*
|
|
292
|
+
* Литерал `const reasoningLevels = {...};` в обоих установщиках JSON-совместим:
|
|
293
|
+
* вложенных объектов внутри нет, поэтому разбор до первой `};` безопасен.
|
|
294
|
+
* Каждый уровень обязан быть строкой: битая карта не должна молча менять патч.
|
|
295
|
+
* @param {unknown} text
|
|
296
|
+
* @returns {Record<string, string[]> | null}
|
|
297
|
+
*/
|
|
298
|
+
export function parseReasoningLevels(text) {
|
|
299
|
+
if (typeof text !== 'string' || text.length === 0) return null
|
|
300
|
+
// Линейный разбор без регулярки: текст приходит из сети, а нежадный
|
|
301
|
+
// `[\s\S]*?` на большом файле — кандидат на квадратичный откат.
|
|
302
|
+
const start = text.indexOf('const reasoningLevels')
|
|
303
|
+
if (start < 0) return null
|
|
304
|
+
const open = text.indexOf('{', start)
|
|
305
|
+
if (open < 0) return null
|
|
306
|
+
const close = text.indexOf('};', open)
|
|
307
|
+
if (close < 0) return null
|
|
308
|
+
/** @type {unknown} */
|
|
309
|
+
let parsed
|
|
310
|
+
try {
|
|
311
|
+
parsed = JSON.parse(text.slice(open, close + 1))
|
|
312
|
+
} catch {
|
|
313
|
+
return null
|
|
314
|
+
}
|
|
315
|
+
if (!isPlainObject(parsed)) return null
|
|
316
|
+
/** @type {Record<string, string[]>} */
|
|
317
|
+
const map = {}
|
|
318
|
+
for (const [id, levels] of Object.entries(parsed)) {
|
|
319
|
+
if (!Array.isArray(levels)) continue
|
|
320
|
+
const clean = levels
|
|
321
|
+
.filter((level) => typeof level === 'string' && level.trim().length > 0)
|
|
322
|
+
.map((level) => level.trim())
|
|
323
|
+
if (clean.length > 0) map[id] = clean
|
|
324
|
+
}
|
|
325
|
+
return Object.keys(map).length > 0 ? map : null
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Забрать карту уровней с первого ответившего установщика.
|
|
330
|
+
* @param {{ urls?: string[], timeoutMs?: number, fetchImpl?: typeof fetch, signal?: AbortSignal }} [options]
|
|
331
|
+
* @returns {Promise<{ levels: Record<string, string[]>, source: string }>}
|
|
332
|
+
*/
|
|
333
|
+
export async function fetchLevels(options = {}) {
|
|
334
|
+
const urls = Array.isArray(options.urls) ? options.urls.filter((url) => typeof url === 'string' && url.trim()) : []
|
|
335
|
+
if (urls.length === 0) {
|
|
336
|
+
throw new CvcApiError('levels-unavailable', 'no installer URL is configured')
|
|
337
|
+
}
|
|
338
|
+
const fetchImpl = typeof options.fetchImpl === 'function' ? options.fetchImpl : fetch
|
|
339
|
+
const timeoutMs = timeoutOr(options.timeoutMs)
|
|
340
|
+
const failures = []
|
|
341
|
+
for (const url of urls) {
|
|
342
|
+
let response
|
|
343
|
+
try {
|
|
344
|
+
response = await fetchImpl(url.trim(), {
|
|
345
|
+
method: 'GET',
|
|
346
|
+
signal: requestSignal(options.signal, timeoutMs),
|
|
347
|
+
})
|
|
348
|
+
} catch (error) {
|
|
349
|
+
const name = error instanceof Error ? error.name : ''
|
|
350
|
+
failures.push(`${url}: ${name === 'TimeoutError' ? 'timeout' : 'network error'}`)
|
|
351
|
+
continue
|
|
352
|
+
}
|
|
353
|
+
if (!response.ok) {
|
|
354
|
+
failures.push(`${url}: HTTP ${response.status}`)
|
|
355
|
+
continue
|
|
356
|
+
}
|
|
357
|
+
let text
|
|
358
|
+
try {
|
|
359
|
+
text = await response.text()
|
|
360
|
+
} catch {
|
|
361
|
+
failures.push(`${url}: body is unreadable`)
|
|
362
|
+
continue
|
|
363
|
+
}
|
|
364
|
+
const levels = parseReasoningLevels(text)
|
|
365
|
+
if (levels === null) {
|
|
366
|
+
failures.push(`${url}: no reasoningLevels literal`)
|
|
367
|
+
continue
|
|
368
|
+
}
|
|
369
|
+
return { levels, source: url.trim() }
|
|
370
|
+
}
|
|
371
|
+
throw new CvcApiError('levels-unavailable', `no installer answered with reasoningLevels (${failures.join('; ')})`)
|
|
372
|
+
}
|
package/lib/http.js
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP-слой плагина: один prefix-маршрут `/cvc`, JSON и фенс same-origin.
|
|
3
|
+
*
|
|
4
|
+
* Все три функции регистрируют свои подмаршруты в одной таблице, поэтому
|
|
5
|
+
* выключенная функция отвечает 404 без повторной регистрации prefix-маршрута
|
|
6
|
+
* на веб-сервере (две регистрации одного префикса конфликтуют).
|
|
7
|
+
*
|
|
8
|
+
* @module cvc-catalog-sync-plugin/lib/http
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Префикс, под которым живёт весь HTTP плагина. */
|
|
12
|
+
export const CVC_PREFIX = '/cvc'
|
|
13
|
+
|
|
14
|
+
/** Верхняя граница тела запроса: конфиг — это несколько килобайт. */
|
|
15
|
+
export const BODY_LIMIT = 65536
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Ошибка HTTP-слоя с кодом ответа.
|
|
19
|
+
*/
|
|
20
|
+
export class HttpError extends Error {
|
|
21
|
+
/**
|
|
22
|
+
* @param {number} status
|
|
23
|
+
* @param {string} message
|
|
24
|
+
*/
|
|
25
|
+
constructor(status, message) {
|
|
26
|
+
super(message)
|
|
27
|
+
this.name = 'HttpError'
|
|
28
|
+
this.status = status
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Ответить JSON без кэширования.
|
|
34
|
+
* @param {import('node:http').ServerResponse} res
|
|
35
|
+
* @param {number} status
|
|
36
|
+
* @param {unknown} body
|
|
37
|
+
*/
|
|
38
|
+
export function sendJson(res, status, body) {
|
|
39
|
+
res.writeHead(status, {
|
|
40
|
+
'content-type': 'application/json; charset=utf-8',
|
|
41
|
+
'cache-control': 'no-store',
|
|
42
|
+
'x-content-type-options': 'nosniff',
|
|
43
|
+
})
|
|
44
|
+
res.end(JSON.stringify(body))
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Запрос объявлен как JSON.
|
|
49
|
+
* @param {import('node:http').IncomingMessage} req
|
|
50
|
+
* @returns {boolean}
|
|
51
|
+
*/
|
|
52
|
+
export function isJsonRequest(req) {
|
|
53
|
+
const header = String(req.headers?.['content-type'] ?? '')
|
|
54
|
+
return header.split(';')[0].trim().toLowerCase() === 'application/json'
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Запрос пришёл с чужого сайта.
|
|
59
|
+
* @param {import('node:http').IncomingMessage} req
|
|
60
|
+
* @returns {boolean}
|
|
61
|
+
*/
|
|
62
|
+
export function isCrossSite(req) {
|
|
63
|
+
return String(req.headers?.['sec-fetch-site'] ?? '').toLowerCase() === 'cross-site'
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Ответить 405 с перечнем допустимых методов.
|
|
68
|
+
* @param {import('node:http').ServerResponse} res
|
|
69
|
+
* @param {readonly string[]} allow
|
|
70
|
+
*/
|
|
71
|
+
export function methodNotAllowed(res, allow) {
|
|
72
|
+
const methods = allow.join(', ')
|
|
73
|
+
res.setHeader?.('allow', methods)
|
|
74
|
+
sendJson(res, 405, { error: `method not allowed; use ${methods}` })
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Прочитать JSON-тело запроса с ограничением размера.
|
|
79
|
+
* @param {import('node:http').IncomingMessage} req
|
|
80
|
+
* @param {number} [limit]
|
|
81
|
+
* @returns {Promise<unknown>}
|
|
82
|
+
*/
|
|
83
|
+
export function readJsonBody(req, limit = BODY_LIMIT) {
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
let size = 0
|
|
86
|
+
const chunks = []
|
|
87
|
+
req.on('data', (chunk) => {
|
|
88
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
|
|
89
|
+
size += buffer.length
|
|
90
|
+
if (size > limit) {
|
|
91
|
+
reject(new HttpError(413, 'request body is too large'))
|
|
92
|
+
req.destroy?.()
|
|
93
|
+
return
|
|
94
|
+
}
|
|
95
|
+
chunks.push(buffer)
|
|
96
|
+
})
|
|
97
|
+
req.on('end', () => {
|
|
98
|
+
const text = Buffer.concat(chunks).toString('utf8')
|
|
99
|
+
if (text.trim().length === 0) {
|
|
100
|
+
resolve({})
|
|
101
|
+
return
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
resolve(JSON.parse(text))
|
|
105
|
+
} catch (error) {
|
|
106
|
+
reject(new HttpError(400, `invalid JSON: ${error instanceof Error ? error.message : String(error)}`))
|
|
107
|
+
}
|
|
108
|
+
})
|
|
109
|
+
req.on('error', reject)
|
|
110
|
+
})
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Убрать слэши с обоих концов пути.
|
|
115
|
+
* @param {unknown} value
|
|
116
|
+
* @returns {string}
|
|
117
|
+
*/
|
|
118
|
+
function trimSlashes(value) {
|
|
119
|
+
const text = String(value ?? '')
|
|
120
|
+
let start = 0
|
|
121
|
+
let end = text.length
|
|
122
|
+
while (start < end && text[start] === '/') start += 1
|
|
123
|
+
while (end > start && text[end - 1] === '/') end -= 1
|
|
124
|
+
return text.slice(start, end)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Создать таблицу маршрутов и обработчик prefix-маршрута.
|
|
129
|
+
*
|
|
130
|
+
* @param {{ prefix?: string, log?: (message: string) => void }} [options]
|
|
131
|
+
* @returns {{
|
|
132
|
+
* prefix: string,
|
|
133
|
+
* register: (path: string, handler: (req: any, res: any) => unknown) => () => void,
|
|
134
|
+
* handle: (req: any, res: any) => Promise<void>,
|
|
135
|
+
* attach: (webServer: { register: (route: unknown) => () => void }) => () => void,
|
|
136
|
+
* paths: () => string[],
|
|
137
|
+
* }}
|
|
138
|
+
*/
|
|
139
|
+
export function createRouter(options = {}) {
|
|
140
|
+
const prefix = typeof options.prefix === 'string' && options.prefix.trim().length > 0
|
|
141
|
+
? `/${trimSlashes(options.prefix)}`
|
|
142
|
+
: CVC_PREFIX
|
|
143
|
+
const log = typeof options.log === 'function' ? options.log : () => {}
|
|
144
|
+
|
|
145
|
+
/** @type {Map<string, (req: any, res: any) => unknown>} */
|
|
146
|
+
const routes = new Map()
|
|
147
|
+
|
|
148
|
+
/** Живая регистрация prefix-маршрута на веб-сервере, если она есть. */
|
|
149
|
+
let attached = null
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Зарегистрировать обработчик подмаршрута.
|
|
153
|
+
* @param {string} path — путь без префикса, например `state`.
|
|
154
|
+
* @param {(req: any, res: any) => unknown} handler
|
|
155
|
+
* @returns {() => void} disposer, снимающий только свою регистрацию.
|
|
156
|
+
*/
|
|
157
|
+
function register(path, handler) {
|
|
158
|
+
if (typeof handler !== 'function') throw new TypeError('createRouter: handler must be a function')
|
|
159
|
+
const key = trimSlashes(path)
|
|
160
|
+
if (routes.has(key)) throw new Error(`cvc: route "${key}" is already registered`)
|
|
161
|
+
routes.set(key, handler)
|
|
162
|
+
return () => {
|
|
163
|
+
if (routes.get(key) === handler) routes.delete(key)
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Обработать запрос: фенс, разбор пути, диспетчеризация.
|
|
169
|
+
*
|
|
170
|
+
* Порядок важен: сначала чужой сайт (403), потом несуществующий путь (404),
|
|
171
|
+
* потом запись без JSON (415) и только затем сам обработчик. Так маршрут,
|
|
172
|
+
* которого нет, отвечает 404, а не «пришлите JSON», и метод проверяет
|
|
173
|
+
* обработчик, знающий свои методы.
|
|
174
|
+
* @param {any} req
|
|
175
|
+
* @param {any} res
|
|
176
|
+
* @returns {Promise<void>}
|
|
177
|
+
*/
|
|
178
|
+
async function handle(req, res) {
|
|
179
|
+
// Same-origin фенс: браузер присылает Sec-Fetch-Site на каждом fetch,
|
|
180
|
+
// 'cross-site' — единственное значение, означающее чужую страницу.
|
|
181
|
+
if (isCrossSite(req)) {
|
|
182
|
+
sendJson(res, 403, { error: 'forbidden' })
|
|
183
|
+
return
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
let pathname
|
|
187
|
+
try {
|
|
188
|
+
pathname = new URL(req.url ?? '/', 'http://localhost').pathname
|
|
189
|
+
} catch {
|
|
190
|
+
sendJson(res, 400, { error: 'malformed url' })
|
|
191
|
+
return
|
|
192
|
+
}
|
|
193
|
+
if (pathname !== prefix && !pathname.startsWith(`${prefix}/`)) {
|
|
194
|
+
sendJson(res, 404, { error: 'not found' })
|
|
195
|
+
return
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const key = trimSlashes(pathname.slice(prefix.length))
|
|
199
|
+
const handler = routes.get(key)
|
|
200
|
+
if (handler === undefined) {
|
|
201
|
+
sendJson(res, 404, { error: 'not found' })
|
|
202
|
+
return
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Тело несут только PUT/POST; они обязаны быть JSON. Проверка идёт после
|
|
206
|
+
// поиска маршрута, чтобы не перекрывать 404/405 ответом про content-type.
|
|
207
|
+
const method = String(req.method ?? 'GET').toUpperCase()
|
|
208
|
+
if ((method === 'PUT' || method === 'POST') && !isJsonRequest(req)) {
|
|
209
|
+
sendJson(res, 415, { error: 'content-type: application/json required' })
|
|
210
|
+
return
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
try {
|
|
214
|
+
await handler(req, res)
|
|
215
|
+
} catch (error) {
|
|
216
|
+
if (res?.writableEnded === true || res?.headersSent === true) {
|
|
217
|
+
log(`cvc: response already sent, error: ${error instanceof Error ? error.message : String(error)}`)
|
|
218
|
+
return
|
|
219
|
+
}
|
|
220
|
+
const status = error instanceof HttpError ? error.status : 500
|
|
221
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
222
|
+
if (status >= 500) log(`cvc: ${key} failed: ${message}`)
|
|
223
|
+
sendJson(res, status, { error: message })
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Повесить prefix-маршрут на веб-сервер DSH.
|
|
229
|
+
*
|
|
230
|
+
* Идемпотентно: повторный `attach` (например, если сервис webServer
|
|
231
|
+
* пересоздали) сначала снимает прежнюю регистрацию, поэтому `/cvc` на
|
|
232
|
+
* сервере всегда один и тот же маршрут, а не два конкурирующих.
|
|
233
|
+
* @param {{ register: (route: unknown) => () => void }} webServer
|
|
234
|
+
* @returns {() => void}
|
|
235
|
+
*/
|
|
236
|
+
function attach(webServer) {
|
|
237
|
+
if (webServer === null || typeof webServer !== 'object' || typeof webServer.register !== 'function') {
|
|
238
|
+
throw new Error('cvc: webServer.register is unavailable')
|
|
239
|
+
}
|
|
240
|
+
if (attached !== null) {
|
|
241
|
+
const previous = attached
|
|
242
|
+
attached = null
|
|
243
|
+
try {
|
|
244
|
+
previous()
|
|
245
|
+
} catch (error) {
|
|
246
|
+
log(`cvc: previous prefix route teardown failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const dispose = webServer.register({
|
|
250
|
+
kind: 'prefix',
|
|
251
|
+
path: prefix,
|
|
252
|
+
handler: (req, res) => handle(req, res),
|
|
253
|
+
})
|
|
254
|
+
const detach = () => {
|
|
255
|
+
if (attached === detach) attached = null
|
|
256
|
+
if (typeof dispose === 'function') dispose()
|
|
257
|
+
}
|
|
258
|
+
attached = detach
|
|
259
|
+
return detach
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return {
|
|
263
|
+
prefix,
|
|
264
|
+
register,
|
|
265
|
+
handle,
|
|
266
|
+
attach,
|
|
267
|
+
paths: () => [...routes.keys()].sort(),
|
|
268
|
+
}
|
|
269
|
+
}
|