@mzzsfy/dsh-stock-assistant 0.7.1 → 0.8.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.
@@ -1,29 +1,85 @@
1
- /**
2
- * 宿主闸门复用。宿主把认证挂在它自己的 `/api` prefix 路由里,而 responder 选择是
3
- * 「exact 先、最长 prefix 后」——插件注册的 `/api/<pkg>` 更长,先命中,`connection.admit`
4
- * 从不执行。所以插件路由必须自己回问一次宿主闸门,否则无 cookie 的调用直接进业务面。
5
- *
6
- * 服务缺失(非 web 传输、旧宿主)时放行:与原行为一致,不新增自有认证层。
7
- */
8
-
9
- export function rejectUnadmitted(ctx, req, res) {
10
- let rejection
11
- try {
12
- const connection = typeof ctx?.get === 'function' ? ctx.get('connection') : undefined
13
- rejection = connection?.requestRejection?.(req)
14
- } catch {
15
- // 闸门自身异常不放行:宁可拒绝,不把故障当认证通过
16
- rejection = 403
17
- }
18
- if (rejection === undefined) return false
19
- res.writeHead(rejection, { 'content-type': 'text/plain; charset=utf-8' })
20
- res.end(rejection === 401 ? 'unauthorized' : 'forbidden')
21
- return true
22
- }
23
-
24
- export function withHostGate(ctx, handler) {
25
- return async (req, res) => {
26
- if (rejectUnadmitted(ctx, req, res)) return
27
- await handler(req, res)
28
- }
29
- }
1
+ /**
2
+ * 宿主闸门复用。宿主把认证挂在它自己的 `/api` prefix 路由里,而 responder 选择是
3
+ * 「exact 先、最长 prefix 后」——插件注册的 `/api/<pkg>` 更长,先命中,`connection.admit`
4
+ * 从不执行。所以插件路由必须自己回问一次宿主闸门,否则无 cookie 的调用直接进业务面。
5
+ *
6
+ * 服务缺失(非 web 传输、旧宿主)时放行:与原行为一致,不新增自有认证层。
7
+ * 写路由再叠加 Origin↔Host 同源比对与 JSON content-type 校验(用 withRouteGate):
8
+ * 这是浏览器侧 CSRF 防线,不是身份认证;禁止在此实现 Host 白名单/DNS-rebinding
9
+ * 防线/自有 token。
10
+ */
11
+
12
+ function sendGuardJson(res, status, error) {
13
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
14
+ res.end(JSON.stringify({ error }))
15
+ }
16
+
17
+ // 宿主闸门返回的拒绝值只有整数 4xx/5xx 可写进 writeHead;null/0/对象/Promise 一律按
18
+ // 默认拒绝码收敛——否则 writeHead 抛 Invalid status code,请求拿不到任何响应。
19
+ const REJECTION_MIN = 400
20
+ const REJECTION_MAX = 599
21
+ const DEFAULT_REJECTION = 403
22
+ const isRejectionCode = (value) => Number.isInteger(value) && value >= REJECTION_MIN && value <= REJECTION_MAX
23
+
24
+ export function rejectUnadmitted(ctx, req, res) {
25
+ let rejection
26
+ try {
27
+ const connection = typeof ctx?.get === 'function' ? ctx.get('connection') : undefined
28
+ rejection = connection?.requestRejection?.(req)
29
+ } catch {
30
+ // 闸门自身异常不放行:宁可拒绝,不把故障当认证通过
31
+ rejection = DEFAULT_REJECTION
32
+ }
33
+ if (rejection === undefined) return false
34
+ const status = isRejectionCode(rejection) ? rejection : DEFAULT_REJECTION
35
+ res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' })
36
+ res.end(status === 401 ? 'unauthorized' : 'forbidden')
37
+ return true
38
+ }
39
+
40
+ export function withHostGate(ctx, handler) {
41
+ return async (req, res) => {
42
+ if (rejectUnadmitted(ctx, req, res)) return
43
+ await handler(req, res)
44
+ }
45
+ }
46
+
47
+ // Origin 存在即比对 Host(大小写不敏感);缺 Origin 的非浏览器调用不受影响。
48
+ // Origin 非法(无法解析)按跨源拒绝。
49
+ export function rejectCrossOrigin(req, res) {
50
+ const origin = req.headers ? req.headers.origin : undefined
51
+ if (!origin) return false
52
+ const host = req.headers ? req.headers.host : undefined
53
+ let sameOrigin = false
54
+ try {
55
+ sameOrigin = typeof host === 'string' && new URL(origin).host.toLowerCase() === host.toLowerCase()
56
+ } catch {
57
+ sameOrigin = false
58
+ }
59
+ if (sameOrigin) return false
60
+ sendGuardJson(res, 403, '跨源请求被拒绝')
61
+ return true
62
+ }
63
+
64
+ // 写方法只接受 JSON:跨站表单(enctype=text/plain 等简单请求)无预检,必须显式拒绝。
65
+ // 媒体类型按 essence 精确比较,避免 application/jsonp / text/plain;...application/json 混入。
66
+ export const WRITE_METHODS = new Set(['POST', 'PATCH', 'PUT', 'DELETE'])
67
+ export function rejectNonJson(req, res) {
68
+ const contentType = req.headers ? String(req.headers['content-type'] || '') : ''
69
+ const essence = contentType.split(';', 1)[0].trim().toLowerCase()
70
+ if (essence === 'application/json') return false
71
+ sendGuardJson(res, 400, 'content-type 须为 application/json')
72
+ return true
73
+ }
74
+
75
+ // 写路由完整闸门:宿主闸门 → 同源 → JSON。GET/HEAD 只过宿主闸门(无写副作用)
76
+ export function withRouteGate(ctx, handler) {
77
+ return async (req, res) => {
78
+ if (rejectUnadmitted(ctx, req, res)) return
79
+ if (WRITE_METHODS.has(String(req.method || '').toUpperCase())) {
80
+ if (rejectCrossOrigin(req, res)) return
81
+ if (rejectNonJson(req, res)) return
82
+ }
83
+ await handler(req, res)
84
+ }
85
+ }
package/src/routes.mjs CHANGED
@@ -1,68 +1,68 @@
1
- import { z } from 'zod'
2
- import { StockError, fail } from './market-model.mjs'
3
- import { rejectUnadmitted } from './route-gate.mjs'
4
- const PREFIX = '/api/stock-assistant'
5
- const operationSchema = z.object({ operationId: z.uuid(), expectedRevision: z.number().int().nonnegative() })
6
- async function body(req) {
7
- const chunks = []; let size = 0
8
- for await (const chunk of req) {
9
- size += chunk.length
10
- if (size > 64 * 1024) fail('BODY_TOO_LARGE', '请求内容过大', 413)
11
- chunks.push(chunk)
12
- }
13
- try { return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') }
14
- catch { fail('INVALID_JSON', '请求必须为JSON') }
15
- }
16
- function json(res, status, value) {
17
- if (res.destroyed || res.writableEnded) return
18
- res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value))
19
- }
20
- export function registerRoutes(webServer, app, ctx) {
21
- const handlers = {
22
- snapshot: ['GET', () => app.snapshot()],
23
- search: ['GET', async (input, signal) => await app.search(input.q || '', input.phase === 'remote' ? 'remote' : 'local', signal)],
24
- browse: ['GET', input => app.browse(input)],
25
- watchlist: ['POST', input => { operationSchema.parse(input); return app.watchlist(input) }],
26
- preferences: ['POST', input => { operationSchema.parse(input); return app.preferences({ ...input, payload: input.patch }) }],
27
- configuration: ['POST', input => { operationSchema.parse(input); return app.configuration({ ...input, payload: { providers: input.providers, routes: input.routes } }) }],
28
- 'provider-check': ['POST', (input, signal) => app.providerCheck(input, signal)],
29
- credential: ['POST', input => app.credential(input)],
30
- 'catalog-sync': ['POST', input => app.sync(input)],
31
- 'route-selection': ['POST', (input, signal) => app.routeSelection(input, signal)],
32
- refresh: ['POST', (input, signal) => app.refresh(input, signal)],
33
- kline: ['GET', (input, signal) => app.kline(input, signal)],
34
- }
35
- const controllers = new Set(), disposers = []
36
- let stopped = false
37
- try {
38
- for (const [name, [method, action]] of Object.entries(handlers)) disposers.push(webServer.register({ kind: 'exact', path: `${PREFIX}/${name}`, async handler(req, res) {
39
- if (rejectUnadmitted(ctx, req, res)) return
40
- if (stopped) return json(res, 503, { ok: false, error: { code: 'STOPPED', message: '工具已停止' } })
41
- if (req.method !== method) { res.setHeader('Allow', method); return json(res, 405, { ok: false, error: { code: 'METHOD_NOT_ALLOWED', message: '请求方法不支持' } }) }
42
- const controller = new AbortController(); controllers.add(controller)
43
- const onClose = () => { if (!res.writableEnded) controller.abort() }
44
- res.on('close', onClose)
45
- const timeout = name === 'provider-check' ? 60 * 1000 : name === 'catalog-sync' ? 120 * 1000 : 10 * 1000
46
- let timer
47
- try {
48
- const input = method === 'GET' ? Object.fromEntries(new URL(req.url, 'http://local').searchParams) : await body(req)
49
- if (method === 'POST' && (input === null || typeof input !== 'object' || Array.isArray(input))) fail('INVALID_REQUEST', '请求内容必须为JSON对象')
50
- if (method === 'POST' && req.headers.origin) {
51
- let same = false
52
- try { same = new URL(req.headers.origin).host === req.headers.host } catch {}
53
- if (!same) fail('CROSS_ORIGIN', '不接受跨源写请求', 403)
54
- }
55
- const data = await Promise.race([
56
- Promise.resolve(action(input, controller.signal)),
57
- new Promise((_, reject) => { timer = setTimeout(() => { controller.abort(); reject(new StockError('TIMEOUT', '操作超时,请稍后重试', 504)) }, timeout) }),
58
- new Promise((_, reject) => controller.signal.addEventListener('abort', () => reject(new StockError('CANCELLED', '操作已取消', stopped ? 503 : 504)), { once: true })),
59
- ])
60
- json(res, 200, { ok: true, data })
61
- } catch (e) {
62
- const error = e instanceof StockError ? e : new StockError('INVALID_REQUEST', e instanceof z.ZodError ? '请求参数格式错误' : '股票工具请求失败', e instanceof z.ZodError ? 400 : 500)
63
- json(res, error.status, { ok: false, error: { code: error.code, message: error.message, retryable: error.retryable, retryAfterMs: error.retryAfterMs }, ...(error.revision === undefined ? {} : { revision: error.revision }), ...(e.snapshot ? { snapshot: e.snapshot } : {}) })
64
- } finally { clearTimeout(timer); controllers.delete(controller); res.removeListener('close', onClose) }
65
- } }))
66
- } catch (e) { for (const dispose of disposers.reverse()) dispose(); throw e }
67
- return () => { stopped = true; for (const dispose of disposers.reverse()) dispose(); for (const c of controllers) c.abort(); controllers.clear() }
68
- }
1
+ import { z } from 'zod'
2
+ import { StockError, fail } from './market-model.mjs'
3
+ import { withRouteGate } from './route-gate.mjs'
4
+ const PREFIX = '/api/stock-assistant'
5
+ const operationSchema = z.object({ operationId: z.uuid(), expectedRevision: z.number().int().nonnegative() })
6
+ async function body(req) {
7
+ const chunks = []; let size = 0
8
+ for await (const chunk of req) {
9
+ size += chunk.length
10
+ if (size > 64 * 1024) fail('BODY_TOO_LARGE', '请求内容过大', 413)
11
+ chunks.push(chunk)
12
+ }
13
+ try { return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') }
14
+ catch { fail('INVALID_JSON', '请求必须为JSON') }
15
+ }
16
+ function json(res, status, value) {
17
+ if (res.destroyed || res.writableEnded) return
18
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value))
19
+ }
20
+ export function registerRoutes(webServer, app, ctx) {
21
+ const handlers = {
22
+ snapshot: ['GET', () => app.snapshot()],
23
+ search: ['GET', async (input, signal) => await app.search(input.q || '', input.phase === 'remote' ? 'remote' : 'local', signal)],
24
+ browse: ['GET', input => app.browse(input)],
25
+ watchlist: ['POST', input => { operationSchema.parse(input); return app.watchlist(input) }],
26
+ preferences: ['POST', input => { operationSchema.parse(input); return app.preferences({ ...input, payload: input.patch }) }],
27
+ configuration: ['POST', input => { operationSchema.parse(input); return app.configuration({ ...input, payload: { providers: input.providers, routes: input.routes } }) }],
28
+ 'provider-check': ['POST', (input, signal) => app.providerCheck(input, signal)],
29
+ credential: ['POST', input => app.credential(input)],
30
+ 'catalog-sync': ['POST', input => app.sync(input)],
31
+ 'route-selection': ['POST', (input, signal) => app.routeSelection(input, signal)],
32
+ refresh: ['POST', (input, signal) => app.refresh(input, signal)],
33
+ kline: ['GET', (input, signal) => app.kline(input, signal)],
34
+ }
35
+ const controllers = new Set(), disposers = []
36
+ let stopped = false
37
+ try {
38
+ for (const [name, [method, action]] of Object.entries(handlers)) {
39
+ // 写方法与读方法统一走共享闸门: 宿主闸门恒过; 写方法再叠同源与 JSON content-type。
40
+ // GET 无写副作用, 只回问宿主闸门。
41
+ const handle = async (req, res) => {
42
+ if (stopped) return json(res, 503, { ok: false, error: { code: 'STOPPED', message: '工具已停止' } })
43
+ if (req.method !== method) { res.setHeader('Allow', method); return json(res, 405, { ok: false, error: { code: 'METHOD_NOT_ALLOWED', message: '请求方法不支持' } }) }
44
+ const controller = new AbortController(); controllers.add(controller)
45
+ const onClose = () => { if (!res.writableEnded) controller.abort() }
46
+ res.on('close', onClose)
47
+ const timeout = name === 'provider-check' ? 60 * 1000 : name === 'catalog-sync' ? 120 * 1000 : 10 * 1000
48
+ let timer
49
+ try {
50
+ const input = method === 'GET' ? Object.fromEntries(new URL(req.url, 'http://local').searchParams) : await body(req)
51
+ if (method === 'POST' && (input === null || typeof input !== 'object' || Array.isArray(input))) fail('INVALID_REQUEST', '请求内容必须为JSON对象')
52
+ const data = await Promise.race([
53
+ Promise.resolve(action(input, controller.signal)),
54
+ // 超时错误随 abort reason 一起下发: 即使 abort 监听先被同步派发, 也拿到 TIMEOUT 而不是 CANCELLED
55
+ new Promise((_, reject) => { timer = setTimeout(() => { const error = new StockError('TIMEOUT', '操作超时,请稍后重试', 504); controller.abort(error); reject(error) }, timeout) }),
56
+ new Promise((_, reject) => controller.signal.addEventListener('abort', () => reject(controller.signal.reason instanceof StockError ? controller.signal.reason : new StockError('CANCELLED', '操作已取消', stopped ? 503 : 504)), { once: true })),
57
+ ])
58
+ json(res, 200, { ok: true, data })
59
+ } catch (e) {
60
+ const error = e instanceof StockError ? e : new StockError('INVALID_REQUEST', e instanceof z.ZodError ? '请求参数格式错误' : '股票工具请求失败', e instanceof z.ZodError ? 400 : 500)
61
+ json(res, error.status, { ok: false, error: { code: error.code, message: error.message, retryable: error.retryable, retryAfterMs: error.retryAfterMs }, ...(error.details === undefined ? {} : { details: error.details }), ...(error.revision === undefined ? {} : { revision: error.revision }), ...(e.snapshot ? { snapshot: e.snapshot } : {}) })
62
+ } finally { clearTimeout(timer); controllers.delete(controller); res.removeListener('close', onClose) }
63
+ }
64
+ disposers.push(webServer.register({ kind: 'exact', path: `${PREFIX}/${name}`, handler: withRouteGate(ctx, handle) }))
65
+ }
66
+ } catch (e) { for (const dispose of disposers.reverse()) dispose(); throw e }
67
+ return () => { stopped = true; for (const dispose of disposers.reverse()) dispose(); for (const c of controllers) c.abort(); controllers.clear() }
68
+ }
package/src/schemas.mjs CHANGED
@@ -12,6 +12,8 @@ export const marksSchema = z.array(markSchema).max(12).default([]).superRefine((
12
12
  const rate = z.number().int().positive().max(100000)
13
13
  // 每票可同时归属的分组上限: 标签是视图视角, 超过这个数量就该换一种组织方式
14
14
  export const MAX_TAGS = 8
15
+ // 一条路由最多挂几个备用源: 再多就不是主备而是轮询列表
16
+ export const MAX_FALLBACKS = 3
15
17
  // 标签名即分组身份: 允许 1-12 字, 不允许首尾空白与控制字符(它们会让同名标签在界面上看起来一样)。
16
18
  // C0/C1/DEL 之外还挡零宽与双向控制符: 它们不占宽度却能让两个不同的标签在 chips 与 tab 上完全同形
17
19
  const TAG_CHARS_SOURCE = '\\u0000-\\u001f\\u007f-\\u009f\\u200b-\\u200f\\u202a-\\u202e'
@@ -22,18 +24,34 @@ export const tagName = z.string().refine(s => {
22
24
  const trimmed = s.trim()
23
25
  return trimmed !== '' && trimmed === s && [...trimmed].length <= 12 && !TAG_CHARS.test(trimmed)
24
26
  }, '标签名需为 1-12 字, 不含首尾空白与控制字符')
25
- export const capability = z.enum(['quotes', 'catalog', 'search', 'calendar', 'kline'])
27
+ // 分时与 K 线是两种上游: 分时(trends2)只有部分来源支持, 日/周/月走另一套端点。
28
+ // 合成一个能力会让"K 线来源选腾讯"静默把分时打死, 所以拆成独立能力各自路由。
29
+ export const CAPABILITIES = ['quotes', 'catalog', 'search', 'calendar', 'kline', 'trend']
30
+ export const capability = z.enum(CAPABILITIES)
26
31
  export const marketSchema = z.enum(Object.keys(MARKET_META))
32
+ const credentialRef = z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/)
33
+ // 代理 URL 与反代端点都只允许主机路径; 账号密码必须走宿主凭据, 否则会随配置进快照与持久化
34
+ const noUserinfo = value => {
35
+ const url = new URL(value)
36
+ return !url.username && !url.password
37
+ }
38
+ const httpUrl = z.string().url().refine(v => v.startsWith('http://') || v.startsWith('https://'), '仅支持 http(s) URL')
39
+ const proxyUrl = httpUrl.refine(noUserinfo, '代理 URL 不能包含账号密码,请写入代理凭据')
40
+ const endpointUrl = httpUrl.refine(noUserinfo, '端点 URL 不能包含账号密码,请改用代理凭据')
27
41
  export const providerSchema = z.strictObject({
28
- id, adapterId: id, enabled: z.boolean(), credentialRef: z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).nullable(), quotaGroup: id,
42
+ id, adapterId: id, enabled: z.boolean(), credentialRef: credentialRef.nullable(), proxyCredentialRef: credentialRef.nullable().optional(), quotaGroup: id,
29
43
  budget: z.strictObject({ requestsPerMinute: rate.nullable(), dailyRequestLimit: rate.nullable(), billingUnit: z.enum(['request', 'symbol']), symbolCreditsPerMinute: rate.nullable(), capabilityLimits: z.partialRecord(capability, rate) }),
30
- endpoints: z.record(z.string().url()).optional(),
31
- // 上游出口代理(反代/正向代理统一走 URL): http(s)://[user:pass@]host:port, 凭据在 userinfo
32
- proxy: z.string().url().refine(v => v.startsWith('http://') || v.startsWith('https://'), '代理仅支持 http(s) URL').optional(),
44
+ endpoints: z.record(z.string(), endpointUrl).optional(),
45
+ // 上游出口代理(反代/正向代理统一走 URL): http(s)://host:port; 账号密码由 proxyCredentialRef 指向宿主凭据
46
+ proxy: proxyUrl.optional(),
33
47
  }).refine(p => p.credentialRef !== null || p.budget.requestsPerMinute !== null, '免凭据来源必须声明保守预算')
34
48
  export const routeSchema = z.strictObject({
35
49
  id, capability, market: marketSchema, instrument: z.literal('equity'), primaryInstanceId: id,
36
- fallbackInstanceIds: z.array(id).max(1), failoverMode: z.enum(['off', 'network']), maxDelaySeconds: z.number().nonnegative().nullable(), acceptUnknownDelay: z.boolean(),
50
+ fallbackInstanceIds: z.array(id).max(MAX_FALLBACKS), failoverMode: z.enum(['off', 'network']), maxDelaySeconds: z.number().nonnegative().nullable(), acceptUnknownDelay: z.boolean(),
51
+ }).superRefine((route, ctx) => {
52
+ // 环里出现重复成员或主源自己: 三轮失败后"换源"其实没换, 只会白换代次丢掉在飞数据
53
+ const ring = [route.primaryInstanceId, ...route.fallbackInstanceIds]
54
+ if (new Set(ring).size !== ring.length) ctx.addIssue({ code: 'custom', path: ['fallbackInstanceIds'], message: '备用源不能重复,也不能与主源相同' })
37
55
  })
38
56
  // GET query 唯一入口: limit 为字符串形态需 coerce
39
57
  export const klineQuerySchema = z.strictObject({
@@ -43,12 +61,28 @@ export const klineQuerySchema = z.strictObject({
43
61
  // 强制刷新:客户端详情页刷新走 ?force=1,服务端据此跳过缓存读;缺省按缓存
44
62
  force: z.enum(['0', '1']).optional(),
45
63
  })
46
- // 路由上限: 八市场×(quotes/catalog/search/calendar/kline) 全开 40 条封顶
47
- const configSchema = z.strictObject({ providers: z.array(providerSchema).max(8), routes: z.array(routeSchema).max(40) })
64
+ // 手动刷新的证券参数: 自选 id 字符串或客户端持有的完整身份(浏览/搜索 peek)。形状在这里定死,
65
+ // 应用层不再手写类型判断 —— 旧实现遇到 null 元素直接 TypeError 变成 500, 坏市场枚举也照发上游。
66
+ const refreshSecuritySchema = z.union([
67
+ z.string().max(64).refine(value => {
68
+ const parts = value.split(':')
69
+ return parts.length === 3 && parts[1] === 'equity' && MARKET_META[parts[0]] !== undefined && /^[\w.]{1,15}$/.test(parts[2])
70
+ }, '证券标识无效'),
71
+ z.object({ id: z.string().min(1).max(64), exchange: marketSchema, code: z.string().min(1).max(20), officialName: z.string().min(1).max(100).optional() })
72
+ .superRefine((value, ctx) => { if (value.id !== `${value.exchange}:equity:${value.code}`) ctx.addIssue({ code: 'custom', message: '证券身份不一致' }) }),
73
+ ])
74
+ export const refreshSecuritiesSchema = z.array(refreshSecuritySchema).max(100)
75
+ // 路由上限: 八市场 × 全部能力, 全开也要装得下
76
+ const MAX_ROUTES = Object.keys(MARKET_META).length * CAPABILITIES.length
77
+ const configSchema = z.strictObject({ providers: z.array(providerSchema).max(8), routes: z.array(routeSchema).max(MAX_ROUTES) })
48
78
  // 悬浮盯盘刷新间隔独立于列表: 窗口只要快慢, 与列表的 15/30/60 不共享档位
49
79
  export const FLOAT_REFRESH_SECONDS = [3, 5, 10, 15, 30]
50
80
  export const DEFAULT_FLOAT_REFRESH_SECONDS = 10
51
81
  export const preferencesSchema = z.strictObject({ refreshSeconds: z.union([z.literal(15), z.literal(30), z.literal(60)]), colorMode: z.enum(['red-up', 'green-up']), floatRefreshSeconds: z.union(FLOAT_REFRESH_SECONDS.map(n => z.literal(n))).default(DEFAULT_FLOAT_REFRESH_SECONDS) })
82
+ // 上游请求的兜底节拍: 取列表与浮窗两处设置里更快的那个, 再留 10% 余量。
83
+ // 留余量是因为定时器唤醒有抖动: 按整周期卡会在下一拍判定时差几毫秒, 反而把拍子推成两倍。
84
+ export const TICK_SAFETY_RATIO = 0.9
85
+ export const tickPeriodMs = preferences => TICK_SAFETY_RATIO * 1000 * Math.min(preferences.refreshSeconds, preferences.floatRefreshSeconds)
52
86
  export const securitySchema = z.object({ id: z.string(), exchange: marketSchema, code: z.string(), officialName: z.string().min(1).max(100), instrument: z.literal('equity'), currency: z.string(), timezone: z.string(), priceScale: z.number().int(), listingStatus: z.string() }).superRefine((s, ctx) => {
53
87
  const meta = MARKET_META[s.exchange]
54
88
  if (!meta || !meta.codePattern.test(s.code) || s.id !== `${s.exchange}:equity:${s.code}`) { ctx.addIssue({ code: 'custom', message: '证券身份不一致' }); return }
@@ -56,7 +90,11 @@ export const securitySchema = z.object({ id: z.string(), exchange: marketSchema,
56
90
  })
57
91
  export function parseConfiguration(value) {
58
92
  const result = configSchema.safeParse(value)
59
- if (!result.success) fail('INVALID_CONFIGURATION', '数据源配置字段或格式无效', 422)
93
+ if (!result.success) {
94
+ // 把 zod 的首个问题路径带进 message: 设置页只能显示 message, 只说"字段或格式无效"用户无处下手
95
+ const [first] = result.error.issues, path = first.path.length ? first.path.join('.') : '根'
96
+ fail('INVALID_CONFIGURATION', `数据源配置字段或格式无效:${path} ${first.message}`, 422, { details: result.error.issues.map(issue => ({ path: issue.path.join('.'), message: issue.message, code: issue.code })) })
97
+ }
60
98
  const config = result.data, seen = new Set(), providerIds = new Set()
61
99
  for (const p of config.providers) {
62
100
  if (providerIds.has(p.id)) fail('DUPLICATE_PROVIDER', '数据源实例名称重复', 422)
@@ -72,12 +110,14 @@ export function parseConfiguration(value) {
72
110
  seen.add(key); routeIds.add(r.id)
73
111
  const targets = [r.primaryInstanceId, ...r.fallbackInstanceIds]
74
112
  if (new Set(targets).size !== targets.length || targets.some(target => !config.providers.some(p => p.id === target && p.enabled))) fail('INVALID_ROUTE', '路由引用了不存在或禁用的数据源', 422)
75
- if (!['quotes', 'kline'].includes(r.capability) && (r.failoverMode !== 'off' || r.fallbackInstanceIds.length)) fail('INVALID_ROUTE', '只有报价与K线支持备用源', 422)
113
+ if (!['quotes', 'kline', 'trend'].includes(r.capability) && (r.failoverMode !== 'off' || r.fallbackInstanceIds.length)) fail('INVALID_ROUTE', '只有报价与K线类能力支持备用源', 422)
76
114
  if (r.failoverMode !== 'off' && !r.fallbackInstanceIds.length) fail('INVALID_ROUTE', '自动切换需要备用报价源', 422)
77
115
  }
78
116
  return config
79
117
  }
80
- export const controlSchema = z.object({ revision: z.number().int().nonnegative(), routingRevision: z.number().int().nonnegative(), watchlist: z.object({ order: z.array(z.string()).max(100), items: z.record(z.string(), securitySchema.safeExtend({ alias: z.string(), pinned: z.boolean(), marks: marksSchema, tags: z.array(tagName).max(MAX_TAGS).refine(list => new Set(list).size === list.length, '标签不能重复').default([]) })) }), preferences: preferencesSchema, providers: z.array(providerSchema), routes: z.array(routeSchema), operations: z.array(z.object({ id: z.uuid(), hash: z.string(), at: z.number(), result: z.object({ revision: z.number() }).passthrough(), action: z.string(), payload: z.unknown() })).max(256) }).superRefine((control, ctx) => {
118
+ // 分时路由的迁移版本: 存量库只补一次(补缺失路由 + 给单源分时登记备源), 用户随后删掉分时路由不该在下次启动被复活
119
+ export const TREND_ROUTE_MIGRATION = 2
120
+ export const controlSchema = z.object({ revision: z.number().int().nonnegative(), routingRevision: z.number().int().nonnegative(), routeMigration: z.number().int().nonnegative().default(0), watchlist: z.object({ order: z.array(z.string()).max(100), items: z.record(z.string(), securitySchema.safeExtend({ alias: z.string(), pinned: z.boolean(), marks: marksSchema, tags: z.array(tagName).max(MAX_TAGS).refine(list => new Set(list).size === list.length, '标签不能重复').default([]) })) }), preferences: preferencesSchema, providers: z.array(providerSchema), routes: z.array(routeSchema), operations: z.array(z.object({ id: z.uuid(), hash: z.string(), at: z.number(), result: z.object({ revision: z.number() }).passthrough(), action: z.string(), payload: z.unknown() })).max(256) }).superRefine((control, ctx) => {
81
121
  const w = control.watchlist
82
122
  if (new Set(w.order).size !== w.order.length || w.order.length !== Object.keys(w.items).length || w.order.some(id => w.items[id]?.id !== id)) ctx.addIssue({ code: 'custom', message: '自选序列与证券不一致' })
83
123
  let unpinned = false
@@ -88,15 +128,70 @@ export const controlSchema = z.object({ revision: z.number().int().nonnegative()
88
128
  // 旧记录要能在数据域打开时通过校验并就地改成新字段 —— 这次校验发生在 storageDomain.open,
89
129
  // 早于插件应用层的任何迁移代码, 迁移写在这一层之外等于永远跑不到。
90
130
  // 新旧字段并存时以新字段为准; 非对象条目原样交给 schema 去拒绝, 不在这里抛
131
+ // 无变化时返回原引用: 上层据此判断"这次读入是否改写了记录", 只有真改了才回写文件。
132
+ const stripUserinfo = value => {
133
+ if (typeof value !== 'string') return value
134
+ try {
135
+ const url = new URL(value)
136
+ if (!url.username && !url.password) return value
137
+ url.username = ''; url.password = ''
138
+ return url.toString()
139
+ } catch { return value }
140
+ }
141
+ const normalizeEndpointMap = endpoints => {
142
+ if (!endpoints || typeof endpoints !== 'object' || Array.isArray(endpoints)) return endpoints
143
+ let changed = false
144
+ const next = Object.fromEntries(Object.entries(endpoints).map(([key, value]) => {
145
+ const stripped = stripUserinfo(value)
146
+ if (stripped !== value) changed = true
147
+ return [key, stripped]
148
+ }))
149
+ return changed ? next : endpoints
150
+ }
91
151
  const normalizeProvider = provider => {
92
- if (!provider || typeof provider !== 'object' || !('credentialEnv' in provider)) return provider
93
- const { credentialEnv, ...rest } = provider
94
- return { ...rest, credentialRef: 'credentialRef' in rest ? rest.credentialRef : credentialEnv ?? null }
152
+ if (!provider || typeof provider !== 'object') return provider
153
+ let next = provider, changed = false
154
+ if ('credentialEnv' in next) {
155
+ const { credentialEnv, ...rest } = next
156
+ next = { ...rest, credentialRef: 'credentialRef' in rest ? rest.credentialRef : credentialEnv ?? null }
157
+ changed = true
158
+ }
159
+ // 旧记录可能把账号密码写在代理 URL 与反代端点的 userinfo 里: 读入即剥离, 防止快照继续回显;
160
+ // 值无法安全迁移(宿主凭据写入是异步的), 用户需按 README 重新录入代理凭据。
161
+ const proxy = stripUserinfo(next.proxy)
162
+ if (proxy !== next.proxy) { next = { ...next, proxy }; changed = true }
163
+ const endpoints = normalizeEndpointMap(next.endpoints)
164
+ if (endpoints !== next.endpoints) { next = { ...next, endpoints }; changed = true }
165
+ return changed ? next : provider
95
166
  }
96
167
  const normalizeCredentialField = root => {
97
168
  if (!root || typeof root !== 'object' || !Array.isArray(root.providers)) return root
98
- if (!root.providers.some(p => p && typeof p === 'object' && 'credentialEnv' in p)) return root
99
- return { ...root, providers: root.providers.map(normalizeProvider) }
169
+ if (!root.providers.some(p => p && typeof p === 'object' && ('credentialEnv' in p || typeof p.proxy === 'string' || p.endpoints))) return root
170
+ let changed = false
171
+ const providers = root.providers.map(p => { const next = normalizeProvider(p); if (next !== p) changed = true; return next })
172
+ return changed ? { ...root, providers } : root
173
+ }
174
+ // 幂等操作台账里的 configuration 载荷是用户当时的完整配置副本: 它和 providers 一样会带代理/端点 URL,
175
+ // 只清洗顶层 providers 会让明文继续留在文件里(快照不返回 operations, 但持久化仍是明文)。
176
+ const normalizeOperations = root => {
177
+ if (!Array.isArray(root?.operations)) return root
178
+ let changed = false
179
+ const operations = root.operations.map(operation => {
180
+ const payload = operation && typeof operation === 'object' ? operation.payload : null
181
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return operation
182
+ let next = payload
183
+ if (Array.isArray(payload.providers)) {
184
+ let providersChanged = false
185
+ const providers = payload.providers.map(p => { const candidate = normalizeProvider(p); if (candidate !== p) providersChanged = true; return candidate })
186
+ if (providersChanged) next = { ...next, providers }
187
+ }
188
+ const endpoints = normalizeEndpointMap(next.endpoints)
189
+ if (endpoints !== next.endpoints) next = { ...next, endpoints }
190
+ if (next === payload) return operation
191
+ changed = true
192
+ return { ...operation, payload: next }
193
+ })
194
+ return changed ? { ...root, operations } : root
100
195
  }
101
196
  // 分组从单值 group 改为多标签 tags。与凭据改名同理, 归一必须在数据域 schema 上做,
102
197
  // 否则存量记录通不过 storageDomain.open 的校验, 插件整体起不来。非字符串 group 也搬进 tags,
@@ -119,7 +214,16 @@ const normalizeWatchlistTags = root => {
119
214
  }))
120
215
  return { ...root, watchlist: { ...root.watchlist, items: next } }
121
216
  }
122
- const normalizeStoredControl = root => normalizeWatchlistTags(normalizeCredentialField(root))
217
+ // 打开数据域时 schema 会就地归一旧记录; 归一发生在校验层, 应用层拿到的已是新值, 无法再判断
218
+ // "文件里是不是还有旧字段/明文"。这里记一个成功归一计数: openState 在打开前后取差, 差值非零即回写,
219
+ // 用户不必先做一次无关写操作才把明文从磁盘清掉。
220
+ let normalizationCount = 0
221
+ export const storedNormalizationCount = () => normalizationCount
222
+ const normalizeStoredControl = root => {
223
+ const next = normalizeOperations(normalizeWatchlistTags(normalizeCredentialField(root)))
224
+ if (next !== root) normalizationCount++
225
+ return next
226
+ }
123
227
  export const storedControlSchema = z.preprocess(normalizeStoredControl, controlSchema)
124
228
  // 存储只有一条记录: 自选与路由。K 线/目录/日历都是可重建的派生数据, 只放内存 ——
125
229
  // 把它们塞进同一个文件曾把文件撑到 3.3 MB, 每次改自选都要整体重写, 写坏一次全没。
@@ -129,7 +233,8 @@ export const domainSpec = { name: 'stock_assistant', version: 1, layout: 'single
129
233
  export const defaultConfig = () => {
130
234
  const budget = (requestsPerMinute, capabilityLimits = {}) => ({ requestsPerMinute, dailyRequestLimit: null, billingUnit: 'request', symbolCreditsPerMinute: null, capabilityLimits })
131
235
  const providers = [
132
- { id: 'em-default', adapterId: 'eastmoney', enabled: true, credentialRef: null, quotaGroup: 'free-quote', budget: budget(60, { kline: 30 }) },
236
+ // 分时子额度按浮窗最快档(3 秒一拍)留量: 20 拍/分还要叠加详情页分时, 顶格会把自己限流
237
+ { id: 'em-default', adapterId: 'eastmoney', enabled: true, credentialRef: null, quotaGroup: 'free-quote', budget: budget(60, { kline: 30, trend: 30 }) },
133
238
  { id: 'sn-backup', adapterId: 'sina', enabled: true, credentialRef: null, quotaGroup: 'free-list', budget: budget(120, { catalog: 60 }) },
134
239
  { id: 'tx-backup', adapterId: 'tencent', enabled: true, credentialRef: null, quotaGroup: 'free-backup', budget: budget(60, { kline: 20 }) },
135
240
  { id: 'xq-backup', adapterId: 'xueqiu', enabled: true, credentialRef: null, quotaGroup: 'free-xq', budget: budget(60) },
@@ -147,7 +252,9 @@ export const defaultConfig = () => {
147
252
  route(market, 'search', 'em-default'),
148
253
  route(market, 'quotes', 'em-default', quoteBackupOf(market)),
149
254
  route(market, 'kline', 'em-default', klineBackup.has(market) ? 'tx-backup' : null),
255
+ // 分时只有东财供得出, 不给备源: 备源不支持分时比没有备源更糟, 会把请求打给一个恒拒绝的源
256
+ route(market, 'trend', 'em-default'),
150
257
  ])
151
258
  return { providers, routes }
152
259
  }
153
- export const initialControl = () => ({ revision: 0, routingRevision: 0, watchlist: { order: [], items: {} }, preferences: { refreshSeconds: 15, colorMode: 'red-up', floatRefreshSeconds: DEFAULT_FLOAT_REFRESH_SECONDS }, ...defaultConfig(), operations: [] })
260
+ export const initialControl = () => ({ revision: 0, routingRevision: 0, routeMigration: TREND_ROUTE_MIGRATION, watchlist: { order: [], items: {} }, preferences: { refreshSeconds: 15, colorMode: 'red-up', floatRefreshSeconds: DEFAULT_FLOAT_REFRESH_SECONDS }, ...defaultConfig(), operations: [] })
package/src/state.mjs CHANGED
@@ -1,24 +1,28 @@
1
1
  import { createHash } from 'node:crypto'
2
- import { domainSpec, initialControl, controlSchema } from './schemas.mjs'
2
+ import { domainSpec, initialControl, controlSchema, storedNormalizationCount } from './schemas.mjs'
3
3
  import { createMemoryCache } from './memory-cache.mjs'
4
4
  import { fail } from './market-model.mjs'
5
5
  const DAY = 24 * 60 * 60 * 1000
6
6
  // 目录/日历条数很少, 给独立小池: 与 K 线共用一个淘汰池时会被几十节 K 线挤掉, 挤掉后又要重新拉目录
7
- const CATALOG_CACHE_LIMIT = 64, KLINE_CACHE_LIMIT = 512
7
+ // 分时当日缓存也走独立池: 它按天增长(每只票一条), 混进 K 线池会把 K 线挤掉
8
+ const CATALOG_CACHE_LIMIT = 64, KLINE_CACHE_LIMIT = 512, TREND_CACHE_LIMIT = 128
8
9
  export const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex')
9
10
  export async function openState(storageDomain, changed = () => {}, now = Date.now) {
10
11
  // 只有控制记录落盘; 派生数据放内存, 所以打开失败只可能是这一个文件
12
+ // schema 在读入时归一旧字段与 URL 明文, 应用层无法再区分"读到的值原本是否合法"; 用计数差值判断,
13
+ // 归一过的记录当场回写, 不必等下一次无关写操作才把明文从磁盘清掉。
14
+ const normalizationBaseline = storedNormalizationCount()
11
15
  const domain = await storageDomain.open(domainSpec)
12
16
  const table = domain.table('control')
13
17
  try {
14
- // 存量字段改名的归一发生在数据域的 valueSchema 上(storageDomain.open 阶段), 这里读到的已是新格式
15
18
  if (!table.get('root')) await table.put('root', initialControl())
19
+ else if (storedNormalizationCount() !== normalizationBaseline) await table.put('root', table.get('root'))
16
20
  } catch (e) { await Promise.allSettled([domain.close()]); throw e }
17
- const cache = createMemoryCache({ limit: CATALOG_CACHE_LIMIT }), klineCache = createMemoryCache({ limit: KLINE_CACHE_LIMIT })
21
+ const cache = createMemoryCache({ limit: CATALOG_CACHE_LIMIT }), klineCache = createMemoryCache({ limit: KLINE_CACHE_LIMIT }), trendCache = createMemoryCache({ limit: TREND_CACHE_LIMIT })
18
22
  let tail = Promise.resolve(), stopped = false
19
23
  return {
20
24
  get: () => structuredClone(table.get('root')),
21
- cache, klineCache,
25
+ cache, klineCache, trendCache,
22
26
  replay(operation) {
23
27
  const prior = table.get('root').operations.find(o => o.id === operation.operationId && now() - o.at < DAY)
24
28
  if (!prior) return null
package/src/ticks.mjs ADDED
@@ -0,0 +1,45 @@
1
+ import { marketDate } from './market-model.mjs'
2
+ // 报价拍点: 分时上游不可用时, 用报价轮询攒下的点续在当日真实分时后面, 好过断在最后一根。
3
+ // 同一分钟只留最后一条(分钟图的分辨率就是这样), 一天一换; 单证券点数按最长交易时段封顶,
4
+ // 证券数也有上限——详情页浏览会带来大量一次性的 peek 报价, 不封就会一直涨。
5
+ const MINUTE_SECONDS = 60
6
+ // 伦敦 8.5 小时是最长的一个交易时段, 其余市场都比它短
7
+ const POINTS_LIMIT = 8 * 60 + 30
8
+ const SECURITY_LIMIT = 200
9
+ const minuteOf = seconds => Math.floor(seconds / MINUTE_SECONDS)
10
+ export function createTickStore({ now = Date.now, limit = POINTS_LIMIT, securities = SECURITY_LIMIT }) {
11
+ const store = new Map()
12
+ const pointsFor = (securityId, sessionDate) => {
13
+ const entry = store.get(securityId)
14
+ // 命中即移到队尾: 淘汰的是"最久没报价"的证券, 不是最早进来的
15
+ if (entry?.sessionDate === sessionDate) { store.delete(securityId); store.set(securityId, entry); return entry.points }
16
+ const points = []
17
+ store.delete(securityId)
18
+ store.set(securityId, { sessionDate, points })
19
+ while (store.size > securities) store.delete(store.keys().next().value)
20
+ return points
21
+ }
22
+ return {
23
+ push(securityId, market, at, price) {
24
+ // 缺失值不是 0: Number(null) 会得到真实的 0, 在图上就是一条贴着地板的价格
25
+ const stamp = at == null || at === '' ? NaN : Number(at), value = price == null || price === '' ? NaN : Number(price)
26
+ if (!Number.isFinite(stamp) || !Number.isFinite(value)) return
27
+ const points = pointsFor(securityId, marketDate(market, stamp * 1000))
28
+ // 同一分钟的点是同一根分钟线的不同快照, 后到的覆盖前一条
29
+ const last = points.at(-1)
30
+ if (last && minuteOf(last.at) === minuteOf(stamp)) { points[points.length - 1] = { at: stamp, price: value }; return }
31
+ points.push({ at: stamp, price: value })
32
+ // 画线要时间序: 补历史点或来源时钟回拨都会让插入顺序不等于时间顺序, 排序后再裁剪
33
+ points.sort((a, b) => a.at - b.at)
34
+ if (points.length > limit) points.splice(0, points.length - limit)
35
+ },
36
+ series(securityId, market) {
37
+ const entry = store.get(securityId)
38
+ if (!entry || entry.sessionDate !== marketDate(market, now())) return []
39
+ return entry.points.map(point => ({ ...point }))
40
+ },
41
+ delete(securityId) { store.delete(securityId) },
42
+ clear() { store.clear() },
43
+ get size() { return store.size },
44
+ }
45
+ }
@@ -0,0 +1,26 @@
1
+ import { marketDate } from './market-model.mjs'
2
+ // 当日分时缓存: 一个交易日一份, 成功一次就覆盖前一份, 只在上游失败时读取。
3
+ // 数据日期取最后一根分时的时间而不是请求时刻: 周末/盘前请求拿到的是上一交易日的线, 不能当成今天的缓存。
4
+ const keyOf = ({ market, code, limit }) => `trend:${market}:${code}:${limit}`
5
+ const dayOf = (market, payload) => {
6
+ const at = Number(payload?.candles?.at(-1)?.at)
7
+ return Number.isFinite(at) ? marketDate(market, at * 1000) : null
8
+ }
9
+ export function createTrendCache({ table, now = Date.now }) {
10
+ return {
11
+ async get(key) {
12
+ const raw = await table.get(keyOf(key))
13
+ // 过期即删: 否则旧记录继续占着淘汰池, 还会被后来者当成"当日缓存"
14
+ const stale = !raw || raw.kind !== 'trend' || !raw.payload?.candles?.length || raw.sessionDate !== marketDate(key.market, now())
15
+ if (!stale) return raw
16
+ if (raw) await table.delete(keyOf(key)).catch(() => {})
17
+ return null
18
+ },
19
+ // 空结果(上游成功但没数据)和兜底结果都不写: 缓存只存"完整的一次真分时"
20
+ async put(key, result) {
21
+ const sessionDate = dayOf(key.market, result)
22
+ if (!sessionDate || result.complete === false || result.offline) return
23
+ await table.put(keyOf(key), { kind: 'trend', sessionDate, cachedAt: now(), payload: result }).catch(() => {})
24
+ },
25
+ }
26
+ }