From a401603ef65695b2741dea55136060c30bd0e78f Mon Sep 17 00:00:00 2001 From: dofastted Date: Tue, 1 Dec 2026 15:17:16 +0800 Subject: [PATCH 01/15] chore(risk): clean backend dead code, fix cache/log/panel inconsistencies, and add regressions --- src/lib/admin/error-class.mjs | 4 +- src/lib/admin/panel-routes.mjs | 114 +++++++++++++++-------- src/lib/core/distill-detect.mjs | 2 +- src/lib/core/errors.mjs | 24 +++-- src/lib/core/refusal-guard.mjs | 4 +- src/lib/core/refusal-similarity.mjs | 8 +- src/lib/db/repos/refusal-guards-repo.mjs | 5 - src/lib/pool/upstream-error-policy.mjs | 4 +- src/lib/protocol/handle-codex.mjs | 2 +- src/lib/protocol/handle-protocol.mjs | 4 +- src/lib/protocol/intercept-gate.mjs | 68 +++++++------- src/lib/protocol/intercept-stats.mjs | 2 + src/lib/protocol/jev-intercept.mjs | 55 ++--------- test/unit/distill-detect.test.mjs | 39 +------- test/unit/errors-map.test.mjs | 4 +- test/unit/jev-intercept.test.mjs | 57 ++++++++++++ test/unit/jev-usage-panel.test.mjs | 3 + test/unit/refusal-guard.test.mjs | 3 + test/unit/refusal-session-block.test.mjs | 24 ++++- test/unit/refusal-similarity.test.mjs | 3 + test/unit/request-redis-opt.test.mjs | 19 ++++ 21 files changed, 264 insertions(+), 184 deletions(-) diff --git a/src/lib/admin/error-class.mjs b/src/lib/admin/error-class.mjs index 0790a77e0b..b5b1b66716 100644 --- a/src/lib/admin/error-class.mjs +++ b/src/lib/admin/error-class.mjs @@ -3,7 +3,7 @@ * Derived from status / error_code / message so historical rows classify without a migration. */ -import { isThirdPartyClientMessage, isUnanswerablePromptMessage } from '../core/errors.mjs' +import { isThirdPartyClientMessage, isUsagePolicyErrorMessage } from '../core/errors.mjs' export const ERROR_CLASSES = { auth: { id: 'auth', owner: 'client', label: '认证' }, @@ -331,7 +331,7 @@ export function classifyRequestError(row = {}) { if ( id !== 'auth' && id !== 'credential' && - isUnanswerablePromptMessage(row?.error_message) && + isUsagePolicyErrorMessage(row?.error_message) && !isOauthCredentialFailure(row, text, code) ) { id = 'refusal' diff --git a/src/lib/admin/panel-routes.mjs b/src/lib/admin/panel-routes.mjs index 8309a9f9c2..11c70472c2 100644 --- a/src/lib/admin/panel-routes.mjs +++ b/src/lib/admin/panel-routes.mjs @@ -1393,11 +1393,7 @@ export function createPanelHandler(ctx) { vms.map((vm) => ({ ...vm, quota: panel.findAccount(accountQuota, vm, accountSnap)?.unified || null })), selectedKeys, ) - return { - ...inventory, - account_type_options: [], - account_plan_type_options: [], - } + return inventory } function withJevEndpointStatus(config) { @@ -1957,24 +1953,6 @@ export function createPanelHandler(ctx) { } } - const shouldSyncSchedulerOnMutation = (method, pathname) => { - if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') return false - return ( - pathname === '/admin/routing' || - pathname === '/api/panel/routing' || - pathname === '/api/panel/api-keys' || - pathname.startsWith('/api/panel/api-keys/') || - pathname === '/api/panel/api-endpoints' || - pathname.startsWith('/api/panel/api-endpoints/') || - pathname === '/api/panel/vms' || - pathname.startsWith('/api/panel/vms/') || - pathname === '/api/panel/refusal-guards' || - pathname.startsWith('/api/panel/refusal-guards/') || - pathname === '/api/panel/jev-intercept' || - pathname.startsWith('/api/panel/jev-intercept/') - ) - } - const isReadOnlyPanelPost = (method, pathname) => { if (method !== 'POST') return false if ( @@ -2001,6 +1979,25 @@ export function createPanelHandler(ctx) { ) } + const shouldSyncSchedulerOnMutation = (method, pathname) => { + if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') return false + if (isReadOnlyPanelPost(method, pathname)) return false + return ( + pathname === '/admin/routing' || + pathname === '/api/panel/routing' || + pathname === '/api/panel/api-keys' || + pathname.startsWith('/api/panel/api-keys/') || + pathname === '/api/panel/api-endpoints' || + pathname.startsWith('/api/panel/api-endpoints/') || + pathname === '/api/panel/vms' || + pathname.startsWith('/api/panel/vms/') || + pathname === '/api/panel/refusal-guards' || + pathname.startsWith('/api/panel/refusal-guards/') || + pathname === '/api/panel/jev-intercept' || + pathname.startsWith('/api/panel/jev-intercept/') + ) + } + const invalidateCachesForPanelMutation = (method, pathname) => { if (method === 'GET' || method === 'HEAD' || method === 'OPTIONS') return if (isReadOnlyPanelPost(method, pathname)) return @@ -2116,7 +2113,6 @@ export function createPanelHandler(ctx) { pathname.startsWith('/api/panel/settings') || pathname.startsWith('/api/panel/model-policy') || pathname.startsWith('/api/panel/distill') || - pathname.startsWith('/api/panel/refusal-') || pathname.startsWith('/api/panel/jev-intercept') || pathname.startsWith('/api/panel/notify') || pathname === '/api/panel/onboarding' @@ -8698,7 +8694,11 @@ export function createPanelHandler(ctx) { if (!repo.remove(deviceId)) { return json(res, 404, { ok: false, - error: { type: 'not_found_error', code: 'refusal_device_not_found', message: 'device 不存在' }, + error: { + type: 'not_found_error', + code: 'refusal_device_not_found', + message: '设备或会话封禁记录不存在', + }, }) } if (existing?.subject_kind === 'session' && existing.session_id) { @@ -8712,7 +8712,7 @@ export function createPanelHandler(ctx) { error: { type: 'invalid_request_error', code: 'confirm_required', - message: '清空 device 封禁须 confirm: true,或传 device_id', + message: '清空设备与根会话封禁须 confirm: true,或传 device_id', }, }) } @@ -8725,25 +8725,33 @@ export function createPanelHandler(ctx) { } if (req.method === 'GET' && p === '/api/panel/jev-usage') { if (panelIdentity(req).role !== 'admin') - return json(res, 403, { ok: false, error: { code: 'forbidden', message: '仅管理员可查看审核用量' } }) + return json(res, 403, { + ok: false, + error: { type: 'permission_error', code: 'forbidden', message: '仅管理员可查看审核用量' }, + }) + const repo = new JevUsageRepo() + let page try { - const repo = new JevUsageRepo() - const page = repo.list(Object.fromEntries(url.searchParams)) - const settings = new SettingsRepo() - const keys = repo.configuredKeys(publicJevKeys(readJevConfig((key, fallback) => settings.get(key, fallback)))) - return json( - res, - 200, - panel.ok({ ...repo.overview(), ...page, keys, storage_errors_since_start: jevUsageStorageErrors() }), - ) + page = repo.list(Object.fromEntries(url.searchParams)) } catch (error) { if (error instanceof TypeError) return json(res, 400, { ok: false, - error: { code: 'invalid_jev_usage_query', message: '用量查询参数不正确' }, + error: { + type: 'invalid_request_error', + code: 'invalid_jev_usage_query', + message: '用量查询参数不正确', + }, }) throw error } + const settings = new SettingsRepo() + const keys = repo.configuredKeys(publicJevKeys(readJevConfig((key, fallback) => settings.get(key, fallback)))) + return json( + res, + 200, + panel.ok({ ...repo.overview(), ...page, keys, storage_errors_since_start: jevUsageStorageErrors() }), + ) } if (req.method === 'GET' && p === '/api/panel/jev-intercept') { return json(res, 200, panel.ok(jevInterceptSnapshot())) @@ -8764,7 +8772,10 @@ export function createPanelHandler(ctx) { return json( res, 200, - panel.ok({ ...patched.config, account_scope: jevScopeInventory(patched.config.account_platform_plans) }), + panel.ok({ + ...withJevEndpointStatus(patched.config), + account_scope: jevScopeInventory(patched.config.account_platform_plans), + }), ) } if (req.method === 'POST' && p === '/api/panel/jev-intercept/models') { @@ -8816,7 +8827,10 @@ export function createPanelHandler(ctx) { } if (req.method === 'POST' && p === '/api/panel/jev-intercept/resume') { if (panelIdentity(req).role !== 'admin') { - return json(res, 403, { ok: false, error: { code: 'forbidden', message: '仅管理员可恢复审核密钥' } }) + return json(res, 403, { + ok: false, + error: { type: 'permission_error', code: 'forbidden', message: '仅管理员可恢复审核密钥' }, + }) } const body = await readBody(req, 8192).catch(() => ({})) const fingerprint = body?.key_fingerprint == null ? '' : String(body.key_fingerprint).trim() @@ -8828,7 +8842,27 @@ export function createPanelHandler(ctx) { } const stored = readJevConfig((key, fallback) => new SettingsRepo().get(key, fallback)) const resumed = resumeJevKeys(stored, fingerprint) - const keys = publicJevKeys(stored) + const rawKeys = publicJevKeys(stored) + let keys = rawKeys + if (rawKeys.length) { + try { + const byFp = new Map( + new JevUsageRepo().configuredKeyStatuses(rawKeys).map((row) => [row.key_fingerprint, row]), + ) + keys = rawKeys.map((key) => { + const row = byFp.get(key.key_fingerprint) + return row + ? { + ...key, + status: row.status, + last_http_status: row.last_http_status ?? null, + } + : key + }) + } catch { + keys = rawKeys + } + } return json(res, 200, panel.ok({ resumed, keys })) } if (req.method === 'GET' && p === '/api/panel/notify') { diff --git a/src/lib/core/distill-detect.mjs b/src/lib/core/distill-detect.mjs index 4945662064..86256db638 100644 --- a/src/lib/core/distill-detect.mjs +++ b/src/lib/core/distill-detect.mjs @@ -303,7 +303,7 @@ export function normalizeDistillRules(raw, options = {}) { const listed = asStringList(src.needles, fill ? base.needles : []) const hardNeedles = resolveHardNeedles(src, listed, fill ? base : null) const hardSet = new Set(hardNeedles.map((item) => item.toLowerCase())) - const patterns = asStringList(src.patterns, fill ? base.patterns : []).slice(0, 80) + const patterns = asStringList(src.patterns, fill ? base.patterns : []).slice(0, 50) return { enabled: src.enabled == null ? base.enabled : src.enabled !== false, skip_official: src.skip_official == null ? base.skip_official : src.skip_official !== false, diff --git a/src/lib/core/errors.mjs b/src/lib/core/errors.mjs index f7ecea4cb6..a6f9c18218 100644 --- a/src/lib/core/errors.mjs +++ b/src/lib/core/errors.mjs @@ -259,12 +259,8 @@ export function isWrapConnectionError(message = '') { return WRAP_CONNECTION_MESSAGE.test(String(message || '')) } -export function isUsagePolicyErrorMessage(message = '') { - return USAGE_POLICY_MESSAGE.test(String(message || '')) -} - /** Usage Policy text the upstream will not answer for this prompt. */ -export function isUnanswerablePromptMessage(message = '') { +export function isUsagePolicyErrorMessage(message = '') { return USAGE_POLICY_MESSAGE.test(String(message || '')) } @@ -1052,6 +1048,17 @@ export function sanitizeErrorDetailsForLog(rawDetails, { status = null, upstream if (riskBucket) out.risk_bucket = riskBucket const punishment = sanitizeErrorToken(src.punishment, 64) if (punishment) out.punishment = punishment + const banSkipped = sanitizeErrorToken(src.ban_skipped, 64) + if (banSkipped) out.ban_skipped = banSkipped + if (typeof src.session_block_ms === 'number' && Number.isFinite(src.session_block_ms) && src.session_block_ms >= 0) { + out.session_block_ms = src.session_block_ms + } + const banReason = sanitizeErrorToken(src.ban_reason, 128) + if (banReason) out.ban_reason = banReason + const expiresAt = sanitizeInterruptedAt(src.expires_at) + if (expiresAt != null) out.expires_at = expiresAt + const tool = sanitizeErrorToken(src.tool, 128) + if (tool) out.tool = tool const u400Category = sanitizeErrorToken(src.upstream_400_category, 48) if (u400Category) out.upstream_400_category = u400Category const u400Action = sanitizeErrorToken(src.upstream_400_action, 32) @@ -1089,6 +1096,11 @@ export function sanitizeErrorDetailsForLog(rawDetails, { status = null, upstream 'gate_miss', 'risk_bucket', 'punishment', + 'ban_skipped', + 'session_block_ms', + 'ban_reason', + 'expires_at', + 'tool', 'upstream_400_category', 'upstream_400_action', ]) { @@ -1403,7 +1415,7 @@ export function mapUpstreamError(status, body, headers = {}) { upstreamStatus: status, }) } - if (isUnanswerablePromptMessage(msg)) { + if (isUsagePolicyErrorMessage(msg)) { return makeRefusalGuardError({ requestId: request_id, details: { diff --git a/src/lib/core/refusal-guard.mjs b/src/lib/core/refusal-guard.mjs index 9a5e406959..81f735c555 100644 --- a/src/lib/core/refusal-guard.mjs +++ b/src/lib/core/refusal-guard.mjs @@ -346,10 +346,11 @@ export function refusalFingerprint(body = {}, inbound = body) { const model = String(body?.model || inbound?.model || '') .trim() .toLowerCase() + const bodyTools = toolNamesOf(body) const payload = { model, prompt: normalizeText([prompt.joined, typeof inbound?.prompt === 'string' ? inbound.prompt : ''].join('\n')), - tools: toolNamesOf(body).length ? toolNamesOf(body) : toolNamesOf(inbound), + tools: bodyTools.length ? bodyTools : toolNamesOf(inbound), } const attachments = [...refusalAttachments(inbound ?? body)].map((item) => createHash('sha256').update(JSON.stringify(item)).digest('hex'), @@ -541,7 +542,6 @@ const UPSTREAM_400_BILLING_CREDIT_CODES = new Set([ 'insufficient_quota', 'usage_limit_reached', 'billing_hard_limit_reached', - 'upstream:billing_refusal', ]) const UPSTREAM_400_BILLING_CREDIT_RE = /credit balance is too low|extra usage required|usage credits? (?:are )?required|out of extra usage|you['’]?ve hit your limit|insufficient[_\s-]?(?:quota|credits?|balance|funds)|billing[_\s-]?(?:hard[_\s-]?limit|not[_\s-]?active|error)|exceeded your current quota|plan does not include/i diff --git a/src/lib/core/refusal-similarity.mjs b/src/lib/core/refusal-similarity.mjs index b1bef61351..34165a0aca 100644 --- a/src/lib/core/refusal-similarity.mjs +++ b/src/lib/core/refusal-similarity.mjs @@ -131,11 +131,9 @@ function collectRefusalUserParts(inbound, body = inbound, options = {}) { const ctx = options.ctx || null const intercept = options.interceptSession const seen = new Set(intercept?.seen || []) - const parts = intercept?.parts?.length && historyPrefixIntact(body, intercept, ctx) ? [...intercept.parts] : [] - const startIndexes = - intercept?.parts?.length && historyPrefixIntact(body, intercept, ctx) - ? [intercept.messageIds.length, intercept.messageIds.length] - : [0, 0] + const intact = Boolean(intercept?.parts?.length && historyPrefixIntact(body, intercept, ctx)) + const parts = intact ? [...intercept.parts] : [] + const startIndexes = intact ? [intercept.messageIds.length, intercept.messageIds.length] : [0, 0] if (!parts.length) seen.clear() for (let s = 0; s < 2; s++) { const src = s === 0 ? inbound : body diff --git a/src/lib/db/repos/refusal-guards-repo.mjs b/src/lib/db/repos/refusal-guards-repo.mjs index 165354abd9..46f52d262f 100644 --- a/src/lib/db/repos/refusal-guards-repo.mjs +++ b/src/lib/db/repos/refusal-guards-repo.mjs @@ -61,7 +61,6 @@ function rowToRec(row) { export class RefusalGuardsRepo { constructor(db = getDb()) { this.db = db - this._get = db.prepare('SELECT * FROM refusal_guards WHERE fingerprint = ?') this._allActive = db.prepare( `SELECT fingerprint, model, first_seen_at, last_seen_at, hit_count, source_request_id, error_message, preview, expires_at, signature @@ -93,10 +92,6 @@ export class RefusalGuardsRepo { source_request_id, error_message, preview, expires_at FROM refusal_guards ORDER BY last_seen_at DESC, fingerprint LIMIT ?`, ) - this._signatures = db.prepare( - `SELECT fingerprint, signature FROM refusal_guards - WHERE signature IS NOT NULL AND (expires_at IS NULL OR expires_at > ?)`, - ) this._count = db.prepare('SELECT COUNT(*) AS n FROM refusal_guards') this._remove = db.prepare('DELETE FROM refusal_guards WHERE fingerprint = ?') this._clear = db.prepare('DELETE FROM refusal_guards') diff --git a/src/lib/pool/upstream-error-policy.mjs b/src/lib/pool/upstream-error-policy.mjs index 74a4a21d4b..0bfbbd1263 100644 --- a/src/lib/pool/upstream-error-policy.mjs +++ b/src/lib/pool/upstream-error-policy.mjs @@ -10,7 +10,7 @@ import { isClientCancelledResult, isIncompleteAssistantMessage, isThirdPartyClientMessage, - isUnanswerablePromptMessage, + isUsagePolicyErrorMessage, isWrapConnectionError, ErrorCode, } from '../core/errors.mjs' @@ -591,7 +591,7 @@ function classifyUpstreamResultRaw( // Claude Code wraps an AUP refusal as "API Error" and the kernel often // surfaces it as HTTP 400. That is the prompt, not a repairable request // and not an account failure: stop, do not hop again, cache forever. - if (isUnanswerablePromptMessage(message) || isUnanswerablePromptMessage(hay)) { + if (isUsagePolicyErrorMessage(message) || isUsagePolicyErrorMessage(hay)) { return cacheRefusal('usage_policy_refusal') } if (refusalCodes(result, code, workerCode).some(isContentPolicyErrorCode)) { diff --git a/src/lib/protocol/handle-codex.mjs b/src/lib/protocol/handle-codex.mjs index 564e00a04e..c25a38838b 100644 --- a/src/lib/protocol/handle-codex.mjs +++ b/src/lib/protocol/handle-codex.mjs @@ -1652,7 +1652,7 @@ export async function handleCodexProtocol({ persistCodexSlotFailure(projectRoot, vm.id, result, failureCls, rt) } - if (policyRefusal && policyRefusal !== 'upstream:billing_refusal') { + if (policyRefusal) { if (!gone.signal.aborted) recordFinal400?.(result) await releaseActiveLeaseNow({ outcome: 'ok', http_status: Number(result?.status) || 400 }) stats.errors++ diff --git a/src/lib/protocol/handle-protocol.mjs b/src/lib/protocol/handle-protocol.mjs index 2362f9d6a6..506933b397 100644 --- a/src/lib/protocol/handle-protocol.mjs +++ b/src/lib/protocol/handle-protocol.mjs @@ -728,8 +728,7 @@ export function createHandleProtocol(deps) { } } const details = result?.explain || result?.body?.error?.details || {} - const policyRefusal = - !opaqueCrag429 && logBag.risk_upstream_reason && logBag.risk_upstream_reason !== 'upstream:billing_refusal' + const policyRefusal = Boolean(!opaqueCrag429 && logBag.risk_upstream_reason) const mapped = policyRefusal ? upstreamRiskClientError( logBag.risk_upstream_reason, @@ -842,7 +841,6 @@ export function createHandleProtocol(deps) { if (decision.action === 'downgrade' && decision.jev_downgrade_pool_id) { logBag.jev_downgrade_pool_id = decision.jev_downgrade_pool_id } - if (!mandatoryOnly) logBag.risk_wait = false if (decision.jev_passed) { logBag._jevPassed = true if (decision.jev_state) logBag._jevPassState = decision.jev_state diff --git a/src/lib/protocol/intercept-gate.mjs b/src/lib/protocol/intercept-gate.mjs index 87143115d2..6168d63257 100644 --- a/src/lib/protocol/intercept-gate.mjs +++ b/src/lib/protocol/intercept-gate.mjs @@ -405,9 +405,7 @@ export function invalidateRiskBanCache(opts = {}) { function attachBanRepoInvalidationHooks(repo, kind) { if (!repo || !repo.db) return const methods = - kind === 'session' - ? ['block', 'remove', 'clear'] - : ['block', 'blockSession', 'recordViolation', 'remove', 'clear', 'linkAlias'] + kind === 'session' ? ['block', 'remove', 'clear'] : ['block', 'blockSession', 'recordViolation', 'remove', 'clear'] const proto = Object.getPrototypeOf(repo) if (proto && proto !== Object.prototype) { if (wrappedBanProtos.has(proto)) return @@ -442,11 +440,8 @@ function deviceBanCacheKey(db, identity, policy) { const parts = [ identity?.principal || '', identity?.deviceId || '', + identity?.machineId || '', identity?.sessionId || '', - identity?.ip || '', - identity?.keyId || '', - identity?.userId || '', - ...(Array.isArray(identity?.aliases) ? identity.aliases : []), ] return `${RISK_DEVICE_PREFIX}${scope}${policyKey}:${parts.join('|')}` } @@ -826,7 +821,7 @@ export function observeUpstreamRisk({ } catch { console.warn('[risk-audit] failed to persist upstream refusal') } - if (reason !== 'upstream:billing_refusal' && !suspectOverRefusal) { + if (!suspectOverRefusal) { const escalated = recordBan( { identity: effectiveIdentity, fingerprint, reason, banDevice: true }, { devices, policy, requestId, now }, @@ -924,19 +919,34 @@ export function commitProtocolBlock(decision, { repo, devices, sessions, policy, } } if (decision.banSession && Number(decision.sessionBlockMs) > 0 && !decision.banDevice) { - if (policy?.session_block_enabled === false) return - try { - const ban = - devices?.blockSession?.(decision.identity, { - requestId, - fingerprint: decision.fingerprint || null, - reason: decision.sessionBlockReason || decision.reason || 'jev:distill', - ttlMs: Number(decision.sessionBlockMs), - now, - }) || null - if (ban) invalidateRiskBanCache({ kind: 'device', db: devices?.db || null }) - } catch { - console.warn('[risk-audit] failed to persist session block') + let ban = null + if (policy?.session_block_enabled !== false) { + try { + ban = + devices?.blockSession?.(decision.identity, { + requestId, + fingerprint: decision.fingerprint || null, + reason: decision.sessionBlockReason || decision.reason || 'jev:distill', + ttlMs: Number(decision.sessionBlockMs), + now, + }) || null + if (ban) invalidateRiskBanCache({ kind: 'device', db: devices?.db || null }) + } catch { + console.warn('[risk-audit] failed to persist session block') + } + } + if (decision.kind === 'jev' && decision.reason === 'jev:distill') { + if (ban) { + const mins = Math.max(1, Math.round(Number(decision.sessionBlockMs) / 60_000)) + decision.errorMessage = `${POLICY_BLOCK_MESSAGE}: distill(已封锁当前会话 ${mins} 分钟)` + } else { + decision.errorMessage = `${POLICY_BLOCK_MESSAGE}: distill(本次请求已拦截,未封锁会话)` + if (decision.errorDetails && typeof decision.errorDetails === 'object') { + const nextDetails = { ...decision.errorDetails } + delete nextDetails.session_block_ms + decision.errorDetails = nextDetails + } + } } return } @@ -1068,7 +1078,6 @@ export async function evaluateProtocolIntercept({ const audit = policy?.risk_audit const isAutoModeClassifier = classifier?.purpose === 'auto_mode_classifier' const effectiveIdentity = resolveAuditSessionIdentity({ inbound, body, headers, identity }) - const rootSessionId = effectiveIdentity.sessionId || '' const reject = (fields) => block({ deviceId: effectiveIdentity.deviceId, identity: effectiveIdentity, ...fields }) const interceptOpts = { interceptSession, ctx: bodyCtx } let scanPair = null @@ -1104,7 +1113,6 @@ export async function evaluateProtocolIntercept({ intercept: gateVerdict({ kind: 'block', by: 'refusal', keyword: 'session' }), sessionId: refused.sessionId, banDevice: false, - remember: false, reason: 'refusal_session', }) } @@ -1144,6 +1152,9 @@ export async function evaluateProtocolIntercept({ via: 'hard-regex', final_state: 'policy_blocked', error, + logErrorCode: 'risk_tool_blocked', + errorMessage: error.body.error.message, + errorDetails: error.body?.error?.details || null, intercept: gateVerdict({ kind: 'block', by: 'hard-regex', keyword: tool.name, rule: 'blocked_tool' }), banDevice: true, reason: `blocked_tool:${tool.name}`, @@ -1359,7 +1370,6 @@ export async function evaluateProtocolIntercept({ category: 'unavailable', banSession: false, banDevice: false, - forceDeviceBan: false, reason: 'jev:unavailable', }) } @@ -1392,7 +1402,7 @@ export async function evaluateProtocolIntercept({ session_block_ms: DISTILL_SESSION_BLOCK_MS, ...jevScoreDetails(verdict.scores), }, - errorMessage: `${POLICY_BLOCK_MESSAGE}: distill(已封锁当前会话 10 分钟)`, + errorMessage: `${POLICY_BLOCK_MESSAGE}: distill`, intercept: gateVerdict({ kind: 'block', by: 'jev', @@ -1400,12 +1410,8 @@ export async function evaluateProtocolIntercept({ }), jevState: verdict.state || '', category: 'distill', - sessionId: rootSessionId, - model: body?.model || inbound?.model || '', - preview: refusalPreview(body, inbound), banSession: true, banDevice: false, - forceDeviceBan: false, sessionBlockMs: DISTILL_SESSION_BLOCK_MS, sessionBlockReason: 'jev:distill', reason: 'jev:distill', @@ -1440,12 +1446,8 @@ export async function evaluateProtocolIntercept({ // Exact payload.state. Context the model scored, not a span it named. jevState: verdict.state || '', category, - sessionId: rootSessionId, - model: body?.model || inbound?.model || '', - preview: refusalPreview(body, inbound), banSession: escalateBan, banDevice: escalateBan, - forceDeviceBan: escalateBan, reason: `jev:${category}`, }) } diff --git a/src/lib/protocol/intercept-stats.mjs b/src/lib/protocol/intercept-stats.mjs index 242486049c..287ccd824a 100644 --- a/src/lib/protocol/intercept-stats.mjs +++ b/src/lib/protocol/intercept-stats.mjs @@ -35,6 +35,8 @@ const BLOCK_LABEL = { const PASS_LABEL = { jev: 'Jev 模型放行', + 'jev-downgrade': 'Jev 降级放行', + trusted: '受信任分组豁免', regex: '正则未命中', 'fail-open': '模型故障放行', classifier: '内置分类器豁免', diff --git a/src/lib/protocol/jev-intercept.mjs b/src/lib/protocol/jev-intercept.mjs index d1290b6b8f..4799a46391 100644 --- a/src/lib/protocol/jev-intercept.mjs +++ b/src/lib/protocol/jev-intercept.mjs @@ -5,8 +5,9 @@ * configured line blocks (0.5 unless the panel changes it). One score within * 0.08 under that line does not. The same state reuses that verdict for the * configured window. A dead model fails open unless fail_open is off. - * 401 / 429 / 529 retires that key and tries the next. A network error or - * other HTTP status skips the rest of that host for this call only. + * 401 pauses that key until manually resumed; 429 / 529 puts it in exponential + * backoff cooldown and tries the next. A network error or other HTTP status + * skips the rest of that host for this call only. * A line may be `https://host[/v1/systemone] `, or a bare URL for a keyless host. */ import { ErrorCode, ErrorType, makeError } from '../core/errors.mjs' @@ -55,14 +56,6 @@ export const POLICY_PROVIDERS = Object.freeze([ * see on the slot. */ export const PLAN_TYPE_NONE = 'none' -export const ACCOUNT_TYPE_NONE = 'none' -export const JEV_ACCOUNT_TYPES = Object.freeze([ - { id: 'oauth', label: 'OAuth' }, - { id: 'setup-token', label: 'Setup Token' }, - { id: 'official-setup-token', label: '官方 Setup Token' }, - { id: 'apikey', label: 'Console API Key' }, - { id: ACCOUNT_TYPE_NONE, label: '无凭证' }, -]) const GPT_PLAN_BUCKETS = Object.freeze([ { id: 'free', label: 'Free', ids: ['free', 'free_workspace', 'guest'] }, { id: 'go', label: 'Go', ids: ['go'] }, @@ -95,15 +88,6 @@ const SCOPE_PLAN_RANK = Object.freeze([ 'edu_pro', 'none', ]) -export const JEV_PLAN_TYPES = Object.freeze([ - { id: 'plus', label: 'Plus' }, - { id: 'pro', label: 'Pro' }, - { id: 'prolite', label: 'Pro Lite' }, - { id: 'self_serve_business_prolite', label: 'Business Premium' }, - { id: 'business', label: 'Business' }, - { id: 'free', label: 'Free' }, - { id: PLAN_TYPE_NONE, label: '未标注' }, -]) const TIMEOUT_MIN = 200 const TIMEOUT_MAX = 8000 @@ -862,6 +846,7 @@ export function normalizeJevConfig(raw) { patterns.push(source) } const apiKeys = normalizeKeys(raw) + const questions = normalizeQuestions(raw) const threshold = Number(raw.safety_threshold) const dedup = Number(raw.dedup_sec) const maxState = Number(raw.max_state_chars) @@ -885,10 +870,8 @@ export function normalizeJevConfig(raw) { timeout_ms: Number.isInteger(timeout) && timeout >= TIMEOUT_MIN && timeout <= TIMEOUT_MAX ? timeout : TIMEOUT_DEFAULT, safety_instruction: storedSafetyInstruction(raw.safety_instruction), - questions: normalizeQuestions(raw), - question_ids: normalizeQuestions(raw) - .filter((item) => item.enabled) - .map((item) => item.id), + questions, + question_ids: questions.filter((item) => item.enabled).map((item) => item.id), safety_threshold: Number.isFinite(threshold) && threshold >= 0 && threshold <= 1 ? threshold : POLICY_NOUL, block_if_below: raw.block_if_below !== false, fail_open: raw.fail_open !== false, @@ -957,10 +940,7 @@ export function publicJevConfig(cfg) { account_ids: [], timeout_ms: TIMEOUT_DEFAULT, }, - account_type_options: JEV_ACCOUNT_TYPES.map((item) => ({ ...item })), - account_plan_type_options: JEV_PLAN_TYPES.map((item) => ({ ...item })), categories: [...JEV_CATEGORIES, 'custom'], - builtin_patterns: HARD_POLICY_RULES.map((rule) => rule.source), builtin_rules: builtinHardRules(), rules: (c.rules || builtinHardRules()).map((rule) => ({ ...rule })), rules_customized: Array.isArray(c.rules), @@ -1559,14 +1539,9 @@ export function jevCurrentAsk(document) { function buildJevModelParts(inbound, body = inbound, { interceptSession = null, ctx = null } = {}) { const seen = new Set(interceptSession?.modelSeen || []) - const parts = - interceptSession?.modelParts?.length && historyPrefixIntact(body, interceptSession, ctx) - ? [...interceptSession.modelParts] - : [] - const messageStart = - interceptSession?.modelParts?.length && historyPrefixIntact(body, interceptSession, ctx) - ? interceptSession.messageIds.length - : 0 + const intact = Boolean(interceptSession?.modelParts?.length && historyPrefixIntact(body, interceptSession, ctx)) + const parts = intact ? [...interceptSession.modelParts] : [] + const messageStart = intact ? interceptSession.messageIds.length : 0 if (!parts.length) seen.clear() const push = (source, text) => { const norm = normalizeText(text) @@ -2181,17 +2156,7 @@ function statusMessage(status) { function sampleScores(payload, cfg) { const decision = parsePolicyDecision(payload, cfg) if (!decision) return null - const answers = payload?.answers || {} - const scores = [] - for (const id of Object.keys(questionsFor(cfg))) { - const score = Number(answers[id]?.noul) - if (Number.isFinite(score)) scores.push(score) - } - if (!scores.length) { - const score = Number(answers.safety?.noul) - if (Number.isFinite(score)) scores.push(score) - } - return { score: scores.length ? Math.min(...scores) : null, blocked: decision.hits.length > 0 } + return { score: decision.score, blocked: decision.hits.length > 0 } } function noteProbe(cfg, url, apiKey, model, started, patch) { diff --git a/test/unit/distill-detect.test.mjs b/test/unit/distill-detect.test.mjs index 6b7d7b8cc3..c2b34de056 100644 --- a/test/unit/distill-detect.test.mjs +++ b/test/unit/distill-detect.test.mjs @@ -3,7 +3,6 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import { fileURLToPath } from 'node:url' import { DEFAULT_DISTILL_RULES, HARD_DISTILL_PATTERNS, @@ -18,7 +17,6 @@ import { ErrorCode } from '../../src/lib/core/errors.mjs' import { evaluateProtocolIntercept } from '../../src/lib/protocol/intercept-gate.mjs' import { matchHardPolicy } from '../../src/lib/protocol/jev-intercept.mjs' -const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..') const REASON_ASK = '请分步解答。先写推理过程,最后单独一行写:\n最终答案:...' function inbound(user, extra = {}) { @@ -615,8 +613,9 @@ test('validateDistillPatch rejects bad status', () => { assert.deepEqual(validateDistillPatch({ enabled: 'yes' }), ['enabled 必须是布尔']) }) -test('save and load round-trip a patch', () => { +test('save and load round-trip a patch', (t) => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-distill-')) + t.after(() => fs.rmSync(dir, { recursive: true, force: true })) const file = path.join(dir, 'distill-rules.json') const saved = saveDistillRules(file, { enabled: false, error: { message: '停' } }) assert.equal(saved.enabled, false) @@ -626,8 +625,9 @@ test('save and load round-trip a patch', () => { assert.equal(loaded.error.message, '停') assert.equal(loaded.skip_official, true) }) -test('save keeps harvest needles unless the panel clears them', () => { +test('save keeps harvest needles unless the panel clears them', (t) => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-distill-hard-')) + t.after(() => fs.rmSync(dir, { recursive: true, force: true })) const file = path.join(dir, 'distill-rules.json') const seeded = saveDistillRules(file, { hard_needles: ['CUSTOM-HARVEST-TOKEN'] }) assert.deepEqual(seeded.hard_needles, ['CUSTOM-HARVEST-TOKEN']) @@ -644,34 +644,3 @@ test('normalize keeps default fingerprints when omitted', () => { assert.ok(r.fingerprints.length >= 5) assert.equal(r.error.message, '不允许蒸馏') }) - -test('handleProtocol intercepts before credential hop', () => { - const src = fs.readFileSync(path.join(root, 'src/lib/protocol/handle-protocol.mjs'), 'utf8') - const early = src.indexOf('await applyProtocolIntercept(') - const codex = src.indexOf('handleCodexProtocol({') - assert.ok(early > 0 && early < codex) - const before = src.indexOf("applyIntercept(cfg.intercept.rules, 'before_upstream'") - const late = src.indexOf('await applyProtocolIntercept(', before) - const apiHop = src.indexOf('await runApiInference(', late) - assert.ok(before > 0) - assert.ok(late > before) - assert.ok(apiHop > late) - const guard = src.slice( - src.indexOf('async function applyProtocolIntercept'), - src.indexOf('function isZeroInjectMode'), - ) - assert.ok(guard.includes('verifyOfficialClaudeCode')) - const countSrc = fs.readFileSync(path.join(root, 'src/lib/protocol/user-count-tokens.mjs'), 'utf8') - const countGuard = countSrc.indexOf('await blockCountTokensBeforeHop(req, parsed.body,') - const countHop = countSrc.indexOf('countTokensViaWorker)(peeked.exec') - assert.ok(countGuard > 0 && countHop > countGuard) -}) - -test('assemble path does not forward onCommit to the kernel hop', () => { - const src = fs.readFileSync(path.join(root, 'src/lib/protocol/handle-protocol.mjs'), 'utf8') - const start = src.indexOf('async function streamAndAssembleClaudeMessage') - const end = src.indexOf('async function handleProtocol') - assert.ok(start > 0 && end > start) - const chunk = src.slice(start, end) - assert.equal(chunk.includes('onCommit'), false) -}) diff --git a/test/unit/errors-map.test.mjs b/test/unit/errors-map.test.mjs index 87e43aa067..04710431ab 100644 --- a/test/unit/errors-map.test.mjs +++ b/test/unit/errors-map.test.mjs @@ -12,7 +12,6 @@ import { isWrapConnectionError, isUsagePolicyErrorMessage, isThirdPartyClientMessage, - isUnanswerablePromptMessage, makeRefusalGuardError, isAssistantMessageBody, isCompleteAssistantMessage, @@ -320,11 +319,10 @@ test('third-party extra-usage 400 and 503 are non-retryable third_party_client e const msg = 'HTTP 400: Third-party apps now draw from your extra usage, not your plan limits. Claim it at claude.ai/settings/usage.' assert.equal(isUsagePolicyErrorMessage(msg), false) - assert.equal(isUnanswerablePromptMessage(msg), false) assert.equal(isThirdPartyClientMessage(msg), true) assert.equal(isThirdPartyClientMessage('400 no third-party apps allowed on subscription'), true) assert.equal(isThirdPartyClientMessage('Extra usage required for this model'), false) - assert.equal(isUnanswerablePromptMessage('Extra usage required for this model'), false) + assert.equal(isUsagePolicyErrorMessage('Extra usage required for this model'), false) for (const status of [400, 503]) { const mapped = mapUpstreamError(status, { type: 'error', diff --git a/test/unit/jev-intercept.test.mjs b/test/unit/jev-intercept.test.mjs index 143c4ee3c4..a744aab77e 100644 --- a/test/unit/jev-intercept.test.mjs +++ b/test/unit/jev-intercept.test.mjs @@ -1320,6 +1320,34 @@ test('probe checks availability and the judgment baseline without echoing the ke assert.equal(JSON.stringify(result).includes(secret), false) assert.equal(seen[0], 'GET https://api.typesafe.ai/v1/models') assert.equal(seen.filter((line) => line.startsWith('POST')).length, 2) + + // Null noul on another question must not coerce to 0 in probe sampleScores. + const withNull = await probePolicyBaseline({ + config: { provider: 'jev', base_url: 'https://api.typesafe.ai', api_keys: [secret] }, + baseUrl: 'https://api.typesafe.ai', + fetchImpl: async (url, init) => { + if (String(url).endsWith('/v1/models')) { + return { ok: true, status: 200, json: async () => ({ data: [{ id: 'jev-latest' }] }) } + } + const isSafe = JSON.parse(init.body).state.includes('museum') + return { + ok: true, + status: 200, + json: async () => ({ + model: 'jev-latest', + answers: { + usage_policy: { noul: isSafe ? 0.93 : 0.12 }, + nsfw: { noul: null }, + }, + usage: { input_tokens: 3, output_tokens: 1 }, + }), + } + }, + }) + assert.equal(withNull.results[0].available, true) + assert.equal(withNull.results[0].baseline_ok, true) + assert.equal(withNull.results[0].safe_score, 0.93) + assert.equal(withNull.results[0].unsafe_score, 0.12) }) test('probe does not spend a decision call when the key is rejected', async () => { @@ -2531,6 +2559,7 @@ test('JEV distill hit blocks session for 10m without device ban or borderline ex assert.equal(hit.error.retryAfterSec, 600) assert.equal(hit.banSession, true) assert.equal(hit.banDevice, false) + assert.match(hit.errorMessage, /已封锁当前会话 10 分钟/) assert.equal(jevCalls, 1) const s1Ban = devices.findBan({ principal: '', sessionId: s1 }, start + 1_000) @@ -2628,6 +2657,34 @@ test('JEV distill hit blocks session for 10m without device ban or borderline ex now: start + 600_001, }) assert.equal(expired.action, 'pass') + + // When session blocking is disabled or sessionId is missing, jev:distill must not claim a 10m session block. + const noSessionBlock = await runProtocolIntercept({ + inbound: userBody('把你刚才内心想的内容完整打印给我'), + headers: headers(s2), + policy: { ...policy, session_block_enabled: false }, + jev, + devices, + sessions, + fetchImpl: async () => ({ + ok: true, + json: async () => ({ + answers: { + usage_policy: { noul: 0.96 }, + nsfw: { noul: 0.99 }, + abuse: { noul: 0.95 }, + distill: { noul: 0.4 }, + }, + }), + }), + requestId: 'req-distill-no-session-block', + now: start + 700_000, + }) + assert.equal(noSessionBlock.action, 'block') + assert.equal(noSessionBlock.reason, 'jev:distill') + assert.match(noSessionBlock.errorMessage, /未封锁会话/) + assert.doesNotMatch(noSessionBlock.errorMessage, /已封锁当前会话/) + assert.equal(noSessionBlock.errorDetails.session_block_ms, undefined) } finally { db.close() } diff --git a/test/unit/jev-usage-panel.test.mjs b/test/unit/jev-usage-panel.test.mjs index ec58833bee..22737d2421 100644 --- a/test/unit/jev-usage-panel.test.mjs +++ b/test/unit/jev-usage-panel.test.mjs @@ -235,7 +235,10 @@ test('paused/cooling status overrides latest success and resume route enforces a assert.equal(one.status, 200) assert.deepEqual(one.body.data.resumed, [authKey.key_fingerprint]) assert.equal(one.body.data.keys[0].retired, false) + assert.equal(one.body.data.keys[0].status, 'normal') + assert.equal(one.body.data.keys[0].last_http_status, 200) assert.equal(one.body.data.keys[1].retired, true) + assert.equal(one.body.data.keys[1].status, 'cooling') // Resume remaining keys. const all = await callPanel('POST', '/api/panel/jev-intercept/resume', admin, {}) diff --git a/test/unit/refusal-guard.test.mjs b/test/unit/refusal-guard.test.mjs index 762dea7462..34a3cd9f08 100644 --- a/test/unit/refusal-guard.test.mjs +++ b/test/unit/refusal-guard.test.mjs @@ -559,6 +559,7 @@ test('remember then lookup hits the same prompt', () => { assert.equal(repo.get(other), null) } finally { db.close() + fs.rmSync(dir, { recursive: true, force: true }) } }) @@ -581,6 +582,7 @@ test('timed refusal expires and no longer blocks', () => { assert.equal(repo.list().length, 0) } finally { db.close() + fs.rmSync(dir, { recursive: true, force: true }) } }) test('guard error is a non-retryable HTTP 400 request rejection, not a login error', () => { @@ -634,6 +636,7 @@ test('list remove and clear', () => { assert.equal(repo.count(), 0) } finally { db.close() + fs.rmSync(dir, { recursive: true, force: true }) } }) diff --git a/test/unit/refusal-session-block.test.mjs b/test/unit/refusal-session-block.test.mjs index ece8780e9a..0dc89880bb 100644 --- a/test/unit/refusal-session-block.test.mjs +++ b/test/unit/refusal-session-block.test.mjs @@ -189,7 +189,7 @@ test('an auto-mode classifier refusal stays on that request; the conversation it assert.deepEqual(refusalSessionBlockDecision(reason, classifier), { block: false, skipped: 'auto_mode_classifier' }) assert.deepEqual(refusalSessionBlockDecision(reason, null), { block: true }) } - for (const reason of ['', 'upstream:billing_refusal', 'upstream:configured_policy']) { + for (const reason of ['', 'upstream:configured_policy']) { assert.deepEqual(refusalSessionBlockDecision(reason, classifier), { block: false }) assert.deepEqual(refusalSessionBlockDecision(reason, null), { block: false }) } @@ -860,6 +860,28 @@ test('recordUpstream400SessionBlock skips non-session 400s without banning and l assert.equal(noSessBan, null) assert.equal(noSessBag.error_details.upstream_400_category, 'context_too_long') assert.equal(noSessBag.error_details.upstream_400_action, 'no_session') + + // Risk audit diagnostic fields survive log sanitization without dropping or leaking arbitrary keys. + const riskSanitized = sanitizeErrorDetailsForLog( + { + reason: 'jev:distill', + ban_skipped: 'borderline_score', + session_block_ms: 600_000, + ban_reason: 'jev:usage_policy', + expires_at: '2026-11-28T12:10:00.000Z', + tool: 'mcp__shell__exec', + raw_prompt: 'must-be-dropped', + }, + { status: 429 }, + ) + assert.deepEqual(riskSanitized, { + reason: 'jev:distill', + ban_skipped: 'borderline_score', + session_block_ms: 600_000, + ban_reason: 'jev:usage_policy', + expires_at: '2026-11-28T12:10:00.000Z', + tool: 'mcp__shell__exec', + }) }) }) diff --git a/test/unit/refusal-similarity.test.mjs b/test/unit/refusal-similarity.test.mjs index 6fb5994ef0..82dc40ba28 100644 --- a/test/unit/refusal-similarity.test.mjs +++ b/test/unit/refusal-similarity.test.mjs @@ -132,6 +132,7 @@ test('stored near-duplicate blocks and then the device blocks any later prompt', assert.equal(devices.block({ deviceId: '' }), null) } finally { db.close() + fs.rmSync(dir, { recursive: true, force: true }) } }) @@ -150,6 +151,7 @@ test('different user text under the same system is not a near match', () => { assert.equal(matchStoredRefusal({ inbound: other, body: other, repo: guards, devices: null }), null) } finally { db.close() + fs.rmSync(dir, { recursive: true, force: true }) } }) @@ -215,5 +217,6 @@ test('turning similarity or device block off skips that check', () => { ) } finally { db.close() + fs.rmSync(dir, { recursive: true, force: true }) } }) diff --git a/test/unit/request-redis-opt.test.mjs b/test/unit/request-redis-opt.test.mjs index bdd18982b3..74b9c9213c 100644 --- a/test/unit/request-redis-opt.test.mjs +++ b/test/unit/request-redis-opt.test.mjs @@ -844,6 +844,25 @@ test('RefusalGuardsRepo snapshot eliminates nearest() DB full scans and intercep db.prepare('DELETE FROM refusal_session_blocks WHERE session_id = ?').run('sess-cache-1') await invalidateRiskBanCache({ kind: 'session', db }) assert.equal((await evaluateProtocolIntercept(baseArgs)).action, 'pass') + + // Device ban cache key must include machineId so distinct machines with empty deviceId never collide + const machBase = { + ...baseArgs, + headers: {}, + identity: { principal: 'key:k1', deviceId: '', machineId: 'machine-cache-a', sessionId: '' }, + } + const machOther = { + ...baseArgs, + headers: {}, + identity: { principal: 'key:k1', deviceId: '', machineId: 'machine-cache-b', sessionId: '' }, + } + devices.recordViolation(machOther.identity, { + requestId: 'req-mach-b', + reason: 'jev:usage_policy', + steps: [10, 10, 0], + }) + assert.equal((await evaluateProtocolIntercept(machBase)).action, 'pass') + assert.equal((await evaluateProtocolIntercept(machOther)).action, 'block') }) test('ThinkingOwnerStore caches owners in L1 and batches record() asynchronously via enqueueWrite', async (t) => { From 82325b4815e2adb6c0a1b3e70986f93b0e6badb7 Mon Sep 17 00:00:00 2001 From: dofastted Date: Tue, 1 Dec 2026 15:14:17 +0800 Subject: [PATCH 02/15] chore(web): align risk audit copy, unify JEV/key status SSOT, and prune dead code --- .../logs/log-detail/summary-tab.test.tsx | 15 +++- .../features/logs/log-detail/summary-tab.tsx | 62 +++++++++------- web/src/features/risk/account-scope.tsx | 2 +- web/src/features/risk/blocks.tsx | 39 ----------- web/src/features/risk/feed.tsx | 70 +++++++++---------- web/src/features/risk/hard-regex-settings.tsx | 5 +- web/src/features/risk/hits.tsx | 26 +++---- web/src/features/risk/index.tsx | 6 +- web/src/features/risk/jev-usage.test.tsx | 36 +++++----- web/src/features/risk/jev-usage.tsx | 31 +++----- web/src/features/risk/model-settings.tsx | 41 +++-------- web/src/features/risk/model.test.ts | 24 ++++++- web/src/features/risk/model.ts | 51 +++++++++++++- web/src/features/risk/queries.ts | 1 - web/src/features/risk/refusal-settings.tsx | 29 +++++--- web/src/features/risk/risk-policy-form.tsx | 4 +- .../risk/risk-reasons-missing.test.tsx | 25 ++++--- web/src/features/risk/status-panel.tsx | 9 ++- web/src/features/risk/upstream-400.ts | 3 - web/src/types/panel-routing.ts | 4 -- 20 files changed, 249 insertions(+), 234 deletions(-) diff --git a/web/src/features/logs/log-detail/summary-tab.test.tsx b/web/src/features/logs/log-detail/summary-tab.test.tsx index 172fb5f5e6..9a89c3afb5 100644 --- a/web/src/features/logs/log-detail/summary-tab.test.tsx +++ b/web/src/features/logs/log-detail/summary-tab.test.tsx @@ -104,7 +104,7 @@ describe('SummaryTab structured error diagnostics (#1845)', () => { expect(html).toContain('recovery_exhausted=false') }) - it('renders risk audit card with disguised 429, gate_miss, JEV scores, and device/session', () => { + it('renders risk audit card with disguised 429, gate_miss, JEV scores (including distill), and deduplicates raw errorDetails', () => { const html = renderToStaticMarkup( { errorCode: 'policy_blocked', inboundDeviceId: 'dev-audit-01', clientSessionId: 'sess-audit-01', + jevState: 'user: sample context', errorDetails: { gate_miss: true, risk_bucket: 'policy_suspect', jev_score_usage_policy: 0.91, jev_score_abuse: 0.12, + jev_score_distill: 0.35, }, })} scrollToRedirect={false} @@ -132,11 +134,17 @@ describe('SummaryTab structured error diagnostics (#1845)', () => { expect(html).toContain('前置放行后上游拒答(漏放)') expect(html).toContain('使用政策: 0.91') expect(html).toContain('破限与攻击: 0.12') + expect(html).toContain('思维链提取与蒸馏: 0.35') + expect(html).not.toContain('低于 0.50 拦截') + expect(html).not.toContain('POST 给模型的') + expect(html).not.toContain('jev_score_usage_policy=') + expect(html).not.toContain('risk_bucket=policy_suspect') + expect(html).not.toContain('gate_miss=true') expect(html).toContain('dev-audit-01') expect(html).toContain('sess-audit-01') }) - it('renders upstream 400 classification category and action badges in risk audit card', () => { + it('renders upstream 400 classification category and action badges in risk audit card while keeping non-risk errorDetails', () => { const html = renderToStaticMarkup( { ) expect(html).toContain('400 分类:工具调用历史配对损坏') expect(html).toContain('已封锁会话 10 分钟') + expect(html).toContain('punishment=session_10m_400') + expect(html).not.toContain('upstream_400_category=tool_pair_broken') + expect(html).not.toContain('upstream_400_action=session_10m') }) }) diff --git a/web/src/features/logs/log-detail/summary-tab.tsx b/web/src/features/logs/log-detail/summary-tab.tsx index 05e95d986d..5b3ae30070 100644 --- a/web/src/features/logs/log-detail/summary-tab.tsx +++ b/web/src/features/logs/log-detail/summary-tab.tsx @@ -125,10 +125,22 @@ const JEV_QUESTION_LABELS: Record = { usage_policy: '使用政策', nsfw: '色情', abuse: '破限与攻击', + distill: '思维链提取与蒸馏', custom: '自定义', safety: '综合', } +const RISK_AUDIT_DETAIL_KEYS = new Set([ + 'risk_bucket', + 'upstream_400_category', + 'upstream_400_action', + 'gate_miss', +]) + +function isRiskAuditDetailKey(key: string) { + return key.startsWith('jev_score_') || RISK_AUDIT_DETAIL_KEYS.has(key) +} + const RISK_BUCKET_LABELS: Record = { policy: '上游政策拒答', policy_suspect: '疑似上游误拒(仅精确指纹)', @@ -177,6 +189,7 @@ function RiskAuditCard({ row }: { row: UsageLogRow }) { gateMiss || !!riskBucket || !!u400Category || + !!u400Action || jevScores.length > 0 if (!hasRisk) return null const disguised429 = @@ -245,7 +258,7 @@ function RiskAuditCard({ row }: { row: UsageLogRow }) { {jevScores.length > 0 ? (

- JEV 题目安全分(0–1,低于 0.50 拦截) + JEV 题目安全分(0–1,默认参考线 0.50,以实际阈值配置为准)

{jevScores.map((item) => { @@ -346,6 +359,15 @@ export function SummaryTab({ ) const cacheRate = actualCacheRate(row) const totalCost = row.actualCostUsd ?? row.costUsd + const visibleErrorDetails = Object.entries(row.errorDetails || {}).filter( + ([key]) => + !isRiskAuditDetailKey(key) && + !( + key === 'upstream_type' && + (row.upstreamType === row.errorDetails?.upstream_type || + row.errorCode === row.errorDetails?.upstream_type) + ) + ) useEffect(() => { if (!scrollToRedirect) return @@ -390,7 +412,9 @@ export function SummaryTab({
- {inFlight ? livePhaseLabel(live?.phase) : (row.statusCode ?? '未知')} + {inFlight + ? livePhaseLabel(live?.phase) + : (row.statusCode ?? '未知')} {inFlight ? ( @@ -813,7 +837,7 @@ export function SummaryTab({ {row.errorMessage || row.errorCode || row.upstreamType || - (row.errorDetails && Object.keys(row.errorDetails).length > 0) ? ( + visibleErrorDetails.length > 0 ? (
错误信息 @@ -843,26 +867,17 @@ export function SummaryTab({ {row.errorMessage}

) : null} - {row.errorDetails && Object.keys(row.errorDetails).length > 0 ? ( + {visibleErrorDetails.length > 0 ? (
- {Object.entries(row.errorDetails) - .filter( - ([key]) => - !( - key === 'upstream_type' && - (row.upstreamType === row.errorDetails?.upstream_type || - row.errorCode === row.errorDetails?.upstream_type) - ) - ) - .map(([key, value]) => ( - - {key}={String(value)} - - ))} + {visibleErrorDetails.map(([key, value]) => ( + + {key}={String(value)} + + ))}
) : null}
@@ -875,8 +890,7 @@ export function SummaryTab({ 决策模型送审正文

- 这是当时 POST 给模型的 - state,含历史用户句。模型只返回题目分数,没有指出其中哪一句。 + 这是当时提交给审核模型的上下文,含历史用户句。模型只返回题目分数,没有指出其中哪一句。

             {row.jevState}
diff --git a/web/src/features/risk/account-scope.tsx b/web/src/features/risk/account-scope.tsx
index ab8c2097c8..8ee5da8766 100644
--- a/web/src/features/risk/account-scope.tsx
+++ b/web/src/features/risk/account-scope.tsx
@@ -192,7 +192,7 @@ export function AccountScopeSettings({
       
         

账号范围同时用于前置蒸馏、类别正则与 - Jev,不跳过封禁、系统改写或禁用工具。 都不选 = + JEV,不跳过封禁、系统改写或禁用工具。 都不选 = 全部账号。指定账号和勾选取并集。只选 GPT 套餐时 Claude 照旧全进关卡;选了 Claude 套餐或指定了账号,才按槽位收窄 Claude。GPT 没设范围时仍看「OpenAI 平台」。 diff --git a/web/src/features/risk/blocks.tsx b/web/src/features/risk/blocks.tsx index 7b0fb6c2a1..393b79a2aa 100644 --- a/web/src/features/risk/blocks.tsx +++ b/web/src/features/risk/blocks.tsx @@ -93,45 +93,6 @@ export function EmptyNotice({ ) } -export function Segmented({ - value, - options, - onChange, -}: { - value: T - options: { value: T; label: string }[] - onChange: (value: T) => void -}) { - return ( -

- {options.map((option) => { - const on = value === option.value - return ( - - ) - })} -
- ) -} - /** Label sits in a fixed column so the inputs and their buttons line up. */ export function FieldLine({ label, diff --git a/web/src/features/risk/feed.tsx b/web/src/features/risk/feed.tsx index 2556b7f3fc..0ccb5de871 100644 --- a/web/src/features/risk/feed.tsx +++ b/web/src/features/risk/feed.tsx @@ -13,7 +13,7 @@ const KIND_NAME: Record = { distill: '蒸馏', 'hard-regex': '硬正则', refusal: '拒答与封禁', - jev: 'Jev', + jev: 'JEV', upstream: '上游拒答', } @@ -36,14 +36,12 @@ export function RiskFeed({ loading, error, empty, - showKind, onOpen, }: { rows: UsageLogRow[] loading: boolean error: Error | null empty: string - showKind: boolean onOpen: (row: UsageLogRow) => void }) { if (loading) { @@ -96,47 +94,43 @@ export function RiskFeed({ date={row.createdAt} className='text-xs text-[var(--text-tertiary)] tabular-nums' /> - {showKind ? ( - + + + {hasUpstream4xx + ? `上游 ${row.upstreamStatus}` + : KIND_NAME[kind]} + + {disguised429 ? ( + + 429 伪装 + + ) : null} + {u400Category ? ( - {hasUpstream4xx - ? `上游 ${row.upstreamStatus}` - : KIND_NAME[kind]} + {upstream400CategoryLabel(u400Category)} - {disguised429 ? ( - - 429 伪装 - - ) : null} - {u400Category ? ( - - {upstream400CategoryLabel(u400Category)} - - ) : null} - - ) : ( - - )} + ) : null} + - + diff --git a/web/src/features/risk/hits.tsx b/web/src/features/risk/hits.tsx index ef8aca2a83..63d9ec15ba 100644 --- a/web/src/features/risk/hits.tsx +++ b/web/src/features/risk/hits.tsx @@ -38,12 +38,10 @@ const SOURCE_STYLE: Record = { export function HitTable({ rows, empty, - showSource, action, }: { rows: GateRow[] empty: string - showSource: boolean action?: (row: GateRow) => React.ReactNode }) { if (!rows.length) { @@ -70,19 +68,17 @@ export function HitTable({ />

- {showSource ? ( - - {row.by === 'jev' - ? 'Jev' - : PREFLIGHT_RULES.find((rule) => rule.id === row.by) - ?.name || row.label} - - ) : null} + + {row.by === 'jev' + ? 'JEV' + : PREFLIGHT_RULES.find((rule) => rule.id === row.by) + ?.name || row.label} + {(row.by === 'refusal' && REFUSAL_KEYWORDS[row.keyword]) || row.keyword || diff --git a/web/src/features/risk/index.tsx b/web/src/features/risk/index.tsx index 04f3f83253..c7716bdbc3 100644 --- a/web/src/features/risk/index.tsx +++ b/web/src/features/risk/index.tsx @@ -41,7 +41,7 @@ import { RiskStatus } from './status-panel' const PAGES = [ { id: 'preflight', label: '前置', icon: ShieldCheck, hint: '硬规则与封禁' }, - { id: 'jev', label: 'Jev', icon: ScanText, hint: '模型与降级策略' }, + { id: 'jev', label: 'JEV', icon: ScanText, hint: '模型与降级策略' }, { id: 'copy', label: '封禁文案', @@ -118,7 +118,7 @@ export function RiskAuditPage() { return ( { expect(usageMoney(null)).toBe('未知') expect(usageMoney(42000)).toBe('$0.00004200') }) - it('distinguishes current accounting from historical balance', () => { - const html = markup() - expect(html).toContain('不是账户余额') - expect(html).toContain('此前未保存的历史用量无法补回') - expect(html).toContain('未知不等于免费') - }) - it('uses the same masked key in both tables and shows unknown usage for unsuccessful calls', () => { + it('renders both summary and detail tables with masked keys and unknown usage for failed calls', () => { const html = markup() expect(html).not.toContain('abcdef123456') + expect(html.match(/ { + it('folds by default while keeping summary meta in the trigger', () => { const html = markup(0, false) expect(html).toContain('JEV 使用记录') - expect(html).toContain('今日') + expect(html).not.toContain(' { - expect(markup(2)).toContain('统计可能不完整') + it('renders an alert banner when storage errors occurred', () => { + const html = markup(2) + expect(html).toContain('role="alert"') + expect(html).toContain('2') }) it('renders paused and cooling states with remaining seconds', () => { const client = new QueryClient({ @@ -160,9 +157,12 @@ describe('JEV usage display', () => { ) - expect(html).toContain('已暂停(需人工)') - expect(html).toContain('冷却中 · 剩余 24 秒') - expect(html).not.toContain('正常请求') + expect(html).toContain(jevKeyStatusTone('paused').text) + expect(html).toContain( + jevKeyStatusTone('cooling', { seconds_left: 24 }).text + ) + expect(html).toContain('529') + expect(html).not.toContain(`>${jevKeyStatusTone('normal').text}`) } finally { client.clear() } diff --git a/web/src/features/risk/jev-usage.tsx b/web/src/features/risk/jev-usage.tsx index fbf49ebb6a..63db96ab29 100644 --- a/web/src/features/risk/jev-usage.tsx +++ b/web/src/features/risk/jev-usage.tsx @@ -3,6 +3,7 @@ import { api } from '@/lib/api' import { Button } from '@/components/ui/button' import { Fold } from './blocks' import { usageMoney } from './jev-usage-format' +import { jevKeyStatusTone } from './model' type Counts = { requests: number @@ -42,16 +43,6 @@ type KeyUsage = { last_request_at: string | null last_http_status: number | null } -const keyStatus: Record = { - normal: '正常请求', - insufficient_balance: '余额不足', - auth_error: '鉴权失败', - rate_limited: '请求限流', - request_error: '请求异常', - unrequested: '未请求', - paused: '已暂停(需人工)', - cooling: '冷却中', -} type UsagePage = { keys: KeyUsage[] started_at: string | null @@ -149,7 +140,9 @@ export function JevUsagePanel({

当前 Key · 已消耗估算费用

按当前已保存明细统计(30 天保留策略),金额为 - USD,不是剩余余额。余额暂不可查询;未返回费用的请求不计入估算。状态依据最近请求,不能代表实时余额。 + USD,不是账户余额。需查实时额度请使用下方「检查剩余额度」(官方 + TypeSafe + 暂不提供余额接口);未返回费用的请求不计入估算,状态仅反映最近请求。

@@ -175,21 +168,19 @@ export function JevUsagePanel({ {key.requests === 0 ? '暂无记录' : usageMoney( - key.unknown_cost_requests === key.requests - ? null - : key.estimated_cost_nano_usd - )} + key.unknown_cost_requests === key.requests + ? null + : key.estimated_cost_nano_usd + )} diff --git a/web/src/features/risk/model-settings.tsx b/web/src/features/risk/model-settings.tsx index 0c7b464df1..f98f8de390 100644 --- a/web/src/features/risk/model-settings.tsx +++ b/web/src/features/risk/model-settings.tsx @@ -5,7 +5,6 @@ import type { JevInterceptConfig, PolicyQuestion, } from '@/types/panel-routing' -import type { StatusTone } from '@/types/status' import { toast } from 'sonner' import { api } from '@/lib/api' import { randomUUID } from '@/lib/random-uuid' @@ -19,6 +18,7 @@ import { Textarea } from '@/components/ui/textarea' import { StatusMark } from '@/components/status-mark' import { SaveBar } from '@/features/settings/save-bar' import { FieldLine, Group, ToggleItem, ToggleList } from './blocks' +import { jevKeyStatusTone } from './model' import { jevInterceptQueryOptions } from './queries' import { QuestionBank } from './question-bank' @@ -29,18 +29,6 @@ const EXAMPLES = [ { id: 'modernbert', label: 'ModernBERT', base_url: 'http://127.0.0.1:8000' }, ] as const -const KEY_STATUS: Record = { - normal: { key: 'ok', cls: 'ok', text: '正常' }, - unrequested: { key: 'none', cls: 'none', text: '未请求' }, - paused: { key: 'bad', cls: 'bad', text: '已暂停(需人工)' }, - cooling: { key: 'warn', cls: 'warn', text: '冷却中' }, - auth_error: { key: 'bad', cls: 'bad', text: '鉴权失败' }, - insufficient_balance: { key: 'bad', cls: 'bad', text: '额度用尽' }, - rate_limited: { key: 'warn', cls: 'warn', text: '限流' }, - request_error: { key: 'caution', cls: 'caution', text: '异常' }, - unsupported: { key: 'caution', cls: 'caution', text: '无余额接口' }, -} - /** Fields this stage owns. Hard-regex fields on the same config stay untouched. */ const OWNED = [ 'enabled', @@ -173,20 +161,6 @@ function blankForm(base = ''): EndpointForm { } } -function toneOf( - status: string | undefined, - row?: Pick -): StatusTone { - if (status === 'cooling' && row?.seconds_left != null) { - return { - key: 'warn', - cls: 'warn', - text: `冷却中 · 剩余 ${row.seconds_left} 秒`, - } - } - return KEY_STATUS[status || ''] || KEY_STATUS.request_error -} - function scoreOf(value: number | null) { return value == null ? '—' : value.toFixed(2) } @@ -328,7 +302,7 @@ export function ModelSettings({ base_url: base, api_keys: typed, model: draft.model, - timeout_ms: Number(draft.timeout_ms) || 2000, + timeout_ms: Number(draft.timeout_ms) || 4000, }), }) const results = data.results || [] @@ -424,7 +398,7 @@ export function ModelSettings({ body: JSON.stringify({ base_url: base, api_key: typed, - timeout_ms: Number(draft?.timeout_ms) || 2000, + timeout_ms: Number(draft?.timeout_ms) || 4000, }), }) }, @@ -531,7 +505,7 @@ export function ModelSettings({
{forms.map((form, index) => { @@ -571,7 +545,8 @@ export function ModelSettings({ const hiddenSummary = hidden .map( (row) => - toneOf(live[row.key_fingerprint] || row.status, row).text + jevKeyStatusTone(live[row.key_fingerprint] || row.status, row) + .text ) .join('、') const adding = savedKeys.length > 0 @@ -1005,7 +980,7 @@ function SavedKey({ return ( {row.masked_key} - + {canResume ? (
- {key.status === 'cooling' && key.seconds_left != null - ? `冷却中 · 剩余 ${key.seconds_left} 秒` - : (keyStatus[key.status] ?? '未知状态')} + {jevKeyStatusTone(key.status, key).text} {key.last_http_status ? ` · ${key.last_http_status}` : ''} {key.retired && - key.status !== 'paused' && - key.status !== 'cooling' + key.status !== 'paused' && + key.status !== 'cooling' ? '(已暂停轮询)' : ''}
:hit` and deliberately + // skip cluster-wide `risk:bans:*` / `risk:guards:*` L1+L2 eviction storms. if (set.has('refusal_session_blocks')) { + runLocalCacheClearers({ db: null, prefixes: ['risk:bans:session:'], reason: 'table_mutated' }) client.invalidate({ prefixes: ['risk:bans:session:'] }).catch(() => {}) } if (set.has('refusal_device_blocks') || set.has('risk_device_aliases')) { + runLocalCacheClearers({ db: null, prefixes: ['risk:bans:device:'], reason: 'table_mutated' }) client.invalidate({ prefixes: ['risk:bans:device:'] }).catch(() => {}) } + if (set.has('refusal_guards')) { + client.invalidate({ prefixes: ['risk:guards:'] }).catch(() => {}) + } if ( set.has('accounts') || diff --git a/src/lib/db/pg/pg-sync-db.mjs b/src/lib/db/pg/pg-sync-db.mjs index 4827740613..5112885038 100644 --- a/src/lib/db/pg/pg-sync-db.mjs +++ b/src/lib/db/pg/pg-sync-db.mjs @@ -39,6 +39,13 @@ const ROUTINE_API_KEY_USAGE_COLUMNS = new Set([ 'updated_at', ]) +/** + * Risk/refusal tables whose routine hit-counter updates (`hit_count`, `last_seen_at`) + * must NOT trigger cluster-wide `risk:bans:*` / `risk:guards:*` L1+L2 invalidation storms. + */ +const ROUTINE_REFUSAL_HIT_TABLES = new Set(['refusal_device_blocks', 'refusal_session_blocks', 'refusal_guards']) +const ROUTINE_REFUSAL_HIT_COLUMNS = new Set(['hit_count', 'last_seen_at']) + /** Extract the SET clause body of a single UPDATE statement, stopping at top-level WHERE/FROM/RETURNING. */ function extractUpdateSetClause(sql, startIdx) { let i = startIdx @@ -165,27 +172,27 @@ function splitTopLevelAssignments(setBody) { return parts.map((s) => s.trim()).filter(Boolean) } -/** - * Returns true iff `sql` is a single `UPDATE api_keys SET ...` that modifies - * ONLY routine usage counter / spend window / `last_used_at` columns. - */ -export function isRoutineApiKeyUsageUpdate(sql) { - if (typeof sql !== 'string') return false +function matchRoutineSingleTableUpdate(sql, allowedTables, allowedColumns) { + if (typeof sql !== 'string') return null const trimmed = sql.trim().replace(/;+\s*$/, '') // Reject multi-statement scripts conservatively - if (!/^UPDATE\s+/i.test(trimmed)) return false - const header = trimmed.match(/^UPDATE\s+["`]?api_keys["`]?(?:\s+(?:AS\s+)?[a-zA-Z_][a-zA-Z0-9_]*)?\s+SET\s+/i) - if (!header) return false + if (!/^UPDATE\s+/i.test(trimmed)) return null + const header = trimmed.match( + /^UPDATE\s+["`]?([a-zA-Z_][a-zA-Z0-9_]*)["`]?(?:\s+(?:AS\s+)?[a-zA-Z_][a-zA-Z0-9_]*)?\s+SET\s+/i, + ) + if (!header) return null + const table = header[1].toLowerCase() + if (!allowedTables.has(table)) return null // Reject if another DML keyword appears after a semicolon - if (/;\s*(?:INSERT|UPDATE|DELETE)\b/i.test(trimmed)) return false + if (/;\s*(?:INSERT|UPDATE|DELETE)\b/i.test(trimmed)) return null const setBody = extractUpdateSetClause(trimmed, header[0].length) const assignments = splitTopLevelAssignments(setBody) - if (!assignments.length) return false + if (!assignments.length) return null for (const item of assignments) { const eqIdx = item.indexOf('=') - if (eqIdx <= 0) return false + if (eqIdx <= 0) return null const lhs = item.slice(0, eqIdx).trim() // Strip optional alias (e.g. `k.quota_used`) and quotes const rawCol = lhs.includes('.') ? lhs.slice(lhs.lastIndexOf('.') + 1) : lhs @@ -193,9 +200,28 @@ export function isRoutineApiKeyUsageUpdate(sql) { .replace(/^["`]|["`]$/g, '') .trim() .toLowerCase() - if (!col || !ROUTINE_API_KEY_USAGE_COLUMNS.has(col)) return false + if (!col || !allowedColumns.has(col)) return null } - return true + return table +} + +const API_KEYS_TABLE_SET = new Set(['api_keys']) + +/** + * Returns true iff `sql` is a single `UPDATE api_keys SET ...` that modifies + * ONLY routine usage counter / spend window / `last_used_at` columns. + */ +export function isRoutineApiKeyUsageUpdate(sql) { + return matchRoutineSingleTableUpdate(sql, API_KEYS_TABLE_SET, ROUTINE_API_KEY_USAGE_COLUMNS) === 'api_keys' +} + +/** + * Returns true iff `sql` is a single `UPDATE SET ...` that + * modifies ONLY `hit_count` / `last_seen_at` on `refusal_device_blocks`, + * `refusal_session_blocks`, or `refusal_guards`. + */ +export function isRoutineRefusalHitUpdate(sql) { + return matchRoutineSingleTableUpdate(sql, ROUTINE_REFUSAL_HIT_TABLES, ROUTINE_REFUSAL_HIT_COLUMNS) !== null } function reconstructError(info) { @@ -341,8 +367,14 @@ export class PgSyncDb { if (!this._onMutation) return const tables = detectMutatedTables(sql) if (!tables.length) return - const normalized = - tables.length === 1 && tables[0] === 'api_keys' && isRoutineApiKeyUsageUpdate(sql) ? ['api_keys:usage'] : tables + let normalized = tables + if (tables.length === 1) { + if (tables[0] === 'api_keys' && isRoutineApiKeyUsageUpdate(sql)) { + normalized = ['api_keys:usage'] + } else if (ROUTINE_REFUSAL_HIT_TABLES.has(tables[0]) && isRoutineRefusalHitUpdate(sql)) { + normalized = [`${tables[0]}:hit`] + } + } if (this._inTransaction) { for (const t of normalized) this._txMutatedTables.add(t) } else { diff --git a/src/lib/db/repos/refusal-device-blocks-repo.mjs b/src/lib/db/repos/refusal-device-blocks-repo.mjs index f738e9ab7b..b0dbb876c8 100644 --- a/src/lib/db/repos/refusal-device-blocks-repo.mjs +++ b/src/lib/db/repos/refusal-device-blocks-repo.mjs @@ -1,12 +1,18 @@ import { createHash } from 'node:crypto' -import { getCacheRuntime } from '../../cache/index.mjs' -import { DB_INSTANCE_ID, getDb, isDbOpen } from '../database.mjs' +import { getDb, getPgPool, withSavepoint } from '../database.mjs' -function invalidateDeviceBanCache(db) { - const client = getCacheRuntime()?.client - if (!client) return - const scope = !db ? 'mock:' : isDbOpen() && db === getDb() ? '' : `${db?.[DB_INSTANCE_ID] || 'isolated'}:` - client.invalidate({ prefixes: [`risk:bans:device:${scope}`] }).catch(() => {}) +function normalizeNowIso(nowIso) { + if (typeof nowIso === 'string' && nowIso.trim()) return nowIso.trim() + if (typeof nowIso === 'number' && Number.isFinite(nowIso)) return new Date(nowIso).toISOString() + if (nowIso instanceof Date) return nowIso.toISOString() + return new Date().toISOString() +} + +function isFkConstraintError(err) { + if (!err) return false + const code = String(err.code || err.pgCode || '') + if (code === '23503' || code === 'SQLITE_CONSTRAINT_FOREIGNKEY') return true + return /foreign key constraint/i.test(String(err.message || '')) } function subjectKey(identity, kind, value = kind === 'session' ? identity.sessionId : identity.deviceId) { @@ -40,8 +46,14 @@ export class RefusalDeviceBlocksRepo { constructor(db = getDb()) { this.db = db this._get = db.prepare('SELECT * FROM refusal_device_blocks WHERE device_id = ?') + this._getForUpdate = undefined this._alias = db.prepare('SELECT device_key FROM risk_device_aliases WHERE alias_key = ?') - this._bindAlias = db.prepare('INSERT OR IGNORE INTO risk_device_aliases (alias_key, device_key) VALUES (?, ?)') + this._bindAlias = db.prepare(` + INSERT INTO risk_device_aliases (alias_key, device_key) + SELECT CAST(? AS TEXT), CAST(? AS TEXT) + WHERE EXISTS (SELECT 1 FROM refusal_device_blocks WHERE device_id = ?) + ON CONFLICT(alias_key) DO NOTHING + `) this._insert = db.prepare(` INSERT INTO refusal_device_blocks ( device_id, first_seen_at, last_seen_at, hit_count, @@ -63,12 +75,80 @@ export class RefusalDeviceBlocksRepo { subject_kind, identity_value, session_id, violations, expires_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(device_id) DO UPDATE SET - last_seen_at = excluded.last_seen_at, source_request_id = excluded.source_request_id, - fingerprint = excluded.fingerprint, reason = excluded.reason, session_id = excluded.session_id, - violations = excluded.violations, expires_at = excluded.expires_at + last_seen_at = excluded.last_seen_at, + source_request_id = excluded.source_request_id, + fingerprint = excluded.fingerprint, + reason = excluded.reason, + session_id = excluded.session_id, + violations = CASE + WHEN refusal_device_blocks.violations > excluded.violations THEN refusal_device_blocks.violations + ELSE excluded.violations + END, + expires_at = CASE + WHEN refusal_device_blocks.expires_at IS NULL THEN NULL + WHEN excluded.expires_at IS NULL THEN NULL + ELSE excluded.expires_at + END + `) + this._blockSessionUpsert = db.prepare(` + INSERT INTO refusal_device_blocks ( + device_id, first_seen_at, last_seen_at, source_request_id, fingerprint, reason, + subject_kind, identity_value, session_id, violations, expires_at + ) VALUES (?, ?, ?, ?, ?, ?, 'session', ?, ?, 1, ?) + ON CONFLICT(device_id) DO UPDATE SET + last_seen_at = CASE + WHEN refusal_device_blocks.expires_at IS NULL THEN refusal_device_blocks.last_seen_at + ELSE excluded.last_seen_at + END, + source_request_id = CASE + WHEN refusal_device_blocks.expires_at IS NULL THEN refusal_device_blocks.source_request_id + ELSE excluded.source_request_id + END, + fingerprint = CASE + WHEN refusal_device_blocks.expires_at IS NULL THEN refusal_device_blocks.fingerprint + ELSE excluded.fingerprint + END, + reason = CASE + WHEN refusal_device_blocks.expires_at IS NULL THEN refusal_device_blocks.reason + ELSE excluded.reason + END, + session_id = CASE + WHEN refusal_device_blocks.expires_at IS NULL THEN refusal_device_blocks.session_id + ELSE excluded.session_id + END, + violations = CASE + WHEN refusal_device_blocks.expires_at IS NULL THEN refusal_device_blocks.violations + WHEN refusal_device_blocks.expires_at > excluded.last_seen_at + THEN CASE WHEN COALESCE(refusal_device_blocks.violations, 0) > 0 THEN refusal_device_blocks.violations ELSE 1 END + ELSE COALESCE(refusal_device_blocks.violations, 0) + 1 + END, + expires_at = CASE + WHEN refusal_device_blocks.expires_at IS NULL THEN NULL + WHEN excluded.expires_at IS NULL THEN NULL + WHEN refusal_device_blocks.expires_at > excluded.expires_at THEN refusal_device_blocks.expires_at + ELSE excluded.expires_at + END + WHERE refusal_device_blocks.expires_at IS NOT NULL + `) + this._list = db.prepare(` + SELECT * FROM refusal_device_blocks + WHERE expires_at IS NULL OR expires_at > ? + ORDER BY last_seen_at DESC, device_id + LIMIT ? + `) + this._count = db.prepare(` + SELECT COUNT(*) AS n FROM refusal_device_blocks + WHERE expires_at IS NULL OR expires_at > ? + `) + this._pruneExpired = db.prepare(` + DELETE FROM refusal_device_blocks + WHERE device_id IN ( + SELECT device_id FROM refusal_device_blocks + WHERE expires_at IS NOT NULL AND expires_at <= ? + ORDER BY expires_at ASC + LIMIT ? + ) `) - this._list = db.prepare('SELECT * FROM refusal_device_blocks ORDER BY last_seen_at DESC, device_id LIMIT ?') - this._count = db.prepare('SELECT COUNT(*) AS n FROM refusal_device_blocks') this._remove = db.prepare('DELETE FROM refusal_device_blocks WHERE device_id = ?') this._removeSessionByValue = db.prepare( "DELETE FROM refusal_device_blocks WHERE subject_kind = 'session' AND (identity_value = ? OR session_id = ?)", @@ -77,6 +157,34 @@ export class RefusalDeviceBlocksRepo { this._clearSessions = db.prepare("DELETE FROM refusal_device_blocks WHERE subject_kind = 'session'") } + _resolvePgPool() { + if (this.db?.pgPool && typeof this.db.pgPool.query === 'function') return this.db.pgPool + if (this.db?.engine === 'postgres') { + const pool = getPgPool() + if (pool && typeof pool.query === 'function') return pool + } + return null + } + + _lockRowForUpdate(deviceId) { + if (this.db?.engine !== 'postgres' || !deviceId) return + if (this._getForUpdate === undefined) { + try { + this._getForUpdate = this.db.prepare( + 'SELECT device_id FROM refusal_device_blocks WHERE device_id = ? FOR UPDATE', + ) + } catch { + this._getForUpdate = null + } + } + if (!this._getForUpdate) return + try { + this._getForUpdate.get(deviceId) + } catch { + this._getForUpdate = null + } + } + get(deviceId) { const id = String(deviceId || '').trim() if (!id) return null @@ -125,37 +233,20 @@ export class RefusalDeviceBlocksRepo { const why = String(reason || 'upstream_400').slice(0, 160) const durationMs = Number(ttlMs) const expiresAt = Number.isFinite(durationMs) && durationMs > 0 ? new Date(now + durationMs).toISOString() : null - this.db.exec('BEGIN IMMEDIATE') - try { - const prior = this._get.get(sessionKey) - // Never downgrade an existing permanent session ban to a temporary cooldown. - if (prior && prior.subject_kind === 'session' && !prior.expires_at) { - this.db.exec('COMMIT') - return rowToRec(prior) - } - const priorActive = Boolean(prior?.expires_at && Date.parse(prior.expires_at) > now) - const violations = prior ? (priorActive ? Number(prior.violations) || 1 : (Number(prior.violations) || 0) + 1) : 1 - const effectiveExpiresAt = - priorActive && expiresAt && Date.parse(prior.expires_at) > Date.parse(expiresAt) ? prior.expires_at : expiresAt - this._violation.run( - sessionKey, - at, - at, - requestId, - fingerprint, - why, - 'session', - identity.sessionId, - identity.sessionId, - violations, - effectiveExpiresAt, - ) - this.db.exec('COMMIT') - return this.get(sessionKey) - } catch (error) { - this.db.exec('ROLLBACK') - throw error - } + // Single atomic UPSERT protects permanent session bans (expires_at IS NULL) + // from being downgraded under concurrent PostgreSQL READ COMMITTED writes. + this._blockSessionUpsert.run( + sessionKey, + at, + at, + requestId, + fingerprint, + why, + identity.sessionId, + identity.sessionId, + expiresAt, + ) + return this.get(sessionKey) } recordViolation( @@ -168,6 +259,11 @@ export class RefusalDeviceBlocksRepo { const why = String(reason).slice(0, 160) this.db.exec('BEGIN IMMEDIATE') try { + const preSubjects = this.deviceSubjects(identity) + if (this.db?.engine === 'postgres') { + const lockKeys = [...new Set([sessionKey, ...preSubjects.map((s) => s.key)].filter(Boolean))].sort() + for (const k of lockKeys) this._lockRowForUpdate(k) + } const rawExisting = this.findBan(identity, now, accepts) // A temporary session cooldown (e.g. 10m upstream_400) must not block // recording a device strike or upgrading the session ban to permanent. @@ -198,7 +294,15 @@ export class RefusalDeviceBlocksRepo { } if (deviceKey && (!existing || existing.device_id === deviceKey)) { for (const { alias, key } of subjects) { - if (alias !== deviceKey && !this._get.get(key)) this._bindAlias.run(alias, deviceKey) + if (alias !== deviceKey && !this._get.get(key)) { + try { + withSavepoint(this.db, 'risk_alias', () => { + this._bindAlias.run(alias, deviceKey, deviceKey) + }) + } catch (err) { + if (!isFkConstraintError(err)) throw err + } + } } } const priorSession = sessionKey && this._get.get(sessionKey) @@ -221,7 +325,9 @@ export class RefusalDeviceBlocksRepo { this.db.exec('COMMIT') return existing || this.get(deviceKey || sessionKey) } catch (error) { - this.db.exec('ROLLBACK') + try { + this.db.exec('ROLLBACK') + } catch {} throw error } } @@ -241,13 +347,54 @@ export class RefusalDeviceBlocksRepo { return this.get(id) } - list(limit = 200) { + /** Lightweight fire-and-forget hit counter (async PG pool when available, single UPDATE on SQLite). */ + recordHit(deviceId) { + const id = String(deviceId || '').trim() + if (!id) return + const nowIso = new Date().toISOString() + const pool = this._resolvePgPool() + if (pool) { + pool + .query('UPDATE refusal_device_blocks SET hit_count = hit_count + 1, last_seen_at = $1 WHERE device_id = $2', [ + nowIso, + id, + ]) + .catch((err) => { + console.warn('[risk-audit] async device ban hit update failed:', err?.message || err) + }) + return + } + this._hit.run(nowIso, id) + } + + list(limit = 200, nowIso = new Date().toISOString()) { const n = Math.min(500, Math.max(1, Number(limit) || 200)) - return this._list.all(n).map(rowToRec) + return this._list.all(normalizeNowIso(nowIso), n).map(rowToRec) + } + + count(nowIso = new Date().toISOString()) { + return Number(this._count.get(normalizeNowIso(nowIso))?.n) || 0 } - count() { - return Number(this._count.get()?.n) || 0 + /** Bounded batch GC for expired temporary device/session bans. */ + async pruneExpired(nowIso = new Date().toISOString(), limit = 500) { + const n = Math.min(5000, Math.max(1, Math.floor(Number(limit) || 500))) + const cutoff = normalizeNowIso(nowIso) + const pool = this._resolvePgPool() + if (pool) { + const res = await pool.query( + `DELETE FROM refusal_device_blocks + WHERE device_id IN ( + SELECT device_id FROM refusal_device_blocks + WHERE expires_at IS NOT NULL AND expires_at <= $1 + ORDER BY expires_at ASC + LIMIT $2 + )`, + [cutoff, n], + ) + return Number(res?.rowCount) || 0 + } + return Number(this._pruneExpired.run(cutoff, n)?.changes) || 0 } remove(deviceId) { @@ -259,9 +406,7 @@ export class RefusalDeviceBlocksRepo { removeSessionByValue(sessionId) { const id = String(sessionId || '').trim() if (!id) return false - const removed = this._removeSessionByValue.run(id, id).changes > 0 - if (this.db) invalidateDeviceBanCache(this.db) - return removed + return this._removeSessionByValue.run(id, id).changes > 0 } clear() { @@ -269,8 +414,6 @@ export class RefusalDeviceBlocksRepo { } clearSessions() { - const changes = this._clearSessions.run().changes - if (this.db) invalidateDeviceBanCache(this.db) - return changes + return this._clearSessions.run().changes } } diff --git a/src/lib/db/repos/refusal-guards-repo.mjs b/src/lib/db/repos/refusal-guards-repo.mjs index 46f52d262f..e49bc3a251 100644 --- a/src/lib/db/repos/refusal-guards-repo.mjs +++ b/src/lib/db/repos/refusal-guards-repo.mjs @@ -8,13 +8,37 @@ */ import { decodeSignature, REFUSAL_SIMILARITY, signatureSimilarity } from '../../core/refusal-similarity.mjs' import { getCacheRuntime, registerLocalCacheClearer } from '../../cache/index.mjs' -import { getDb, isDbOpen } from '../database.mjs' +import { getDb, getPgPool, isDbOpen } from '../database.mjs' const GUARD_CACHE_PREFIX = 'risk:guards:' const SNAPSHOT_TTL_MS = 60_000 let dbSnapshots = new WeakMap() // db -> { revision, loadedAt, byFingerprint, signatures } const hookedClients = new WeakSet() +const pendingSelfRememberInvalidations = new WeakMap() // client -> count of in-flight self remember() broadcasts + +function normalizeNowIso(nowIso) { + if (typeof nowIso === 'string' && nowIso.trim()) return nowIso.trim() + if (typeof nowIso === 'number' && Number.isFinite(nowIso)) return new Date(nowIso).toISOString() + if (nowIso instanceof Date) return nowIso.toISOString() + return new Date().toISOString() +} + +function hasAutomaticDbInvalidation(db) { + return Boolean(db && db.engine === 'postgres' && typeof db._onMutation === 'function' && isDbOpen() && db === getDb()) +} + +function incrementSelfRememberPending(client) { + if (!client) return + pendingSelfRememberInvalidations.set(client, (pendingSelfRememberInvalidations.get(client) || 0) + 1) +} + +function decrementSelfRememberPending(client) { + if (!client) return + const cur = pendingSelfRememberInvalidations.get(client) || 0 + if (cur <= 1) pendingSelfRememberInvalidations.delete(client) + else pendingSelfRememberInvalidations.set(client, cur - 1) +} function ensureGuardInvalidationHook(cache) { const client = cache?.client @@ -22,12 +46,18 @@ function ensureGuardInvalidationHook(cache) { hookedClients.add(client) client.onInvalidate((payload) => { if (!payload) return - const matchPrefix = - Array.isArray(payload.prefixes) && - payload.prefixes.some((p) => p === GUARD_CACHE_PREFIX || GUARD_CACHE_PREFIX.startsWith(p)) - if (matchPrefix) { - invalidateRefusalGuardsSnapshot() + const prefixes = Array.isArray(payload.prefixes) ? payload.prefixes : [] + const matchPrefix = prefixes.some((p) => p === GUARD_CACHE_PREFIX || GUARD_CACHE_PREFIX.startsWith(p)) + if (!matchPrefix) return + // When this instance's own `remember()` incrementally updated its local snapshot + // and broadcast `risk:guards:` for peers, skip wiping the fresh local snapshot. + const isSelfOnlyGuardEvent = + payload.origin === client.instanceId && prefixes.length === 1 && prefixes[0] === GUARD_CACHE_PREFIX + if (isSelfOnlyGuardEvent && (pendingSelfRememberInvalidations.get(client) || 0) > 0) { + decrementSelfRememberPending(client) + return } + invalidateRefusalGuardsSnapshot() }) } @@ -39,7 +69,11 @@ export function invalidateRefusalGuardsSnapshot(db = null) { } } -registerLocalCacheClearer(({ db = null } = {}) => { +registerLocalCacheClearer(({ db = null, prefixes = null } = {}) => { + if (Array.isArray(prefixes) && prefixes.length > 0) { + const match = prefixes.some((p) => p === GUARD_CACHE_PREFIX || GUARD_CACHE_PREFIX.startsWith(p)) + if (!match) return + } invalidateRefusalGuardsSnapshot(db) }) @@ -90,16 +124,41 @@ export class RefusalGuardsRepo { this._list = db.prepare( `SELECT fingerprint, model, first_seen_at, last_seen_at, hit_count, source_request_id, error_message, preview, expires_at - FROM refusal_guards ORDER BY last_seen_at DESC, fingerprint LIMIT ?`, + FROM refusal_guards + WHERE expires_at IS NULL OR expires_at > ? + ORDER BY last_seen_at DESC, fingerprint + LIMIT ?`, + ) + this._signatures = db.prepare( + `SELECT fingerprint, signature FROM refusal_guards + WHERE signature IS NOT NULL AND (expires_at IS NULL OR expires_at > ?)`, ) - this._count = db.prepare('SELECT COUNT(*) AS n FROM refusal_guards') + this._count = db.prepare('SELECT COUNT(*) AS n FROM refusal_guards WHERE expires_at IS NULL OR expires_at > ?') + this._pruneExpired = db.prepare(` + DELETE FROM refusal_guards + WHERE fingerprint IN ( + SELECT fingerprint FROM refusal_guards + WHERE expires_at IS NOT NULL AND expires_at <= ? + ORDER BY expires_at ASC + LIMIT ? + ) + `) this._remove = db.prepare('DELETE FROM refusal_guards WHERE fingerprint = ?') this._clear = db.prepare('DELETE FROM refusal_guards') } + _resolvePgPool() { + if (this.db?.pgPool && typeof this.db.pgPool.query === 'function') return this.db.pgPool + if (this.db?.engine === 'postgres') { + const pool = getPgPool() + if (pool && typeof pool.query === 'function') return pool + } + return null + } + _invalidateSnapshot(broadcast = true) { dbSnapshots.delete(this.db) - if (broadcast && isDbOpen() && this.db === getDb()) { + if (broadcast && isDbOpen() && this.db === getDb() && !hasAutomaticDbInvalidation(this.db)) { const client = getCacheRuntime()?.client client?.invalidate?.({ prefixes: [GUARD_CACHE_PREFIX] }).catch(() => {}) } @@ -162,20 +221,82 @@ export class RefusalGuardsRepo { } = {}) { const fp = String(fingerprint || '').trim() if (!fp) return null - const now = new Date().toISOString() - this._insert.run( - fp, - String(model || ''), - now, - now, - requestId, - errorMessage ? String(errorMessage).slice(0, 500) : null, - preview ? String(preview).slice(0, 240) : null, - expiresAt || null, - signature || null, - ) - this._invalidateSnapshot(true) - return this.get(fp) + const nowMs = Date.now() + const now = new Date(nowMs).toISOString() + const modelStr = String(model || '') + const errMsg = errorMessage ? String(errorMessage).slice(0, 500) : null + const previewStr = preview ? String(preview).slice(0, 240) : null + const expStr = expiresAt || null + const sigVal = signature || null + + const cache = getCacheRuntime() + ensureGuardInvalidationHook(cache) + const client = cache?.client || null + const isPrimary = isDbOpen() && this.db === getDb() + const autoPg = hasAutomaticDbInvalidation(this.db) + const suppressAutoSelf = Boolean(autoPg && isPrimary && client && !this.db.isTransaction) + + if (suppressAutoSelf) incrementSelfRememberPending(client) + let res + try { + res = this._insert.run(fp, modelStr, now, now, requestId, errMsg, previewStr, expStr, sigVal) + } catch (err) { + if (suppressAutoSelf) decrementSelfRememberPending(client) + throw err + } + if (suppressAutoSelf && !(res?.changes > 0)) { + decrementSelfRememberPending(client) + } + + // Incrementally maintain any warm in-process snapshot instead of invalidating + // and triggering immediate + delayed double full-table rescans. + const snap = dbSnapshots.get(this.db) + const prev = snap?.byFingerprint?.get(fp)?.rec || null + const effectiveExpiresAt = prev ? (prev.expires_at === null || expStr === null ? null : expStr) : expStr + const rec = { + fingerprint: fp, + model: prev ? prev.model : modelStr, + first_seen_at: prev ? prev.first_seen_at : now, + last_seen_at: now, + hit_count: prev ? prev.hit_count : 0, + source_request_id: prev ? prev.source_request_id : requestId, + error_message: errMsg ?? prev?.error_message ?? null, + preview: previewStr ?? prev?.preview ?? null, + expires_at: effectiveExpiresAt, + } + const expiresAtMs = rec.expires_at ? Date.parse(rec.expires_at) : null + const expired = expiresAtMs != null && Number.isFinite(expiresAtMs) && expiresAtMs <= nowMs + + if (snap) { + if (expired) { + snap.byFingerprint.delete(fp) + const idx = snap.signatures.findIndex((item) => item.fingerprint === fp) + if (idx !== -1) snap.signatures.splice(idx, 1) + } else { + snap.byFingerprint.set(fp, { rec, expiresAtMs }) + const existingSigIdx = snap.signatures.findIndex((item) => item.fingerprint === fp) + if (sigVal != null) { + const decoded = decodeSignature(sigVal) + if (decoded) { + const sigEntry = { fingerprint: fp, sig: decoded, expiresAtMs } + if (existingSigIdx !== -1) snap.signatures[existingSigIdx] = sigEntry + else snap.signatures.push(sigEntry) + } + } else if (existingSigIdx !== -1) { + snap.signatures[existingSigIdx].expiresAtMs = expiresAtMs + } + } + } + + // Broadcast to peer instances (SQLite / non-auto-PG mode) without wiping this instance's snapshot. + if (!autoPg && isPrimary && client?.invalidate) { + incrementSelfRememberPending(client) + client.invalidate({ prefixes: [GUARD_CACHE_PREFIX] }).catch(() => { + decrementSelfRememberPending(client) + }) + } + + return expired ? null : { ...rec } } hit(fingerprint) { @@ -193,6 +314,32 @@ export class RefusalGuardsRepo { return this.get(fp) } + /** Lightweight fire-and-forget hit counter (async PG pool when available, single UPDATE on SQLite). */ + recordHit(fingerprint) { + const fp = String(fingerprint || '').trim() + if (!fp) return + const nowIso = new Date().toISOString() + const snap = dbSnapshots.get(this.db) + const entry = snap?.byFingerprint?.get(fp) + if (entry) { + entry.rec.hit_count = (Number(entry.rec.hit_count) || 0) + 1 + entry.rec.last_seen_at = nowIso + } + const pool = this._resolvePgPool() + if (pool) { + pool + .query('UPDATE refusal_guards SET hit_count = hit_count + 1, last_seen_at = $1 WHERE fingerprint = $2', [ + nowIso, + fp, + ]) + .catch((err) => { + console.warn('[refusal-guard] async hit update failed:', err?.message || err) + }) + return + } + this._hit.run(nowIso, fp) + } + /** Highest stored user-text signature at or above the threshold (served from in-memory snapshot). */ nearest(signature, threshold = REFUSAL_SIMILARITY) { const query = Array.isArray(signature) ? signature : decodeSignature(signature) @@ -213,17 +360,51 @@ export class RefusalGuardsRepo { return { ...rec, score: best.score } } - list(limit = 200) { + list(limit = 200, nowIso = new Date().toISOString()) { const n = Math.min(500, Math.max(1, Number(limit) || 200)) - const now = Date.now() - return this._list - .all(n) - .map(rowToRec) - .filter((rec) => !rec.expires_at || Date.parse(rec.expires_at) > now) + return this._list.all(normalizeNowIso(nowIso), n).map(rowToRec) } - count() { - return Number(this._count.get()?.n) || 0 + count(nowIso = new Date().toISOString()) { + return Number(this._count.get(normalizeNowIso(nowIso))?.n) || 0 + } + + /** Bounded batch GC for expired refusal guards. */ + async pruneExpired(nowIso = new Date().toISOString(), limit = 500) { + const n = Math.min(5000, Math.max(1, Math.floor(Number(limit) || 500))) + const cutoff = normalizeNowIso(nowIso) + const cutoffMs = Date.parse(cutoff) + let deleted = 0 + const pool = this._resolvePgPool() + if (pool) { + const res = await pool.query( + `DELETE FROM refusal_guards + WHERE fingerprint IN ( + SELECT fingerprint FROM refusal_guards + WHERE expires_at IS NOT NULL AND expires_at <= $1 + ORDER BY expires_at ASC + LIMIT $2 + )`, + [cutoff, n], + ) + deleted = Number(res?.rowCount) || 0 + } else { + deleted = Number(this._pruneExpired.run(cutoff, n)?.changes) || 0 + } + if (deleted > 0 && Number.isFinite(cutoffMs)) { + const snap = dbSnapshots.get(this.db) + if (snap) { + for (const [fp, entry] of snap.byFingerprint) { + if (entry.expiresAtMs != null && Number.isFinite(entry.expiresAtMs) && entry.expiresAtMs <= cutoffMs) { + snap.byFingerprint.delete(fp) + } + } + snap.signatures = snap.signatures.filter( + (item) => item.expiresAtMs == null || !Number.isFinite(item.expiresAtMs) || item.expiresAtMs > cutoffMs, + ) + } + } + return deleted } remove(fingerprint) { diff --git a/src/lib/db/repos/refusal-session-blocks-repo.mjs b/src/lib/db/repos/refusal-session-blocks-repo.mjs index 67c12e8739..f2626d6eaa 100644 --- a/src/lib/db/repos/refusal-session-blocks-repo.mjs +++ b/src/lib/db/repos/refusal-session-blocks-repo.mjs @@ -2,7 +2,7 @@ * Permanent block of an inbound caller session after an upstream refusal. * Keyed by the root caller session id; empty ids are never stored. */ -import { getDb } from '../database.mjs' +import { getDb, getPgPool } from '../database.mjs' function rowToRec(row) { if (!row) return null @@ -75,6 +75,15 @@ export class RefusalSessionBlocksRepo { return this.get(id) } + _resolvePgPool() { + if (this.db?.pgPool && typeof this.db.pgPool.query === 'function') return this.db.pgPool + if (this.db?.engine === 'postgres') { + const pool = getPgPool() + if (pool && typeof pool.query === 'function') return pool + } + return null + } + hit(sessionId) { const id = String(sessionId || '').trim() if (!id) return null @@ -82,6 +91,26 @@ export class RefusalSessionBlocksRepo { return this.get(id) } + /** Lightweight fire-and-forget hit counter (async PG pool when available, single UPDATE on SQLite). */ + recordHit(sessionId) { + const id = String(sessionId || '').trim() + if (!id) return + const nowIso = new Date().toISOString() + const pool = this._resolvePgPool() + if (pool) { + pool + .query('UPDATE refusal_session_blocks SET hit_count = hit_count + 1, last_seen_at = $1 WHERE session_id = $2', [ + nowIso, + id, + ]) + .catch((err) => { + console.warn('[refusal-session] async hit update failed:', err?.message || err) + }) + return + } + this._hit.run(nowIso, id) + } + list(limit = 200) { const n = Math.min(500, Math.max(1, Number(limit) || 200)) return this._list.all(n).map(rowToRec) diff --git a/src/lib/protocol/intercept-gate.mjs b/src/lib/protocol/intercept-gate.mjs index e7137adc5a..dba17ccb45 100644 --- a/src/lib/protocol/intercept-gate.mjs +++ b/src/lib/protocol/intercept-gate.mjs @@ -1,6 +1,7 @@ import { detectDistill, distillBlockError, isOpenaiPlatformModel } from '../core/distill-detect.mjs' import { DB_INSTANCE_ID, getDb, isDbOpen } from '../db/database.mjs' -import { getCacheRuntime } from '../cache/index.mjs' +import { BoundedLruCache } from '../cache/cache-client.mjs' +import { getCacheRuntime, registerLocalCacheClearer } from '../cache/index.mjs' import { redactSecrets } from '../core/security.mjs' import { ErrorType, @@ -374,9 +375,69 @@ const RISK_SESSION_PREFIX = 'risk:bans:session:' const RISK_DEVICE_PREFIX = 'risk:bans:device:' const RISK_BAN_L1_TTL_MS = 10_000 const RISK_BAN_L2_TTL_MS = 15_000 +const RISK_BAN_NEG_L1_TTL_MS = 3_000 +const RISK_BAN_NEG_MAX_ITEMS = 4_096 const wrappedBanRepos = new WeakSet() const wrappedBanProtos = new WeakSet() +const clientNegCaches = new WeakMap() // MultiTierCacheClient -> BoundedLruCache + +function clearNegCacheByPrefixes(neg, prefixes) { + if (!neg || !Array.isArray(prefixes) || !prefixes.length) return + for (const p of prefixes) { + if (!p) continue + if (p === RISK_BAN_PREFIX || RISK_BAN_PREFIX.startsWith(p)) { + neg.clear() + return + } + if (p.startsWith(RISK_BAN_PREFIX)) { + neg.deleteByPrefix(p) + } + } +} + +function getRiskNegCache(client) { + let neg = clientNegCaches.get(client) + if (!neg) { + neg = new BoundedLruCache(RISK_BAN_NEG_MAX_ITEMS) + clientNegCaches.set(client, neg) + if (typeof client.onInvalidate === 'function') { + client.onInvalidate((payload) => { + if (!payload) return + if (Array.isArray(payload.keys)) { + for (const k of payload.keys) { + if (typeof k === 'string' && k.startsWith(RISK_BAN_PREFIX)) neg.delete(k) + } + } + clearNegCacheByPrefixes(neg, payload.prefixes) + }) + } + } + return neg +} + +registerLocalCacheClearer(({ prefixes = null } = {}) => { + const client = getCacheRuntime()?.client + const neg = client ? clientNegCaches.get(client) : null + if (!neg) return + if (Array.isArray(prefixes) && prefixes.length > 0) { + clearNegCacheByPrefixes(neg, prefixes) + } else { + neg.clear() + } +}) + +function hasAutomaticDbInvalidation(db) { + return Boolean(db && db.engine === 'postgres' && typeof db._onMutation === 'function' && isDbOpen() && db === getDb()) +} + +function maybeInvalidateBanCacheAfterWrite(repo, kind) { + if (!repo) return + if (hasAutomaticDbInvalidation(repo.db)) return + const proto = Object.getPrototypeOf(repo) + if ((proto && wrappedBanProtos.has(proto)) || wrappedBanRepos.has(repo)) return + invalidateRiskBanCache({ kind, db: repo.db || null }) +} function riskScopePrefix(db) { if (!db) return 'mock:' @@ -400,6 +461,8 @@ export function invalidateRiskBanCache(opts = {}) { : kind === 'device' ? `${RISK_DEVICE_PREFIX}${db ? riskScopePrefix(db) : ''}` : `${RISK_BAN_PREFIX}` + const neg = clientNegCaches.get(client) + if (neg) clearNegCacheByPrefixes(neg, [prefix]) return client.invalidate({ prefixes: [prefix] }).catch(() => {}) } @@ -416,7 +479,9 @@ function attachBanRepoInvalidationHooks(repo, kind) { if (typeof orig !== 'function') continue proto[name] = function wrappedRiskBanWrite(...args) { const out = orig.apply(this, args) - if (this?.db) invalidateRiskBanCache({ kind, db: this.db }) + if (this?.db && !hasAutomaticDbInvalidation(this.db)) { + invalidateRiskBanCache({ kind, db: this.db }) + } return out } } @@ -429,13 +494,15 @@ function attachBanRepoInvalidationHooks(repo, kind) { const orig = repo[name].bind(repo) repo[name] = (...args) => { const out = orig(...args) - invalidateRiskBanCache({ kind, db: repo.db }) + if (!hasAutomaticDbInvalidation(repo.db)) { + invalidateRiskBanCache({ kind, db: repo.db }) + } return out } } } -function deviceBanCacheKey(db, identity, policy) { +export function deviceBanCacheKey(db, identity, policy) { const scope = riskScopePrefix(db) const policyKey = `${policy?.enabled ? 1 : 0}:${policy?.device_block_enabled ? 1 : 0}:${policy?.session_block_enabled === false ? 0 : 1}` const parts = [ @@ -449,7 +516,8 @@ function deviceBanCacheKey(db, identity, policy) { async function cachedMatchRefusalSession({ inbound, body, headers, sessions, now }) { if (!sessions) return null - const useCache = Boolean(sessions.db && getCacheRuntime()?.client?.enabled && Math.abs(now - Date.now()) <= 60_000) + const client = getCacheRuntime()?.client + const useCache = Boolean(sessions.db && client?.enabled && Math.abs(now - Date.now()) <= 60_000) if (!useCache) { return matchRefusalSession({ inbound, body, headers, sessions }) } @@ -458,42 +526,41 @@ async function cachedMatchRefusalSession({ inbound, body, headers, sessions, now if (!sessionId) return null const scope = riskScopePrefix(sessions.db) const key = `${RISK_SESSION_PREFIX}${scope}${sessionId}` - const client = getCacheRuntime().client const isPrimary = scope === '' - const hit = await client.get(key, { - useL2: isPrimary, - prefixes: [RISK_BAN_PREFIX, RISK_SESSION_PREFIX], - maxL1TtlMs: RISK_BAN_L1_TTL_MS, - }) - if (hit.hit) { - const cached = hit.value?.v ?? null - if (!cached) return null - if (cached.row?.expires_at && Date.parse(cached.row.expires_at) <= now) { - invalidateRiskBanCache({ kind: 'session', db: sessions.db }) - return null - } - return cached - } - const matched = matchRefusalSession({ inbound, body, headers, sessions }) - if (isPrimary) { - await client.set( - key, - { v: matched || null }, - { - ttlMs: RISK_BAN_L2_TTL_MS, - l1TtlMs: RISK_BAN_L1_TTL_MS, - prefixes: [RISK_BAN_PREFIX, RISK_SESSION_PREFIX], - }, - ) - } else { - client.setL1(key, { v: matched || null }, RISK_BAN_L1_TTL_MS) + const negCache = getRiskNegCache(client) + if (negCache.get(key).hit) return null + + const env = await client.getOrLoad( + key, + () => { + const matched = matchRefusalSession({ inbound, body, headers, sessions }) + if (!matched) { + negCache.set(key, null, RISK_BAN_NEG_L1_TTL_MS) + return undefined + } + return { v: matched } + }, + { + useL2: isPrimary, + ttlMs: RISK_BAN_L2_TTL_MS, + l1TtlMs: RISK_BAN_L1_TTL_MS, + maxL1TtlMs: RISK_BAN_L1_TTL_MS, + prefixes: [RISK_BAN_PREFIX, RISK_SESSION_PREFIX], + }, + ) + const cached = env?.v ?? null + if (!cached) return null + if (cached.row?.expires_at && Date.parse(cached.row.expires_at) <= now) { + invalidateRiskBanCache({ kind: 'session', db: sessions.db }) + return null } - return matched + return cached } async function cachedFindDeviceBan({ devices, identity, policy, now }) { if (!devices?.findBan) return null - const useCache = Boolean(devices.db && getCacheRuntime()?.client?.enabled && Math.abs(now - Date.now()) <= 60_000) + const client = getCacheRuntime()?.client + const useCache = Boolean(devices.db && client?.enabled && Math.abs(now - Date.now()) <= 60_000) const accepts = (row) => enforcesBan(policy, row) if (!useCache) { return devices.findBan(identity, now, accepts) @@ -501,37 +568,35 @@ async function cachedFindDeviceBan({ devices, identity, policy, now }) { attachBanRepoInvalidationHooks(devices, 'device') const scope = riskScopePrefix(devices.db) const key = deviceBanCacheKey(devices.db, identity, policy) - const client = getCacheRuntime().client const isPrimary = scope === '' - const hit = await client.get(key, { - useL2: isPrimary, - prefixes: [RISK_BAN_PREFIX, RISK_DEVICE_PREFIX], - maxL1TtlMs: RISK_BAN_L1_TTL_MS, - }) - if (hit.hit) { - const cached = hit.value?.v ?? null - if (!cached) return null - if (cached.expires_at && Date.parse(cached.expires_at) <= now) { - invalidateRiskBanCache({ kind: 'device', db: devices.db }) - } else { - return cached - } - } - const found = devices.findBan(identity, now, accepts) || null - if (isPrimary) { - await client.set( - key, - { v: found }, - { - ttlMs: RISK_BAN_L2_TTL_MS, - l1TtlMs: RISK_BAN_L1_TTL_MS, - prefixes: [RISK_BAN_PREFIX, RISK_DEVICE_PREFIX], - }, - ) - } else { - client.setL1(key, { v: found }, RISK_BAN_L1_TTL_MS) + const negCache = getRiskNegCache(client) + if (negCache.get(key).hit) return null + + const env = await client.getOrLoad( + key, + () => { + const found = devices.findBan(identity, now, accepts) || null + if (!found) { + negCache.set(key, null, RISK_BAN_NEG_L1_TTL_MS) + return undefined + } + return { v: found } + }, + { + useL2: isPrimary, + ttlMs: RISK_BAN_L2_TTL_MS, + l1TtlMs: RISK_BAN_L1_TTL_MS, + maxL1TtlMs: RISK_BAN_L1_TTL_MS, + prefixes: [RISK_BAN_PREFIX, RISK_DEVICE_PREFIX], + }, + ) + const cached = env?.v ?? null + if (!cached) return null + if (cached.expires_at && Date.parse(cached.expires_at) <= now) { + invalidateRiskBanCache({ kind: 'device', db: devices.db }) + return devices.findBan(identity, now, accepts) || null } - return found + return cached } function recordBan(decision, { devices, policy, requestId, now = Date.now() }) { @@ -553,12 +618,12 @@ function recordBan(decision, { devices, policy, requestId, now = Date.now() }) { now, accepts: (row) => enforcesBan(policy, row), }) || null - if (ban) invalidateRiskBanCache({ kind: 'device', db: store.db || null }) + if (ban) maybeInvalidateBanCacheAfterWrite(store, 'device') return ban } if (identity.deviceId) { const ban = store?.block?.({ ...evidence, deviceId: identity.deviceId }) || null - if (ban) invalidateRiskBanCache({ kind: 'device', db: store.db || null }) + if (ban) maybeInvalidateBanCacheAfterWrite(store, 'device') return ban } } catch { @@ -680,7 +745,7 @@ export function recordUpstream400SessionBlock({ ttlMs: UPSTREAM_400_SESSION_BLOCK_MS, now, }) || null - if (ban) invalidateRiskBanCache({ kind: 'device', db: devices?.db || null }) + if (ban) maybeInvalidateBanCacheAfterWrite(devices, 'device') if (ban && ban.expires_at) { mergeLogErrorDetails(logBag, { upstream_400_category: verdict.category, @@ -904,7 +969,8 @@ export function commitProtocolBlock(decision, { repo, devices, sessions, policy, if (!decision || decision.action !== 'block') return if (decision.kind === 'session') { try { - sessions?.hit?.(decision.sessionId) + if (typeof sessions?.recordHit === 'function') sessions.recordHit(decision.sessionId) + else sessions?.hit?.(decision.sessionId) } catch { /* counter is best-effort */ } @@ -912,7 +978,8 @@ export function commitProtocolBlock(decision, { repo, devices, sessions, policy, } if (decision.kind === 'device') { try { - devices?.hit?.(decision.deviceId) + if (typeof devices?.recordHit === 'function') devices.recordHit(decision.deviceId) + else devices?.hit?.(decision.deviceId) } catch { console.warn('[risk-audit] failed to record ban hit') } @@ -920,7 +987,8 @@ export function commitProtocolBlock(decision, { repo, devices, sessions, policy, } if ((decision.kind === 'exact' || decision.kind === 'similar') && decision.fingerprint) { try { - repo?.hit?.(decision.fingerprint) + if (typeof repo?.recordHit === 'function') repo.recordHit(decision.fingerprint) + else repo?.hit?.(decision.fingerprint) } catch { console.warn('[risk-audit] failed to record refusal cache hit') } @@ -937,7 +1005,7 @@ export function commitProtocolBlock(decision, { repo, devices, sessions, policy, ttlMs: Number(decision.sessionBlockMs), now, }) || null - if (ban) invalidateRiskBanCache({ kind: 'device', db: devices?.db || null }) + if (ban) maybeInvalidateBanCacheAfterWrite(devices, 'device') } catch { console.warn('[risk-audit] failed to persist session block') } diff --git a/test/unit/cache-layer.test.mjs b/test/unit/cache-layer.test.mjs index c8368cf60d..568a3cdd05 100644 --- a/test/unit/cache-layer.test.mjs +++ b/test/unit/cache-layer.test.mjs @@ -23,7 +23,7 @@ import { import { SCHED_REV_KEY, SCHED_SNAPSHOT_KEY, SchedulerSnapshotCache } from '../../src/lib/cache/scheduler-cache.mjs' import { createDatabase } from '../../src/lib/db/database.mjs' import { RefusalGuardsRepo } from '../../src/lib/db/repos/refusal-guards-repo.mjs' -import { isRoutineApiKeyUsageUpdate } from '../../src/lib/db/pg/pg-sync-db.mjs' +import { isRoutineApiKeyUsageUpdate, isRoutineRefusalHitUpdate } from '../../src/lib/db/pg/pg-sync-db.mjs' /** * Deterministic in-memory mock Redis supporting pipelines, MULTI/EXEC, TTL/PTTL, @@ -983,11 +983,61 @@ test('isRoutineApiKeyUsageUpdate and onDbTablesMutated prevent L1 invalidation s // Risk ban tables invalidate risk:bans:session: and risk:bans:device: caches await rt.client.set('risk:bans:session:s1', { blocked: true }, { ttlMs: 15_000 }) await rt.client.set('risk:bans:device:d1', { blocked: true }, { ttlMs: 15_000 }) + await rt.client.set('risk:guards:g1', { blocked: true }, { ttlMs: 15_000 }) + + // Routine hit_count updates emit `
:hit` and MUST NOT nuke risk:bans:* or risk:guards:* + assert.equal( + isRoutineRefusalHitUpdate( + 'UPDATE refusal_device_blocks SET hit_count = hit_count + 1, last_seen_at = ? WHERE device_id = ?', + ), + true, + ) + assert.equal( + isRoutineRefusalHitUpdate( + 'UPDATE refusal_session_blocks SET hit_count = hit_count + 1, last_seen_at = ? WHERE session_id = ?', + ), + true, + ) + assert.equal( + isRoutineRefusalHitUpdate( + 'UPDATE refusal_guards SET hit_count = hit_count + 1, last_seen_at = ? WHERE fingerprint = ?', + ), + true, + ) + assert.equal( + isRoutineRefusalHitUpdate( + 'UPDATE refusal_device_blocks SET expires_at = NULL, last_seen_at = ? WHERE device_id = ?', + ), + false, + ) + assert.equal(isRoutineRefusalHitUpdate('DELETE FROM refusal_device_blocks WHERE device_id = ?'), false) + assert.equal( + isRoutineRefusalHitUpdate( + 'UPDATE refusal_device_blocks SET hit_count = hit_count + 1 WHERE device_id = ?; DELETE FROM refusal_device_blocks', + ), + false, + ) + + notifyDbTablesMutated(['refusal_device_blocks:hit', 'refusal_session_blocks:hit', 'refusal_guards:hit']) + assert.equal( + (await rt.client.get('risk:bans:session:s1')).hit, + true, + 'session hit_count must not nuke risk:bans:session:', + ) + assert.equal( + (await rt.client.get('risk:bans:device:d1')).hit, + true, + 'device hit_count must not nuke risk:bans:device:', + ) + assert.equal((await rt.client.get('risk:guards:g1')).hit, true, 'guard hit_count must not nuke risk:guards:') + notifyDbTablesMutated(['refusal_session_blocks']) assert.equal((await rt.client.get('risk:bans:session:s1')).hit, false) assert.equal((await rt.client.get('risk:bans:device:d1')).hit, true) notifyDbTablesMutated(['refusal_device_blocks']) assert.equal((await rt.client.get('risk:bans:device:d1')).hit, false) + notifyDbTablesMutated(['refusal_guards']) + assert.equal((await rt.client.get('risk:guards:g1')).hit, false) } finally { await closeCacheRuntime() } diff --git a/test/unit/pg-sync-db-rpc.test.mjs b/test/unit/pg-sync-db-rpc.test.mjs index be720a4a1c..325e780cef 100644 --- a/test/unit/pg-sync-db-rpc.test.mjs +++ b/test/unit/pg-sync-db-rpc.test.mjs @@ -184,4 +184,54 @@ describe('PgSyncDb synchronous RPC framing & correlation', () => { db.close() } }) + + it('classifies refusal hit_count updates as
:hit without triggering broad table invalidation', async () => { + const { worker, port } = await spawnMockSyncWorker(`async (msg, reply) => { + if (msg.op === 'run') { + reply(msg.sab, { id: msg.id, ok: true, result: { changes: 1, lastInsertRowid: 0 } }) + return + } + if (msg.op === 'begin') { + reply(msg.sab, { id: msg.id, ok: true, result: { inTransaction: true } }) + return + } + if (msg.op === 'commit') { + reply(msg.sab, { id: msg.id, ok: true, result: { inTransaction: false } }) + return + } + reply(msg.sab, { id: msg.id, ok: true, result: null }) + }`) + const emitted = [] + const db = new PgSyncDb({ + worker, + port, + ownsWorker: true, + rpcTimeoutMs: 2_000, + onMutation: (tables) => emitted.push(tables), + }) + try { + db.prepare( + 'UPDATE refusal_device_blocks SET hit_count = hit_count + 1, last_seen_at = ? WHERE device_id = ?', + ).run('2026-12-01T00:00:00.000Z', 'dev-1') + db.prepare( + 'UPDATE refusal_session_blocks SET hit_count = hit_count + 1, last_seen_at = ? WHERE session_id = ?', + ).run('2026-12-01T00:00:00.000Z', 'sess-1') + db.prepare('UPDATE refusal_guards SET hit_count = hit_count + 1, last_seen_at = ? WHERE fingerprint = ?').run( + '2026-12-01T00:00:00.000Z', + 'fp-1', + ) + db.prepare('DELETE FROM refusal_device_blocks WHERE device_id = ?').run('dev-1') + db.prepare('INSERT INTO refusal_guards (fingerprint) VALUES (?)').run('fp-2') + + assert.deepEqual(emitted, [ + ['refusal_device_blocks:hit'], + ['refusal_session_blocks:hit'], + ['refusal_guards:hit'], + ['refusal_device_blocks'], + ['refusal_guards'], + ]) + } finally { + db.close() + } + }) }) diff --git a/test/unit/refusal-guard.test.mjs b/test/unit/refusal-guard.test.mjs index c54d86bf89..fe5077665b 100644 --- a/test/unit/refusal-guard.test.mjs +++ b/test/unit/refusal-guard.test.mjs @@ -3,10 +3,18 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import { createDatabase } from '../../src/lib/db/database.mjs' +import { closeDatabase, createDatabase, openDatabase } from '../../src/lib/db/database.mjs' +import { closeCacheRuntime, getCacheRuntime, initCacheRuntime } from '../../src/lib/cache/index.mjs' import { RefusalGuardsRepo } from '../../src/lib/db/repos/refusal-guards-repo.mjs' import { RefusalDeviceBlocksRepo } from '../../src/lib/db/repos/refusal-device-blocks-repo.mjs' -import { observeUpstreamRisk, runProtocolIntercept, systemRewrite } from '../../src/lib/protocol/intercept-gate.mjs' +import { RefusalSessionBlocksRepo } from '../../src/lib/db/repos/refusal-session-blocks-repo.mjs' +import { + deviceBanCacheKey, + evaluateProtocolIntercept, + observeUpstreamRisk, + runProtocolIntercept, + systemRewrite, +} from '../../src/lib/protocol/intercept-gate.mjs' import { REFUSAL_GUARD_MESSAGE, REFUSAL_GUARD_SETTING, @@ -28,6 +36,7 @@ import { } from '../../src/lib/core/refusal-guard.mjs' import { REFUSAL_SIMILARITY, + encodeSignature, refusalSignature, refusalUserDocument, signatureSimilarity, @@ -106,7 +115,8 @@ test('a conflicting device and machine pair does not merge independent strike hi assert.equal(secondDevice.violations, 2) assert.equal(devices.get(machineBan.device_id).violations, secondMachine.violations) assert.equal(devices.findBan(machine, start + 180_000), null) - assert.equal(devices.count(), 2) + assert.equal(devices.count(new Date(start + 180_000).toISOString()), 1) + assert.equal(db.prepare('SELECT COUNT(*) AS n FROM refusal_device_blocks').get().n, 2) } finally { db.close() } @@ -321,7 +331,7 @@ test('post-hop warms the right front rule and blocks the session for 10m on upst assert.equal(opts.logBag.audit_upstream_400_message, 'API Error: invalid tokens. Bearer ***REDACTED***') assert.equal(opts.logBag.error_details.punishment, 'session_10m_400') assert.equal(repo.count(), 0) - assert.equal(devices.count(), 1) + assert.equal(devices.count(new Date(start).toISOString()), 1) assert.equal(devices.findBan(deviceOnly, start), null) const protocol400Ban = devices.findBan(identity, start) assert.equal(protocol400Ban.subject_kind, 'session') @@ -1192,3 +1202,261 @@ test('turning similarity or device block off skips that check', () => { fs.rmSync(dir, { recursive: true, force: true }) } }) + +test('deviceBanCacheKey includes machineId, coalesces misses via singleflight, and isolates negative cache from shared L1', async () => { + const db = createDatabase({ dbPath: ':memory:' }) + await closeCacheRuntime() + const rt = await initCacheRuntime({ + redisConfig: null, + cacheConfig: { disabled: false, l1MaxItems: 64, defaultTtlMs: 30_000 }, + }) + try { + const policy = { enabled: true, device_block_enabled: true, session_block_enabled: true } + const kA = deviceBanCacheKey(db, { principal: 'user:p1', machineId: 'mach-A' }, policy) + const kB = deviceBanCacheKey(db, { principal: 'user:p1', machineId: 'mach-B' }, policy) + assert.notEqual(kA, kB, 'deviceBanCacheKey must differentiate distinct machineId values') + + const devices = new RefusalDeviceBlocksRepo(db) + const sessions = new RefusalSessionBlocksRepo(db) + const now = Date.now() + devices.recordViolation({ principal: 'user:p1', machineId: 'mach-A' }, { steps: [10, 20, 0], now }) + + // Machine A is blocked while Machine B under the same principal still passes (no cache key collision) + const resA = await evaluateProtocolIntercept({ + inbound: body('hello'), + identity: { principal: 'user:p1', machineId: 'mach-A' }, + policy, + devices, + sessions, + mandatoryOnly: true, + now, + }) + const resB = await evaluateProtocolIntercept({ + inbound: body('hello'), + identity: { principal: 'user:p1', machineId: 'mach-B' }, + policy, + devices, + sessions, + mandatoryOnly: true, + now, + }) + assert.equal(resA.action, 'block') + assert.equal(resB.action, 'pass') + + // Singleflight coalescing: 8 concurrent misses for the same clean identity trigger only 1 findBan/get call + let devCalls = 0 + let sessCalls = 0 + const origFind = devices.findBan.bind(devices) + const origSessGet = sessions.get.bind(sessions) + devices.findBan = (...args) => { + devCalls += 1 + return origFind(...args) + } + sessions.get = (...args) => { + sessCalls += 1 + return origSessGet(...args) + } + const sfBatch = await Promise.all( + Array.from({ length: 8 }, () => + evaluateProtocolIntercept({ + inbound: body('concurrent'), + headers: { 'x-claude-code-session-id': 'sf-session-0001' }, + identity: { principal: 'user:sf', machineId: 'mach-sf-1', sessionId: 'sf-session-0001' }, + policy, + devices, + sessions, + mandatoryOnly: true, + now, + }), + ), + ) + assert.ok(sfBatch.every((d) => d.action === 'pass')) + assert.equal(devCalls, 1, 'concurrent device ban misses must coalesce via singleflight') + assert.equal(sessCalls, 1, 'concurrent session ban misses must coalesce via singleflight') + + // Negative cache must NOT evict hot apikey:/entity: entries from shared L1 (l1MaxItems = 64) + for (let i = 0; i < 40; i += 1) { + rt.client.setL1(`apikey:hot:${i}`, { id: `k-${i}` }, 60_000) + } + const evictionsBefore = rt.client.l1.evictions + for (let i = 0; i < 120; i += 1) { + const r = await evaluateProtocolIntercept({ + inbound: body('clean traffic'), + headers: { 'x-claude-code-session-id': `clean-sess-${String(i).padStart(4, '0')}` }, + identity: { principal: 'user:clean', deviceId: `clean-dev-${i}` }, + policy, + devices, + sessions, + mandatoryOnly: true, + now, + }) + assert.equal(r.action, 'pass') + } + assert.equal(rt.client.l1.evictions, evictionsBefore, 'negative ban lookups must not evict shared L1 entries') + for (let i = 0; i < 40; i += 1) { + assert.equal(rt.client.getL1(`apikey:hot:${i}`).hit, true) + } + } finally { + await closeCacheRuntime() + db.close() + } +}) + +test('list and count filter expired rows in SQL and pruneExpired performs bounded batch GC for devices and guards', async () => { + const db = createDatabase({ dbPath: ':memory:' }) + try { + const devices = new RefusalDeviceBlocksRepo(db) + const guards = new RefusalGuardsRepo(db) + const baseMs = Date.parse('2026-12-01T12:00:00.000Z') + const nowIso = new Date(baseMs).toISOString() + + // Insert 3 active/permanent device bans (older last_seen_at) + 10 expired bans (newer last_seen_at) + const olderAt = new Date(baseMs - 60_000).toISOString() + const newerAt = new Date(baseMs - 1_000).toISOString() + const futureExp = new Date(baseMs + 600_000).toISOString() + const insDev = db.prepare(` + INSERT INTO refusal_device_blocks ( + device_id, first_seen_at, last_seen_at, hit_count, reason, subject_kind, identity_value, violations, expires_at + ) VALUES (?, ?, ?, 0, 'test', 'device', ?, 1, ?) + `) + insDev.run('active-perm', olderAt, olderAt, 'active-perm', null) + insDev.run('active-temp-1', olderAt, olderAt, 'active-temp-1', futureExp) + insDev.run('active-temp-2', olderAt, olderAt, 'active-temp-2', futureExp) + for (let i = 0; i < 10; i += 1) { + const expIso = new Date(baseMs - (10 - i) * 1_000).toISOString() + insDev.run(`expired-dev-${i}`, newerAt, newerAt, `expired-dev-${i}`, expIso) + } + + assert.equal(devices.count(nowIso), 3, 'count() must exclude expired device/session bans in SQL') + const activeDevs = devices.list(3, nowIso) + assert.equal(activeDevs.length, 3, 'list(limit) must not be crowded out by newer expired rows') + assert.ok(activeDevs.every((r) => r.device_id.startsWith('active-'))) + + // Bounded pruneExpired deletes in batches of 4 and never removes active/permanent rows + assert.equal(await devices.pruneExpired(nowIso, 4), 4) + assert.equal(await devices.pruneExpired(nowIso, 4), 4) + assert.equal(await devices.pruneExpired(nowIso, 4), 2) + assert.equal(await devices.pruneExpired(nowIso, 4), 0) + assert.equal(db.prepare('SELECT COUNT(*) AS n FROM refusal_device_blocks').get().n, 3) + + // Same verification for RefusalGuardsRepo (fixes LIMIT-before-JS-filter bug) + const insGuard = db.prepare(` + INSERT INTO refusal_guards ( + fingerprint, model, first_seen_at, last_seen_at, hit_count, error_message, preview, expires_at + ) VALUES (?, 'claude-opus-5', ?, ?, 0, 'refused', 'p', ?) + `) + insGuard.run('guard-perm', olderAt, olderAt, null) + insGuard.run('guard-active-1', olderAt, olderAt, futureExp) + insGuard.run('guard-active-2', olderAt, olderAt, futureExp) + for (let i = 0; i < 10; i += 1) { + const expIso = new Date(baseMs - (10 - i) * 1_000).toISOString() + insGuard.run(`guard-exp-${i}`, newerAt, newerAt, expIso) + } + + assert.equal(guards.count(nowIso), 3) + const activeGuards = guards.list(3, nowIso) + assert.equal(activeGuards.length, 3, 'guards.list(limit) must filter expired rows before LIMIT') + assert.ok( + activeGuards.every((r) => r.fingerprint.startsWith('guard-perm') || r.fingerprint.startsWith('guard-active')), + ) + + assert.equal(await guards.pruneExpired(nowIso, 4), 4) + assert.equal(await guards.pruneExpired(nowIso, 4), 4) + assert.equal(await guards.pruneExpired(nowIso, 4), 2) + assert.equal(await guards.pruneExpired(nowIso, 4), 0) + assert.equal(db.prepare('SELECT COUNT(*) AS n FROM refusal_guards').get().n, 3) + + // Verify async pgPool path on pruneExpired + const pgQueries = [] + const pgDb = new Proxy(db, { + get(target, prop) { + if (prop === 'pgPool') { + return { + async query(sql, params) { + pgQueries.push({ sql, params }) + return { rowCount: 7 } + }, + } + } + const v = Reflect.get(target, prop) + return typeof v === 'function' ? v.bind(target) : v + }, + }) + assert.equal(await new RefusalDeviceBlocksRepo(pgDb).pruneExpired(nowIso, 250), 7) + assert.equal(await new RefusalGuardsRepo(pgDb).pruneExpired(nowIso, 250), 7) + assert.equal(pgQueries.length, 2) + assert.match(pgQueries[0].sql, /DELETE FROM refusal_device_blocks/) + assert.match(pgQueries[1].sql, /DELETE FROM refusal_guards/) + } finally { + db.close() + } +}) + +test('RefusalGuardsRepo.remember() incrementally updates warm snapshot without double full-table rescan while still broadcasting to peers', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-guards-remember-')) + closeDatabase() + await closeCacheRuntime() + const db = openDatabase({ dbPath: path.join(dir, 'app.db') }) + const rt = await initCacheRuntime({ redisConfig: null }) + try { + const guards = new RefusalGuardsRepo(db) + let allActiveScans = 0 + const origAll = guards._allActive.all.bind(guards._allActive) + guards._allActive.all = (...args) => { + allActiveScans += 1 + return origAll(...args) + } + + // Track invalidation broadcasts observed on client + const broadcasts = [] + const unsub = rt.client.onInvalidate((payload) => broadcasts.push(payload)) + + // Warm snapshot once (scan #1) + assert.equal(guards.get('non-existent'), null) + assert.equal(allActiveScans, 1) + + const longText = + 'deterministic long prompt text for testing incremental snapshot updates in refusal guards repo without rescans '.repeat( + 6, + ) + const sig = refusalSignature(longText) + assert.ok(sig) + + // remember() must update warm snapshot incrementally (0 rescans) and return record directly + const remembered = guards.remember({ + fingerprint: 'fp-inc-1', + model: 'claude-sonnet-4-6', + requestId: 'req-inc-1', + errorMessage: 'Usage Policy', + preview: 'deterministic long prompt', + signature: encodeSignature(sig), + }) + assert.equal(remembered.fingerprint, 'fp-inc-1') + assert.equal(remembered.hit_count, 0) + assert.equal(allActiveScans, 1, 'remember() must not trigger a full-table rescan') + + // Wait for async client.invalidate() callback to fire + await new Promise((r) => setTimeout(r, 20)) + assert.ok( + broadcasts.some((b) => Array.isArray(b.prefixes) && b.prefixes.includes('risk:guards:')), + 'remember() must still broadcast risk:guards: invalidation to peer instances', + ) + + // Local snapshot must STILL be warm (not wiped by self-originated broadcast) -> 0 rescans! + assert.equal(guards.get('fp-inc-1')?.fingerprint, 'fp-inc-1') + assert.equal(guards.nearest(sig, 0.85)?.fingerprint, 'fp-inc-1') + assert.equal(allActiveScans, 1, 'self-originated remember() broadcast must not trigger a second full-table rescan') + + // Remote peer invalidation MUST still clear the local snapshot and trigger reload on next read + rt.client._handleRemoteInvalidation( + JSON.stringify({ origin: 'remote-peer-node', prefixes: ['risk:guards:'], keys: [] }), + ) + assert.equal(guards.get('fp-inc-1')?.fingerprint, 'fp-inc-1') + assert.equal(allActiveScans, 2, 'remote peer invalidation must reload snapshot cleanly') + unsub() + } finally { + await closeCacheRuntime() + closeDatabase() + fs.rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/test/unit/refusal-session-block.test.mjs b/test/unit/refusal-session-block.test.mjs index 0fefe3bf21..169b800e1b 100644 --- a/test/unit/refusal-session-block.test.mjs +++ b/test/unit/refusal-session-block.test.mjs @@ -8,6 +8,7 @@ import { closeDatabase, createDatabase, openDatabase } from '../../src/lib/db/da import { closeCacheRuntime, initCacheRuntime } from '../../src/lib/cache/index.mjs' import { createPanelHandler } from '../../src/lib/admin/panel-routes.mjs' import { RefusalDeviceBlocksRepo } from '../../src/lib/db/repos/refusal-device-blocks-repo.mjs' +import { RefusalGuardsRepo } from '../../src/lib/db/repos/refusal-guards-repo.mjs' import { RefusalSessionBlocksRepo } from '../../src/lib/db/repos/refusal-session-blocks-repo.mjs' import { sanitizeErrorDetailsForLog } from '../../src/lib/core/errors.mjs' import { @@ -1469,3 +1470,114 @@ test('DELETE /api/panel/refusal-session-blocks unbans both tables + clears cache fs.rmSync(dir, { recursive: true, force: true }) } }) + +test('blockSession SQL atomically protects permanent bans, recordViolation avoids 23503 alias FK crash, and recordHit uses lightweight/async path', async () => { + await withDb(async (db) => { + const devices = new RefusalDeviceBlocksRepo(db) + const sessions = new RefusalSessionBlocksRepo(db) + const guards = new RefusalGuardsRepo(db) + const start = Date.parse('2026-12-01T10:00:00.000Z') + const permId = { principal: 'user:perm-sql', deviceId: 'dev-perm-sql', sessionId: 'sess-perm-sql' } + + // 1. Permanent session ban created by recordViolation must never be downgraded by blockSession + devices.recordViolation(permId, { + requestId: 'req-perm-1', + reason: 'jev:usage_policy', + steps: [10, 60, 0], + now: start, + }) + const permBefore = devices.findBan(permId, start) + assert.equal(permBefore.subject_kind, 'session') + assert.equal(permBefore.expires_at, null) + + const afterTemp = devices.blockSession(permId, { + requestId: 'req-temp-400', + reason: 'upstream_400:unknown', + ttlMs: 10 * 60_000, + now: start + 5_000, + }) + assert.equal(afterTemp.expires_at, null) + assert.equal(afterTemp.reason, 'jev:usage_policy') + assert.equal(afterTemp.source_request_id, 'req-perm-1') + assert.equal(afterTemp.last_seen_at, permBefore.last_seen_at) + + // 2. Concurrent admin remove(deviceKey) before alias insert must NOT fail with FK error (23503) + const raceId = { principal: 'user:fk', deviceId: 'dev-fk-1', machineId: 'mach-fk-1', sessionId: 'sess-fk-1' } + const created = devices.recordViolation( + { principal: 'user:fk', deviceId: 'dev-fk-1' }, + { steps: [10, 60, 0], now: start }, + ) + // Simulate concurrent admin remove right before _bindAlias runs inside recordViolation + const origBindRun = devices._bindAlias.run.bind(devices._bindAlias) + let bindCalls = 0 + devices._bindAlias.run = (...args) => { + bindCalls += 1 + db.prepare('DELETE FROM refusal_device_blocks WHERE device_id = ?').run(created.device_id) + return origBindRun(...args) + } + try { + const res = devices.recordViolation(raceId, { steps: [10, 60, 0], now: start + 1_000 }) + assert.ok(res) + assert.equal(bindCalls, 1) + // Session ban still committed cleanly despite parent device row being concurrently removed + assert.ok(devices.findBan({ principal: 'user:fk', sessionId: 'sess-fk-1' }, start + 1_000)) + } finally { + devices._bindAlias.run = origBindRun + } + + // 3. Lightweight SQLite recordHit executes UPDATE without trailing get() + sessions.block({ sessionId: SESSION }) + guards.remember({ fingerprint: 'fp-hit-test', model: 'claude-opus-5', preview: 'hit' }) + let devGetCalls = 0 + let sessGetCalls = 0 + let guardGetCalls = 0 + const origDevGet = devices.get.bind(devices) + const origSessGet = sessions.get.bind(sessions) + const origGuardGet = guards.get.bind(guards) + devices.get = (...a) => { + devGetCalls += 1 + return origDevGet(...a) + } + sessions.get = (...a) => { + sessGetCalls += 1 + return origSessGet(...a) + } + guards.get = (...a) => { + guardGetCalls += 1 + return origGuardGet(...a) + } + commitProtocolBlock({ action: 'block', kind: 'device', deviceId: permBefore.device_id }, { devices }) + commitProtocolBlock({ action: 'block', kind: 'session', sessionId: SESSION }, { sessions }) + commitProtocolBlock({ action: 'block', kind: 'exact', fingerprint: 'fp-hit-test' }, { repo: guards }) + assert.equal(devGetCalls, 0, 'commitProtocolBlock device recordHit must not run trailing get()') + assert.equal(sessGetCalls, 0, 'commitProtocolBlock session recordHit must not run trailing get()') + assert.equal(guardGetCalls, 0, 'commitProtocolBlock guard recordHit must not run trailing get()') + assert.equal(origDevGet(permBefore.device_id).hit_count, 1) + assert.equal(origSessGet(SESSION).hit_count, 1) + assert.equal(origGuardGet('fp-hit-test').hit_count, 1) + + // 4. Async pgPool recordHit offloads hit_count updates off the sync path + const asyncHits = [] + const pgDb = new Proxy(db, { + get(target, prop) { + if (prop === 'pgPool') { + return { + async query(sql, params) { + asyncHits.push({ sql, params }) + return { rowCount: 1 } + }, + } + } + const v = Reflect.get(target, prop) + return typeof v === 'function' ? v.bind(target) : v + }, + }) + new RefusalDeviceBlocksRepo(pgDb).recordHit('dev-async-1') + new RefusalSessionBlocksRepo(pgDb).recordHit('sess-async-1') + new RefusalGuardsRepo(pgDb).recordHit('fp-async-1') + assert.equal(asyncHits.length, 3) + assert.match(asyncHits[0].sql, /UPDATE refusal_device_blocks SET hit_count = hit_count \+ 1/) + assert.match(asyncHits[1].sql, /UPDATE refusal_session_blocks SET hit_count = hit_count \+ 1/) + assert.match(asyncHits[2].sql, /UPDATE refusal_guards SET hit_count = hit_count \+ 1/) + }) +}) From 00d1cbc6826b9cd1d660af20021b7d1266df4834 Mon Sep 17 00:00:00 2001 From: dofastted Date: Tue, 1 Dec 2026 20:10:37 +0800 Subject: [PATCH 11/15] perf(risk,jev): async batch JevUsageRepo, unify channel EntityCache settings, bound verdictCache & sync Redis/DB SSOT --- src/lib/core/distill-detect.mjs | 179 +++++++- src/lib/db/repos/jev-usage-repo.mjs | 406 +++++++++++++++++-- src/lib/gemini/routes.mjs | 4 +- src/lib/protocol/handle-codex.mjs | 4 +- src/lib/protocol/handle-protocol.mjs | 121 +----- src/lib/protocol/jev-intercept.mjs | 298 ++++++++++++-- src/lib/protocol/responses-ws.mjs | 4 +- src/lib/protocol/unified-pre-dispatch.mjs | 228 ++++++++++- src/lib/protocol/user-count-tokens.mjs | 103 ++--- test/unit/distill-detect.test.mjs | 57 +++ test/unit/jev-intercept.test.mjs | 224 ++++++++++ test/unit/jev-usage.test.mjs | 201 +++++++++ test/unit/scheduler-m1a-jev-unified.test.mjs | 66 +++ 13 files changed, 1618 insertions(+), 277 deletions(-) diff --git a/src/lib/core/distill-detect.mjs b/src/lib/core/distill-detect.mjs index 6bed8faec7..fb424ffee5 100644 --- a/src/lib/core/distill-detect.mjs +++ b/src/lib/core/distill-detect.mjs @@ -7,10 +7,17 @@ import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' +import { getCacheRuntime } from '../cache/index.mjs' +import { DB_INSTANCE_ID, getDb, getPgPool, isDbOpen } from '../db/database.mjs' +import { SettingsRepo } from '../db/repos/settings-repo.mjs' import { detectInboundPlatform } from '../protocol/platform-detect.mjs' import { atomicWriteJson } from '../vm/vm-file.mjs' import { ErrorType, ErrorCode, POLICY_BLOCK_STATUS, makeDistillBlockError } from './errors.mjs' +export const DISTILL_RULES_SETTING = 'distill_rules' +const DISTILL_SETTING_MISSING = Symbol('vm2api.distill_setting_missing') +const cachedDistillSettingsRepos = new WeakMap() + const HIGH_EFFORT = new Set(['high', 'xhigh', 'max']) /** Transport wrapper used by normal agent sessions. Not a harvest needle. */ @@ -417,18 +424,7 @@ export function validateDistillPatch(body = {}) { return [...typeProblems(body), ...sizeProblems(body), ...errorProblems(body.error), ...structureProblems(body)] } -export function loadDistillRules(file) { - try { - if (!file || !fs.existsSync(file)) return normalizeDistillRules(DEFAULT_DISTILL_RULES) - const data = JSON.parse(fs.readFileSync(file, 'utf8')) - return normalizeDistillRules(data) - } catch { - return normalizeDistillRules(DEFAULT_DISTILL_RULES) - } -} - -export function saveDistillRules(file, patch) { - const cur = loadDistillRules(file) +function mergeDistillRules(cur, patch) { const src = patch && typeof patch === 'object' ? patch : {} const merged = { ...cur, @@ -450,11 +446,168 @@ export function saveDistillRules(file, patch) { ) merged.hard_needles = (cur.hard_needles || []).filter((item) => submitted.has(String(item).trim().toLowerCase())) } - const next = normalizeDistillRules(merged) + return normalizeDistillRules(merged) +} + +function resolveDistillSettingsTarget(db = null) { + if (db && typeof db.get === 'function' && typeof db.prepare !== 'function') { + return { targetDb: db.db || null, repo: db, isDirectRepo: true } + } + const targetDb = db || (isDbOpen() ? getDb() : null) + if (!targetDb) return { targetDb: null, repo: null, isDirectRepo: false } + let repo = cachedDistillSettingsRepos.get(targetDb) + if (!repo) { + repo = new SettingsRepo(targetDb) + cachedDistillSettingsRepos.set(targetDb, repo) + } + return { targetDb, repo, isDirectRepo: false } +} + +function resolveDistillEntityCache(cache = null) { + if (cache) { + if (cache.entity && typeof cache.entity.getSetting === 'function') { + return { entity: cache.entity, enabled: cache.client?.enabled !== false } + } + if (typeof cache.getSetting === 'function') { + return { entity: cache, enabled: cache.cache?.enabled !== false } + } + return null + } + try { + const rt = getCacheRuntime() + if (!rt?.entity) return null + return { entity: rt.entity, enabled: rt.client?.enabled !== false } + } catch { + return null + } +} + +function distillSettingCacheKey(targetDb) { + if (!targetDb || targetDb.engine === 'postgres') return DISTILL_RULES_SETTING + return `${targetDb?.[DB_INSTANCE_ID] || 'sqlite'}:${DISTILL_RULES_SETTING}` +} + +async function readDistillSettingFromDbAsync(targetDb, repo) { + const pool = targetDb?.pgPool || (targetDb?.engine === 'postgres' ? getPgPool() : null) + if (pool && typeof pool.query === 'function') { + try { + const res = await pool.query('SELECT value FROM settings WHERE key = $1', [DISTILL_RULES_SETTING]) + const row = res?.rows?.[0] + if (!row) return { __missing: true } + try { + return { value: JSON.parse(row.value) } + } catch { + return { __missing: true } + } + } catch { + // Fall back to sync SettingsRepo + } + } + const val = repo.get(DISTILL_RULES_SETTING, DISTILL_SETTING_MISSING) + return val === DISTILL_SETTING_MISSING ? { __missing: true } : { value: val } +} + +export function loadDistillRules(file) { + try { + if (!file || !fs.existsSync(file)) return normalizeDistillRules(DEFAULT_DISTILL_RULES) + const data = JSON.parse(fs.readFileSync(file, 'utf8')) + return normalizeDistillRules(data) + } catch { + return normalizeDistillRules(DEFAULT_DISTILL_RULES) + } +} + +export function saveDistillRules(file, patch) { + const cur = loadDistillRules(file) + const next = mergeDistillRules(cur, patch) atomicWriteJson(file, next) return next } +/** + * Multi-instance SSOT loader: prefers DB `settings` (`distill_rules`) via + * EntityCache (L1 + Redis L2 + singleflight), falling back to local + * `config/distill-rules.json` / `DEFAULT_DISTILL_RULES` when DB is unavailable + * or has no stored `distill_rules` row yet. + */ +export async function loadDistillRulesFromSettings(db = null, cache = null, { file = DEFAULT_FILE } = {}) { + try { + const { targetDb, repo, isDirectRepo } = resolveDistillSettingsTarget(db) + if (repo) { + let wrapped + const ec = isDirectRepo && !cache ? null : resolveDistillEntityCache(cache) + if (ec && ec.enabled && typeof ec.entity.getSetting === 'function') { + wrapped = await ec.entity.getSetting(distillSettingCacheKey(targetDb), () => + readDistillSettingFromDbAsync(targetDb, repo), + ) + } else { + wrapped = await readDistillSettingFromDbAsync(targetDb, repo) + } + if (wrapped && !wrapped.__missing && wrapped.value && typeof wrapped.value === 'object') { + return normalizeDistillRules(wrapped.value) + } + } + } catch { + // Fall back to local file/defaults when DB or cache is unavailable + } + return loadDistillRules(file) +} + +/** Sync L1-first variant for synchronous callers (falls back to local file/defaults). */ +export function loadDistillRulesFromSettingsSync(db = null, cache = null, { file = DEFAULT_FILE } = {}) { + try { + const { targetDb, repo, isDirectRepo } = resolveDistillSettingsTarget(db) + if (repo) { + let wrapped + const ec = isDirectRepo && !cache ? null : resolveDistillEntityCache(cache) + if (ec && ec.enabled && typeof ec.entity.getSettingSync === 'function') { + wrapped = ec.entity.getSettingSync(distillSettingCacheKey(targetDb), () => { + const val = repo.get(DISTILL_RULES_SETTING, DISTILL_SETTING_MISSING) + return val === DISTILL_SETTING_MISSING ? { __missing: true } : { value: val } + }) + } else { + const val = repo.get(DISTILL_RULES_SETTING, DISTILL_SETTING_MISSING) + wrapped = val === DISTILL_SETTING_MISSING ? { __missing: true } : { value: val } + } + if (wrapped && !wrapped.__missing && wrapped.value && typeof wrapped.value === 'object') { + return normalizeDistillRules(wrapped.value) + } + } + } catch { + // Fall back to local file/defaults + } + return loadDistillRules(file) +} + +/** + * Multi-instance SSOT writer: persists normalized `distill_rules` to DB + * `settings`, invalidates EntityCache across instances, and keeps local + * `config/distill-rules.json` compatibly synced (best-effort on read-only FS). + */ +export async function saveDistillRulesToSettings(db = null, rules = {}, cache = null, { file = DEFAULT_FILE } = {}) { + const cur = await loadDistillRulesFromSettings(db, cache, { file }) + const next = mergeDistillRules(cur, rules) + const { targetDb, repo } = resolveDistillSettingsTarget(db) + if (repo && typeof repo.set === 'function') { + repo.set(DISTILL_RULES_SETTING, next) + const ec = resolveDistillEntityCache(cache) + if (ec && typeof ec.entity.invalidateSetting === 'function') { + try { + await ec.entity.invalidateSetting(distillSettingCacheKey(targetDb)) + } catch {} + } + } + if (file) { + try { + atomicWriteJson(file, next) + } catch { + // Tolerate read-only containers when DB settings is the SSOT + if (!repo) throw new Error(`Failed to persist distill rules to ${file}`) + } + } + return next +} + export function distillBlockError(rules, requestId) { const r = normalizeDistillRules(rules) return makeDistillBlockError({ diff --git a/src/lib/db/repos/jev-usage-repo.mjs b/src/lib/db/repos/jev-usage-repo.mjs index a1ba4cf893..7a45668f4e 100644 --- a/src/lib/db/repos/jev-usage-repo.mjs +++ b/src/lib/db/repos/jev-usage-repo.mjs @@ -1,4 +1,4 @@ -import { getDb, withTransaction } from '../database.mjs' +import { getDb, getPgPool, withTransaction } from '../database.mjs' import { shanghaiUsageDay } from '../../protocol/jev-usage.mjs' const FIELDS = [ @@ -18,6 +18,23 @@ const FIELDS = [ 'output_nano_usd_per_token', 'pricing_basis', ] +const FIELD_TYPES = [ + 'text', + 'text', + 'text', + 'text', + 'text', + 'text', + 'integer', + 'text', + 'bigint', + 'bigint', + 'bigint', + 'bigint', + 'bigint', + 'bigint', + 'text', +] const COUNTS = [ 'requests', 'successful', @@ -27,8 +44,63 @@ const COUNTS = [ 'estimated_cost_nano_usd', 'unknown_cost_requests', ] +const DEFAULT_BATCH_SIZE = 64 +const DEFAULT_FLUSH_INTERVAL_MS = 1500 +const DEFAULT_MAX_PENDING = 4096 +const DEFAULT_CONFIGURED_KEYS_CACHE_TTL_MS = 15_000 +const MAX_CONFIGURED_KEYS_CACHE_ENTRIES = 32 + +const PG_BATCH_INSERT_EVENTS_SQL = `INSERT INTO jev_usage_events (${FIELDS.join(',')}) +SELECT * FROM UNNEST(${FIELD_TYPES.map((type, idx) => `$${idx + 1}::${type}[]`).join(',')}) +ON CONFLICT (id) DO NOTHING +RETURNING id` + +const PG_UPSERT_TOTAL_SQL = `INSERT INTO jev_usage_totals (period,${COUNTS.join(',')}) +VALUES ($1,$2,$3,$4,$5,$6,$7,$8) +ON CONFLICT(period) DO UPDATE SET ${COUNTS.map((name) => `${name}=jev_usage_totals.${name}+excluded.${name}`).join(',')}` + +const PG_PRUNE_EVENTS_SQL = + 'DELETE FROM jev_usage_events WHERE id IN (SELECT id FROM jev_usage_events WHERE created_at < $1 ORDER BY created_at,id LIMIT 500)' +const PG_PRUNE_TOTALS_SQL = + "DELETE FROM jev_usage_totals WHERE period IN (SELECT period FROM jev_usage_totals WHERE period <> 'all' AND period < $1 LIMIT 32)" + +const PG_CONFIGURED_KEYS_TOTALS_SQL = `SELECT key_fingerprint, + COUNT(*)::bigint AS requests, + SUM(CASE WHEN outcome='success' THEN 1 ELSE 0 END)::bigint AS successful, + SUM(COALESCE(estimated_cost_nano_usd,0))::bigint AS estimated_cost_nano_usd, + SUM(CASE WHEN estimated_cost_nano_usd IS NULL THEN 1 ELSE 0 END)::bigint AS unknown_cost_requests +FROM jev_usage_events +WHERE key_fingerprint = ANY($1::text[]) +GROUP BY key_fingerprint` + +const PG_CONFIGURED_KEYS_LATEST_SQL = `SELECT DISTINCT ON (key_fingerprint) + key_fingerprint, created_at, http_status, outcome +FROM jev_usage_events +WHERE key_fingerprint = ANY($1::text[]) +ORDER BY key_fingerprint, created_at DESC, id DESC` + const empty = () => Object.fromEntries(COUNTS.map((name) => [name, 0])) +function eventAmounts(event) { + return [ + 1, + event.outcome === 'success' ? 1 : 0, + event.input_tokens ?? 0, + event.output_tokens ?? 0, + event.input_tokens === null || event.output_tokens === null ? 1 : 0, + event.estimated_cost_nano_usd ?? 0, + event.estimated_cost_nano_usd === null ? 1 : 0, + ] +} + +function resolveNowMs(nowIso, fallbackNow) { + if (nowIso == null) return fallbackNow() + if (typeof nowIso === 'number' && Number.isFinite(nowIso)) return nowIso + if (nowIso instanceof Date && Number.isFinite(nowIso.getTime())) return nowIso.getTime() + const parsed = Date.parse(String(nowIso)) + return Number.isFinite(parsed) ? parsed : fallbackNow() +} + /** * A configured key's panel status, decided by its latest event; with no event at * all the configuration itself answers. Single source so the panel and the usage @@ -45,27 +117,106 @@ function latestKeyStatus(last, key) { return key.retired ? 'paused' : 'unrequested' } +function coalesceBatchTotals(events) { + const byPeriod = new Map() + const add = (period, amounts) => { + let acc = byPeriod.get(period) + if (!acc) { + acc = [0, 0, 0, 0, 0, 0, 0] + byPeriod.set(period, acc) + } + for (let i = 0; i < amounts.length; i += 1) acc[i] += amounts[i] + } + for (const event of events) { + const amounts = eventAmounts(event) + add('all', amounts) + add(shanghaiUsageDay(event.created_at), amounts) + } + // Deterministic lock order: 'all' first, then days ascending. + return [...byPeriod.entries()].sort(([a], [b]) => { + if (a === 'all') return -1 + if (b === 'all') return 1 + return a.localeCompare(b) + }) +} + export class JevUsageRepo { - constructor(db = getDb(), { now = Date.now } = {}) { + constructor( + db = getDb(), + { + now = Date.now, + pgPool = null, + batchSize = DEFAULT_BATCH_SIZE, + flushIntervalMs = DEFAULT_FLUSH_INTERVAL_MS, + maxPending = DEFAULT_MAX_PENDING, + configuredKeysCacheTtlMs = DEFAULT_CONFIGURED_KEYS_CACHE_TTL_MS, + } = {}, + ) { this.db = db this.now = now this.nextPruneAt = 0 - this.insert = db.prepare( - `INSERT INTO jev_usage_events (${FIELDS.join(',')}) VALUES (${FIELDS.map(() => '?').join(',')})`, + this._explicitPgPool = pgPool || null + this._batchSize = Math.max(1, Math.trunc(Number(batchSize) || DEFAULT_BATCH_SIZE)) + this._flushIntervalMs = Math.max(10, Math.trunc(Number(flushIntervalMs) || DEFAULT_FLUSH_INTERVAL_MS)) + this._maxPending = Math.max(this._batchSize, Math.trunc(Number(maxPending) || DEFAULT_MAX_PENDING)) + this._configuredKeysCacheTtlMs = Math.max( + 0, + Math.trunc(Number(configuredKeysCacheTtlMs ?? DEFAULT_CONFIGURED_KEYS_CACHE_TTL_MS) || 0), ) - this.sum = db.prepare(`INSERT INTO jev_usage_totals (period,${COUNTS.join(',')}) VALUES (?,?,?,?,?,?,?,?) + this._queue = [] + this._timer = null + this._flushPromise = null + this._closed = false + this.droppedEvents = 0 + this.flushErrors = 0 + this._configuredKeysCache = new Map() + if (typeof db?.prepare === 'function') { + this.insert = db.prepare( + `INSERT INTO jev_usage_events (${FIELDS.join(',')}) VALUES (${FIELDS.map(() => '?').join(',')})`, + ) + this.sum = db.prepare(`INSERT INTO jev_usage_totals (period,${COUNTS.join(',')}) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(period) DO UPDATE SET ${COUNTS.map((name) => `${name}=jev_usage_totals.${name}+excluded.${name}`).join(',')}`) + } + } + + _resolvePgPool(override = null) { + const pool = + override || this._explicitPgPool || this.db?.pgPool || (this.db?.engine === 'postgres' ? getPgPool() : null) + return pool && typeof pool.query === 'function' ? pool : null + } + + _armFlushTimer() { + if (this._timer || this._closed) return + this._timer = setTimeout(() => { + this._timer = null + this.flush().catch(() => {}) + }, this._flushIntervalMs) + this._timer.unref?.() } + + _clearFlushTimer() { + if (!this._timer) return + clearTimeout(this._timer) + this._timer = null + } + record(event) { - const amounts = [ - 1, - event.outcome === 'success' ? 1 : 0, - event.input_tokens ?? 0, - event.output_tokens ?? 0, - event.input_tokens === null || event.output_tokens === null ? 1 : 0, - event.estimated_cost_nano_usd ?? 0, - event.estimated_cost_nano_usd === null ? 1 : 0, - ] + const pool = this._resolvePgPool() + if (pool) { + if (this._queue.length >= this._maxPending) { + this._queue.shift() + this.droppedEvents += 1 + } + this._queue.push(event) + if (this._queue.length >= this._batchSize) { + this._clearFlushTimer() + this.flush().catch(() => {}) + } else { + this._armFlushTimer() + } + return + } + const amounts = eventAmounts(event) withTransaction(this.db, () => { this.insert.run(...FIELDS.map((name) => event[name])) this.sum.run('all', ...amounts) @@ -74,17 +225,139 @@ export class JevUsageRepo { const now = this.now() if (now >= this.nextPruneAt) { this.nextPruneAt = now + 60000 - // Both deletes are indexed and bounded; lifetime counters are never removed. - this.db - .prepare( - 'DELETE FROM jev_usage_events WHERE id IN (SELECT id FROM jev_usage_events WHERE created_at < ? ORDER BY created_at,id LIMIT 500)', - ) - .run(new Date(now - 30 * 86400000).toISOString()) - this.db - .prepare( - "DELETE FROM jev_usage_totals WHERE period IN (SELECT period FROM jev_usage_totals WHERE period <> 'all' AND period < ? LIMIT 32)", - ) - .run(shanghaiUsageDay(new Date(now - 90 * 86400000).toISOString())) + this.pruneOldEvents(now) + } + } + + async _flushBatchPg(pool, batch) { + const deduped = [] + const seenIds = new Set() + for (const event of batch) { + if (!event || seenIds.has(event.id)) continue + seenIds.add(event.id) + deduped.push(event) + } + if (!deduped.length) return 0 + + const columns = FIELDS.map((field) => deduped.map((event) => (event[field] === undefined ? null : event[field]))) + + const runBatch = async (executor) => { + const insertRes = await executor.query(PG_BATCH_INSERT_EVENTS_SQL, columns) + let toAggregate = deduped + if (Array.isArray(insertRes?.rows) && insertRes.rows.some((row) => row && row.id != null)) { + const insertedIds = new Set(insertRes.rows.map((row) => row.id)) + toAggregate = deduped.filter((event) => insertedIds.has(event.id)) + } else if (typeof insertRes?.rowCount === 'number' && insertRes.rowCount === 0) { + toAggregate = [] + } + if (!toAggregate.length) return 0 + const periodDeltas = coalesceBatchTotals(toAggregate) + for (const [period, sums] of periodDeltas) { + await executor.query(PG_UPSERT_TOTAL_SQL, [period, ...sums]) + } + return toAggregate.length + } + + if (typeof pool.connect === 'function') { + const client = await pool.connect() + try { + await client.query('BEGIN') + const written = await runBatch(client) + await client.query('COMMIT') + return written + } catch (err) { + try { + await client.query('ROLLBACK') + } catch {} + throw err + } finally { + client.release?.() + } + } + return runBatch(pool) + } + + async flush() { + this._clearFlushTimer() + if (this._flushPromise) { + await this._flushPromise + if (!this._queue.length) return { flushed: 0, errors: 0 } + } + const pool = this._resolvePgPool() + if (!pool || !this._queue.length) return { flushed: 0, errors: 0 } + + let flushed = 0 + let errors = 0 + const run = (async () => { + while (this._queue.length > 0) { + const batch = this._queue.splice(0, this._batchSize) + try { + const count = await this._flushBatchPg(pool, batch) + flushed += count + this._configuredKeysCache.clear() + } catch (err) { + errors += 1 + this.flushErrors += 1 + console.warn('[jev-usage] async batch flush failed:', err?.message || err) + } + } + return { flushed, errors } + })() + + this._flushPromise = run + try { + return await run + } finally { + if (this._flushPromise === run) this._flushPromise = null + if (!this._closed && this._queue.length > 0) this._armFlushTimer() + } + } + + async close() { + this._closed = true + this._clearFlushTimer() + const result = await this.flush() + this._configuredKeysCache.clear() + return result + } + + /** + * Bounded retention cleanup: removes events older than 30 days and daily + * totals older than 90 days (lifetime `'all'` row is never deleted). + * Runs asynchronously via `pgPool` in PostgreSQL mode, synchronously on SQLite. + */ + pruneOldEvents(nowIso = null) { + const nowMs = resolveNowMs(nowIso, this.now) + const eventCutoff = new Date(nowMs - 30 * 86400000).toISOString() + const totalCutoff = shanghaiUsageDay(new Date(nowMs - 90 * 86400000).toISOString()) + const pool = this._resolvePgPool() + if (pool) { + return (async () => { + const [evRes, totRes] = await Promise.all([ + pool.query(PG_PRUNE_EVENTS_SQL, [eventCutoff]), + pool.query(PG_PRUNE_TOTALS_SQL, [totalCutoff]), + ]) + this._configuredKeysCache.clear() + return { + eventsDeleted: Number(evRes?.rowCount || 0), + totalsDeleted: Number(totRes?.rowCount || 0), + } + })() + } + // Both deletes are indexed and bounded; lifetime counters are never removed. + const evRes = this.db + .prepare( + 'DELETE FROM jev_usage_events WHERE id IN (SELECT id FROM jev_usage_events WHERE created_at < ? ORDER BY created_at,id LIMIT 500)', + ) + .run(eventCutoff) + const totRes = this.db + .prepare( + "DELETE FROM jev_usage_totals WHERE period IN (SELECT period FROM jev_usage_totals WHERE period <> 'all' AND period < ? LIMIT 32)", + ) + .run(totalCutoff) + return { + eventsDeleted: Number(evRes?.changes || 0), + totalsDeleted: Number(totRes?.changes || 0), } } /** Latest event per key. Shared so a status never depends on which caller asked. */ @@ -139,6 +412,89 @@ export class JevUsageRepo { } }) } + + /** + * Async panel summary for configured keys: uses native `pgPool` with a short + * TTL in-memory cache (15s default) in PostgreSQL mode to avoid blocking the + * main thread on panel polls; falls back to sync `configuredKeys` on SQLite. + */ + async configuredKeysAsync(configuredList, options = {}) { + const keys = Array.isArray(configuredList) ? configuredList : [] + const pool = this._resolvePgPool(options?.pgPool || null) + if (!pool) return this.configuredKeys(keys) + if (!keys.length) return [] + + const fps = [...new Set(keys.map((key) => key?.key_fingerprint).filter(Boolean))].sort() + const nowMs = this.now() + const ttlMs = Math.max(0, Math.trunc(Number(options?.ttlMs ?? this._configuredKeysCacheTtlMs) || 0)) + const bypass = options?.bypass === true + const cacheKey = fps.join(',') + + let cached = !bypass && ttlMs > 0 ? this._configuredKeysCache.get(cacheKey) : null + if (cached && nowMs >= cached.expiresAt) { + this._configuredKeysCache.delete(cacheKey) + cached = null + } + + let totals + let latest + if (cached) { + totals = cached.totals + latest = cached.latest + } else if (!fps.length) { + totals = new Map() + latest = new Map() + } else { + const [totalsRes, latestRes] = await Promise.all([ + pool.query(PG_CONFIGURED_KEYS_TOTALS_SQL, [fps]), + pool.query(PG_CONFIGURED_KEYS_LATEST_SQL, [fps]), + ]) + totals = new Map() + for (const row of totalsRes?.rows || []) { + totals.set(row.key_fingerprint, { + key_fingerprint: row.key_fingerprint, + requests: Number(row.requests || 0), + successful: Number(row.successful || 0), + estimated_cost_nano_usd: Number(row.estimated_cost_nano_usd || 0), + unknown_cost_requests: Number(row.unknown_cost_requests || 0), + }) + } + latest = new Map() + for (const row of latestRes?.rows || []) { + latest.set(row.key_fingerprint, { + created_at: row.created_at ?? null, + http_status: row.http_status == null ? null : Number(row.http_status), + outcome: row.outcome ?? null, + }) + } + if (ttlMs > 0) { + if (this._configuredKeysCache.size >= MAX_CONFIGURED_KEYS_CACHE_ENTRIES) { + const oldest = this._configuredKeysCache.keys().next().value + if (oldest !== undefined) this._configuredKeysCache.delete(oldest) + } + this._configuredKeysCache.set(cacheKey, { + totals, + latest, + expiresAt: nowMs + ttlMs, + }) + } + } + + return keys.map((key) => { + const last = latest.get(key.key_fingerprint) + return { + ...key, + requests: 0, + successful: 0, + estimated_cost_nano_usd: 0, + unknown_cost_requests: 0, + ...totals.get(key.key_fingerprint), + status: latestKeyStatus(last, key), + last_request_at: last?.created_at ?? null, + last_http_status: last?.http_status ?? null, + } + }) + } overview() { const today = shanghaiUsageDay(new Date(this.now()).toISOString()) const rows = this.db.prepare("SELECT * FROM jev_usage_totals WHERE period IN ('all', ?)").all(today) diff --git a/src/lib/gemini/routes.mjs b/src/lib/gemini/routes.mjs index 513f1eee9c..d250fe3c1e 100644 --- a/src/lib/gemini/routes.mjs +++ b/src/lib/gemini/routes.mjs @@ -91,7 +91,7 @@ import { import { clientBlockErrorOf, isTrustedGateDecision, - resolveRiskRepos, + resolveRiskReposAsync, runUnifiedPreDispatch, } from '../protocol/unified-pre-dispatch.mjs' import { firstUserIdentityText, parseUserId, resolveSchedulerIdentity } from '../identity/identity-rewrite.mjs' @@ -4551,7 +4551,7 @@ export function createGeminiPublicHandler({ // Bypasses #1-#4 closed: every public Gemini inference call must clear the // unified pre-dispatch JEV gate BEFORE any Gemini account/slot reservation. - const geminiRiskState = resolveRiskRepos({ settings, refusalGuards, refusalDevices, refusalSessions }) + const geminiRiskState = await resolveRiskReposAsync({ settings, refusalGuards, refusalDevices, refusalSessions }) const baseGeminiIdentity = resolveAuditSessionIdentity({ inbound: body, body, diff --git a/src/lib/protocol/handle-codex.mjs b/src/lib/protocol/handle-codex.mjs index 18a0a7d5c7..d42c572bb7 100644 --- a/src/lib/protocol/handle-codex.mjs +++ b/src/lib/protocol/handle-codex.mjs @@ -56,7 +56,7 @@ import { clientBlockErrorOf, isTrustedGateDecision, projectCandidateAccounts, - resolveRiskRepos, + resolveRiskReposAsync, runUnifiedPreDispatch, } from './unified-pre-dispatch.mjs' import { @@ -866,7 +866,7 @@ export async function handleCodexProtocol({ // Enforce pre-dispatch JEV BEFORE Rust `acquireNode` so blocked requests reserve zero slots. if (!isTrustedGateDecision(preDispatchDecision || req?._preDispatchDecision) && settings) { - const riskState = resolveRiskRepos({ settings, refusalGuards, refusalDevices, refusalSessions }) + const riskState = await resolveRiskReposAsync({ settings, refusalGuards, refusalDevices, refusalSessions }) const candidateAccounts = projectCandidateAccounts({ projectRoot, keyScope, diff --git a/src/lib/protocol/handle-protocol.mjs b/src/lib/protocol/handle-protocol.mjs index 506933b397..20675143ab 100644 --- a/src/lib/protocol/handle-protocol.mjs +++ b/src/lib/protocol/handle-protocol.mjs @@ -21,19 +21,13 @@ import { isUpstreamRefusal, isUpstreamSessionBlockReason, refusalAuditIdentity, - refusalGuardPolicy, refusalPreview, refusalSessionId, riskPrincipal, } from '../core/refusal-guard.mjs' -import { DB_INSTANCE_ID, getDb, isDbOpen } from '../db/database.mjs' +import { isDbOpen } from '../db/database.mjs' import { getCacheRuntime } from '../cache/index.mjs' -import { RefusalGuardsRepo } from '../db/repos/refusal-guards-repo.mjs' -import { RefusalDeviceBlocksRepo } from '../db/repos/refusal-device-blocks-repo.mjs' -import { RefusalSessionBlocksRepo } from '../db/repos/refusal-session-blocks-repo.mjs' -import { SettingsRepo } from '../db/repos/settings-repo.mjs' import { makeApiKeyGateError } from '../admin/api-keys.mjs' -import { readJevConfig } from './jev-intercept.mjs' import { invalidateRiskBanCache, observeUpstreamRisk, @@ -44,6 +38,8 @@ import { clientBlockErrorOf, isTrustedGateDecision, projectCandidateAccounts, + readRuntimeJevConfigAsync, + resolveRiskReposAsync, runUnifiedPreDispatch, } from './unified-pre-dispatch.mjs' import { @@ -431,30 +427,13 @@ export function createHandleProtocol(deps) { requestLog?.updatePhase?.(requestId, patch) } catch {} } - const cachedSettingsRepos = new WeakMap() - const cachedRefusalGuardsRepos = new WeakMap() - const cachedRefusalDeviceRepos = new WeakMap() - const cachedRefusalSessionRepos = new WeakMap() - const SETTING_MISSING = Symbol('setting_missing') - const readCachedSetting = (key, fallback = null) => { - if (deps.settings) return deps.settings.get(key, fallback) - if (!isDbOpen()) return fallback - const db = getDb() - let repo = cachedSettingsRepos.get(db) - if (!repo) { - repo = new SettingsRepo(db) - cachedSettingsRepos.set(db, repo) - } - const cache = getCacheRuntime() - if (!cache?.client?.enabled) return repo.get(key, fallback) - const cacheKey = db.engine === 'postgres' ? String(key) : `${db?.[DB_INSTANCE_ID] || 'sqlite'}:${key}` - const wrapped = cache.entity.getSettingSync(cacheKey, () => { - const val = repo.get(key, SETTING_MISSING) - return val === SETTING_MISSING ? { __missing: true } : { value: val } + const resolveHandleRiskState = () => + resolveRiskReposAsync({ + settings: deps.settings || null, + refusalGuards: deps.refusalGuards || null, + refusalDevices: deps.refusalDevices || null, + refusalSessions: deps.refusalSessions || null, }) - if (!wrapped || wrapped.__missing) return fallback - return wrapped.value - } const cfg = deps.cfg const requestLog = deps.requestLog const stickyRouter = deps.stickyRouter @@ -826,14 +805,6 @@ export function createHandleProtocol(deps) { return finalizeAssembledAssistantHop(result) } - function readRuntimeJev() { - try { - return readJevConfig((key, fallback) => readCachedSetting(key, fallback)) - } catch { - return readJevConfig() - } - } - function applyGateDecisionToLogBag(decision, logBag, { mandatoryOnly = false } = {}) { if (!decision) return if (!mandatoryOnly && decision.intercept) logBag.intercept = decision.intercept @@ -939,7 +910,7 @@ export function createHandleProtocol(deps) { : isZeroInjectMode(req?._poolAccess?.effectivePool || null, channel), distillRules: cfg.distill, policy: riskState.policy, - jev: mandatoryOnly ? null : readRuntimeJev(), + jev: mandatoryOnly ? null : await readRuntimeJevConfigAsync(deps.settings || null), repo: riskState.repo, devices: riskState.devices, sessions: riskState.sessions, @@ -1120,54 +1091,6 @@ export function createHandleProtocol(deps) { ) } - function refusalRepo() { - if (deps.refusalGuards) return deps.refusalGuards - try { - if (!isDbOpen()) return null - const db = getDb() - let repo = cachedRefusalGuardsRepos.get(db) - if (!repo) { - repo = new RefusalGuardsRepo(db) - cachedRefusalGuardsRepos.set(db, repo) - } - return repo - } catch { - return null - } - } - - function deviceRepo() { - if (deps.refusalDevices) return deps.refusalDevices - try { - if (!isDbOpen()) return null - const db = getDb() - let repo = cachedRefusalDeviceRepos.get(db) - if (!repo) { - repo = new RefusalDeviceBlocksRepo(db) - cachedRefusalDeviceRepos.set(db, repo) - } - return repo - } catch { - return null - } - } - - function sessionRepo() { - if (deps.refusalSessions) return deps.refusalSessions - try { - if (!isDbOpen()) return null - const db = getDb() - let repo = cachedRefusalSessionRepos.get(db) - if (!repo) { - repo = new RefusalSessionBlocksRepo(db) - cachedRefusalSessionRepos.set(db, repo) - } - return repo - } catch { - return null - } - } - /** An upstream content refusal ends the caller session for good (own switch, default on). */ function blockRefusedSession({ inbound, body, headers, result, requestId, policy, sessions, reason = null }) { if (policy?.session_block_enabled === false) return @@ -1189,14 +1112,6 @@ export function createHandleProtocol(deps) { } } - function refusalPolicy() { - try { - return refusalGuardPolicy((key, fallback) => readCachedSetting(key, fallback)) - } catch { - return refusalGuardPolicy() - } - } - async function streamAndAssembleClaudeMessage({ candidate, body, @@ -1529,7 +1444,7 @@ export function createHandleProtocol(deps) { }, } } - const riskState = { policy: refusalPolicy(), repo: refusalRepo(), devices: deviceRepo(), sessions: sessionRepo() } + const riskState = await resolveHandleRiskState() const gateArgs = { req, inbound, @@ -5009,12 +4924,7 @@ export function createHandleProtocol(deps) { headers: req.headers, principal: riskPrincipal(req), }) - const searchRiskState = { - policy: refusalPolicy(), - repo: refusalRepo(), - devices: deviceRepo(), - sessions: sessionRepo(), - } + const searchRiskState = await resolveHandleRiskState() if ( await applyProtocolIntercept({ req, @@ -5329,12 +5239,7 @@ export function createHandleProtocol(deps) { headers: req.headers, principal: riskPrincipal(req), }) - const imagesRiskState = { - policy: refusalPolicy(), - repo: refusalRepo(), - devices: deviceRepo(), - sessions: sessionRepo(), - } + const imagesRiskState = await resolveHandleRiskState() if ( await applyProtocolIntercept({ req, diff --git a/src/lib/protocol/jev-intercept.mjs b/src/lib/protocol/jev-intercept.mjs index 266db90518..365e4fd27b 100644 --- a/src/lib/protocol/jev-intercept.mjs +++ b/src/lib/protocol/jev-intercept.mjs @@ -10,6 +10,9 @@ * skips the rest of that host for this call only. * A line may be `https://host[/v1/systemone] `, or a bare URL for a keyless host. */ +import { createHash } from 'node:crypto' +import { getCacheRuntime, registerLocalCacheClearer } from '../cache/index.mjs' +import { BoundedLruCache } from '../cache/cache-client.mjs' import { POLICY_BLOCK_MESSAGE, makePolicyBlockError } from '../core/errors.mjs' import { historyPrefixIntact, refusalUserDocument, refusalUserDocumentCache } from '../core/refusal-similarity.mjs' import { isNegatedExtraction, normalizeText } from '../core/distill-detect.mjs' @@ -459,7 +462,32 @@ function askedIds(cfg) { return questionIdsOf(cfg) } -const verdictCache = new Map() +export const VERDICT_CACHE_MAX = 2048 +const JEV_VERDICT_PREFIX = 'risk:jev:verdict:' +const JEV_PAUSE_PREFIX = 'risk:jev:pause:' +const JEV_AUTH_PAUSE_REDIS_TTL_MS = 24 * 60 * 60 * 1000 +const JEV_PAUSE_REDIS_HEAL_GRACE_MS = 5_000 + +const verdictCache = new BoundedLruCache(VERDICT_CACHE_MAX) +const subscribedCacheClients = new WeakSet() + +export function clearJevVerdictCache() { + verdictCache.clear() +} + +export function jevVerdictCacheStats() { + return { + size: verdictCache.size(), + maxItems: verdictCache.maxItems, + hits: verdictCache.hits, + misses: verdictCache.misses, + evictions: verdictCache.evictions, + } +} + +export function jevVerdictCacheKeys() { + return [...verdictCache.map.keys()] +} function providerOf(id) { return POLICY_PROVIDERS.find((item) => item.id === id) || POLICY_PROVIDERS[0] @@ -1691,11 +1719,17 @@ export function questionsFor(config) { return questions } -function dedupKey(url, model, config, state) { +export function jevVerdictCacheKey(url, model, config, state) { const asked = Object.entries(questionsFor(config)) .map(([id, question]) => `${id}:${question.instructions}`) .join('\n') - return `${url}\0${model}\0${config.safety_threshold}\0${config.block_if_below}\0${asked}\0${state}` + return createHash('sha256') + .update(`${url}\0${model}\0${config.safety_threshold}\0${config.block_if_below}\0${asked}\0${state}`) + .digest('hex') +} + +function dedupKey(url, model, config, state) { + return jevVerdictCacheKey(url, model, config, state) } /** Model catalog lives beside systemone: strip /decide and /v1, then add /v1/models. */ @@ -1771,14 +1805,79 @@ export async function listPolicyModels( return { url, models } } -function cachedVerdict(key, now, windowMs) { - const row = verdictCache.get(key) - if (!row) return null - if (now - row.at > windowMs) { - verdictCache.delete(key) +function activeCacheClient(override = null) { + try { + const rt = override || getCacheRuntime() + const client = rt?.client || (typeof rt?.getRedisClient === 'function' ? rt : null) + if (!client || client.enabled === false) return null + ensureJevCacheInvalidationListener(client) + return client + } catch { + return null + } +} + +function compactCachedVerdict(verdict) { + if (!verdict || typeof verdict !== 'object') return verdict + const { state: _omitted, ...rest } = verdict + return rest +} + +function trimExpiredVerdicts(now) { + if (verdictCache.size() < verdictCache.maxItems) return + for (const [k, entry] of verdictCache.map) { + if (entry.expiresAt > 0 && entry.expiresAt <= now) { + verdictCache.map.delete(k) + } else { + break + } + } +} + +async function readCachedVerdictAsync(keyHash, now, windowMs, cacheOverride = null) { + const local = verdictCache.get(keyHash, now) + if (local.hit) return local.value + + const client = activeCacheClient(cacheOverride) + if (!client?.hasRedis) return null + const redis = client.getRedisClient?.() + if (!redis || typeof redis.get !== 'function') return null + try { + const rKey = await client.resolveRedisKey(`${JEV_VERDICT_PREFIX}${keyHash}`, [ + 'risk:', + 'risk:jev:', + JEV_VERDICT_PREFIX, + ]) + const raw = await redis.get(rKey) + if (raw == null) return null + const parsed = JSON.parse(raw) + const verdict = parsed?.verdict + if (!verdict || typeof verdict !== 'object' || !verdict.action) return null + const storedAt = typeof parsed.at === 'number' ? parsed.at : now + const age = Math.max(0, now - storedAt) + if (age >= windowMs) return null + const remainingMs = Math.max(1, windowMs - age) + trimExpiredVerdicts(now) + verdictCache.set(keyHash, compactCachedVerdict(verdict), remainingMs, now) + return verdict + } catch { return null } - return row.verdict +} + +function writeCachedVerdict(keyHash, verdict, now, windowMs, cacheOverride = null) { + const compact = compactCachedVerdict(verdict) + trimExpiredVerdicts(now) + verdictCache.set(keyHash, compact, windowMs, now) + + const client = activeCacheClient(cacheOverride) + if (!client?.hasRedis) return + const redis = client.getRedisClient?.() + if (!redis || typeof redis.set !== 'function') return + client + .resolveRedisKey(`${JEV_VERDICT_PREFIX}${keyHash}`, ['risk:', 'risk:jev:', JEV_VERDICT_PREFIX]) + .then((rKey) => redis.set(rKey, JSON.stringify({ verdict: compact, at: now }), 'PX', windowMs)) + .catch(() => {}) } function unavailable(config, detail = '') { @@ -1805,6 +1904,134 @@ function jevKeyId(url, apiKey) { return `${url}\0${apiKey}` } +function jevPauseRedisKey(id) { + const hash = createHash('sha256').update(String(id)).digest('hex').slice(0, 32) + return `${JEV_PAUSE_PREFIX}${hash}` +} + +function ensureJevCacheInvalidationListener(client) { + if (!client || typeof client.onInvalidate !== 'function' || subscribedCacheClients.has(client)) return + subscribedCacheClients.add(client) + client.onInvalidate((payload) => { + const keys = Array.isArray(payload?.keys) ? payload.keys : [] + const prefixes = Array.isArray(payload?.prefixes) ? payload.prefixes : [] + if ( + prefixes.some( + (p) => p === 'risk:' || p === 'risk:jev:' || p === JEV_VERDICT_PREFIX || JEV_VERDICT_PREFIX.startsWith(p), + ) + ) { + verdictCache.clear() + } + if ( + prefixes.some( + (p) => p === 'risk:' || p === 'risk:jev:' || p === JEV_PAUSE_PREFIX || JEV_PAUSE_PREFIX.startsWith(p), + ) + ) { + pausedJevKeys.clear() + return + } + if (!keys.length) return + const pauseKeys = new Set(keys.filter((k) => typeof k === 'string' && k.startsWith(JEV_PAUSE_PREFIX))) + if (!pauseKeys.size) return + for (const id of [...pausedJevKeys.keys()]) { + if (pauseKeys.has(jevPauseRedisKey(id))) pausedJevKeys.delete(id) + } + }) +} + +registerLocalCacheClearer((ctx) => { + const prefixes = Array.isArray(ctx?.prefixes) ? ctx.prefixes : [] + if ( + !prefixes.length || + prefixes.some((p) => p === 'risk:' || p === 'risk:jev:' || JEV_VERDICT_PREFIX.startsWith(p)) + ) { + verdictCache.clear() + } + if (!prefixes.length || prefixes.some((p) => p === 'risk:' || p === 'risk:jev:' || JEV_PAUSE_PREFIX.startsWith(p))) { + pausedJevKeys.clear() + } +}) + +function syncPauseToRedis(id, row, now, cacheOverride = null) { + const client = activeCacheClient(cacheOverride) + if (!client?.hasRedis) return + const redis = client.getRedisClient?.() + if (!redis || typeof redis.set !== 'function') return + const ttlMs = row.until !== null ? Math.max(1_000, row.until - now) : JEV_AUTH_PAUSE_REDIS_TTL_MS + const redisKey = client.redisKey(jevPauseRedisKey(id)) + Promise.resolve() + .then(() => redis.set(redisKey, JSON.stringify(row), 'PX', ttlMs)) + .catch(() => {}) +} + +function clearPausedKeysInRedis(ids, cacheOverride = null) { + const uniqueIds = [...new Set((ids || []).filter(Boolean))] + if (!uniqueIds.length) return + const client = activeCacheClient(cacheOverride) + if (!client) return + const logicalKeys = uniqueIds.map(jevPauseRedisKey) + if (client.hasRedis) { + const redis = client.getRedisClient?.() + if (redis && typeof redis.del === 'function') { + const redisKeys = logicalKeys.map((k) => client.redisKey(k)) + Promise.resolve() + .then(() => redis.del(...redisKeys)) + .catch(() => {}) + } + } + if (typeof client.invalidate === 'function') { + client.invalidate({ keys: logicalKeys }).catch(() => {}) + } +} + +async function syncPausedJevKeysFromRedis(targets, now = Date.now(), cacheOverride = null) { + const client = activeCacheClient(cacheOverride) + if (!client?.hasRedis) return + const redis = client.getRedisClient?.() + if (!redis || typeof redis.mget !== 'function') return + const keyed = (targets || []).filter((target) => target?.apiKey && target?.id) + if (!keyed.length) return + try { + const redisKeys = keyed.map((target) => client.redisKey(jevPauseRedisKey(target.id))) + const rows = await redis.mget(...redisKeys) + if (!Array.isArray(rows)) return + for (let i = 0; i < keyed.length; i += 1) { + const id = keyed[i].id + const raw = rows[i] + if (raw == null) { + const local = pausedJevKeys.get(id) + if (local && now - local.at >= JEV_PAUSE_REDIS_HEAL_GRACE_MS) { + pausedJevKeys.delete(id) + } + continue + } + let remote + try { + remote = JSON.parse(raw) + } catch { + continue + } + if (!remote || typeof remote !== 'object' || !remote.reason) continue + if (remote.until !== null && now >= remote.until) { + pausedJevKeys.delete(id) + continue + } + const local = pausedJevKeys.get(id) + if (!local || Number(remote.at || 0) >= Number(local.at || 0)) { + pausedJevKeys.set(id, { + reason: remote.reason, + http_status: Number(remote.http_status) || 0, + at: Number(remote.at) || now, + until: remote.until == null ? null : Number(remote.until), + strikes: Number(remote.strikes) || 1, + }) + } + } + } catch { + // Fail open on Redis errors + } +} + function pauseReasonFor(status) { if (status === 401) return 'auth' if (status === 429) return 'rate_limited' @@ -1828,28 +2055,32 @@ function isPaused(id, now = Date.now()) { return activePause(id, now) !== null } -function pauseJevKey(id, status, now = Date.now()) { +function pauseJevKey(id, status, now = Date.now(), cacheOverride = null) { const reason = pauseReasonFor(status) if (!id || !reason) return const prev = pausedJevKeys.get(id) const strikes = (prev?.strikes || 0) + 1 const until = reason === 'auth' ? null : now + pauseBackoffMs(strikes) - pausedJevKeys.set(id, { reason, http_status: status, at: now, until, strikes }) + const row = { reason, http_status: status, at: now, until, strikes } + pausedJevKeys.set(id, row) + syncPauseToRedis(id, row, now, cacheOverride) } -function clearPausedKeyById(id) { +function clearPausedKeyById(id, cacheOverride = null) { if (!id) return false - return pausedJevKeys.delete(id) + const deleted = pausedJevKeys.delete(id) + if (deleted) clearPausedKeysInRedis([id], cacheOverride) + return deleted } -function clearPausedKey(url, apiKey) { +function clearPausedKey(url, apiKey, cacheOverride = null) { if (!apiKey) return false - return clearPausedKeyById(jevKeyId(url, apiKey)) + return clearPausedKeyById(jevKeyId(url, apiKey), cacheOverride) } -function pausePolicyKey(url, apiKey, status, now = Date.now()) { +function pausePolicyKey(url, apiKey, status, now = Date.now(), cacheOverride = null) { if (!apiKey) return - pauseJevKey(jevKeyId(url, apiKey), status, now) + pauseJevKey(jevKeyId(url, apiKey), status, now, cacheOverride) } function pausedUnavailableDetail(all, now = Date.now()) { @@ -2028,30 +2259,45 @@ export function jevHealthSnapshot(config, now = Date.now()) { } /** Manually resume paused/cooling keys without mutating settings. Omit fingerprint to resume all. */ -export function resumeJevKeys(config, fingerprint = '', now = Date.now()) { +export function resumeJevKeys(config, fingerprint = '', now = Date.now(), { cache = null } = {}) { const normalized = normalizeJevConfig(config) const want = String(fingerprint || '').trim() const resumed = [] const seen = new Set() + const clearedIds = [] for (const target of jevTargets(normalized)) { if (!target.apiKey) continue const fp = jevKeyFingerprint(target.apiKey) if (want && fp !== want) continue const wasPaused = isPaused(target.id, now) pausedJevKeys.delete(target.id) + clearedIds.push(target.id) if (wasPaused && !seen.has(fp)) { seen.add(fp) resumed.push(fp) } } + clearPausedKeysInRedis(clearedIds, cache) return resumed } -function rearmJevKeys(config) { - const live = new Set(jevTargets(config).map((target) => target.id)) +/** Alias for `resumeJevKeys` (sync/async compatible: clears local map + Redis pause keys). */ +export function resumePausedJevKeys(config, fingerprint = '', now = Date.now(), options = {}) { + return resumeJevKeys(config, fingerprint, now, options) +} + +/** Rearm all configured live JEV keys (clears local map + Redis pause keys + cross-instance broadcast). */ +export function rearmJevKeys(config, { cache = null } = {}) { + const normalized = normalizeJevConfig(config) + const liveIds = jevTargets(normalized) + .filter((target) => target.apiKey) + .map((target) => target.id) + const live = new Set(liveIds) for (const id of [...pausedJevKeys.keys()]) { if (live.has(id)) pausedJevKeys.delete(id) } + clearPausedKeysInRedis(liveIds, cache) + return liveIds.length } function flattenJevEndpoints(current, endpoints) { @@ -2443,6 +2689,7 @@ export function sliceJevState(text, maxChars) { * @returns {{ action: 'pass', reason?: string } | { action: 'block', category: string, categories: string[] }} */ export async function classifyJev(text, cfg, fetchImpl = globalThis.fetch, now = Date.now()) { + const cacheOverride = cfg?.cache || null const config = normalizeJevConfig(cfg) const document = sliceJevState( prepareInterceptText(text, { @@ -2458,12 +2705,13 @@ export async function classifyJev(text, cfg, fetchImpl = globalThis.fetch, now = const windowMs = config.dedup_sec * 1000 const key = dedupKey(url, model, config, document) if (windowMs > 0) { - const cached = cachedVerdict(key, now, windowMs) - if (cached) return { ...cached, reason: 'replay' } + const cached = await readCachedVerdictAsync(key, now, windowMs, cacheOverride) + if (cached) return { ...cached, state: document, reason: 'replay' } } const payload = { state: document, questions: questionsFor(config) } if (model) payload.model = model const all = jevTargets(config) + await syncPausedJevKeysFromRedis(all, now, cacheOverride) const targets = all.filter((target) => !isPaused(target.id, now)) if (!targets.length) return unavailable(config, pausedUnavailableDetail(all, now)) const start = keyCursor++ @@ -2500,7 +2748,7 @@ export async function classifyJev(text, cfg, fetchImpl = globalThis.fetch, now = const status = Number(response?.status) || 0 if (status === 400) recordHttp400(jevKeyFingerprint(target.apiKey), now) if (status === 401 || status === 429 || status === 529) { - if (target.apiKey) pauseJevKey(target.id, status, now) + if (target.apiKey) pauseJevKey(target.id, status, now, cacheOverride) continue } skipUrl.add(target.url) @@ -2513,7 +2761,7 @@ export async function classifyJev(text, cfg, fetchImpl = globalThis.fetch, now = const decision = parsePolicyDecision(responsePayload, config) if (!decision) return unavailable(config, '审核评分无效') attemptUsage.outcome = 'success' - clearPausedKeyById(target.id) + clearPausedKeyById(target.id, cacheOverride) const verdict = decision.hits.length ? { action: 'block', @@ -2532,7 +2780,7 @@ export async function classifyJev(text, cfg, fetchImpl = globalThis.fetch, now = margin: decision.margin, scores: decision.scores, } - if (windowMs > 0) verdictCache.set(key, { verdict, at: now }) + if (windowMs > 0) writeCachedVerdict(key, verdict, now, windowMs, cacheOverride) return verdict } catch { // Host-level. Do not retire keys, and do not walk the rest of this host. diff --git a/src/lib/protocol/responses-ws.mjs b/src/lib/protocol/responses-ws.mjs index c7c5364135..7e3f878593 100644 --- a/src/lib/protocol/responses-ws.mjs +++ b/src/lib/protocol/responses-ws.mjs @@ -19,7 +19,7 @@ import { detectInboundPlatform } from './platform-detect.mjs' import { clientBlockErrorOf, projectCandidateAccounts, - resolveRiskRepos, + resolveRiskReposAsync, runUnifiedPreDispatch, } from './unified-pre-dispatch.mjs' import { CLIENT_OVERLOAD_429_MESSAGE, ErrorType } from '../core/errors.mjs' @@ -647,7 +647,7 @@ export function createResponsesWsHandler({ .toLowerCase() const zeroInject = personaInject === 'zero' || personaPreset === 'zero' const official = isOfficialClaudeCodeTraffic(req.headers, hopBody) - const riskState = resolveRiskRepos({ settings, refusalGuards, refusalDevices, refusalSessions }) + const riskState = await resolveRiskReposAsync({ settings, refusalGuards, refusalDevices, refusalSessions }) const preDispatchInput = { req, inbound: hopBody, diff --git a/src/lib/protocol/unified-pre-dispatch.mjs b/src/lib/protocol/unified-pre-dispatch.mjs index 3c0b83cedf..f0aee7eddc 100644 --- a/src/lib/protocol/unified-pre-dispatch.mjs +++ b/src/lib/protocol/unified-pre-dispatch.mjs @@ -13,17 +13,167 @@ import { keyAllowsVm, vmGroupType } from '../admin/key-scope.mjs' import { findAccount } from '../admin/panel-api.mjs' import { vmMatchesOwnerScope } from '../admin/resource-owner.mjs' +import { getCacheRuntime } from '../cache/index.mjs' import { CLIENT_POOL_BUSY_MESSAGE, makePolicyOverloadError } from '../core/errors.mjs' -import { refusalAuditIdentity, refusalGuardPolicy, riskPrincipal } from '../core/refusal-guard.mjs' +import { + REFUSAL_DEVICE_BLOCK_SETTING, + REFUSAL_GUARD_SETTING, + REFUSAL_SESSION_BLOCK_SETTING, + REFUSAL_SIMILARITY_SETTING, + REFUSAL_SIMILARITY_VALUE_SETTING, + RISK_AUDIT_SETTING, + refusalAuditIdentity, + refusalGuardPolicy, + riskPrincipal, +} from '../core/refusal-guard.mjs' +import { DB_INSTANCE_ID, getDb, getPgPool, isDbOpen } from '../db/database.mjs' import { RefusalDeviceBlocksRepo } from '../db/repos/refusal-device-blocks-repo.mjs' import { RefusalGuardsRepo } from '../db/repos/refusal-guards-repo.mjs' import { RefusalSessionBlocksRepo } from '../db/repos/refusal-session-blocks-repo.mjs' import { SettingsRepo } from '../db/repos/settings-repo.mjs' import { listVms } from '../vm/vm-registry.mjs' import { normalizeJevProfile, runProtocolIntercept } from './intercept-gate.mjs' -import { readJevConfig, scopeAccountFromVm } from './jev-intercept.mjs' +import { JEV_SETTING, readJevConfig, scopeAccountFromVm } from './jev-intercept.mjs' const TRUSTED_DECISION_TAG = Symbol('vm2api.trusted_pre_dispatch') +const SETTING_MISSING = Symbol('vm2api.setting_missing') + +const REFUSAL_POLICY_SETTING_KEYS = Object.freeze([ + REFUSAL_GUARD_SETTING, + REFUSAL_SIMILARITY_SETTING, + REFUSAL_SIMILARITY_VALUE_SETTING, + REFUSAL_DEVICE_BLOCK_SETTING, + REFUSAL_SESSION_BLOCK_SETTING, + RISK_AUDIT_SETTING, +]) + +const cachedSettingsRepos = new WeakMap() +const cachedRefusalGuardsRepos = new WeakMap() +const cachedRefusalDeviceRepos = new WeakMap() +const cachedRefusalSessionRepos = new WeakMap() + +function resolveTargetDb(db = null) { + if (db) return db + return isDbOpen() ? getDb() : null +} + +function getCachedRepo(cacheMap, Factory, db = null) { + try { + const targetDb = resolveTargetDb(db) + if (!targetDb) return null + let repo = cacheMap.get(targetDb) + if (!repo) { + repo = new Factory(targetDb) + cacheMap.set(targetDb, repo) + } + return repo + } catch { + return null + } +} + +export function getCachedSettingsRepo(db = null) { + return getCachedRepo(cachedSettingsRepos, SettingsRepo, db) +} + +export function getCachedRefusalGuardsRepo(db = null) { + return getCachedRepo(cachedRefusalGuardsRepos, RefusalGuardsRepo, db) +} + +export function getCachedRefusalDeviceBlocksRepo(db = null) { + return getCachedRepo(cachedRefusalDeviceRepos, RefusalDeviceBlocksRepo, db) +} + +export function getCachedRefusalSessionBlocksRepo(db = null) { + return getCachedRepo(cachedRefusalSessionRepos, RefusalSessionBlocksRepo, db) +} + +function resolveEntityCache(cache = null) { + if (cache) { + if (cache.entity && typeof cache.entity.getSetting === 'function') { + return { entity: cache.entity, enabled: cache.client?.enabled !== false } + } + if (typeof cache.getSetting === 'function') { + return { entity: cache, enabled: cache.cache?.enabled !== false } + } + return null + } + try { + const rt = getCacheRuntime() + if (!rt?.entity) return null + return { entity: rt.entity, enabled: rt.client?.enabled !== false } + } catch { + return null + } +} + +function settingCacheKey(db, key) { + return db?.engine === 'postgres' ? String(key) : `${db?.[DB_INSTANCE_ID] || 'sqlite'}:${key}` +} + +async function loadSettingWrappedAsync(targetDb, repo, key) { + const pool = targetDb?.pgPool || (targetDb?.engine === 'postgres' ? getPgPool() : null) + if (pool && typeof pool.query === 'function') { + try { + const res = await pool.query('SELECT value FROM settings WHERE key = $1', [key]) + const row = res?.rows?.[0] + if (!row) return { __missing: true } + try { + return { value: JSON.parse(row.value) } + } catch { + return { __missing: true } + } + } catch { + // Fall back to sync SettingsRepo if async pool query fails + } + } + const val = repo.get(key, SETTING_MISSING) + return val === SETTING_MISSING ? { __missing: true } : { value: val } +} + +/** + * Sync EntityCache-backed setting reader (L1 + fire-and-forget L2 write). + * Seamlessly falls back to `SettingsRepo.get` when cache is unavailable/disabled. + */ +export function readCachedSettingSync(key, fallback = null, { settings = null, db = null, cache = null } = {}) { + if (settings) return settings.get(key, fallback) + const targetDb = resolveTargetDb(db) + if (!targetDb) return fallback + const repo = getCachedSettingsRepo(targetDb) + if (!repo) return fallback + const ec = resolveEntityCache(cache) + if (!ec || !ec.enabled || typeof ec.entity.getSettingSync !== 'function') { + return repo.get(key, fallback) + } + const wrapped = ec.entity.getSettingSync(settingCacheKey(targetDb, key), () => { + const val = repo.get(key, SETTING_MISSING) + return val === SETTING_MISSING ? { __missing: true } : { value: val } + }) + if (!wrapped || wrapped.__missing) return fallback + return wrapped.value +} + +/** + * Async EntityCache-backed setting reader (L1 + Redis L2 + singleflight + async pgPool). + * Seamlessly falls back to `SettingsRepo.get` when cache is unavailable/disabled. + */ +export async function readCachedSettingAsync(key, fallback = null, { settings = null, db = null, cache = null } = {}) { + if (settings) return settings.get(key, fallback) + const targetDb = resolveTargetDb(db) + if (!targetDb) return fallback + const repo = getCachedSettingsRepo(targetDb) + if (!repo) return fallback + const ec = resolveEntityCache(cache) + if (!ec || !ec.enabled || typeof ec.entity.getSetting !== 'function') { + const wrapped = await loadSettingWrappedAsync(targetDb, repo, key) + return !wrapped || wrapped.__missing ? fallback : wrapped.value + } + const wrapped = await ec.entity.getSetting(settingCacheKey(targetDb, key), () => + loadSettingWrappedAsync(targetDb, repo, key), + ) + if (!wrapped || wrapped.__missing) return fallback + return wrapped.value +} export function isTrustedGateDecision(decision) { return Boolean(decision && typeof decision === 'object' && decision[TRUSTED_DECISION_TAG] === true) @@ -64,19 +214,43 @@ export function clientBlockErrorOf(decision) { } } -export function readRuntimeJevConfig(settings = null) { +export function readRuntimeJevConfig(settings = null, opts = {}) { try { - const repo = settings || new SettingsRepo() - return readJevConfig((key, fallback) => repo.get(key, fallback)) + return readJevConfig((key, fallback) => readCachedSettingSync(key, fallback, { settings, ...opts })) } catch { return readJevConfig() } } -export function readRuntimeRefusalPolicy(settings = null) { +export async function readRuntimeJevConfigAsync(settings = null, opts = {}) { + if (settings) return readRuntimeJevConfig(settings, opts) try { - const repo = settings || new SettingsRepo() - return refusalGuardPolicy((key, fallback) => repo.get(key, fallback)) + const val = await readCachedSettingAsync(JEV_SETTING, SETTING_MISSING, opts) + return readJevConfig((_key, fallback) => (val === SETTING_MISSING ? fallback : val)) + } catch { + return readJevConfig() + } +} + +export function readRuntimeRefusalPolicy(settings = null, opts = {}) { + try { + return refusalGuardPolicy((key, fallback) => readCachedSettingSync(key, fallback, { settings, ...opts })) + } catch { + return refusalGuardPolicy() + } +} + +export async function readRuntimeRefusalPolicyAsync(settings = null, opts = {}) { + if (settings) return readRuntimeRefusalPolicy(settings, opts) + try { + const entries = await Promise.all( + REFUSAL_POLICY_SETTING_KEYS.map(async (key) => [key, await readCachedSettingAsync(key, SETTING_MISSING, opts)]), + ) + const values = new Map(entries) + return refusalGuardPolicy((key, fallback) => { + const val = values.get(key) + return val === undefined || val === SETTING_MISSING ? fallback : val + }) } catch { return refusalGuardPolicy() } @@ -87,20 +261,30 @@ export function resolveRiskRepos({ refusalGuards = null, refusalDevices = null, refusalSessions = null, + db = null, + cache = null, } = {}) { - const safe = (provided, Factory) => { - if (provided) return provided - try { - return new Factory() - } catch { - return null - } + return { + policy: readRuntimeRefusalPolicy(settings, { db, cache }), + repo: refusalGuards || getCachedRefusalGuardsRepo(db), + devices: refusalDevices || getCachedRefusalDeviceBlocksRepo(db), + sessions: refusalSessions || getCachedRefusalSessionBlocksRepo(db), } +} + +export async function resolveRiskReposAsync({ + settings = null, + refusalGuards = null, + refusalDevices = null, + refusalSessions = null, + db = null, + cache = null, +} = {}) { return { - policy: readRuntimeRefusalPolicy(settings), - repo: safe(refusalGuards, RefusalGuardsRepo), - devices: safe(refusalDevices, RefusalDeviceBlocksRepo), - sessions: safe(refusalSessions, RefusalSessionBlocksRepo), + policy: await readRuntimeRefusalPolicyAsync(settings, { db, cache }), + repo: refusalGuards || getCachedRefusalGuardsRepo(db), + devices: refusalDevices || getCachedRefusalDeviceBlocksRepo(db), + sessions: refusalSessions || getCachedRefusalSessionBlocksRepo(db), } } @@ -263,8 +447,10 @@ export async function runUnifiedPreDispatch({ headers, principal: req ? riskPrincipal(req) : '', }) - const resolvedJev = mandatoryOnly ? null : jev !== undefined ? jev : readRuntimeJevConfig(settings) - const resolvedPolicy = policy || readRuntimeRefusalPolicy(settings) + const [resolvedJev, resolvedPolicy] = await Promise.all([ + mandatoryOnly ? null : jev !== undefined ? jev : readRuntimeJevConfigAsync(settings), + policy || readRuntimeRefusalPolicyAsync(settings), + ]) // Public non-Claude generation/search/Gemini endpoints must never be skipped // by `openai_platform_enabled=false`. diff --git a/src/lib/protocol/user-count-tokens.mjs b/src/lib/protocol/user-count-tokens.mjs index 09857fc95f..a303f509b1 100644 --- a/src/lib/protocol/user-count-tokens.mjs +++ b/src/lib/protocol/user-count-tokens.mjs @@ -14,15 +14,17 @@ import { ErrorType, ErrorCode, } from '../core/errors.mjs' -import { refusalAuditIdentity, refusalGuardPolicy, riskPrincipal } from '../core/refusal-guard.mjs' -import { getDb, isDbOpen } from '../db/database.mjs' -import { RefusalGuardsRepo } from '../db/repos/refusal-guards-repo.mjs' -import { RefusalDeviceBlocksRepo } from '../db/repos/refusal-device-blocks-repo.mjs' -import { RefusalSessionBlocksRepo } from '../db/repos/refusal-session-blocks-repo.mjs' -import { SettingsRepo } from '../db/repos/settings-repo.mjs' +import { refusalAuditIdentity, riskPrincipal } from '../core/refusal-guard.mjs' +import { isDbOpen } from '../db/database.mjs' import { findAccount } from '../admin/panel-api.mjs' -import { readJevConfig, scopeAccountFromVm } from './jev-intercept.mjs' +import { scopeAccountFromVm } from './jev-intercept.mjs' import { recordUpstream400SessionBlock, runProtocolIntercept } from './intercept-gate.mjs' +import { + getCachedRefusalDeviceBlocksRepo, + readRuntimeJevConfigAsync, + readRuntimeRefusalPolicy, + resolveRiskReposAsync, +} from './unified-pre-dispatch.mjs' import { inboundBodyLimit, readRoutingConfigFile } from '../core/config.mjs' import { verifyOfficialClaudeCode } from '../identity/official-cc-verifier.mjs' import { @@ -232,74 +234,17 @@ function distillContext( return { official, zeroInject } } -function refusalPolicy(deps) { - try { - const settings = deps.settings || new SettingsRepo() - return refusalGuardPolicy((key, fallback) => settings.get(key, fallback)) - } catch { - return refusalGuardPolicy() - } -} - -const refusalReposByDb = new WeakMap() - -function cachedRefusalRepos() { - if (!isDbOpen()) return null - const db = getDb() - if (!db || typeof db !== 'object') return null - let entry = refusalReposByDb.get(db) - if (!entry) { - entry = {} - refusalReposByDb.set(db, entry) - } - return { db, entry } -} - -function refusalRepo(deps) { - if (deps.refusalGuards) return deps.refusalGuards - try { - const cached = cachedRefusalRepos() - if (!cached) return null - if (!cached.entry.guards) cached.entry.guards = new RefusalGuardsRepo(cached.db) - return cached.entry.guards - } catch { - return null - } -} - -function deviceRepo(deps) { - if (deps.refusalDevices) return deps.refusalDevices - try { - const cached = cachedRefusalRepos() - if (!cached) return null - if (!cached.entry.devices) cached.entry.devices = new RefusalDeviceBlocksRepo(cached.db) - return cached.entry.devices - } catch { - return null - } -} - -function sessionRepo(deps) { - if (deps.refusalSessions) return deps.refusalSessions - try { - const cached = cachedRefusalRepos() - if (!cached) return null - if (!cached.entry.sessions) cached.entry.sessions = new RefusalSessionBlocksRepo(cached.db) - return cached.entry.sessions - } catch { - return null - } -} - /** Distill, hard regex, refusal cache, and jev. `wait` means the slot is required before a verdict. */ export async function blockCountTokensBeforeHop(req, inbound, deps = {}) { - let jev - try { - const settings = deps.settings || new SettingsRepo() - jev = readJevConfig((key, fallback) => settings.get(key, fallback)) - } catch { - jev = readJevConfig() - } + const [jev, riskState] = await Promise.all([ + readRuntimeJevConfigAsync(deps.settings || null), + resolveRiskReposAsync({ + settings: deps.settings || null, + refusalGuards: deps.refusalGuards || null, + refusalDevices: deps.refusalDevices || null, + refusalSessions: deps.refusalSessions || null, + }), + ]) const decision = await runProtocolIntercept({ inbound, body: inbound, @@ -317,12 +262,12 @@ export async function blockCountTokensBeforeHop(req, inbound, deps = {}) { official: deps.official, }), distillRules: deps.cfg?.distill, - policy: refusalPolicy(deps), + policy: riskState.policy, jev, poolJevProfile: deps.effectivePool?.jev_profile || req?.poolJevProfile || req?.apiKeyRecord?.jev_profile || null, - repo: refusalRepo(deps), - devices: deviceRepo(deps), - sessions: sessionRepo(deps), + repo: riskState.repo, + devices: riskState.devices, + sessions: riskState.sessions, account: deps.account || null, }) return { error: decision?.action === 'block' ? decision.error : null, wait: decision.wait === true } @@ -669,8 +614,8 @@ export async function handleUserCountTokens(req, res, deps) { principal: riskPrincipal(req), }), result: hop, - policy: refusalPolicy(deps), - devices: deviceRepo(deps), + policy: readRuntimeRefusalPolicy(deps.settings || null), + devices: deps.refusalDevices || getCachedRefusalDeviceBlocksRepo(), }) } const outboundBody = officialTraffic ? parsed.body : sanitizeThirdPartyCountTokensBody(parsed.body, { routing }) diff --git a/test/unit/distill-detect.test.mjs b/test/unit/distill-detect.test.mjs index 531ef913ca..f03f313659 100644 --- a/test/unit/distill-detect.test.mjs +++ b/test/unit/distill-detect.test.mjs @@ -5,14 +5,21 @@ import os from 'node:os' import path from 'node:path' import { DEFAULT_DISTILL_RULES, + DISTILL_RULES_SETTING, HARD_DISTILL_PATTERNS, detectDistill, distillBlockError, loadDistillRules, + loadDistillRulesFromSettings, normalizeDistillRules, saveDistillRules, + saveDistillRulesToSettings, validateDistillPatch, } from '../../src/lib/core/distill-detect.mjs' +import { MultiTierCacheClient } from '../../src/lib/cache/cache-client.mjs' +import { EntityCache } from '../../src/lib/cache/entity-cache.mjs' +import { createDatabase } from '../../src/lib/db/database.mjs' +import { SettingsRepo } from '../../src/lib/db/repos/settings-repo.mjs' import { ErrorCode } from '../../src/lib/core/errors.mjs' import { evaluateProtocolIntercept } from '../../src/lib/protocol/intercept-gate.mjs' import { matchHardPolicy } from '../../src/lib/protocol/jev-intercept.mjs' @@ -661,3 +668,53 @@ test('normalize keeps default fingerprints when omitted', () => { assert.ok(r.fingerprints.length >= 5) assert.equal(r.error.message, '不允许蒸馏') }) +test('loadDistillRulesFromSettings and saveDistillRulesToSettings use DB settings SSOT with EntityCache and local fallback', async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-distill-db-')) + const file = path.join(dir, 'distill-rules.json') + const db = createDatabase({ dbPath: path.join(dir, 'kin.db') }) + const client = new MultiTierCacheClient({ redisConfig: null, cacheConfig: { disabled: false } }) + const entity = new EntityCache(client) + t.after(() => { + db.close() + fs.rmSync(dir, { recursive: true, force: true }) + }) + + // 1. No DB row yet -> falls back to local file rules + saveDistillRules(file, { enabled: true, error: { message: '本地回退' } }) + const fallback = await loadDistillRulesFromSettings(db, { client, entity }, { file }) + assert.equal(fallback.error.message, '本地回退') + + // 2. Save via DB settings SSOT persists to settings table, updates local file, and invalidates EntityCache + const saved = await saveDistillRulesToSettings( + db, + { enabled: false, error: { message: '数据库SSOT' }, hard_needles: ['DB-NEEDLE'] }, + { client, entity }, + { file }, + ) + assert.equal(saved.enabled, false) + assert.equal(saved.error.message, '数据库SSOT') + assert.deepEqual(saved.hard_needles, ['DB-NEEDLE']) + + const storedInDb = new SettingsRepo(db).get(DISTILL_RULES_SETTING, null) + assert.equal(storedInDb.error.message, '数据库SSOT') + assert.equal(loadDistillRules(file).error.message, '数据库SSOT') + + // 3. Subsequent load reads through EntityCache (hits L1 even if local file is deleted) + fs.rmSync(file, { force: true }) + const fromCache1 = await loadDistillRulesFromSettings(db, { client, entity }, { file }) + assert.equal(fromCache1.enabled, false) + assert.equal(fromCache1.error.message, '数据库SSOT') + assert.deepEqual(fromCache1.hard_needles, ['DB-NEEDLE']) + + // 4. Updating via saveDistillRulesToSettings invalidates EntityCache immediately for hot reload + await saveDistillRulesToSettings( + db, + { enabled: true, error: { message: '热更新生效' } }, + { client, entity }, + { file }, + ) + const fromCache2 = await loadDistillRulesFromSettings(db, { client, entity }, { file }) + assert.equal(fromCache2.enabled, true) + assert.equal(fromCache2.error.message, '热更新生效') + assert.deepEqual(fromCache2.hard_needles, ['DB-NEEDLE']) +}) diff --git a/test/unit/jev-intercept.test.mjs b/test/unit/jev-intercept.test.mjs index 39a0ee32f6..091fa0cac5 100644 --- a/test/unit/jev-intercept.test.mjs +++ b/test/unit/jev-intercept.test.mjs @@ -23,7 +23,14 @@ import { publicJevConfig, publicJevKeys, jevHealthSnapshot, + jevVerdictCacheKey, + jevVerdictCacheKeys, + jevVerdictCacheStats, + clearJevVerdictCache, + VERDICT_CACHE_MAX, + rearmJevKeys, resumeJevKeys, + resumePausedJevKeys, probePolicyBaseline, probePolicyQuota, questionsFor, @@ -2795,3 +2802,220 @@ test('thinking-content reproduction prompts hit hard distill rules (>=95%) with db.close() } }) + +test('verdictCache uses SHA-256 keys without storing raw prompt text and enforces bounded 2048 LRU eviction', async () => { + clearJevVerdictCache() + const cfg = { + enabled: true, + hard_regex_enabled: false, + base_url: 'http://127.0.0.1:9', + model: 'jev-latest', + timeout_ms: 500, + dedup_sec: 120, + } + const safeFetch = async () => ({ + ok: true, + json: async () => ({ answers: { usage_policy: { type: 'noul', noul: 0.95 } } }), + }) + const longPrompt = `SENSITIVE-PROMPT-PREFIX-${'x'.repeat(12000)}` + const t0 = 10_000 + const v0 = await classifyJev(longPrompt, cfg, safeFetch, t0) + assert.equal(v0.action, 'pass') + const keysAfterFirst = jevVerdictCacheKeys() + assert.equal(keysAfterFirst.length, 1) + assert.match(keysAfterFirst[0], /^[a-f0-9]{64}$/) + assert.equal(keysAfterFirst[0].includes('SENSITIVE-PROMPT'), false) + assert.equal( + keysAfterFirst[0], + jevVerdictCacheKey(decisionUrl(cfg.base_url), 'jev-latest', normalizeJevConfig(cfg), longPrompt), + ) + + // Fill past VERDICT_CACHE_MAX (2048) and verify bounded LRU eviction keeps size <= 2048 + const firstKey = keysAfterFirst[0] + for (let i = 1; i <= VERDICT_CACHE_MAX + 24; i += 1) { + await classifyJev(`lru-entry-${i}`, cfg, safeFetch, t0 + i) + } + const stats = jevVerdictCacheStats() + assert.equal(stats.maxItems, 2048) + assert.equal(stats.size, VERDICT_CACHE_MAX) + assert.ok(stats.evictions >= 25) + assert.equal(jevVerdictCacheKeys().includes(firstKey), false) + clearJevVerdictCache() +}) + +test('verdictCache Redis L2 shares deduplicated verdicts across instances without storing prompt text', async () => { + clearJevVerdictCache() + const store = new Map() + const setCalls = [] + const mockRedis = { + async get(k) { + return store.has(k) ? store.get(k) : null + }, + async set(k, val, mode, ttl) { + setCalls.push({ key: k, val, mode, ttl }) + store.set(k, val) + return 'OK' + }, + async mget(...keys) { + return keys.map((k) => (store.has(k) ? store.get(k) : null)) + }, + async del(...keys) { + let n = 0 + for (const k of keys) if (store.delete(k)) n += 1 + return n + }, + } + const listeners = new Set() + const mockCache = { + enabled: true, + hasRedis: true, + getRedisClient: () => mockRedis, + redisKey: (k) => `vm2api:${k}`, + resolveRedisKey: async (k) => `vm2api:${k}`, + onInvalidate: (fn) => { + listeners.add(fn) + return () => listeners.delete(fn) + }, + invalidate: async () => {}, + } + + let fetches = 0 + const fetchImpl = async () => { + fetches += 1 + return { ok: true, json: async () => ({ answers: { usage_policy: { type: 'noul', noul: 0.1 } } }) } + } + const cfg = { + enabled: true, + hard_regex_enabled: false, + base_url: 'http://127.0.0.1:9', + model: 'jev-latest', + timeout_ms: 500, + dedup_sec: 60, + cache: mockCache, + } + const prompt = 'cross-instance-l2-verdict-secret-body' + const first = await classifyJev(prompt, cfg, fetchImpl, 50_000) + assert.equal(first.action, 'block') + assert.equal(fetches, 1) + await Promise.resolve() + await Promise.resolve() + assert.equal(setCalls.length, 1) + assert.match(setCalls[0].key, /^vm2api:risk:jev:verdict:[a-f0-9]{64}$/) + assert.equal(setCalls[0].val.includes(prompt), false) + + // Simulate another instance with empty local L1 reading from Redis L2 + clearJevVerdictCache() + const second = await classifyJev(prompt, cfg, fetchImpl, 55_000) + assert.equal(second.action, 'block') + assert.equal(second.reason, 'replay') + assert.equal(second.state, prompt) + assert.equal(fetches, 1) + clearJevVerdictCache() +}) + +test('pausedJevKeys syncs via Redis TTL keys and rearmJevKeys/resumePausedJevKeys clear local and Redis state', async () => { + const store = new Map() + const invalidations = [] + const listeners = new Set() + const mockRedis = { + async set(k, val) { + store.set(k, val) + return 'OK' + }, + async mget(...keys) { + return keys.map((k) => (store.has(k) ? store.get(k) : null)) + }, + async del(...keys) { + let n = 0 + for (const k of keys) if (store.delete(k)) n += 1 + return n + }, + } + const mockCache = { + enabled: true, + hasRedis: true, + getRedisClient: () => mockRedis, + redisKey: (k) => `vm2api:${k}`, + resolveRedisKey: async (k) => `vm2api:${k}`, + onInvalidate: (fn) => { + listeners.add(fn) + return () => listeners.delete(fn) + }, + invalidate: async (payload) => { + invalidations.push(payload) + for (const fn of listeners) fn(payload) + }, + } + const secretKey = 'jev-secret-sync-key-1' + const backupKey = 'jev-secret-sync-key-2' + const cfg = { + enabled: true, + hard_regex_enabled: false, + base_url: 'http://127.0.0.1:9', + api_keys: [secretKey, backupKey], + model: 'jev-latest', + timeout_ms: 500, + dedup_sec: 0, + cache: mockCache, + } + const t0 = 200_000 + let pausedAuth = '' + const verdict = await classifyJev( + 'sync pause test', + cfg, + async (_url, init) => { + const auth = init.headers.authorization + if (!pausedAuth) { + pausedAuth = auth + return { ok: false, status: 429 } + } + return { ok: true, json: async () => ({ answers: { usage_policy: { noul: 0.9 } } }) } + }, + t0, + ) + assert.equal(verdict.action, 'pass') + await Promise.resolve() + await Promise.resolve() + + const pausedSecret = pausedAuth.replace(/^Bearer /, '') + const otherSecret = pausedSecret === secretKey ? backupKey : secretKey + const pauseKeys = [...store.keys()].filter((k) => k.startsWith('vm2api:risk:jev:pause:')) + assert.equal(pauseKeys.length, 1) + // Raw API key must never appear in Redis key name or value + assert.equal(pauseKeys[0].includes(pausedSecret), false) + assert.equal(store.get(pauseKeys[0]).includes(pausedSecret), false) + + // Resume clears both local map and Redis key (sync + await compatible) + const resumed = await resumePausedJevKeys(cfg, '', t0 + 1_000, { cache: mockCache }) + assert.equal(resumed.length, 1) + await Promise.resolve() + await Promise.resolve() + assert.equal([...store.keys()].filter((k) => k.startsWith('vm2api:risk:jev:pause:')).length, 0) + assert.ok(invalidations.some((p) => Array.isArray(p.keys) && p.keys.some((k) => k.startsWith('risk:jev:pause:')))) + + // Simulate another instance pausing pausedSecret directly in Redis -> classifyJev skips it via MGET + store.set( + pauseKeys[0], + JSON.stringify({ reason: 'rate_limited', http_status: 429, at: t0 + 2_000, until: t0 + 60_000, strikes: 1 }), + ) + const seenKeys = [] + const second = await classifyJev( + 'sync pause test 2', + cfg, + async (_url, init) => { + seenKeys.push(init.headers.authorization) + return { ok: true, json: async () => ({ answers: { usage_policy: { noul: 0.9 } } }) } + }, + t0 + 3_000, + ) + assert.equal(second.action, 'pass') + assert.equal(seenKeys.length, 1) + assert.equal(seenKeys[0], `Bearer ${otherSecret}`) + + // rearmJevKeys clears both local and Redis pause state + const rearmed = rearmJevKeys(cfg, { cache: mockCache }) + assert.equal(rearmed, 2) + await Promise.resolve() + await Promise.resolve() + assert.equal([...store.keys()].filter((k) => k.startsWith('vm2api:risk:jev:pause:')).length, 0) +}) diff --git a/test/unit/jev-usage.test.mjs b/test/unit/jev-usage.test.mjs index 099b3f7fa5..721eecc830 100644 --- a/test/unit/jev-usage.test.mjs +++ b/test/unit/jev-usage.test.mjs @@ -604,3 +604,204 @@ test('paused/cooling status overrides latest success and resume route enforces a ) resumeJevKeys(cfg) }) + +test('PG async batching coalesces all/day totals into 1 UPSERT per period, supports flush/close, and moves prune off hot path', async () => { + const queries = [] + let txCount = 0 + let released = 0 + const mockPool = { + async connect() { + return { + async query(sql, params = []) { + const text = String(sql).trim() + if (text === 'BEGIN') txCount += 1 + queries.push({ sql: text, params }) + if (text.startsWith('INSERT INTO jev_usage_events')) { + const ids = params[0] || [] + return { rows: ids.map((id) => ({ id })), rowCount: ids.length } + } + return { rows: [], rowCount: 1 } + }, + release() { + released += 1 + }, + } + }, + async query(sql, params = []) { + const text = String(sql).trim() + queries.push({ sql: text, params }) + return { rows: [], rowCount: 3 } + }, + } + + let nowMs = NOW + const mockPgDb = { engine: 'postgres', pgPool: mockPool } + const repo = new JevUsageRepo(mockPgDb, { + now: () => nowMs, + batchSize: 64, + flushIntervalMs: 60_000, + maxPending: 4, + }) + + // 3 events across 2 Shanghai days (2 on 2026-10-25, 1 on 2026-10-24) + repo.record(normalizeJevUsage(value({ created_at: '2026-10-25T02:00:00.000Z' }))) + repo.record( + normalizeJevUsage( + value({ + created_at: '2026-10-25T03:00:00.000Z', + outcome: 'http_error', + http_status: 429, + usage: null, + }), + ), + ) + repo.record(normalizeJevUsage(value({ created_at: '2026-10-24T12:00:00.000Z' }))) + + // Hot path: 0 synchronous PG calls and 0 prune DELETEs before flush() + assert.equal(queries.length, 0) + + const flushed = await repo.flush() + assert.equal(flushed.flushed, 3) + assert.equal(flushed.errors, 0) + assert.equal(txCount, 1) + assert.equal(released, 1) + + const batchInserts = queries.filter((q) => q.sql.startsWith('INSERT INTO jev_usage_events')) + assert.equal(batchInserts.length, 1) + assert.equal(batchInserts[0].params[0].length, 3) + + const totalUpserts = queries.filter((q) => q.sql.startsWith('INSERT INTO jev_usage_totals')) + // Exactly 1 UPSERT for 'all' + 1 for '2026-10-24' + 1 for '2026-10-25' + assert.equal(totalUpserts.length, 3) + assert.deepEqual( + totalUpserts.map((q) => q.params[0]), + ['all', '2026-10-24', '2026-10-25'], + ) + // 'all': 3 requests, 2 successful, 2000 input, 40 output, 1 unknown usage, 84000 nano USD, 1 unknown cost + assert.deepEqual(totalUpserts[0].params, ['all', 3, 2, 2000, 40, 1, 84000, 1]) + assert.deepEqual(totalUpserts[1].params, ['2026-10-24', 1, 1, 1000, 20, 0, 42000, 0]) + assert.deepEqual(totalUpserts[2].params, ['2026-10-25', 2, 1, 1000, 20, 1, 42000, 1]) + + // No prune DELETE ran on hot path + assert.equal( + queries.some((q) => q.sql.startsWith('DELETE FROM jev_usage_')), + false, + ) + + // Explicit async pruneOldEvents runs bounded PG DELETEs + const pruned = await repo.pruneOldEvents(new Date(nowMs).toISOString()) + assert.deepEqual(pruned, { eventsDeleted: 3, totalsDeleted: 3 }) + assert.equal(queries.filter((q) => q.sql.startsWith('DELETE FROM jev_usage_')).length, 2) + + // Bounded queue cap drops oldest to prevent OOM when PG flush is stalled, and close() drains remaining + let releaseConnect + let stalledOnce = false + const stalledPool = { + async connect() { + if (!stalledOnce) { + stalledOnce = true + await new Promise((resolve) => { + releaseConnect = resolve + }) + } + return mockPool.connect() + }, + query: mockPool.query, + } + const cappedRepo = new JevUsageRepo( + { engine: 'postgres', pgPool: stalledPool }, + { now: () => nowMs, batchSize: 2, flushIntervalMs: 60_000, maxPending: 4 }, + ) + // First 2 trigger an in-flight flush (spliced out); next 6 queue up against maxPending=4 -> 2 dropped + for (let i = 0; i < 8; i += 1) { + cappedRepo.record(normalizeJevUsage(value({ request_id: `req-cap-${i}` }))) + } + assert.equal(cappedRepo.droppedEvents, 2) + releaseConnect() + const closed = await cappedRepo.close() + assert.equal(closed.flushed, 0) + // Total written to mockPool: 3 from first flush + 6 (2 in-flight + 4 queued) from cappedRepo + const cappedInserts = queries.filter((q) => q.sql.startsWith('INSERT INTO jev_usage_events')) + assert.equal( + cappedInserts.reduce((sum, q) => sum + (q.params[0]?.length || 0), 0), + 9, + ) +}) + +test('configuredKeysAsync uses async pgPool with short-TTL cache in PG mode and falls back to sync on SQLite', async (t) => { + const fpA = jevKeyFingerprint('pg-async-a') + const fpB = jevKeyFingerprint('pg-async-b') + let poolCalls = 0 + const mockPool = { + async query(sql, params) { + poolCalls += 1 + if (String(sql).includes('GROUP BY key_fingerprint')) { + assert.deepEqual(params[0], [fpA, fpB].sort()) + return { + rows: [ + { + key_fingerprint: fpA, + requests: '5', + successful: '4', + estimated_cost_nano_usd: '168000', + unknown_cost_requests: '1', + }, + ], + } + } + if (String(sql).includes('DISTINCT ON (key_fingerprint)')) { + return { + rows: [ + { + key_fingerprint: fpA, + created_at: '2026-10-25T02:05:00.000Z', + http_status: 200, + outcome: 'success', + }, + ], + } + } + return { rows: [] } + }, + } + + let clock = NOW + const pgRepo = new JevUsageRepo( + { engine: 'postgres', pgPool: mockPool }, + { now: () => clock, configuredKeysCacheTtlMs: 15_000 }, + ) + const first = await pgRepo.configuredKeysAsync([ + { number: 1, key_fingerprint: fpA, retired: false }, + { number: 2, key_fingerprint: fpB, retired: false }, + ]) + assert.equal(poolCalls, 2) + assert.equal(first[0].requests, 5) + assert.equal(first[0].estimated_cost_nano_usd, 168000) + assert.equal(first[0].status, 'normal') + assert.equal(first[1].requests, 0) + assert.equal(first[1].status, 'unrequested') + + // Within 15s TTL: 0 extra PG queries, yet dynamic paused_reason reflects immediately + clock += 5_000 + const cached = await pgRepo.configuredKeysAsync([ + { number: 1, key_fingerprint: fpA, retired: true, paused_reason: 'auth' }, + { number: 2, key_fingerprint: fpB, retired: false }, + ]) + assert.equal(poolCalls, 2) + assert.equal(cached[0].status, 'paused') + assert.equal(cached[0].requests, 5) + + // After TTL expiry: refreshes from pgPool + clock += 11_000 + await pgRepo.configuredKeysAsync([ + { number: 1, key_fingerprint: fpA, retired: false }, + { number: 2, key_fingerprint: fpB, retired: false }, + ]) + assert.equal(poolCalls, 4) + + // SQLite fallback matches configuredKeys() + const sqliteRepo = fixture(t) + sqliteRepo.record(normalizeJevUsage(value({ key_fingerprint: fpA }))) + const sqliteAsync = await sqliteRepo.configuredKeysAsync([{ number: 1, key_fingerprint: fpA, retired: false }]) + assert.deepEqual(sqliteAsync, sqliteRepo.configuredKeys([{ number: 1, key_fingerprint: fpA, retired: false }])) +}) diff --git a/test/unit/scheduler-m1a-jev-unified.test.mjs b/test/unit/scheduler-m1a-jev-unified.test.mjs index b647f8ab83..6fea044124 100644 --- a/test/unit/scheduler-m1a-jev-unified.test.mjs +++ b/test/unit/scheduler-m1a-jev-unified.test.mjs @@ -20,9 +20,17 @@ import { handleCodexProtocol } from '../../src/lib/protocol/handle-codex.mjs' import { createHandleProtocol } from '../../src/lib/protocol/handle-protocol.mjs' import { jevDocument, jevModelDocument, normalizeJevConfig } from '../../src/lib/protocol/jev-intercept.mjs' import { createResponsesWsHandler } from '../../src/lib/protocol/responses-ws.mjs' +import { MultiTierCacheClient } from '../../src/lib/cache/cache-client.mjs' +import { EntityCache } from '../../src/lib/cache/entity-cache.mjs' +import { SettingsRepo } from '../../src/lib/db/repos/settings-repo.mjs' import { clientBlockErrorOf, isTrustedGateDecision, + readCachedSettingAsync, + readRuntimeJevConfigAsync, + readRuntimeRefusalPolicyAsync, + resolveRiskRepos, + resolveRiskReposAsync, runUnifiedPreDispatch, } from '../../src/lib/protocol/unified-pre-dispatch.mjs' @@ -1714,3 +1722,61 @@ for (const { scope = {}, blocked, downgrade, denied } of [ assert.equal(logs.at(-1).final_state, denied ? null : blocked ? 'policy_blocked' : 'verified') }) } + +test('unified-pre-dispatch reuses WeakMap risk repos per DB and reads settings via EntityCache with fallback', async (t) => { + const dir1 = fs.mkdtempSync(path.join(os.tmpdir(), 'unified-risk-1-')) + const dir2 = fs.mkdtempSync(path.join(os.tmpdir(), 'unified-risk-2-')) + const db1 = createDatabase({ dbPath: path.join(dir1, 'kin.db') }) + const db2 = createDatabase({ dbPath: path.join(dir2, 'kin.db') }) + t.after(() => { + db1.close() + db2.close() + fs.rmSync(dir1, { recursive: true, force: true }) + fs.rmSync(dir2, { recursive: true, force: true }) + }) + + const settingsRepo = new SettingsRepo(db1) + settingsRepo.set('jev_intercept', { enabled: true, base_url: 'http://127.0.0.1:9', safety_threshold: 0.6 }) + settingsRepo.set('refusal_similarity', 85) + + const cacheClient = new MultiTierCacheClient({ redisConfig: null, cacheConfig: { disabled: false } }) + const entityCache = new EntityCache(cacheClient) + const cacheRuntime = { client: cacheClient, entity: entityCache } + + // 1. WeakMap caches the 3 risk repos per DB instance (zero per-request `new`) + const first = await resolveRiskReposAsync({ db: db1, cache: cacheRuntime }) + const second = resolveRiskRepos({ db: db1, cache: cacheRuntime }) + assert.ok(first.repo && first.devices && first.sessions) + assert.equal(first.repo, second.repo) + assert.equal(first.devices, second.devices) + assert.equal(first.sessions, second.sessions) + + // Distinct DB receives distinct repo instances + const otherDbRepos = await resolveRiskReposAsync({ db: db2, cache: cacheRuntime }) + assert.notEqual(otherDbRepos.repo, first.repo) + assert.notEqual(otherDbRepos.devices, first.devices) + assert.notEqual(otherDbRepos.sessions, first.sessions) + + // 2. Async EntityCache reads hit L1 after first load (even before invalidation) + const jevCfg1 = await readRuntimeJevConfigAsync(null, { db: db1, cache: cacheRuntime }) + assert.equal(jevCfg1.enabled, true) + assert.equal(jevCfg1.safety_threshold, 0.6) + const policy1 = await readRuntimeRefusalPolicyAsync(null, { db: db1, cache: cacheRuntime }) + assert.equal(policy1.similarity, 85) + + // Direct DB mutation without invalidation proves EntityCache L1 served the cached value + settingsRepo.set('refusal_similarity', 95) + const cachedVal = await readCachedSettingAsync('refusal_similarity', 90, { db: db1, cache: cacheRuntime }) + assert.equal(cachedVal, 85) + + // Invalidate EntityCache -> sees updated DB value + await entityCache.invalidateSettings() + const freshVal = await readCachedSettingAsync('refusal_similarity', 90, { db: db1, cache: cacheRuntime }) + assert.equal(freshVal, 95) + + // 3. Disabled cache seamlessly degrades to direct SettingsRepo.get + const disabledCache = { client: { enabled: false }, entity: entityCache } + settingsRepo.set('refusal_similarity', 80) + const degradedVal = await readCachedSettingAsync('refusal_similarity', 90, { db: db1, cache: disabledCache }) + assert.equal(degradedVal, 80) +}) From afac45d02c517d212f7211ba6aa0193021082043 Mon Sep 17 00:00:00 2001 From: dofastted Date: Tue, 1 Dec 2026 20:00:27 +0800 Subject: [PATCH 12/15] perf(db): single-scan protocolEntryStats async offload and risk/jev index migrations --- src/lib/admin/request-log.mjs | 4 + .../migrations/075_optimize_risk_indexes.sql | 19 ++ .../014_optimize_risk_and_jev_indexes.sql | 31 +++ src/lib/db/repos/usage-logs-repo.mjs | 126 +++++++----- test/unit/pg-log-writer.test.mjs | 78 +++++++- test/unit/request-log.test.mjs | 3 +- test/unit/scheduler-m0-migrations.test.mjs | 7 +- test/unit/usage-logs-repo.test.mjs | 188 ++++++++++++++++++ 8 files changed, 399 insertions(+), 57 deletions(-) create mode 100644 src/lib/db/migrations/075_optimize_risk_indexes.sql create mode 100644 src/lib/db/pg/pg-migrations/014_optimize_risk_and_jev_indexes.sql diff --git a/src/lib/admin/request-log.mjs b/src/lib/admin/request-log.mjs index ce804b5828..3ad33bbf59 100644 --- a/src/lib/admin/request-log.mjs +++ b/src/lib/admin/request-log.mjs @@ -1888,6 +1888,10 @@ export class RequestLogStore { return this.repo.protocolEntryStats(opts) } + async protocolEntryStatsAsync(opts = {}) { + return this.repo.protocolEntryStatsAsync(opts) + } + listDebug({ limit = 20, exclude_error_class = null, diff --git a/src/lib/db/migrations/075_optimize_risk_indexes.sql b/src/lib/db/migrations/075_optimize_risk_indexes.sql new file mode 100644 index 0000000000..8971b956ee --- /dev/null +++ b/src/lib/db/migrations/075_optimize_risk_indexes.sql @@ -0,0 +1,19 @@ +-- 075_optimize_risk_indexes — Align SQLite risk/usage_logs partial indexes with +-- PostgreSQL migration 014_optimize_risk_and_jev_indexes.sql (SQLite does not +-- support table fillfactor storage parameters). + +DROP INDEX IF EXISTS idx_refusal_guards_model; + +CREATE INDEX IF NOT EXISTS idx_refusal_device_blocks_expires + ON refusal_device_blocks (expires_at) + WHERE expires_at IS NOT NULL; + +CREATE INDEX IF NOT EXISTS idx_refusal_guards_expires + ON refusal_guards (expires_at) + WHERE expires_at IS NOT NULL; + +DROP INDEX IF EXISTS idx_usage_logs_upstream_400; + +CREATE INDEX IF NOT EXISTS idx_usage_logs_upstream_risk + ON usage_logs (created_at DESC, id DESC) + WHERE upstream_status IN (400, 401, 403, 422); diff --git a/src/lib/db/pg/pg-migrations/014_optimize_risk_and_jev_indexes.sql b/src/lib/db/pg/pg-migrations/014_optimize_risk_and_jev_indexes.sql new file mode 100644 index 0000000000..a8573a6fac --- /dev/null +++ b/src/lib/db/pg/pg-migrations/014_optimize_risk_and_jev_indexes.sql @@ -0,0 +1,31 @@ +-- 014_optimize_risk_and_jev_indexes.sql +-- Idempotent PG18 partial index & fillfactor optimizations for risk audit tables, +-- usage_logs risk polling, and high-frequency jev_usage_totals HOT updates. +-- +-- 1. Drop unused idx_refusal_guards_model (0 scans; pure write amplification). +-- 2. Add partial expires_at indexes on refusal_device_blocks and refusal_guards +-- to accelerate active/expired TTL scans without indexing permanent NULL rows. +-- 3. Replace narrow idx_usage_logs_upstream_400 (WHERE upstream_status = 400) +-- with superset idx_usage_logs_upstream_risk (WHERE upstream_status IN (400, 401, 403, 422)) +-- to cover the risk page's 30s upstream_risk_errors polling while also +-- implying legacy upstream_status = 400 predicates without duplicate write amplification. +-- 4. Set jev_usage_totals fillfactor = 70 to reserve page headroom for HOT updates +-- on the hot `period = 'all'` row and curb MVCC dead-tuple bloat. + +DROP INDEX IF EXISTS idx_refusal_guards_model; + +CREATE INDEX IF NOT EXISTS idx_refusal_device_blocks_expires + ON refusal_device_blocks (expires_at) + WHERE expires_at IS NOT NULL; + +CREATE INDEX IF NOT EXISTS idx_refusal_guards_expires + ON refusal_guards (expires_at) + WHERE expires_at IS NOT NULL; + +DROP INDEX IF EXISTS idx_usage_logs_upstream_400; + +CREATE INDEX IF NOT EXISTS idx_usage_logs_upstream_risk + ON usage_logs (created_at DESC, id DESC) + WHERE upstream_status IN (400, 401, 403, 422); + +ALTER TABLE jev_usage_totals SET (fillfactor = 70); diff --git a/src/lib/db/repos/usage-logs-repo.mjs b/src/lib/db/repos/usage-logs-repo.mjs index e1e3b10785..9dd76e5427 100644 --- a/src/lib/db/repos/usage-logs-repo.mjs +++ b/src/lib/db/repos/usage-logs-repo.mjs @@ -1260,12 +1260,7 @@ export class UsageLogsRepo { } } - /** - * Shanghai-day protocol gate: blocks, passes, and the words that blocked. - * `total` is every inbound inference request (warmup answers included) plus - * gate blocks on other paths, so each stage's share uses one denominator. - */ - protocolEntryStats({ since = shanghaiDayStartIso() } = {}) { + _protocolEntryStatsSql() { // COALESCE: a bare `col = x` on NULL yields NULL, and `NOT NULL` drops the row. const block = `( COALESCE(error_code, '') = 'policy_blocked' @@ -1273,56 +1268,91 @@ export class UsageLogsRepo { OR COALESCE(final_state, '') IN ('policy_blocked', 'distill_blocked', 'refusal_guard', 'refusal_similar', 'refusal_device', 'refusal_session') )` const inference = `path IN ('/v1/messages', '/v1/responses', '/v1/chat/completions', '/v1/completions')` - const row = this.db - .prepare( - `SELECT - SUM(CASE WHEN ${inference} OR ${block} THEN 1 ELSE 0 END) AS total, - SUM(CASE WHEN ${block} THEN 1 ELSE 0 END) AS blocked, - SUM(CASE WHEN ${inference} - AND NOT ${block} - AND COALESCE(via, '') != 'warmup-intercept' - THEN 1 ELSE 0 END) AS passed, - SUM(CASE WHEN ${inference} - AND NOT ${block} - AND COALESCE(attempt_count, 0) > 0 - AND ( - COALESCE(error_code, '') IN ('content_filter_refusal', 'refusal_guard') - OR COALESCE(stop_reason, '') = 'refusal' - OR COALESCE(final_state, '') = 'content_filter' - ) - THEN 1 ELSE 0 END) AS upstream_refusals - FROM usage_logs - WHERE created_at >= ?`, - ) - .get(since) - const grouped = this.db - .prepare( - `SELECT intercept, via, error_message AS message, - CASE WHEN ${block} THEN 1 ELSE 0 END AS blocked, - CASE WHEN COALESCE(attempt_count, 0) > 0 THEN 1 ELSE 0 END AS hopped, - COUNT(*) AS count - FROM usage_logs - WHERE created_at >= ? - AND ( - ${block} - OR (${inference} AND COALESCE(via, '') != 'warmup-intercept') - ) - GROUP BY intercept, via, error_message, blocked, hopped`, - ) - .all(since) - const folded = foldInterceptRows(grouped) + return `SELECT + intercept, + via, + CASE WHEN ${block} AND COALESCE(intercept, '') = '' THEN error_message ELSE NULL END AS message, + CASE WHEN ${block} THEN 1 ELSE 0 END AS blocked, + CASE WHEN COALESCE(attempt_count, 0) > 0 THEN 1 ELSE 0 END AS hopped, + CASE WHEN ${inference} AND NOT ${block} AND COALESCE(via, '') = 'warmup-intercept' THEN 1 ELSE 0 END AS warmup, + COUNT(*) AS count, + SUM(CASE WHEN ${inference} + AND NOT ${block} + AND COALESCE(attempt_count, 0) > 0 + AND ( + COALESCE(error_code, '') IN ('content_filter_refusal', 'refusal_guard') + OR COALESCE(stop_reason, '') = 'refusal' + OR COALESCE(final_state, '') = 'content_filter' + ) + THEN 1 ELSE 0 END) AS upstream_refusals + FROM usage_logs + WHERE created_at >= ? + AND (${inference} OR ${block}) + GROUP BY 1, 2, 3, 4, 5, 6` + } + + _formatProtocolEntryStats(since, rows) { + let total = 0 + let blocked = 0 + let passed = 0 + let upstreamRefusals = 0 + const interceptRows = [] + for (const r of rows || []) { + const count = Number(r?.count || 0) + if (!count) continue + const isBlocked = Number(r?.blocked) === 1 + const isWarmup = Number(r?.warmup) === 1 + total += count + upstreamRefusals += Number(r?.upstream_refusals || 0) + if (isBlocked) { + blocked += count + interceptRows.push(r) + } else if (!isWarmup) { + passed += count + interceptRows.push(r) + } + } + const folded = foldInterceptRows(interceptRows) return { since, - total: Number(row?.total || 0), - blocked: Number(row?.blocked || 0), - passed: Number(row?.passed || 0), - upstreamRefusals: Number(row?.upstream_refusals || 0), + total, + blocked, + passed, + upstreamRefusals, blocks: folded.blocks, passes: folded.passes, routes: folded.routes, } } + /** + * Shanghai-day protocol gate: blocks, passes, and the words that blocked. + * `total` is every inbound inference request (warmup answers included) plus + * gate blocks on other paths, so each stage's share uses one denominator. + */ + protocolEntryStats({ since = shanghaiDayStartIso() } = {}) { + const rows = this.db.prepare(this._protocolEntryStatsSql()).all(since) + return this._formatProtocolEntryStats(since, rows) + } + + /** + * Async variant of `protocolEntryStats`: prefers non-blocking `_readRowsAsync` + * (`pgPool` on PostgreSQL or worker read pool on SQLite), falling back to the + * synchronous `protocolEntryStats` when no async backend is active. + */ + async protocolEntryStatsAsync(opts = {}) { + const hasAsyncBackend = + isDbOpen() && + this.db === getDb() && + ((this.db?.engine === 'postgres' && !!getPgPool()) || (this.db?.engine !== 'postgres' && usagePoolEnabled())) + if (!hasAsyncBackend && this._readRowsAsync === UsageLogsRepo.prototype._readRowsAsync) { + return this.protocolEntryStats(opts) + } + const { since = shanghaiDayStartIso() } = opts || {} + const rows = await this._readRowsAsync(this._protocolEntryStatsSql(), [since]) + return this._formatProtocolEntryStats(since, rows) + } + /** Clear in-process billing snapshot cache and related DashboardCache namespaces. */ invalidateBillingCache() { this._billingStatsCache.clear() diff --git a/test/unit/pg-log-writer.test.mjs b/test/unit/pg-log-writer.test.mjs index d1c5bba7cc..c6a2365767 100644 --- a/test/unit/pg-log-writer.test.mjs +++ b/test/unit/pg-log-writer.test.mjs @@ -110,11 +110,13 @@ function parsePgTableColumnTypes(tableName) { return typeMap } -test('PG migrations 011 and 012 optimize usage_logs/request_attempts/account_allocations indexes idempotently', async () => { +test('PG migrations 011, 012, and 014 optimize usage_logs/request_attempts/risk/jev indexes idempotently', async () => { const mig011 = '011_drop_duplicate_usage_logs_indexes.sql' const mig012 = '012_optimize_usage_logs_and_attempts_indexes.sql' + const mig014 = '014_optimize_risk_and_jev_indexes.sql' const sql011 = fs.readFileSync(path.join(PG_MIGRATIONS_DIR, mig011), 'utf8') const sql012 = fs.readFileSync(path.join(PG_MIGRATIONS_DIR, mig012), 'utf8') + const sql014 = fs.readFileSync(path.join(PG_MIGRATIONS_DIR, mig014), 'utf8') assert.match(sql011, /DROP INDEX IF EXISTS idx_reqlog_cost_ts;/i) assert.match(sql011, /DROP INDEX IF EXISTS idx_usage_logs_request_id;/i) @@ -155,7 +157,51 @@ test('PG migrations 011 and 012 optimize usage_logs/request_attempts/account_all /CREATE INDEX IF NOT EXISTS idx_alloc_account_id_desc\s+ON account_allocations \(account_id, id DESC\);/i, ) - // Verify applyPgMigrations loads and applies 011 & 012 cleanly and idempotently via mock client + // 014 drops dead/superseded risk indexes, adds partial risk/expiry indexes, and sets jev_usage_totals fillfactor + assert.match(sql014, /DROP INDEX IF EXISTS idx_refusal_guards_model;/i) + assert.match(sql014, /DROP INDEX IF EXISTS idx_usage_logs_upstream_400;/i) + assert.match( + sql014, + /CREATE INDEX IF NOT EXISTS idx_refusal_device_blocks_expires\s+ON refusal_device_blocks \(expires_at\)\s+WHERE expires_at IS NOT NULL;/i, + ) + assert.match( + sql014, + /CREATE INDEX IF NOT EXISTS idx_refusal_guards_expires\s+ON refusal_guards \(expires_at\)\s+WHERE expires_at IS NOT NULL;/i, + ) + assert.match( + sql014, + /CREATE INDEX IF NOT EXISTS idx_usage_logs_upstream_risk\s+ON usage_logs \(created_at DESC, id DESC\)\s+WHERE upstream_status IN \(400, 401, 403, 422\);/i, + ) + assert.match(sql014, /ALTER TABLE jev_usage_totals SET \(fillfactor = 70\);/i) + + // Verify SQLite migration 075 aligns indexes identically with PG 014 + const sqliteDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vm2api-sqlite-075-idx-')) + try { + const sqliteDb = createDatabase({ dbPath: path.join(sqliteDir, 'kin.db') }) + try { + const idxNames = new Set( + sqliteDb + .prepare("SELECT name FROM sqlite_master WHERE type = 'index'") + .all() + .map((r) => r.name), + ) + assert.equal(idxNames.has('idx_refusal_guards_model'), false, 'SQLite 075 must drop idx_refusal_guards_model') + assert.equal( + idxNames.has('idx_usage_logs_upstream_400'), + false, + 'SQLite 075 must drop superseded idx_usage_logs_upstream_400', + ) + assert.equal(idxNames.has('idx_refusal_device_blocks_expires'), true) + assert.equal(idxNames.has('idx_refusal_guards_expires'), true) + assert.equal(idxNames.has('idx_usage_logs_upstream_risk'), true) + } finally { + sqliteDb.close() + } + } finally { + fs.rmSync(sqliteDir, { recursive: true, force: true }) + } + + // Verify applyPgMigrations loads and applies 011, 012, and 014 cleanly and idempotently via mock client const appliedVersions = new Map() const executedSql = [] const client = { @@ -181,10 +227,14 @@ test('PG migrations 011 and 012 optimize usage_logs/request_attempts/account_all const mockPool = { connect: async () => client } const first = await applyPgMigrations(mockPool) - assert.equal(first.at(-1), mig012) + assert.ok(first.includes(mig011)) + assert.ok(first.includes(mig012)) + assert.equal(first.at(-1), mig014) assert.ok(executedSql.some((s) => s.includes('DROP INDEX IF EXISTS idx_reqlog_cost_ts'))) assert.ok(executedSql.some((s) => s.includes('DROP INDEX IF EXISTS idx_request_attempt_request'))) assert.ok(executedSql.some((s) => s.includes('idx_alloc_account_id_desc'))) + assert.ok(executedSql.some((s) => s.includes('idx_usage_logs_upstream_risk'))) + assert.ok(executedSql.some((s) => s.includes('ALTER TABLE jev_usage_totals SET (fillfactor = 70)'))) const second = await applyPgMigrations(mockPool) assert.deepEqual(second, []) @@ -895,9 +945,9 @@ test('Live PostgreSQL end-to-end: migrations 011+012, UNNEST PgLogWriter, and ru try { await applyPgMigrations(pool) - // Verify 011 + 012 dropped redundant indexes while preserving required indexes + // Verify 011 + 012 + 014 dropped redundant/superseded indexes while preserving required indexes const idxRes = await pool.query( - `SELECT tablename, indexname FROM pg_indexes WHERE schemaname = $1 AND tablename IN ('usage_logs', 'request_attempts', 'account_allocations')`, + `SELECT tablename, indexname FROM pg_indexes WHERE schemaname = $1 AND tablename IN ('usage_logs', 'request_attempts', 'account_allocations', 'refusal_guards', 'refusal_device_blocks')`, [schema], ) const usageNames = new Set(idxRes.rows.filter((r) => r.tablename === 'usage_logs').map((r) => r.indexname)) @@ -913,6 +963,7 @@ test('Live PostgreSQL end-to-end: migrations 011+012, UNNEST PgLogWriter, and ru 'idx_usage_logs_model_created', 'idx_usage_logs_session_created', 'idx_reqlog_account', + 'idx_usage_logs_upstream_400', ]) { assert.equal(usageNames.has(gone), false, `expected ${gone} dropped`) } @@ -925,7 +976,7 @@ test('Live PostgreSQL end-to-end: migrations 011+012, UNNEST PgLogWriter, and ru 'idx_usage_logs_vm_owner', 'idx_reqlog_vm', 'idx_usage_logs_outbound_session_created', - 'idx_usage_logs_upstream_400', + 'idx_usage_logs_upstream_risk', 'idx_usage_logs_pricing_null', ]) { assert.equal(usageNames.has(kept), true, `expected ${kept} preserved`) @@ -937,6 +988,21 @@ test('Live PostgreSQL end-to-end: migrations 011+012, UNNEST PgLogWriter, and ru const allocNames = new Set(idxRes.rows.filter((r) => r.tablename === 'account_allocations').map((r) => r.indexname)) assert.equal(allocNames.has('idx_alloc_account_id_desc'), true) + const guardNames = new Set(idxRes.rows.filter((r) => r.tablename === 'refusal_guards').map((r) => r.indexname)) + assert.equal(guardNames.has('idx_refusal_guards_model'), false) + assert.equal(guardNames.has('idx_refusal_guards_expires'), true) + + const devBlockNames = new Set( + idxRes.rows.filter((r) => r.tablename === 'refusal_device_blocks').map((r) => r.indexname), + ) + assert.equal(devBlockNames.has('idx_refusal_device_blocks_expires'), true) + + const jevOptRes = await pool.query( + `SELECT c.reloptions FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = $1 AND c.relname = 'jev_usage_totals'`, + [schema], + ) + assert.ok((jevOptRes.rows?.[0]?.reloptions || []).includes('fillfactor=70')) + const writer = createPgLogWriter(pool, { batchSize: 16, concurrency: 2, flushIntervalMs: 5000 }) const oldTs = '2026-10-01T00:00:00.000Z' const newTs = '2026-11-28T10:00:00.000Z' diff --git a/test/unit/request-log.test.mjs b/test/unit/request-log.test.mjs index 1140ccde82..d532ed2445 100644 --- a/test/unit/request-log.test.mjs +++ b/test/unit/request-log.test.mjs @@ -942,7 +942,7 @@ test('risk audit counts only routed hops and looks up upstream 400s by original assert.equal(view.listBatch({ request_id: original.request_id }).logs[0].id, requests[0].id) }) -test('protocolEntryStats counts upstreamRefusals and UsageLogsView supports via/upstream_risk_errors + JEV details', () => { +test('protocolEntryStats counts upstreamRefusals and UsageLogsView supports via/upstream_risk_errors + JEV details', async () => { const store = tmpStore() logOne(store, { status: 429, @@ -977,6 +977,7 @@ test('protocolEntryStats counts upstreamRefusals and UsageLogsView supports via/ const stats = store.protocolEntryStats({ since: '1970-01-01T00:00:00.000Z' }) assert.equal(stats.blocked, 1) assert.equal(stats.upstreamRefusals, 1) + assert.deepEqual(await store.protocolEntryStatsAsync({ since: '1970-01-01T00:00:00.000Z' }), stats) const view = new UsageLogsView(store.db) const jevOnly = view.listBatch({ via: 'jev', include_muted: true }).logs diff --git a/test/unit/scheduler-m0-migrations.test.mjs b/test/unit/scheduler-m0-migrations.test.mjs index f5806b14d6..85cf92ccf0 100644 --- a/test/unit/scheduler-m0-migrations.test.mjs +++ b/test/unit/scheduler-m0-migrations.test.mjs @@ -75,7 +75,7 @@ test('SQLite 071 upgrades pre-071 DB cleanly, preserves existing api_keys, and e ) const applied = applyMigrations(db) - assert.deepEqual(applied, [ + assert.deepEqual(applied.slice(0, 3), [ '071_scheduler_center.sql', '072_scheduler_pool_prompt_default.sql', '073_api_endpoint_body_policy_default.sql', @@ -736,7 +736,10 @@ test('072 SQLite / 009 PG migrations safely repair untouched legacy vm_pools bac ).run('pool_openai_pt', 'openai-pt', 'OpenAI Pool', now, now) const applied = applyMigrations(db) - assert.deepEqual(applied, ['072_scheduler_pool_prompt_default.sql', '073_api_endpoint_body_policy_default.sql']) + assert.deepEqual(applied.slice(0, 2), [ + '072_scheduler_pool_prompt_default.sql', + '073_api_endpoint_body_policy_default.sql', + ]) const modeOf = (id) => db.prepare('SELECT system_prompt_mode FROM scheduler_pools WHERE id = ?').get(id).system_prompt_mode diff --git a/test/unit/usage-logs-repo.test.mjs b/test/unit/usage-logs-repo.test.mjs index c5780bc65f..6869637519 100644 --- a/test/unit/usage-logs-repo.test.mjs +++ b/test/unit/usage-logs-repo.test.mjs @@ -5,6 +5,8 @@ import os from 'node:os' import path from 'node:path' import { createDatabase } from '../../src/lib/db/database.mjs' import { UsageLogsRepo } from '../../src/lib/db/repos/usage-logs-repo.mjs' +import { translateSqliteToPg } from '../../src/lib/db/pg/sql-compat.mjs' +import { gateVerdict } from '../../src/lib/protocol/intercept-stats.mjs' import { codexBodyToAnthropicMessage } from '../../src/lib/protocol/codex-convert.mjs' import { estimateWindow } from '../../src/lib/admin/window-estimate.mjs' @@ -660,3 +662,189 @@ test('aligned windows keep boundary, sign, unpriced and Fable rules per row', () fs.rmSync(dir, { recursive: true, force: true }) } }) + +test('protocolEntryStats uses a single SQL scan, derives keywords in memory, and matches protocolEntryStatsAsync', async () => { + const { dir, db, repo } = freshDb() + try { + const since = '2026-11-20T00:00:00.000Z' + const routeVerdict = gateVerdict({ + kind: 'pass', + by: 'jev', + route: { kind: 'pool', target: 'pool_alpha', score: 0.7 }, + }) + seed(repo, [ + // Before `since` — must be excluded + { + created_at: '2026-11-19T23:59:59.000Z', + path: '/v1/messages', + status: 403, + via: 'hard-regex', + error_code: 'policy_blocked', + error_message: '请求被协议拦截: oldword', + }, + // Non-inference non-blocked — must be excluded + { + created_at: '2026-11-20T01:00:00.000Z', + path: '/v1/models', + status: 200, + }, + // Warmup intercept on inference path — counted in total, excluded from passed/passes + { + created_at: '2026-11-20T01:05:00.000Z', + path: '/v1/messages', + via: 'warmup-intercept', + status: 200, + }, + // Passed inference with routed hop + { + created_at: '2026-11-20T01:10:00.000Z', + path: '/v1/messages', + status: 200, + attempt_count: 1, + intercept: routeVerdict, + }, + // Passed inference with routed verdict but attempt_count=0 (not hopped -> not in routes) + { + created_at: '2026-11-20T01:12:00.000Z', + path: '/v1/responses', + status: 503, + attempt_count: 0, + error_message: 'distinct upstream error A', + intercept: routeVerdict, + }, + // Passed inference with upstream refusal + { + created_at: '2026-11-20T01:15:00.000Z', + path: '/v1/chat/completions', + status: 400, + attempt_count: 1, + error_code: 'content_filter_refusal', + error_message: 'distinct upstream error B', + intercept: gateVerdict({ kind: 'pass', by: 'regex' }), + }, + // Blocked rows (two messages collapsing to keyword 'alpha', one to 'beta', one on non-inference path) + { + created_at: '2026-11-20T01:20:00.000Z', + path: '/v1/messages', + status: 403, + via: 'hard-regex', + final_state: 'policy_blocked', + error_code: 'policy_blocked', + error_message: '请求被协议拦截: rule-1: alpha', + intercept: gateVerdict({ kind: 'block', by: 'hard-regex', keyword: 'alpha', rule: 'r1' }), + }, + { + created_at: '2026-11-20T01:21:00.000Z', + path: '/v1/messages', + status: 403, + via: 'jev', + final_state: 'policy_blocked', + error_code: 'policy_blocked', + error_message: '请求被协议拦截: rule-2: alpha', + intercept: gateVerdict({ kind: 'block', by: 'jev', keyword: 'alpha', rule: 'r2' }), + }, + { + created_at: '2026-11-20T01:22:00.000Z', + path: '/v1/other', + status: 403, + via: 'distill-detect', + final_state: 'distill_blocked', + error_code: 'distill_blocked', + error_message: '请求被协议拦截: beta', + intercept: gateVerdict({ kind: 'block', by: 'distill', keyword: 'beta' }), + }, + // Blocked row with empty error_message — counted in blocked/blocks, skipped in keywords + { + created_at: '2026-11-20T01:23:00.000Z', + path: '/v1/messages', + status: 503, + via: 'refusal-guard', + final_state: 'refusal_device', + error_code: 'refusal_guard', + error_message: '', + intercept: gateVerdict({ kind: 'block', by: 'refusal', keyword: 'device' }), + }, + ]) + + // Count exact SQL statements prepared during protocolEntryStats() + const preparedSqls = [] + const origPrepare = db.prepare.bind(db) + db.prepare = (sql) => { + preparedSqls.push(sql) + return origPrepare(sql) + } + let syncStats + try { + syncStats = repo.protocolEntryStats({ since }) + } finally { + db.prepare = origPrepare + } + + assert.equal(preparedSqls.length, 1, 'protocolEntryStats must execute only 1 single-scan SQL query') + assert.doesNotMatch(preparedSqls[0], /LIMIT\s+50/i, 'separate keywords SQL must be removed') + + // Verify SQL translates cleanly to PostgreSQL ($1 bind, no residual ?) + const translated = translateSqliteToPg(preparedSqls[0]) + assert.equal(translated.special, null) + assert.match(translated.sql, /\$1/) + assert.doesNotMatch(translated.sql, /\?/) + + assert.equal(syncStats.since, since) + assert.equal(syncStats.total, 8) + assert.equal(syncStats.blocked, 4) + assert.equal(syncStats.passed, 3) + assert.equal(syncStats.upstreamRefusals, 1) + assert.deepEqual(syncStats.keywords, [ + { keyword: 'alpha', count: 2 }, + { keyword: 'beta', count: 1 }, + ]) + assert.deepEqual(syncStats.routes, [{ kind: 'pool', target: 'pool_alpha', count: 1 }]) + assert.equal( + syncStats.blocks.reduce((sum, r) => sum + r.count, 0), + 4, + ) + assert.equal( + syncStats.passes.reduce((sum, r) => sum + r.count, 0), + 3, + ) + + // Fallback path (no pgPool / isolated SQLite): degrades to sync and matches identically + let fallbackCalls = 0 + const origSync = repo.protocolEntryStats.bind(repo) + repo.protocolEntryStats = (opts) => { + fallbackCalls += 1 + return origSync(opts) + } + try { + const fallbackStats = await repo.protocolEntryStatsAsync({ since }) + assert.equal(fallbackCalls, 1) + assert.deepEqual(fallbackStats, syncStats) + } finally { + repo.protocolEntryStats = origSync + } + + // Async pgPool path via _readRowsAsync (simulate PG returning bigint strings) + const asyncSqls = [] + repo._readRowsAsync = async (sql, params) => { + asyncSqls.push({ sql, params }) + return db + .prepare(sql) + .all(...params) + .map((row) => ({ + ...row, + blocked: String(row.blocked), + hopped: String(row.hopped), + warmup: String(row.warmup), + count: String(row.count), + upstream_refusals: String(row.upstream_refusals), + })) + } + const asyncStats = await repo.protocolEntryStatsAsync({ since }) + assert.equal(asyncSqls.length, 1, 'protocolEntryStatsAsync must issue only 1 async query') + assert.deepEqual(asyncSqls[0].params, [since]) + assert.deepEqual(asyncStats, syncStats) + } finally { + db.close() + fs.rmSync(dir, { recursive: true, force: true }) + } +}) From 1ab480257e1279afa8479a1a69c80b7d2545e7f8 Mon Sep 17 00:00:00 2001 From: dofastted Date: Tue, 1 Dec 2026 20:24:39 +0800 Subject: [PATCH 13/15] feat(risk,pg): wire async SWR stats, distill settings sync, bounded GC, and PG parity tests --- src/lib/admin/panel-routes.mjs | 56 ++++++++++++--- src/server.mjs | 100 +++++++++++++++++++++++++- test/unit/panel-redis-opt.test.mjs | 66 ++++++++++++++++- test/unit/pg-repos-parity.test.mjs | 111 +++++++++++++++++++++++++---- 4 files changed, 306 insertions(+), 27 deletions(-) diff --git a/src/lib/admin/panel-routes.mjs b/src/lib/admin/panel-routes.mjs index fbfdaf43dd..079824ede8 100644 --- a/src/lib/admin/panel-routes.mjs +++ b/src/lib/admin/panel-routes.mjs @@ -31,7 +31,11 @@ import { twoFactorStatus, verifyTwoFactorCode, } from '../core/panel-2fa.mjs' -import { loadDistillRules, saveDistillRules, validateDistillPatch } from '../core/distill-detect.mjs' +import { + loadDistillRulesFromSettings, + saveDistillRulesToSettings, + validateDistillPatch, +} from '../core/distill-detect.mjs' import { applyRefusalGuardPatch, refusalGuardPolicy, @@ -47,7 +51,7 @@ import { publicJevConfig, publicJevKeys, readJevConfig, - resumeJevKeys, + resumePausedJevKeys, } from '../protocol/jev-intercept.mjs' import { invalidateRiskBanCache } from '../protocol/intercept-gate.mjs' import { JevUsageRepo } from '../db/repos/jev-usage-repo.mjs' @@ -1347,11 +1351,13 @@ export function createPanelHandler(ctx) { } function distillFile() { - return path.join(cfg.paths.root, 'config', 'distill-rules.json') + const base = cfg?.paths?.root || cfg?.paths?.project + return base ? path.join(base, 'config', 'distill-rules.json') : null } - function reloadDistill() { - cfg.distill = loadDistillRules(distillFile()) + async function reloadDistill() { + const file = distillFile() + cfg.distill = await loadDistillRulesFromSettings(resolvePanelDb(), null, file ? { file } : {}) return cfg.distill } @@ -8596,7 +8602,7 @@ export function createPanelHandler(ctx) { ) } if (req.method === 'GET' && p === '/api/panel/distill') { - return json(res, 200, panel.ok(reloadDistill())) + return json(res, 200, panel.ok(await reloadDistill())) } if (req.method === 'PUT' && p === '/api/panel/distill') { const body = await readBody(req, 256 * 1024) @@ -8612,7 +8618,8 @@ export function createPanelHandler(ctx) { }, }) } - cfg.distill = saveDistillRules(distillFile(), body) + const file = distillFile() + cfg.distill = await saveDistillRulesToSettings(resolvePanelDb(), body, null, file ? { file } : {}) return json(res, 200, panel.ok(cfg.distill)) } if (req.method === 'GET' && p === '/api/panel/refusal-guards') { @@ -8726,7 +8733,31 @@ export function createPanelHandler(ctx) { return json(res, 200, panel.ok(refusalGuardSnapshot())) } if (req.method === 'GET' && p === '/api/panel/protocol-entry') { - return json(res, 200, panel.ok(requestLog.protocolEntryStats())) + const bypass = url.searchParams.get('refresh') === '1' + const load = async () => { + const statsData = + typeof requestLog?.protocolEntryStatsAsync === 'function' + ? await requestLog.protocolEntryStatsAsync() + : requestLog.protocolEntryStats() + return panel.ok(statsData) + } + let dashboard = null + try { + dashboard = getCacheRuntime()?.dashboard || null + } catch {} + const payload = + dashboard && typeof dashboard.getOrSetSWR === 'function' + ? await dashboard.getOrSetSWR( + 'panel', + { + ep: 'protocol-entry', + scope: cacheScopeOf(requestLog?.repo?.db || resolvePanelDb()), + }, + load, + { freshTtlMs: 15_000, ttlMs: 60_000, bypass }, + ) + : await load() + return sendCachedJson(req, res, 200, payload) } if (req.method === 'GET' && p === '/api/panel/jev-usage') { if (panelIdentity(req).role !== 'admin') @@ -8751,7 +8782,12 @@ export function createPanelHandler(ctx) { throw error } const settings = new SettingsRepo() - const keys = repo.configuredKeys(publicJevKeys(readJevConfig((key, fallback) => settings.get(key, fallback)))) + const configured = publicJevKeys(readJevConfig((key, fallback) => settings.get(key, fallback))) + const bypass = url.searchParams.get('refresh') === '1' + const keys = + typeof repo.configuredKeysAsync === 'function' + ? await repo.configuredKeysAsync(configured, { bypass }) + : repo.configuredKeys(configured) return json( res, 200, @@ -8846,7 +8882,7 @@ export function createPanelHandler(ctx) { }) } const stored = readJevConfig((key, fallback) => new SettingsRepo().get(key, fallback)) - const resumed = resumeJevKeys(stored, fingerprint) + const resumed = await resumePausedJevKeys(stored, fingerprint) const rawKeys = publicJevKeys(stored) let keys = rawKeys if (rawKeys.length) { diff --git a/src/server.mjs b/src/server.mjs index 023403357f..be11dd29ce 100644 --- a/src/server.mjs +++ b/src/server.mjs @@ -157,12 +157,15 @@ import { ensureProxyEgress, proxyEgressReady } from './lib/vm/egress.mjs' import { syncIpv6ProxyEgress } from './lib/vm/proxy-policy-runtime.mjs' import { GATEWAY_CAPABILITIES } from './lib/vm/execution-context.mjs' import { isTelemetryPath, telemetryInterceptResponse } from './lib/identity/telemetry-rewrite.mjs' -import { openDatabaseAsync, closeDatabaseAsync, getDb, getDbEngine, getPgPool } from './lib/db/database.mjs' +import { openDatabaseAsync, closeDatabaseAsync, getDb, getDbEngine, getPgPool, isDbOpen } from './lib/db/database.mjs' import { startDashboardAggregator, stopDashboardAggregator } from './lib/db/pg/dashboard-aggregator.mjs' import { startPgLogWriter, stopPgLogWriter } from './lib/db/pg/pg-log-writer.mjs' -import { closeCacheRuntime, snapshotCacheMetrics } from './lib/cache/index.mjs' +import { closeCacheRuntime, getCacheRuntime, snapshotCacheMetrics } from './lib/cache/index.mjs' import { armWriteBehind, flushWrites } from './lib/db/write-behind.mjs' +import { DISTILL_RULES_SETTING, loadDistillRulesFromSettings } from './lib/core/distill-detect.mjs' import { JevUsageRepo } from './lib/db/repos/jev-usage-repo.mjs' +import { RefusalDeviceBlocksRepo } from './lib/db/repos/refusal-device-blocks-repo.mjs' +import { RefusalGuardsRepo } from './lib/db/repos/refusal-guards-repo.mjs' import { installJevUsageRecorder } from './lib/protocol/jev-usage.mjs' import { jevHealthSnapshot, readJevConfig } from './lib/protocol/jev-intercept.mjs' import { runLegacyImport } from './lib/db/legacy-import.mjs' @@ -401,7 +404,82 @@ if (getDbEngine() === 'postgres' && getPgPool()) { startPgLogWriter(getPgPool()) } const jevUsageRepo = new JevUsageRepo() +const refusalDeviceBlocksRepo = new RefusalDeviceBlocksRepo() +const refusalGuardsRepo = new RefusalGuardsRepo() installJevUsageRecorder((event) => jevUsageRepo.record(event)) +const distillRulesFile = path.join(cfg.paths.root, 'config', 'distill-rules.json') +try { + cfg.distill = await loadDistillRulesFromSettings(getDb(), getCacheRuntime(), { file: distillRulesFile }) +} catch (e) { + console.warn('[distill] boot load from settings failed', e?.message || e) +} +let refreshingDistill = false +let pendingDistillRefresh = false +const refreshDistillFromSettings = async () => { + if (refreshingDistill) { + pendingDistillRefresh = true + return + } + refreshingDistill = true + try { + do { + pendingDistillRefresh = false + if (!isDbOpen()) break + cfg.distill = await loadDistillRulesFromSettings(getDb(), getCacheRuntime(), { file: distillRulesFile }) + } while (pendingDistillRefresh) + } catch (e) { + console.warn('[distill] settings sync refresh failed', e?.message || e) + } finally { + refreshingDistill = false + } +} +const unsubDistillInvalidation = getCacheRuntime().client.onInvalidate((payload) => { + const keys = Array.isArray(payload?.keys) ? payload.keys : [] + const prefixes = Array.isArray(payload?.prefixes) ? payload.prefixes : [] + const hitsDistillKey = keys.some( + (k) => + k === `entity:setting:${DISTILL_RULES_SETTING}` || + (k.startsWith('entity:setting:') && k.endsWith(`:${DISTILL_RULES_SETTING}`)), + ) + const hitsSettingsPrefix = prefixes.some( + (p) => p === 'entity:' || p === 'entity:setting:' || 'entity:setting:'.startsWith(p), + ) + if (hitsDistillKey || hitsSettingsPrefix) { + void refreshDistillFromSettings() + } +}) +const RISK_GC_INTERVAL_MS = 10 * 60_000 +let riskGcTimer = null +let riskGcRunning = false +function stopRiskGcTimer() { + if (riskGcTimer) { + clearInterval(riskGcTimer) + riskGcTimer = null + } +} +async function runRiskBoundedGc() { + if (riskGcRunning || !isDbOpen()) return + riskGcRunning = true + try { + try { + await refusalDeviceBlocksRepo.pruneExpired() + } catch (e) { + console.warn('[risk-gc] refusal_device_blocks prune failed:', e?.message || e) + } + try { + await refusalGuardsRepo.pruneExpired() + } catch (e) { + console.warn('[risk-gc] refusal_guards prune failed:', e?.message || e) + } + try { + await jevUsageRepo.pruneOldEvents() + } catch (e) { + console.warn('[risk-gc] jev_usage_events prune failed:', e?.message || e) + } + } finally { + riskGcRunning = false + } +} try { loadModelPolicy() } catch (e) { @@ -2082,6 +2160,10 @@ const gracefulShutdown = createGracefulShutdown({ stopLeaderJobs() }, afterDrain: async () => { + stopRiskGcTimer() + try { + unsubDistillInvalidation?.() + } catch {} foreignLoadWriter?.stop() // Let host cleanup finish without extending shutdown to the launch deadline. await Promise.race([geminiTerminalDrain, delay(2000, undefined, { ref: false })]) @@ -2121,6 +2203,12 @@ const gracefulShutdown = createGracefulShutdown({ } catch (e) { console.warn('[shutdown] api-key usage flush failed', e?.message || e) } + try { + installJevUsageRecorder(null) + await jevUsageRepo.close() + } catch (e) { + console.warn('[shutdown] jev-usage flush failed', e?.message || e) + } try { await stopPgLogWriter() } catch (e) { @@ -2830,6 +2918,14 @@ server.listen(cfg.port, cfg.host, () => { startDashboardAggregator(getPgPool()) onLeaderStop(() => stopDashboardAggregator()) } + { + stopRiskGcTimer() + riskGcTimer = setInterval(() => { + void runRiskBoundedGc() + }, RISK_GC_INTERVAL_MS) + riskGcTimer.unref?.() + onLeaderStop(stopRiskGcTimer) + } if (process.env.KIN_CRS_MOCK !== '1') { void cragSubscription.recover().catch(() => { console.warn('[crag-subscription] startup recovery failed; use the administrator panel to retry') diff --git a/test/unit/panel-redis-opt.test.mjs b/test/unit/panel-redis-opt.test.mjs index fefac70964..34f1cd1a9f 100644 --- a/test/unit/panel-redis-opt.test.mjs +++ b/test/unit/panel-redis-opt.test.mjs @@ -17,6 +17,7 @@ import { closeDatabase, createDatabase, openDatabase } from '../../src/lib/db/da import { snapshotDatabaseMetricsAsync } from '../../src/lib/db/database-metrics.mjs' import { runDashboardAggregation } from '../../src/lib/db/pg/dashboard-aggregator.mjs' import { AccountRuntimeRepo } from '../../src/lib/db/repos/account-runtime-repo.mjs' +import { SettingsRepo } from '../../src/lib/db/repos/settings-repo.mjs' import { StatisticsRepo } from '../../src/lib/db/repos/statistics-repo.mjs' import { UsageLogsRepo } from '../../src/lib/db/repos/usage-logs-repo.mjs' import { UsersRepo } from '../../src/lib/db/repos/users-repo.mjs' @@ -707,8 +708,10 @@ test('panel-routes & scheduler-pools-routes: ETag/304, single api-keys scan, ten pricing_model: 'claude-opus-4-1', }) + fs.mkdirSync(path.join(dir, 'config'), { recursive: true }) + const panelCfg = { paths: { root: dir, project: dir, data: dir }, limits: { max_body_bytes: 1024 * 1024 } } const handler = createPanelHandler({ - cfg: { paths: { project: dir, data: dir }, limits: { max_body_bytes: 1024 * 1024 } }, + cfg: panelCfg, getDb: () => db, apiKeyStore, panelUsers, @@ -971,6 +974,67 @@ test('panel-routes & scheduler-pools-routes: ETag/304, single api-keys scan, ten assert.equal(delDev.statusCode, 200) assert.equal((await cacheClient.get('risk:bans:device:dev-1')).hit, false) assert.equal((await cacheClient.get('risk:bans:session:sess-2')).hit, false) + + // 8. GET /api/panel/protocol-entry uses protocolEntryStatsAsync + DashboardCache SWR ('panel', 15s/60s) + ETag/304 + refresh=1 bypass + let protoAsyncCalls = 0 + const origProtoAsync = requestLog.protocolEntryStatsAsync.bind(requestLog) + requestLog.protocolEntryStatsAsync = async (opts) => { + protoAsyncCalls += 1 + return origProtoAsync(opts) + } + const protoSwrCalls = [] + const origProtoSwr = dashCache.getOrSetSWR.bind(dashCache) + dashCache.getOrSetSWR = (ns, key, loader, opts) => { + if (key?.ep === 'protocol-entry') protoSwrCalls.push({ ns, opts }) + return origProtoSwr(ns, key, loader, opts) + } + try { + const pe1 = await call('GET', '/api/panel/protocol-entry', { auth: adminAuth }) + assert.equal(pe1.statusCode, 200) + assert.equal(pe1.body.ok, true) + assert.equal(protoAsyncCalls, 1) + assert.equal(protoSwrCalls.length, 1) + assert.equal(protoSwrCalls[0].ns, 'panel') + assert.equal(protoSwrCalls[0].opts.freshTtlMs, 15_000) + assert.equal(protoSwrCalls[0].opts.ttlMs, 60_000) + assert.ok(pe1.getHeader('etag')) + + const pe304 = await call('GET', '/api/panel/protocol-entry', { + auth: adminAuth, + headers: { 'if-none-match': pe1.getHeader('etag') }, + }) + assert.equal(pe304.statusCode, 304) + assert.equal(protoAsyncCalls, 1, 'second protocol-entry call within fresh window must hit SWR cache') + + const peBypass = await call('GET', '/api/panel/protocol-entry?refresh=1', { auth: adminAuth }) + assert.equal(peBypass.statusCode, 200) + assert.equal(protoAsyncCalls, 2, 'refresh=1 must bypass protocol-entry SWR cache') + } finally { + requestLog.protocolEntryStatsAsync = origProtoAsync + dashCache.getOrSetSWR = origProtoSwr + } + + // 9. PUT /api/panel/distill & GET /api/panel/distill persist to DB settings['distill_rules'] SSOT and sync cfg.distill + const putDistill = await call('PUT', '/api/panel/distill', { + auth: adminAuth, + body: { enabled: true, needles: ['panel-ssot-needle-01'] }, + }) + assert.equal(putDistill.statusCode, 200) + assert.equal(putDistill.body.ok, true) + assert.ok(putDistill.body.data.needles.includes('panel-ssot-needle-01')) + assert.ok(panelCfg.distill?.needles?.includes('panel-ssot-needle-01')) + + const storedDistill = new SettingsRepo(db).get('distill_rules') + assert.ok(storedDistill && Array.isArray(storedDistill.needles)) + assert.ok(storedDistill.needles.includes('panel-ssot-needle-01')) + + // Even if local cfg.distill is cleared and local file is removed, GET /api/panel/distill reloads from DB SSOT + panelCfg.distill = null + fs.rmSync(path.join(dir, 'config', 'distill-rules.json'), { force: true }) + const getDistill = await call('GET', '/api/panel/distill', { auth: adminAuth }) + assert.equal(getDistill.statusCode, 200) + assert.ok(getDistill.body.data.needles.includes('panel-ssot-needle-01')) + assert.ok(panelCfg.distill?.needles?.includes('panel-ssot-needle-01')) } finally { closeDatabase() fs.rmSync(dir, { recursive: true, force: true }) diff --git a/test/unit/pg-repos-parity.test.mjs b/test/unit/pg-repos-parity.test.mjs index 328861d434..b747a3019d 100644 --- a/test/unit/pg-repos-parity.test.mjs +++ b/test/unit/pg-repos-parity.test.mjs @@ -85,7 +85,7 @@ function approxEqual(a, b, eps = 1e-6, label = '') { * Execute the full 22-repository scenario against any `db` (SQLite or PgSyncDb) * and return a normalized snapshot of every assertion & query output. */ -function runAll22ReposScenario(db) { +async function runAll22ReposScenario(db, { pgPool = null } = {}) { const now = '2026-06-15T10:00:00.000Z' const oldTs = '2025-01-01T00:00:00.000Z' const snap = {} @@ -528,8 +528,9 @@ function runAll22ReposScenario(db) { nearestScore: near?.score, } - // 16. RefusalDeviceBlocksRepo (exercises BEGIN IMMEDIATE + risk_device_aliases!) + // 16. RefusalDeviceBlocksRepo (exercises BEGIN IMMEDIATE + risk_device_aliases + blockSession permanent protection + expiry GC!) const devBlocks = new RefusalDeviceBlocksRepo(db) + const nowMs = Date.parse(now) const viol = devBlocks.recordViolation( { principal: 'key_p1', deviceId: 'dev-abc', machineId: 'mach-xyz', sessionId: 'sess-ban-1' }, { @@ -537,18 +538,43 @@ function runAll22ReposScenario(db) { fingerprint: 'fp_parity_1', reason: 'policy_violation', steps: [15, 60, 0], - now: Date.parse(now), + now: nowMs, }, ) const foundBan = devBlocks.findBan( { principal: 'key_p1', deviceId: 'dev-abc', machineId: 'mach-xyz', sessionId: 'sess-ban-1' }, - Date.parse(now) + 1000, + nowMs + 1000, ) + // Permanent session ban must never be downgraded to temporary 10m block by blockSession + const permAfterTemp = devBlocks.blockSession( + { principal: 'key_p1', deviceId: 'dev-abc', sessionId: 'sess-ban-1' }, + { requestId: 'req_400_perm', reason: 'upstream_400:unknown', ttlMs: 10 * 60_000, now: nowMs + 2000 }, + ) + // Temporary session ban visible before expiry, filtered out by list/count after expiry, and removed by pruneExpired + devBlocks.blockSession( + { principal: 'key_p1', sessionId: 'sess-temp-exp' }, + { requestId: 'req_400_temp', reason: 'upstream_400:tool_pair_broken', ttlMs: 60_000, now: nowMs }, + ) + const beforeExpIso = new Date(nowMs + 5_000).toISOString() + const afterExpIso = new Date(nowMs + 120_000).toISOString() + const countBeforeExp = devBlocks.count(beforeExpIso) + const listBeforeExpLen = devBlocks.list(200, beforeExpIso).length + const countAfterExp = devBlocks.count(afterExpIso) + const listAfterExpLen = devBlocks.list(200, afterExpIso).length + const prunedDevices = await devBlocks.pruneExpired(afterExpIso, 100) snap.devBlocks = { - count: devBlocks.count(), + count: devBlocks.count(beforeExpIso), violatedKind: viol?.subject_kind, foundBanKind: foundBan?.subject_kind, foundViolations: foundBan?.violations, + permKeptNullExpires: permAfterTemp?.expires_at ?? null, + permKeptReason: permAfterTemp?.reason ?? null, + countBeforeExp, + listBeforeExpLen, + countAfterExp, + listAfterExpLen, + prunedDevices, + permSurvivedPrune: devBlocks.get(permAfterTemp.device_id)?.expires_at === null, } // 17. RefusalSessionBlocksRepo @@ -567,15 +593,16 @@ function runAll22ReposScenario(db) { hits: sessBlocks.get('sess-blocked-1')?.hit_count, } - // 18. JevUsageRepo (exercises ON CONFLICT(period) DO UPDATE SET col=jev_usage_totals.col+excluded.col!) - const jev = new JevUsageRepo(db, { now: () => Date.parse(now) }) + // 18. JevUsageRepo (exercises PG batch UNNEST flush, ON CONFLICT(period) DO UPDATE, tuple cursor list, configuredKeysAsync & pruneOldEvents!) + const jev = new JevUsageRepo(db, { now: () => nowMs, pgPool, batchSize: 10, flushIntervalMs: 60_000 }) + const jevKeyFp = 'aabbccddeeff' jev.record({ - id: 'jev_p1', + id: '11111111-1111-4111-8111-111111111101', created_at: now, request_id: 'req_p1', provider: 'anthropic', model: 'claude-sonnet-4-5', - key_fingerprint: 'kf_parity_1', + key_fingerprint: jevKeyFp, http_status: 200, outcome: 'success', duration_ms: 300, @@ -587,12 +614,12 @@ function runAll22ReposScenario(db) { pricing_basis: 'catalog', }) jev.record({ - id: 'jev_p2', + id: '11111111-1111-4111-8111-111111111102', created_at: now, request_id: 'req_p2', provider: 'anthropic', model: 'claude-sonnet-4-5', - key_fingerprint: 'kf_parity_1', + key_fingerprint: jevKeyFp, http_status: 429, outcome: 'error', duration_ms: 150, @@ -603,13 +630,50 @@ function runAll22ReposScenario(db) { output_nano_usd_per_token: 15000, pricing_basis: 'catalog', }) + jev.record({ + id: '11111111-1111-4111-8111-111111111103', + created_at: oldTs, + request_id: 'req_p_old_jev', + provider: 'anthropic', + model: 'claude-sonnet-4-5', + key_fingerprint: jevKeyFp, + http_status: 200, + outcome: 'success', + duration_ms: 100, + input_tokens: 100, + output_tokens: 50, + estimated_cost_nano_usd: 1_000_000, + input_nano_usd_per_token: 3000, + output_nano_usd_per_token: 15000, + pricing_basis: 'catalog', + }) + await jev.flush() const jevOv = jev.overview() - const jevSt = jev.configuredKeyStatuses([{ key_fingerprint: 'kf_parity_1' }]) + const jevSt = jev.configuredKeyStatuses([{ key_fingerprint: jevKeyFp }]) + const jevPage1 = jev.list({ limit: 1, key_fingerprint: jevKeyFp }) + const jevPage2 = jev.list({ + limit: 10, + cursor_created_at: jevPage1.next_cursor.created_at, + cursor_id: jevPage1.next_cursor.id, + key_fingerprint: jevKeyFp, + }) + const jevCfgSync = jev.configuredKeys([{ key_fingerprint: jevKeyFp }]) + const jevCfgAsync = await jev.configuredKeysAsync([{ key_fingerprint: jevKeyFp }], { bypass: true }) + assert.deepEqual(jevCfgAsync, jevCfgSync, 'JevUsageRepo configuredKeysAsync must match configuredKeys') + const jevPruned = await jev.pruneOldEvents(now) + const jevAfterPrune = jev.list({ limit: 10, key_fingerprint: jevKeyFp }) + await jev.close() snap.jev = { allRequests: jevOv.total.requests, allSuccess: jevOv.total.successful, allCostNano: jevOv.total.estimated_cost_nano_usd, latestStatus: jevSt[0]?.status, + page1Id: jevPage1.rows[0]?.id, + page1HasMore: jevPage1.has_more, + page2Ids: jevPage2.rows.map((r) => r.id), + configuredKeys: jevCfgSync, + prunedEvents: jevPruned.eventsDeleted, + remainingAfterPrune: jevAfterPrune.rows.length, } // 19. BackupRepo @@ -728,9 +792,27 @@ function runAll22ReposScenario(db) { total_cost: 0.004, actual_cost: 0.004, }) + usage.insertSummary({ + request_id: 'req_p_block', + ts: now, + method: 'POST', + path: '/v1/messages', + protocol: 'anthropic', + api_key_id: 'key_p1', + owner_user_id: 'usr_p1', + model: 'claude-sonnet-4-5', + status: 400, + final_state: 'distill_blocked', + error_code: 'distill_blocked', + error_message: 'distill needle hit', + duration_ms: 5, + }) usage.insertDebug('req_p1', now, { request_id: 'req_p1', payload: { msg: 'hello debug' } }) const debugFetched = usage.getDebug('req_p1') const totalsBeforeCleanup = usage.totals() + const protoSync = usage.protocolEntryStats({ since: '2026-06-14T00:00:00.000Z' }) + const protoAsync = await usage.protocolEntryStatsAsync({ since: '2026-06-14T00:00:00.000Z' }) + assert.deepEqual(protoAsync, protoSync, 'UsageLogsRepo protocolEntryStatsAsync must match protocolEntryStats') const aggDay = usage.aggregate({ bucket: 'day' }) const aggHour = usage.aggregate({ bucket: 'hour' }) const qRes = usage.query({ status: 'error', limit: 10 }) @@ -797,6 +879,7 @@ function runAll22ReposScenario(db) { archiveTokens: Number(archiveRow?.total_tokens || 0), archiveCost: Number(Number(archiveRow?.total_cost || 0).toFixed(6)), remainingCount: usage.count(), + protoEntry: protoSync, } // 23. ThinkingOwnerStore (CREATE TABLE BIGINT + json_each + INSERT OR IGNORE + UPDATE refresh) @@ -832,11 +915,11 @@ test('Tier 2: All 22 repositories + ThinkingOwnerStore produce identical behavio // Run on SQLite const sqliteDb = openDatabase({ dataDir: tmpDir, driver: 'sqlite', pooled: false }) - const sqliteSnap = runAll22ReposScenario(sqliteDb) + const sqliteSnap = await runAll22ReposScenario(sqliteDb) closeDatabase() // Run on PostgreSQL - const pgSnap = runAll22ReposScenario(pgSyncDb) + const pgSnap = await runAll22ReposScenario(pgSyncDb, { pgPool }) // Deep-compare every single repository section! assert.deepEqual(pgSnap.settings, sqliteSnap.settings, 'SettingsRepo mismatch') From 9c1eb7fb48320aad51fdf7f5435c006a95961c93 Mon Sep 17 00:00:00 2001 From: dofastted Date: Tue, 1 Dec 2026 21:16:20 +0800 Subject: [PATCH 14/15] chore(risk,pg): finish cross-branch consolidation for async refusal-guards SWR, ban hooks, stats cleanup, and docs --- docs/PANEL_API.md | 13 ++-- docs/RISK.md | 4 +- src/lib/admin/panel-routes.mjs | 69 +++++++++++++------ .../db/repos/refusal-device-blocks-repo.mjs | 30 ++++++++ src/lib/db/repos/refusal-guards-repo.mjs | 32 +++++++++ .../db/repos/refusal-session-blocks-repo.mjs | 22 ++++++ src/lib/protocol/intercept-gate.mjs | 4 +- test/unit/panel-redis-opt.test.mjs | 65 +++++++++++++++++ test/unit/usage-logs-repo.test.mjs | 9 +-- 9 files changed, 211 insertions(+), 37 deletions(-) diff --git a/docs/PANEL_API.md b/docs/PANEL_API.md index b1202f280a..870f06a18c 100644 --- a/docs/PANEL_API.md +++ b/docs/PANEL_API.md @@ -452,28 +452,29 @@ Claude `routing.quota` 的 5h/7d 闸分三段(`critical_band` 默认 0.05,`g | 方法 | 路径 | 说明 | |------|------|------| -| GET/PUT | `/distill` | 协议入口蒸馏拦截。命中后返回 `error` 里配置的状态、code 和文案,不 hop 凭证 | +| GET/PUT | `/distill` | 协议入口蒸馏拦截。以数据库 `settings['distill_rules']` 为 SSOT(启动及跨实例缓存失效时热加载,本地 `src/config/distill-rules.json` 作为兼容回退与同步副本)。命中后默认返回不可重试的 HTTP 400 `policy_blocked`(`code=distill_blocked`,支持在 `error` 里显式覆盖状态码、type、code 与文案),不 hop 凭证 | -`PUT` 热更新 `src/config/distill-rules.json`。字段:`enabled`、`skip_official`(官方 Claude Code 放行普通针、指纹和结构)、`skip_zero`(`persona_preset/inject=zero` 放行这些)、`error.{status,type,code,message}`、`hard_needles[]`(收割包装:官方和 0 注入也拦;面板删掉即停,不会补回)、`needles[]`、`patterns[]`(附加正则,官方和 0 注入也拦)、`fingerprints[]`、`structure.{min_max_tokens,require_no_tools,require_single_turn,contest_pattern}`。`contest_pattern` 为空则不做赛题结构收割。思考预算是否算收割,用的是同一个 `min_max_tokens`,不是写死的 8192。确定性蒸馏短语在硬正则的 distill 类别里,不在这里补回。**不含**单独的 `Persistable response items`(普通 agent 信封)。仅 admin。 +`PUT` 写入数据库 `settings['distill_rules']`(并同步回写 `src/config/distill-rules.json` 与广播缓存失效)。字段:`enabled`、`skip_official`(官方 Claude Code 放行普通针、指纹和结构)、`skip_zero`(`persona_preset/inject=zero` 放行这些)、`error.{status,type,code,message}`、`hard_needles[]`(收割包装:官方和 0 注入也拦;面板删掉即停,不会补回)、`needles[]`、`patterns[]`(附加正则,官方和 0 注入也拦)、`fingerprints[]`、`structure.{min_max_tokens,require_no_tools,require_single_turn,contest_pattern}`。`contest_pattern` 为空则不做赛题结构收割。思考预算是否算收割,用的是同一个 `min_max_tokens`,不是写死的 8192。确定性蒸馏短语在硬正则的 distill 类别里,不在这里补回。**不含**单独的 `Persistable response items`(普通 agent 信封)。仅 admin。 ## 拒答缓存 | 方法 | 路径 | 说明 | |------|------|------| -| GET/PUT | `/refusal-guards` | 精确指纹,以及可选的用户正文近似(`similarity_enabled`,`similarity` 为 80/85/90/95,默认开、90)。命中 HTTP 400 `policy_blocked`,`code=refusal_guard`,不 hop。相似度只比用户正文。`device_block_enabled` 默认开:命中后按 `risk_audit.ban_steps` 封禁阶梯(默认 `[10, 10, 0]`,即第 1 次 10 分钟、第 2 次 10 分钟、第 3 次永久,非递减)封禁入站设备。`session_block_enabled` 默认开(独立于 `enabled`),控制根会话封锁与会话级临时/永久封禁。`risk_audit` 包含 `ban_steps`、`blocked_tools`、`block_system_prompt_rewrite`、`upstream_policy_phrases`、`downgrade_pool`、`downgrade_endpoint`、`downgrade_model`、`route_margin`、`model_margin`。响应带 `count`、`items`、`device_count`、`devices`、`session_count`、`sessions` | +| GET/PUT | `/refusal-guards` | 精确指纹,以及可选的用户正文近似(`similarity_enabled`,`similarity` 为 80/85/90/95,默认开、90)。命中 HTTP 400 `policy_blocked`,`code=refusal_guard`,不 hop。相似度只比用户正文。`device_block_enabled` 默认开:命中后按 `risk_audit.ban_steps` 封禁阶梯(默认 `[10, 10, 0]`,即第 1 次 10 分钟、第 2 次 10 分钟、第 3 次永久,非递减)封禁入站设备。`session_block_enabled` 默认开(独立于 `enabled`),控制根会话封锁与会话级临时/永久封禁。`risk_audit` 包含 `ban_steps`、`blocked_tools`、`block_system_prompt_rewrite`、`upstream_policy_phrases`、`downgrade_pool`、`downgrade_endpoint`、`downgrade_model`、`route_margin`、`model_margin`、`commercial_400_notice_enabled` 及会话封禁文案预设配置。响应带 `count`、`items`、`device_count`、`devices`、`session_count`、`sessions`(列表与计数均在 SQL 层自动过滤已过期项;`GET` 走短 TTL SWR 缓存与 ETag/304,支持 `?refresh=1` 旁路缓存) | | DELETE | `/refusal-guards/:fingerprint` | 删除一条 64 位 hex 指纹 | | DELETE | `/refusal-guards` | 须 `{ "confirm": true }` 清空 | -| DELETE | `/refusal-session-blocks` | `{ "session_id" }` 解封一条全局根会话封锁;`{ "confirm": true }` 清空 `refusal_session_blocks`(仅操作根会话封锁表,不删除 `refusal_device_blocks` 中租户隔离的会话记录) | +| DELETE | `/refusal-session-blocks` | **双表对称解封**:`{ "session_id" }` 同时移除 `refusal_session_blocks` 中的全局根会话封锁与 `refusal_device_blocks` 中 `subject_kind='session'` 的租户隔离会话记录(不伤及同设备 `subject_kind='device'` 封禁);`{ "confirm": true }` 清空 `refusal_session_blocks` 及 `refusal_device_blocks` 中全部 `subject_kind='session'` 记录 | | DELETE | `/refusal-device-blocks` | `{ "device_id" }` 按记录键(含租户隔离哈希键)解封单条设备或会话封禁(若该记录为会话封禁且关联 `session_id`,会同步移除对应根会话封锁);`{ "confirm": true }` **级联清空** `refusal_device_blocks` 与 `refusal_session_blocks`(包含所有设备封禁与根会话封锁)。空 device、短于 8 字符的值不会入库 | -`PUT { enabled }` 写入 SQLite `settings.refusal_guard_enabled`;同接口支持更新 `similarity_enabled`、`similarity`、`device_block_enabled`、`session_block_enabled` 与 `risk_audit`。环境变量 `REFUSAL_GUARD=0` 仍强制关闭拒答缓存。与蒸馏拦截独立:0 注入跳过普通蒸馏针,本缓存仍生效。`count_tokens` 同样在 peek / worker hop 之前拦截。device 取入站 `metadata.user_id.device_id`,否则显式 `device_id` / `x-kin-device-id`,不用 IP、UA 或 API key。仅 admin。 +`PUT { enabled }` 写入数据库 `settings.refusal_guard_enabled`;同接口支持更新 `similarity_enabled`、`similarity`、`device_block_enabled`、`session_block_enabled` 与 `risk_audit`。环境变量 `REFUSAL_GUARD=0` 仍强制关闭拒答缓存。与蒸馏拦截独立:0 注入跳过普通蒸馏针,本缓存仍生效。`count_tokens` 同样在 peek / worker hop 之前拦截。device 取入站 `metadata.user_id.device_id`,否则显式 `device_id` / `x-kin-device-id`,不用 IP、UA 或 API key。仅 admin。 ## 决策模型与硬正则 | 方法 | 路径 | 说明 | |------|------|------| | GET/PUT | `/jev-intercept` | 协议入口。前置顺序:会话/设备封禁 → 禁用工具 → 系统提示词改写 → 蒸馏 → 去掉 reminder、按需展开 base64 后的硬正则 → 拒答缓存 → JEV 决策模型。没配地址则跳过模型;模型失败默认放行。`fail_open: false` 时模型不可用返回 503(`overloaded_error` / `policy_blocked`),不封设备 | -| GET | `/jev-usage` | 仅 admin。返回 JEV 调用总览(`started_at`、`day`、`timezone`、`total`、`today`、`detail_retention_days: 30`)、分页事件 `rows`(支持 `limit`、`cursor_created_at`、`cursor_id`、`key_fingerprint`)、`has_more`、`next_cursor`、`keys` 与 `storage_errors_since_start` | +| GET | `/protocol-entry` | 今日协议关卡拦截、放行与降级路线统计(单扫聚合 + SWR 缓存 + ETag/304,支持 `?refresh=1` 旁路缓存) | +| GET | `/jev-usage` | 仅 admin。返回 JEV 调用总览(`started_at`、`day`、`timezone`、`total`、`today`、`detail_retention_days: 30`)、分页事件 `rows`(支持 `limit`、`cursor_created_at`、`cursor_id`、`key_fingerprint`)、`has_more`、`next_cursor`、`keys` 与 `storage_errors_since_start`(支持 `?refresh=1` 旁路密钥用量聚合缓存) | | POST | `/jev-intercept/resume` | 仅 admin。手动恢复暂停或冷却中的 JEV 密钥(`{ "key_fingerprint"?: "<12位hex>" }`,省略则恢复全部,无需重新保存密钥列表),返回 `{ resumed, keys }` | `PUT` 写入 SQLite `settings.jev_intercept`。字段:`enabled`(默认关)、`hard_regex_enabled`(默认开)、`openai_platform_enabled`(默认关)、`provider`(`jev` 默认、`laya`、`modernbert`)、`base_url`、`model`、`timeout_ms`(200–8000,默认 4000)、`patterns[]`、`rules`(逐条编辑/禁用/删除硬正则规则;`null` 与空数组 `[]` 回退内置规则;关掉整层用 `hard_regex_enabled: false`)、`api_key` 或 `api_keys`(最多 999 把)、`question_ids`(题库 id,缺省为全部)。省略密钥保持原值;`api_key: ""` 或 `api_keys: []` 清除。一行可以是裸 key(用 `base_url`),或 `https://host/v1/systemone ` 打到另一个 systemone。`401` 永久暂停该 key(可调用 `POST /jev-intercept/resume` 或重新保存密钥恢复);`429` / `529` 触发自动指数退避冷却(`30s / 60s / 120s / 300s`,冷却期满自动恢复,也可调用 `POST /jev-intercept/resume` 提前恢复)。网络错误和其它 HTTP 状态只跳过这一跳的同一主机,不暂停 key;失败放行的原因写在放行 keyword(`网络异常` 或 `上游 `)。另有 `safety_instruction`(空则不加自定义题)、`safety_threshold`(0–1,默认 0.5)、`block_if_below`(默认开)、`fail_open`(默认开)、`dedup_sec`(0–3600,默认 60)、`max_state_chars`(256–64000,默认 16000)、`expand_base64`、`strip_reminders`(后两个默认开)。GET 不回密钥,回 `api_key_set`、`api_key_count`、`question_bank`、`providers`、`builtin_rules`、`rules`、`rules_customized`、`openai_platform_enabled`。 diff --git a/docs/RISK.md b/docs/RISK.md index 58f2ec304e..d1e3133d84 100644 --- a/docs/RISK.md +++ b/docs/RISK.md @@ -13,7 +13,7 @@ 2. 在启用范围内依次执行**蒸馏**和**硬正则**规则。它们仍使用已经配置的开关、例外和规则;蒸馏默认返回不可重试 400 `policy_blocked`(仍支持在配置中自定义状态码与文案),思考泄露类蒸馏硬正则仅封锁当前会话 10 分钟(不封设备);普通硬正则统一返回不可重试 400 `policy_blocked`,只拒绝本次请求,不封设备、不封会话(与改写规则同一理由:正常文档会引用 `keygen` 这类子命令名,真实越狱仍会被上游拒绝并进入拒答缓存);NSFW 类别证据确凿,维持强制阶梯封禁。JEV 不参与这些硬规则。 3. 检查**拒答缓存**(精确指纹与可选的用户正文近似匹配)。命中返回不可自动重试的 400 `refusal_guard`,不调用 JEV 或推理上游。 4. 通过硬规则与拒答缓存后进入 **JEV** 决策模型(内置四题:`usage_policy`、`nsfw`、`abuse`、`distill`)。JEV 只收到用户会话和可解析的内联文件文本,包括纯文本和 UTF-8 base64 文本。不发 system/developer、助手历史、工具声明、调用、返回、环境或二进制文件;不按 URL 或文件 ID 拉取。最近的用户输入在截断窗口内优先保留。审核服务不可用时沿用失败放行开关;关闭时返回 503,不计违规。 -5. 上游明确出现 Usage Policy、内容拒答或已配置的策略短语时,写入拒答缓存,供下次前置拦截。带附件的请求仅做精确匹配,指纹包含附件,避免把不同文件的同一句问法一起拦下。明确标记会话时封会话,不把当时可能无害的正文加入全局指纹库。普通 `api_error`、400 参数错误、认证和限流不计入设备违规,也不污染全局拒答指纹。 +5. 上游明确出现 Usage Policy、内容拒答或已配置的策略短语时,写入拒答缓存,供下次前置拦截。带附件的请求仅做精确匹配,指纹包含附件(Gemini 原生协议同步提取 `contents`、`systemInstruction` 与 `inlineData`/`fileData` 附件),避免把不同文件的同一句问法一起拦下或产生空指纹误撞。明确标记会话时封会话,不把当时可能无害的正文加入全局指纹库。普通 `api_error`、400 参数错误、认证和限流不计入设备违规,也不污染全局拒答指纹。 6. **上游 HTTP 400 细粒度分类与 10 分钟会话封锁**:请求在完成重试/修复后若仍以真实上游 400 结束,网关统一经 `classifyUpstream400` 清洗分类(仅在「封锁拒答会话」开启时执行,默认开,不受拒答缓存总开关与设备封禁开关影响,绝不降级已有永久会话封禁): - **清洗排除(不封会话,`upstream_400_action=skipped`)**:`account_disabled`(上游账号/组织禁用、地区受限)、`auth_credential`(凭据刷新失败/令牌撤销/鉴权失效)、`billing_credit`(上游账号余额/额度/Extra Usage 不足)、`model_unavailable`(模型不存在/下线/无权限)、`gateway_local`(网关/Kernel/License/分类器本地拒绝)、`auto_mode_classifier`(Claude Code 自动模式分类器侧请求)。 - **会话封锁 10 分钟(`upstream_400:`,`upstream_400_action=session_10m`)**:`policy_refusal`(降级/未开永久封禁时的策略拒答)、`third_party_client`(第三方客户端 Extra Usage 拒绝)、`context_too_long`(上下文/Token 超限)、`tool_pair_broken`(工具调用与返回配对损坏)、`thinking_history_broken`(Thinking/Reasoning 签名或块损坏)、`search_or_cache_invalid`(搜索加密块或 `cache_control` 非法)、`media_invalid`(图片/PDF/文档超限或损坏)、`message_structure_invalid`(角色顺序错乱或空消息)、`tool_schema_invalid`(工具 Schema/参数校验失败)、`state_reference_invalid`(失效的 `previous_response_id`/会话引用)、`beta_or_header_invalid`(非法 Beta 头或采样参数)以及通过上述排除项后的兜底 `unknown`。封锁期内同一租户下的同会话(含子 agent)前置拦截直接返回不可重试 400(带 `x-should-retry: false`)并递增 `hit_count`,不伤及同设备其他会话。 @@ -40,7 +40,7 @@ | 路线降级 | ≤ 0.15 | OAuth 限于指定账号池与原授权的交集;API 限于指定同平台渠道 | | 常规放行 | 其余 | 保留原模型和调度 | -阈值可配置,先检查模型降级,再检查路线降级。选择器从现有账号池、API 渠道和模型目录读取:每种目标独立选择一项,无需手填 ID。空目标跳过对应降级;选中但目标不可用时返回 503,不回退原路线。无有效分数、未审核或失败放行不触发降级。 +阈值可配置,先检查模型降级,再检查路线降级。选择器统一从 `/api/panel/pools`(支持自定义分组池 ID)、API 渠道和模型目录读取:每种目标独立选择一项,无需手填 ID。空目标跳过对应降级;选中但目标不可用时返回 503,不回退原路线。无有效分数、未审核或失败放行不触发降级。 ## 查证据 diff --git a/src/lib/admin/panel-routes.mjs b/src/lib/admin/panel-routes.mjs index 079824ede8..04013ba6a3 100644 --- a/src/lib/admin/panel-routes.mjs +++ b/src/lib/admin/panel-routes.mjs @@ -38,10 +38,10 @@ import { } from '../core/distill-detect.mjs' import { applyRefusalGuardPatch, - refusalGuardPolicy, SESSION_BLOCK_COPY_PRESETS, SESSION_BLOCK_COPY_SCENARIOS, } from '../core/refusal-guard.mjs' +import { readRuntimeRefusalPolicyAsync } from '../protocol/unified-pre-dispatch.mjs' import { applyJevPatch, buildScopeInventory, @@ -1361,22 +1361,32 @@ export function createPanelHandler(ctx) { return cfg.distill } - function refusalGuardSnapshot() { - const settings = new SettingsRepo() - const repo = new RefusalGuardsRepo() - const devices = new RefusalDeviceBlocksRepo() - const sessions = new RefusalSessionBlocksRepo() - const read = (key, fallback) => settings.get(key, fallback) + async function refusalGuardSnapshotAsync({ bypassSettings = false } = {}) { + const db = resolvePanelDb() + const repo = new RefusalGuardsRepo(db) + const devices = new RefusalDeviceBlocksRepo(db) + const sessions = new RefusalSessionBlocksRepo(db) + const nowIso = new Date().toISOString() + const policyOpts = bypassSettings ? { db, cache: { client: { enabled: false } } } : { db } + const [policy, count, items, deviceCount, deviceList, sessionCount, sessionList] = await Promise.all([ + readRuntimeRefusalPolicyAsync(null, policyOpts), + repo.countAsync(nowIso), + repo.listAsync(200, nowIso), + devices.countAsync(nowIso), + devices.listAsync(200, nowIso), + sessions.countAsync(), + sessions.listAsync(200), + ]) return { - ...refusalGuardPolicy(read), + ...policy, session_block_copy_presets: SESSION_BLOCK_COPY_PRESETS, session_block_copy_scenarios: SESSION_BLOCK_COPY_SCENARIOS, - count: repo.count(), - items: repo.list(), - device_count: devices.count(), - devices: devices.list(), - session_count: sessions.count(), - sessions: sessions.list(), + count, + items, + device_count: deviceCount, + devices: deviceList, + session_count: sessionCount, + sessions: sessionList, } } @@ -8623,7 +8633,22 @@ export function createPanelHandler(ctx) { return json(res, 200, panel.ok(cfg.distill)) } if (req.method === 'GET' && p === '/api/panel/refusal-guards') { - return json(res, 200, panel.ok(refusalGuardSnapshot())) + const bypass = url.searchParams.get('refresh') === '1' + const load = async () => panel.ok(await refusalGuardSnapshotAsync({ bypassSettings: bypass })) + let dashboard = null + try { + dashboard = getCacheRuntime()?.dashboard || null + } catch {} + const payload = + dashboard && typeof dashboard.getOrSetSWR === 'function' + ? await dashboard.getOrSetSWR( + 'panel', + { ep: 'refusal-guards', scope: cacheScopeOf(resolvePanelDb()) }, + load, + { freshTtlMs: 10_000, ttlMs: 30_000, bypass }, + ) + : await load() + return sendCachedJson(req, res, 200, payload) } if (req.method === 'PUT' && p === '/api/panel/refusal-guards') { const body = await readBody(req, 8 * 1024).catch(() => ({})) @@ -8638,7 +8663,7 @@ export function createPanelHandler(ctx) { }, }) } - return json(res, 200, panel.ok(refusalGuardSnapshot())) + return json(res, 200, panel.ok(await refusalGuardSnapshotAsync({ bypassSettings: true }))) } if (req.method === 'DELETE' && /^\/api\/panel\/refusal-guards\/[0-9a-f]{64}$/i.test(p)) { const fp = p.split('/').pop() @@ -8649,7 +8674,7 @@ export function createPanelHandler(ctx) { error: { type: 'not_found_error', code: 'refusal_guard_not_found', message: '指纹不存在' }, }) } - return json(res, 200, panel.ok(refusalGuardSnapshot())) + return json(res, 200, panel.ok(await refusalGuardSnapshotAsync({ bypassSettings: true }))) } if (req.method === 'DELETE' && p === '/api/panel/refusal-guards') { const body = await readBody(req, 8 * 1024).catch(() => ({})) @@ -8664,7 +8689,7 @@ export function createPanelHandler(ctx) { }) } new RefusalGuardsRepo().clear() - return json(res, 200, panel.ok(refusalGuardSnapshot())) + return json(res, 200, panel.ok(await refusalGuardSnapshotAsync({ bypassSettings: true }))) } if (req.method === 'DELETE' && p === '/api/panel/refusal-session-blocks') { const body = await readBody(req, 8 * 1024).catch(() => ({})) @@ -8680,7 +8705,7 @@ export function createPanelHandler(ctx) { error: { type: 'not_found_error', code: 'refusal_session_not_found', message: '会话不存在' }, }) } - return json(res, 200, panel.ok(refusalGuardSnapshot())) + return json(res, 200, panel.ok(await refusalGuardSnapshotAsync({ bypassSettings: true }))) } if (body?.confirm !== true) { return json(res, 400, { @@ -8694,7 +8719,7 @@ export function createPanelHandler(ctx) { } repo.clear() devicesRepo.clearSessions() - return json(res, 200, panel.ok(refusalGuardSnapshot())) + return json(res, 200, panel.ok(await refusalGuardSnapshotAsync({ bypassSettings: true }))) } if (req.method === 'DELETE' && p === '/api/panel/refusal-device-blocks') { const body = await readBody(req, 8 * 1024).catch(() => ({})) @@ -8716,7 +8741,7 @@ export function createPanelHandler(ctx) { if (existing?.subject_kind === 'session' && existing.session_id) { sessionsRepo.remove(existing.session_id) } - return json(res, 200, panel.ok(refusalGuardSnapshot())) + return json(res, 200, panel.ok(await refusalGuardSnapshotAsync({ bypassSettings: true }))) } if (body?.confirm !== true) { return json(res, 400, { @@ -8730,7 +8755,7 @@ export function createPanelHandler(ctx) { } repo.clear() sessionsRepo.clear() - return json(res, 200, panel.ok(refusalGuardSnapshot())) + return json(res, 200, panel.ok(await refusalGuardSnapshotAsync({ bypassSettings: true }))) } if (req.method === 'GET' && p === '/api/panel/protocol-entry') { const bypass = url.searchParams.get('refresh') === '1' diff --git a/src/lib/db/repos/refusal-device-blocks-repo.mjs b/src/lib/db/repos/refusal-device-blocks-repo.mjs index b0dbb876c8..52cb063064 100644 --- a/src/lib/db/repos/refusal-device-blocks-repo.mjs +++ b/src/lib/db/repos/refusal-device-blocks-repo.mjs @@ -372,10 +372,40 @@ export class RefusalDeviceBlocksRepo { return this._list.all(normalizeNowIso(nowIso), n).map(rowToRec) } + async listAsync(limit = 200, nowIso = new Date().toISOString()) { + const n = Math.min(500, Math.max(1, Number(limit) || 200)) + const cutoff = normalizeNowIso(nowIso) + const pool = this._resolvePgPool() + if (pool) { + const res = await pool.query( + `SELECT * FROM refusal_device_blocks + WHERE expires_at IS NULL OR expires_at > $1 + ORDER BY last_seen_at DESC, device_id + LIMIT $2`, + [cutoff, n], + ) + return (res?.rows || []).map(rowToRec) + } + return this.list(n, cutoff) + } + count(nowIso = new Date().toISOString()) { return Number(this._count.get(normalizeNowIso(nowIso))?.n) || 0 } + async countAsync(nowIso = new Date().toISOString()) { + const cutoff = normalizeNowIso(nowIso) + const pool = this._resolvePgPool() + if (pool) { + const res = await pool.query( + 'SELECT COUNT(*) AS n FROM refusal_device_blocks WHERE expires_at IS NULL OR expires_at > $1', + [cutoff], + ) + return Number(res?.rows?.[0]?.n) || 0 + } + return this.count(cutoff) + } + /** Bounded batch GC for expired temporary device/session bans. */ async pruneExpired(nowIso = new Date().toISOString(), limit = 500) { const n = Math.min(5000, Math.max(1, Math.floor(Number(limit) || 500))) diff --git a/src/lib/db/repos/refusal-guards-repo.mjs b/src/lib/db/repos/refusal-guards-repo.mjs index e49bc3a251..b30a45c585 100644 --- a/src/lib/db/repos/refusal-guards-repo.mjs +++ b/src/lib/db/repos/refusal-guards-repo.mjs @@ -365,10 +365,42 @@ export class RefusalGuardsRepo { return this._list.all(normalizeNowIso(nowIso), n).map(rowToRec) } + async listAsync(limit = 200, nowIso = new Date().toISOString()) { + const n = Math.min(500, Math.max(1, Number(limit) || 200)) + const cutoff = normalizeNowIso(nowIso) + const pool = this._resolvePgPool() + if (pool) { + const res = await pool.query( + `SELECT fingerprint, model, first_seen_at, last_seen_at, hit_count, + source_request_id, error_message, preview, expires_at + FROM refusal_guards + WHERE expires_at IS NULL OR expires_at > $1 + ORDER BY last_seen_at DESC, fingerprint + LIMIT $2`, + [cutoff, n], + ) + return (res?.rows || []).map(rowToRec) + } + return this.list(n, cutoff) + } + count(nowIso = new Date().toISOString()) { return Number(this._count.get(normalizeNowIso(nowIso))?.n) || 0 } + async countAsync(nowIso = new Date().toISOString()) { + const cutoff = normalizeNowIso(nowIso) + const pool = this._resolvePgPool() + if (pool) { + const res = await pool.query( + 'SELECT COUNT(*) AS n FROM refusal_guards WHERE expires_at IS NULL OR expires_at > $1', + [cutoff], + ) + return Number(res?.rows?.[0]?.n) || 0 + } + return this.count(cutoff) + } + /** Bounded batch GC for expired refusal guards. */ async pruneExpired(nowIso = new Date().toISOString(), limit = 500) { const n = Math.min(5000, Math.max(1, Math.floor(Number(limit) || 500))) diff --git a/src/lib/db/repos/refusal-session-blocks-repo.mjs b/src/lib/db/repos/refusal-session-blocks-repo.mjs index f2626d6eaa..cad420cdd2 100644 --- a/src/lib/db/repos/refusal-session-blocks-repo.mjs +++ b/src/lib/db/repos/refusal-session-blocks-repo.mjs @@ -116,10 +116,32 @@ export class RefusalSessionBlocksRepo { return this._list.all(n).map(rowToRec) } + async listAsync(limit = 200) { + const n = Math.min(500, Math.max(1, Number(limit) || 200)) + const pool = this._resolvePgPool() + if (pool) { + const res = await pool.query( + 'SELECT * FROM refusal_session_blocks ORDER BY last_seen_at DESC, session_id LIMIT $1', + [n], + ) + return (res?.rows || []).map(rowToRec) + } + return this.list(n) + } + count() { return Number(this._count.get()?.n) || 0 } + async countAsync() { + const pool = this._resolvePgPool() + if (pool) { + const res = await pool.query('SELECT COUNT(*) AS n FROM refusal_session_blocks') + return Number(res?.rows?.[0]?.n) || 0 + } + return this.count() + } + remove(sessionId) { const id = String(sessionId || '').trim() if (!id) return false diff --git a/src/lib/protocol/intercept-gate.mjs b/src/lib/protocol/intercept-gate.mjs index dba17ccb45..5cd15d6820 100644 --- a/src/lib/protocol/intercept-gate.mjs +++ b/src/lib/protocol/intercept-gate.mjs @@ -469,7 +469,9 @@ export function invalidateRiskBanCache(opts = {}) { function attachBanRepoInvalidationHooks(repo, kind) { if (!repo || !repo.db) return const methods = - kind === 'session' ? ['block', 'remove', 'clear'] : ['block', 'blockSession', 'recordViolation', 'remove', 'clear'] + kind === 'session' + ? ['block', 'remove', 'clear'] + : ['block', 'blockSession', 'recordViolation', 'remove', 'removeSessionByValue', 'clear', 'clearSessions'] const proto = Object.getPrototypeOf(repo) if (proto && proto !== Object.prototype) { if (wrappedBanProtos.has(proto)) return diff --git a/test/unit/panel-redis-opt.test.mjs b/test/unit/panel-redis-opt.test.mjs index 34f1cd1a9f..0834e740d4 100644 --- a/test/unit/panel-redis-opt.test.mjs +++ b/test/unit/panel-redis-opt.test.mjs @@ -1035,6 +1035,71 @@ test('panel-routes & scheduler-pools-routes: ETag/304, single api-keys scan, ten assert.equal(getDistill.statusCode, 200) assert.ok(getDistill.body.data.needles.includes('panel-ssot-needle-01')) assert.ok(panelCfg.distill?.needles?.includes('panel-ssot-needle-01')) + + // 10. GET /api/panel/refusal-guards uses DashboardCache SWR ('panel', 10s/30s) + ETag/304 + refresh=1 bypass + mutation invalidation + const rgSwrCalls = [] + let rgLoaderRuns = 0 + const origRgSwr = dashCache.getOrSetSWR.bind(dashCache) + dashCache.getOrSetSWR = (ns, key, loader, opts) => { + if (key?.ep === 'refusal-guards') { + rgSwrCalls.push({ ns, opts }) + return origRgSwr( + ns, + key, + async () => { + rgLoaderRuns += 1 + return loader() + }, + opts, + ) + } + return origRgSwr(ns, key, loader, opts) + } + try { + const rg1 = await call('GET', '/api/panel/refusal-guards', { auth: adminAuth }) + assert.equal(rg1.statusCode, 200) + assert.equal(rg1.body.ok, true) + assert.equal(rgLoaderRuns, 1) + assert.equal(rgSwrCalls.length, 1) + assert.equal(rgSwrCalls[0].ns, 'panel') + assert.equal(rgSwrCalls[0].opts.freshTtlMs, 10_000) + assert.equal(rgSwrCalls[0].opts.ttlMs, 30_000) + assert.ok(rg1.getHeader('etag')) + + const rg304 = await call('GET', '/api/panel/refusal-guards', { + auth: adminAuth, + headers: { 'if-none-match': rg1.getHeader('etag') }, + }) + assert.equal(rg304.statusCode, 304) + assert.equal(rgLoaderRuns, 1, 'second refusal-guards call within fresh window must hit SWR cache') + + // Direct DB update is still masked by SWR until ?refresh=1 bypasses it + new SettingsRepo(db).set('refusal_similarity', 85) + const rgCached = await call('GET', '/api/panel/refusal-guards', { auth: adminAuth }) + assert.equal(rgCached.statusCode, 200) + assert.equal(rgCached.body.data.similarity, 90) + assert.equal(rgLoaderRuns, 1) + + const rgBypass = await call('GET', '/api/panel/refusal-guards?refresh=1', { auth: adminAuth }) + assert.equal(rgBypass.statusCode, 200) + assert.equal(rgBypass.body.data.similarity, 85) + assert.equal(rgLoaderRuns, 2, 'refresh=1 must bypass refusal-guards SWR cache and entity setting cache') + + // PUT mutation invalidates panel namespace and returns fresh snapshot immediately + const putRg = await call('PUT', '/api/panel/refusal-guards', { + auth: adminAuth, + body: { similarity: 95 }, + }) + assert.equal(putRg.statusCode, 200) + assert.equal(putRg.body.data.similarity, 95) + + const rgAfterPut = await call('GET', '/api/panel/refusal-guards', { auth: adminAuth }) + assert.equal(rgAfterPut.statusCode, 200) + assert.equal(rgAfterPut.body.data.similarity, 95) + assert.equal(rgLoaderRuns, 3, 'PUT /api/panel/refusal-guards must invalidate panel SWR cache') + } finally { + dashCache.getOrSetSWR = origRgSwr + } } finally { closeDatabase() fs.rmSync(dir, { recursive: true, force: true }) diff --git a/test/unit/usage-logs-repo.test.mjs b/test/unit/usage-logs-repo.test.mjs index 6869637519..a1cff9e801 100644 --- a/test/unit/usage-logs-repo.test.mjs +++ b/test/unit/usage-logs-repo.test.mjs @@ -663,7 +663,7 @@ test('aligned windows keep boundary, sign, unpriced and Fable rules per row', () } }) -test('protocolEntryStats uses a single SQL scan, derives keywords in memory, and matches protocolEntryStatsAsync', async () => { +test('protocolEntryStats uses a single SQL scan without keywords and matches protocolEntryStatsAsync', async () => { const { dir, db, repo } = freshDb() try { const since = '2026-11-20T00:00:00.000Z' @@ -753,7 +753,7 @@ test('protocolEntryStats uses a single SQL scan, derives keywords in memory, and error_message: '请求被协议拦截: beta', intercept: gateVerdict({ kind: 'block', by: 'distill', keyword: 'beta' }), }, - // Blocked row with empty error_message — counted in blocked/blocks, skipped in keywords + // Blocked row with empty error_message — counted in blocked/blocks { created_at: '2026-11-20T01:23:00.000Z', path: '/v1/messages', @@ -794,10 +794,7 @@ test('protocolEntryStats uses a single SQL scan, derives keywords in memory, and assert.equal(syncStats.blocked, 4) assert.equal(syncStats.passed, 3) assert.equal(syncStats.upstreamRefusals, 1) - assert.deepEqual(syncStats.keywords, [ - { keyword: 'alpha', count: 2 }, - { keyword: 'beta', count: 1 }, - ]) + assert.equal(Object.hasOwn(syncStats, 'keywords'), false, 'dead keywords field must not be emitted') assert.deepEqual(syncStats.routes, [{ kind: 'pool', target: 'pool_alpha', count: 1 }]) assert.equal( syncStats.blocks.reduce((sum, r) => sum + r.count, 0), From 15d1577506eab7c3931e8e9407768d174faee440 Mon Sep 17 00:00:00 2001 From: dofastted Date: Wed, 2 Dec 2026 01:07:58 +0800 Subject: [PATCH 15/15] fix(risk,jev): resolve PR #2462 review findings (M1-M5, Minors 5-7) --- src/lib/admin/panel-routes.mjs | 11 +- src/lib/admin/usage-profile.mjs | 19 +++- src/lib/core/distill-detect.mjs | 67 +++++++++-- ...exes.sql => 076_optimize_risk_indexes.sql} | 4 +- ... => 015_optimize_risk_and_jev_indexes.sql} | 2 +- src/lib/db/repos/jev-usage-repo.mjs | 18 ++- .../db/repos/refusal-device-blocks-repo.mjs | 21 +++- src/lib/protocol/handle-protocol.mjs | 14 +-- src/lib/protocol/jev-intercept.mjs | 19 +++- src/lib/protocol/jev-usage.mjs | 12 ++ src/server.mjs | 1 + test/unit/distill-detect.test.mjs | 70 ++++++++++++ test/unit/jev-intercept.test.mjs | 107 ++++++++++++++++++ test/unit/jev-usage.test.mjs | 72 ++++++++++++ test/unit/pg-log-writer.test.mjs | 32 +++--- test/unit/pg-repos-parity.test.mjs | 8 +- test/unit/refusal-guard.test.mjs | 62 +++++++++- test/unit/usage-profile.test.mjs | 65 ++++++++++- 18 files changed, 543 insertions(+), 61 deletions(-) rename src/lib/db/migrations/{075_optimize_risk_indexes.sql => 076_optimize_risk_indexes.sql} (82%) rename src/lib/db/pg/pg-migrations/{014_optimize_risk_and_jev_indexes.sql => 015_optimize_risk_and_jev_indexes.sql} (97%) diff --git a/src/lib/admin/panel-routes.mjs b/src/lib/admin/panel-routes.mjs index ddbda5ce4c..977efa41e4 100644 --- a/src/lib/admin/panel-routes.mjs +++ b/src/lib/admin/panel-routes.mjs @@ -98,7 +98,7 @@ import { officialCcHome, readOfficialCcStatus, scheduleOfficialCcBootstrap } fro import { invalidateLiveCredentialCache } from './panel-live-credentials.mjs' import { ensureCodexKernel, stopCodexKernel } from '../transport/codex-kernel-supervisor.mjs' import { listOfficialModels, seedModelCatalog } from '../protocol/models.mjs' -import { jevUsageStorageErrors } from '../protocol/jev-usage.mjs' +import { jevUsageDroppedEvents, jevUsageStorageErrors } from '../protocol/jev-usage.mjs' import { getModelPolicy, saveModelPolicy, resetModelPolicy, listPolicyModels } from '../protocol/model-policy.mjs' import { getGptModelPolicy, @@ -2728,6 +2728,7 @@ export function createPanelHandler(ctx) { mode: body?.mode, persistRouting: (patch) => persistRoutingPatch(patch), settings, + db: getDb(), distillFile: distillFile(), setDistill: (rules) => { cfg.distill = rules @@ -8834,7 +8835,13 @@ export function createPanelHandler(ctx) { return json( res, 200, - panel.ok({ ...repo.overview(), ...page, keys, storage_errors_since_start: jevUsageStorageErrors() }), + panel.ok({ + ...repo.overview(), + ...page, + keys, + storage_errors_since_start: jevUsageStorageErrors(), + dropped_events_since_start: jevUsageDroppedEvents(), + }), ) } if (req.method === 'GET' && p === '/api/panel/jev-intercept') { diff --git a/src/lib/admin/usage-profile.mjs b/src/lib/admin/usage-profile.mjs index a293f7f91f..95b56dfbd1 100644 --- a/src/lib/admin/usage-profile.mjs +++ b/src/lib/admin/usage-profile.mjs @@ -4,7 +4,7 @@ * relay writes the shipped quota and risk defaults back. * Persona, probes, health cache, and every other switch stay untouched. */ -import { saveDistillRules } from '../core/distill-detect.mjs' +import { saveDistillRules, saveDistillRulesToSettings } from '../core/distill-detect.mjs' import { applyRefusalGuardPatch, refusalGuardPolicy } from '../core/refusal-guard.mjs' import { DEFAULT_TIER_POLICIES } from '../pool/quota-tiers.mjs' import { OPENAI_QUOTA_DEFAULTS } from '../pool/openai-quota-policy.mjs' @@ -90,9 +90,17 @@ export function riskPatchForProfile(mode) { } /** - * @param {{ mode: string, persistRouting: (patch: object) => unknown, settings: { get: Function, set: Function }, distillFile: string, setDistill?: (rules: object) => void }} input + * @param {{ mode: string, persistRouting: (patch: object) => unknown, settings: { get: Function, set: Function }, db?: unknown, cache?: unknown, distillFile: string, setDistill?: (rules: object) => void }} input */ -export async function applyUsageProfile({ mode, persistRouting, settings, distillFile, setDistill } = {}) { +export async function applyUsageProfile({ + mode, + persistRouting, + settings, + db = null, + cache = null, + distillFile, + setDistill, +} = {}) { const profile = normalizeUsageProfile(mode) if (!profile) { const err = new Error('mode 必须是 personal 或 relay') @@ -101,7 +109,10 @@ export async function applyUsageProfile({ mode, persistRouting, settings, distil } const routing = await persistRouting(routingPatchForProfile(profile)) const risk = riskPatchForProfile(profile) - const distill = saveDistillRules(distillFile, risk.distill) + const distillTarget = db || (settings && typeof settings.set === 'function' ? settings : null) + const distill = distillTarget + ? await saveDistillRulesToSettings(distillTarget, risk.distill, cache, { file: distillFile }) + : saveDistillRules(distillFile, risk.distill) if (typeof setDistill === 'function') setDistill(distill) const jev = applyJevPatch(settings, risk.jev) if (!jev.ok) { diff --git a/src/lib/core/distill-detect.mjs b/src/lib/core/distill-detect.mjs index fb424ffee5..c405b9d5ad 100644 --- a/src/lib/core/distill-detect.mjs +++ b/src/lib/core/distill-detect.mjs @@ -300,8 +300,22 @@ function resolveHardNeedles(src, listed, base) { return factoryHard.filter((item) => have.has(item.toLowerCase())) } +const LEGACY_DISTILL_ERROR_STATUS = 403 +const LEGACY_DISTILL_ERROR_TYPE = 'permission_error' + +function isLegacyDefaultDistillError(err) { + if (!err || typeof err !== 'object') return false + if (err.explicit_status === true) return false + return ( + Number(err.status) === LEGACY_DISTILL_ERROR_STATUS && + String(err.type || '') === LEGACY_DISTILL_ERROR_TYPE && + String(err.code || ErrorCode.DISTILL_BLOCKED) === ErrorCode.DISTILL_BLOCKED + ) +} + export function normalizeDistillRules(raw, options = {}) { const fill = options.fill !== false + const migrateLegacyDefault = options.migrateLegacyDefault === true const src = raw && typeof raw === 'object' ? raw : {} const base = fill ? factoryRules() : blankDistillRules() const err = src.error && typeof src.error === 'object' ? src.error : {} @@ -311,16 +325,32 @@ export function normalizeDistillRules(raw, options = {}) { const hardNeedles = resolveHardNeedles(src, listed, fill ? base : null) const hardSet = new Set(hardNeedles.map((item) => item.toLowerCase())) const patterns = asStringList(src.patterns, fill ? base.patterns : []).slice(0, 50) + const upgradeLegacy = migrateLegacyDefault && isLegacyDefaultDistillError(err) + const status = upgradeLegacy + ? POLICY_BLOCK_STATUS + : clampStatus(err.status == null ? base.error.status : err.status, base.error.status) + const type = upgradeLegacy ? ErrorType.POLICY : String(err.type || base.error.type || ErrorType.POLICY) + const code = String(err.code || base.error.code || ErrorCode.DISTILL_BLOCKED) + const error = { + status, + type, + code, + message: message.slice(0, 200), + } + if ( + !upgradeLegacy && + err.explicit_status === true && + status === LEGACY_DISTILL_ERROR_STATUS && + type === LEGACY_DISTILL_ERROR_TYPE && + code === ErrorCode.DISTILL_BLOCKED + ) { + error.explicit_status = true + } return { enabled: src.enabled == null ? base.enabled : src.enabled !== false, skip_official: src.skip_official == null ? base.skip_official : src.skip_official !== false, skip_zero: src.skip_zero == null ? base.skip_zero : src.skip_zero !== false, - error: { - status: clampStatus(err.status == null ? base.error.status : err.status, base.error.status), - type: String(err.type || base.error.type || ErrorType.POLICY), - code: String(err.code || base.error.code || ErrorCode.DISTILL_BLOCKED), - message: message.slice(0, 200), - }, + error, structure: { min_max_tokens: positiveInt( st.min_max_tokens == null ? base.structure.min_max_tokens : st.min_max_tokens, @@ -426,10 +456,27 @@ export function validateDistillPatch(body = {}) { function mergeDistillRules(cur, patch) { const src = patch && typeof patch === 'object' ? patch : {} + const nextError = { ...cur.error, ...(src.error || {}) } + const explicitOverride = + src.error && + typeof src.error === 'object' && + (Object.prototype.hasOwnProperty.call(src.error, 'status') || + Object.prototype.hasOwnProperty.call(src.error, 'type')) + if (explicitOverride) { + if ( + Number(nextError.status) === LEGACY_DISTILL_ERROR_STATUS && + String(nextError.type || '') === LEGACY_DISTILL_ERROR_TYPE && + String(nextError.code || ErrorCode.DISTILL_BLOCKED) === ErrorCode.DISTILL_BLOCKED + ) { + nextError.explicit_status = true + } else { + delete nextError.explicit_status + } + } const merged = { ...cur, ...src, - error: { ...cur.error, ...(src.error || {}) }, + error: nextError, structure: { ...cur.structure, ...(src.structure || {}) }, } // Old clients only had `needles`. A phrase removed from that list is removed @@ -511,7 +558,7 @@ export function loadDistillRules(file) { try { if (!file || !fs.existsSync(file)) return normalizeDistillRules(DEFAULT_DISTILL_RULES) const data = JSON.parse(fs.readFileSync(file, 'utf8')) - return normalizeDistillRules(data) + return normalizeDistillRules(data, { migrateLegacyDefault: true }) } catch { return normalizeDistillRules(DEFAULT_DISTILL_RULES) } @@ -544,7 +591,7 @@ export async function loadDistillRulesFromSettings(db = null, cache = null, { fi wrapped = await readDistillSettingFromDbAsync(targetDb, repo) } if (wrapped && !wrapped.__missing && wrapped.value && typeof wrapped.value === 'object') { - return normalizeDistillRules(wrapped.value) + return normalizeDistillRules(wrapped.value, { migrateLegacyDefault: true }) } } } catch { @@ -570,7 +617,7 @@ export function loadDistillRulesFromSettingsSync(db = null, cache = null, { file wrapped = val === DISTILL_SETTING_MISSING ? { __missing: true } : { value: val } } if (wrapped && !wrapped.__missing && wrapped.value && typeof wrapped.value === 'object') { - return normalizeDistillRules(wrapped.value) + return normalizeDistillRules(wrapped.value, { migrateLegacyDefault: true }) } } } catch { diff --git a/src/lib/db/migrations/075_optimize_risk_indexes.sql b/src/lib/db/migrations/076_optimize_risk_indexes.sql similarity index 82% rename from src/lib/db/migrations/075_optimize_risk_indexes.sql rename to src/lib/db/migrations/076_optimize_risk_indexes.sql index 8971b956ee..39ef4b1af8 100644 --- a/src/lib/db/migrations/075_optimize_risk_indexes.sql +++ b/src/lib/db/migrations/076_optimize_risk_indexes.sql @@ -1,5 +1,5 @@ --- 075_optimize_risk_indexes — Align SQLite risk/usage_logs partial indexes with --- PostgreSQL migration 014_optimize_risk_and_jev_indexes.sql (SQLite does not +-- 076_optimize_risk_indexes — Align SQLite risk/usage_logs partial indexes with +-- PostgreSQL migration 015_optimize_risk_and_jev_indexes.sql (SQLite does not -- support table fillfactor storage parameters). DROP INDEX IF EXISTS idx_refusal_guards_model; diff --git a/src/lib/db/pg/pg-migrations/014_optimize_risk_and_jev_indexes.sql b/src/lib/db/pg/pg-migrations/015_optimize_risk_and_jev_indexes.sql similarity index 97% rename from src/lib/db/pg/pg-migrations/014_optimize_risk_and_jev_indexes.sql rename to src/lib/db/pg/pg-migrations/015_optimize_risk_and_jev_indexes.sql index a8573a6fac..e29725e955 100644 --- a/src/lib/db/pg/pg-migrations/014_optimize_risk_and_jev_indexes.sql +++ b/src/lib/db/pg/pg-migrations/015_optimize_risk_and_jev_indexes.sql @@ -1,4 +1,4 @@ --- 014_optimize_risk_and_jev_indexes.sql +-- 015_optimize_risk_and_jev_indexes.sql -- Idempotent PG18 partial index & fillfactor optimizations for risk audit tables, -- usage_logs risk polling, and high-frequency jev_usage_totals HOT updates. -- diff --git a/src/lib/db/repos/jev-usage-repo.mjs b/src/lib/db/repos/jev-usage-repo.mjs index 7a45668f4e..74c8e0854c 100644 --- a/src/lib/db/repos/jev-usage-repo.mjs +++ b/src/lib/db/repos/jev-usage-repo.mjs @@ -1,5 +1,5 @@ import { getDb, getPgPool, withTransaction } from '../database.mjs' -import { shanghaiUsageDay } from '../../protocol/jev-usage.mjs' +import { recordJevUsageDropped, recordJevUsageStorageError, shanghaiUsageDay } from '../../protocol/jev-usage.mjs' const FIELDS = [ 'id', @@ -206,6 +206,8 @@ export class JevUsageRepo { if (this._queue.length >= this._maxPending) { this._queue.shift() this.droppedEvents += 1 + recordJevUsageDropped(1) + recordJevUsageStorageError(1) } this._queue.push(event) if (this._queue.length >= this._batchSize) { @@ -298,7 +300,21 @@ export class JevUsageRepo { } catch (err) { errors += 1 this.flushErrors += 1 + recordJevUsageStorageError(1) + // Re-queue failed batch up to bounded capacity so transient PG errors + // do not silently drop events; overflow is counted as both dropped & storage error. + const combined = [...batch, ...this._queue] + const overflow = Math.max(0, combined.length - this._maxPending) + if (overflow > 0) { + this.droppedEvents += overflow + recordJevUsageDropped(overflow) + recordJevUsageStorageError(overflow) + this._queue = combined.slice(overflow) + } else { + this._queue = combined + } console.warn('[jev-usage] async batch flush failed:', err?.message || err) + break } } return { flushed, errors } diff --git a/src/lib/db/repos/refusal-device-blocks-repo.mjs b/src/lib/db/repos/refusal-device-blocks-repo.mjs index 52cb063064..b7eb68de6c 100644 --- a/src/lib/db/repos/refusal-device-blocks-repo.mjs +++ b/src/lib/db/repos/refusal-device-blocks-repo.mjs @@ -1,6 +1,8 @@ import { createHash } from 'node:crypto' import { getDb, getPgPool, withSavepoint } from '../database.mjs' +export const DEFAULT_DEVICE_BLOCK_PRUNE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000 + function normalizeNowIso(nowIso) { if (typeof nowIso === 'string' && nowIso.trim()) return nowIso.trim() if (typeof nowIso === 'number' && Number.isFinite(nowIso)) return new Date(nowIso).toISOString() @@ -406,10 +408,23 @@ export class RefusalDeviceBlocksRepo { return this.count(cutoff) } - /** Bounded batch GC for expired temporary device/session bans. */ - async pruneExpired(nowIso = new Date().toISOString(), limit = 500) { + /** + * Bounded batch GC for expired temporary device/session bans. + * Keeps expired rows for `retentionMs` (default 30 days) after expiry so + * device escalation counters (`violations`) and `risk_device_aliases` + * (`ON DELETE CASCADE`) remain intact across cooldown windows. + */ + async pruneExpired( + nowIso = new Date().toISOString(), + limit = 500, + { retentionMs = DEFAULT_DEVICE_BLOCK_PRUNE_RETENTION_MS } = {}, + ) { const n = Math.min(5000, Math.max(1, Math.floor(Number(limit) || 500))) - const cutoff = normalizeNowIso(nowIso) + const nowMs = Date.parse(normalizeNowIso(nowIso)) + const rawRetention = Number(retentionMs) + const retainMs = + Number.isFinite(rawRetention) && rawRetention >= 0 ? rawRetention : DEFAULT_DEVICE_BLOCK_PRUNE_RETENTION_MS + const cutoff = new Date(nowMs - retainMs).toISOString() const pool = this._resolvePgPool() if (pool) { const res = await pool.query( diff --git a/src/lib/protocol/handle-protocol.mjs b/src/lib/protocol/handle-protocol.mjs index cd7634d154..b5b99819f5 100644 --- a/src/lib/protocol/handle-protocol.mjs +++ b/src/lib/protocol/handle-protocol.mjs @@ -32,6 +32,7 @@ import { invalidateRiskBanCache, observeUpstreamRisk, recordUpstream400SessionBlock, + refusalSessionBlockDecision, upstreamRiskClientError, } from './intercept-gate.mjs' import { @@ -297,18 +298,7 @@ import { formatSchedulerError, } from '../scheduler/scheduler-runtime.mjs' -/** - * Which upstream refusals end the caller session. Claude Code's auto-mode - * classifier is a side request judging one tool action: its refusal stays on - * that request. The main conversation carries the same transcript, so a real - * violation still ends the session the first time the conversation itself is - * refused. - */ -export function refusalSessionBlockDecision(reason, classifier = null) { - if (!isUpstreamSessionBlockReason(reason)) return { block: false } - if (classifier?.purpose === 'auto_mode_classifier') return { block: false, skipped: 'auto_mode_classifier' } - return { block: true } -} +export { refusalSessionBlockDecision } /** * Drop only genuine internal `response_headers` SSE control frames, never diff --git a/src/lib/protocol/jev-intercept.mjs b/src/lib/protocol/jev-intercept.mjs index 365e4fd27b..fa7e77247b 100644 --- a/src/lib/protocol/jev-intercept.mjs +++ b/src/lib/protocol/jev-intercept.mjs @@ -465,7 +465,6 @@ function askedIds(cfg) { export const VERDICT_CACHE_MAX = 2048 const JEV_VERDICT_PREFIX = 'risk:jev:verdict:' const JEV_PAUSE_PREFIX = 'risk:jev:pause:' -const JEV_AUTH_PAUSE_REDIS_TTL_MS = 24 * 60 * 60 * 1000 const JEV_PAUSE_REDIS_HEAL_GRACE_MS = 5_000 const verdictCache = new BoundedLruCache(VERDICT_CACHE_MAX) @@ -1957,10 +1956,14 @@ function syncPauseToRedis(id, row, now, cacheOverride = null) { if (!client?.hasRedis) return const redis = client.getRedisClient?.() if (!redis || typeof redis.set !== 'function') return - const ttlMs = row.until !== null ? Math.max(1_000, row.until - now) : JEV_AUTH_PAUSE_REDIS_TTL_MS const redisKey = client.redisKey(jevPauseRedisKey(id)) + const isManualAuthPause = row.reason === 'auth' || row.until === null Promise.resolve() - .then(() => redis.set(redisKey, JSON.stringify(row), 'PX', ttlMs)) + .then(() => + isManualAuthPause + ? redis.set(redisKey, JSON.stringify(row)) + : redis.set(redisKey, JSON.stringify(row), 'PX', Math.max(1_000, row.until - now)), + ) .catch(() => {}) } @@ -2000,7 +2003,15 @@ async function syncPausedJevKeysFromRedis(targets, now = Date.now(), cacheOverri const raw = rows[i] if (raw == null) { const local = pausedJevKeys.get(id) - if (local && now - local.at >= JEV_PAUSE_REDIS_HEAL_GRACE_MS) { + // 401 auth pauses stay paused until manually resumed (or explicitly + // invalidated by another instance); never auto-clear them when Redis + // is missing the key (e.g. Redis write failure or flush). + if ( + local && + local.reason !== 'auth' && + local.until !== null && + now - local.at >= JEV_PAUSE_REDIS_HEAL_GRACE_MS + ) { pausedJevKeys.delete(id) } continue diff --git a/src/lib/protocol/jev-usage.mjs b/src/lib/protocol/jev-usage.mjs index 3d9a602d5c..f88f78e3d5 100644 --- a/src/lib/protocol/jev-usage.mjs +++ b/src/lib/protocol/jev-usage.mjs @@ -3,13 +3,25 @@ import { createHash, randomUUID } from 'node:crypto' let recorder = null let storageErrors = 0 +let droppedEvents = 0 export function installJevUsageRecorder(value) { if (value !== null && typeof value !== 'function') throw new TypeError('Invalid usage recorder') recorder = value } +export function recordJevUsageStorageError(count = 1) { + const n = Math.trunc(Number(count)) + storageErrors += Number.isFinite(n) && n > 0 ? n : 1 +} +export function recordJevUsageDropped(count = 1) { + const n = Math.trunc(Number(count)) + droppedEvents += Number.isFinite(n) && n > 0 ? n : 1 +} export function jevUsageStorageErrors() { return storageErrors } +export function jevUsageDroppedEvents() { + return droppedEvents +} const count = (value) => (Number.isSafeInteger(value) && value >= 0 && value <= 1000000000 ? value : null) const label = (value, max = 80) => typeof value === 'string' && value.length <= max && /^[a-zA-Z0-9_.:-]+$/.test(value) ? value : '' diff --git a/src/server.mjs b/src/server.mjs index cda2838f96..0c35c27409 100644 --- a/src/server.mjs +++ b/src/server.mjs @@ -462,6 +462,7 @@ async function runRiskBoundedGc() { riskGcRunning = true try { try { + // Keeps expired rows for 30 days by default so violations escalation & aliases survive. await refusalDeviceBlocksRepo.pruneExpired() } catch (e) { console.warn('[risk-gc] refusal_device_blocks prune failed:', e?.message || e) diff --git a/test/unit/distill-detect.test.mjs b/test/unit/distill-detect.test.mjs index f03f313659..80181d3d8c 100644 --- a/test/unit/distill-detect.test.mjs +++ b/test/unit/distill-detect.test.mjs @@ -718,3 +718,73 @@ test('loadDistillRulesFromSettings and saveDistillRulesToSettings use DB setting assert.equal(fromCache2.error.message, '热更新生效') assert.deepEqual(fromCache2.hard_needles, ['DB-NEEDLE']) }) + +test('persisted legacy default 403/permission_error/distill_blocked upgrades to 400/policy_blocked while preserving explicit custom overrides', async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-distill-legacy-403-')) + const file = path.join(dir, 'distill-rules.json') + const db = createDatabase({ dbPath: path.join(dir, 'kin.db') }) + const settings = new SettingsRepo(db) + t.after(() => { + db.close() + fs.rmSync(dir, { recursive: true, force: true }) + }) + + // 1. Legacy persisted file with old default tuple (403 + permission_error + distill_blocked) upgrades to 400/policy_blocked + fs.writeFileSync( + file, + JSON.stringify({ + enabled: true, + error: { status: 403, type: 'permission_error', code: 'distill_blocked', message: '旧默认文案' }, + }), + ) + const fromLegacyFile = loadDistillRules(file) + assert.equal(fromLegacyFile.error.status, 400) + assert.equal(fromLegacyFile.error.type, 'policy_blocked') + assert.equal(fromLegacyFile.error.code, 'distill_blocked') + assert.equal(fromLegacyFile.error.message, '旧默认文案') + assert.equal(distillBlockError(fromLegacyFile, 'req-legacy-file').status, 400) + + // 2. Legacy persisted DB settings row also upgrades cleanly on loadDistillRulesFromSettings (and sync variant) + const client = new MultiTierCacheClient({ redisConfig: null, cacheConfig: { disabled: false } }) + const entity = new EntityCache(client) + const cache = { client, entity } + settings.set(DISTILL_RULES_SETTING, { + enabled: true, + error: { status: 403, type: 'permission_error', code: 'distill_blocked', message: '不允许蒸馏' }, + }) + const fromLegacyDb = await loadDistillRulesFromSettings(db, cache, { file }) + assert.equal(fromLegacyDb.error.status, 400) + assert.equal(fromLegacyDb.error.type, 'policy_blocked') + assert.equal(distillBlockError(fromLegacyDb, 'req-legacy-db').status, 400) + + // 3. Truly custom persisted status/type (e.g. 429 or custom type) is preserved untouched + settings.set(DISTILL_RULES_SETTING, { + enabled: true, + error: { status: 429, type: 'rate_limit_error', code: 'distill_blocked', message: '限流伪装' }, + }) + await entity.invalidateSettings() + const customStatus = await loadDistillRulesFromSettings(db, cache, { file }) + assert.equal(customStatus.error.status, 429) + assert.equal(customStatus.error.type, 'rate_limit_error') + + settings.set(DISTILL_RULES_SETTING, { + enabled: true, + error: { status: 403, type: 'custom_forbidden', code: 'distill_blocked', message: '自定义403' }, + }) + await entity.invalidateSettings() + const customType = await loadDistillRulesFromSettings(db, cache, { file }) + assert.equal(customType.error.status, 403) + assert.equal(customType.error.type, 'custom_forbidden') + + // 4. Operator explicitly saving 403 + permission_error post-upgrade is preserved across reload + await saveDistillRulesToSettings( + db, + { error: { status: 403, type: 'permission_error', code: 'distill_blocked', message: '显式403' } }, + cache, + { file }, + ) + const explicit403 = await loadDistillRulesFromSettings(db, cache, { file }) + assert.equal(explicit403.error.status, 403) + assert.equal(explicit403.error.type, 'permission_error') + assert.equal(explicit403.error.message, '显式403') +}) diff --git a/test/unit/jev-intercept.test.mjs b/test/unit/jev-intercept.test.mjs index 091fa0cac5..ddebdb59c9 100644 --- a/test/unit/jev-intercept.test.mjs +++ b/test/unit/jev-intercept.test.mjs @@ -3019,3 +3019,110 @@ test('pausedJevKeys syncs via Redis TTL keys and rearmJevKeys/resumePausedJevKey await Promise.resolve() assert.equal([...store.keys()].filter((k) => k.startsWith('vm2api:risk:jev:pause:')).length, 0) }) + +test('401 auth pause persists in Redis without auto-expiry TTL and stays paused when Redis write fails beyond 5s grace', async () => { + const setCalls = [] + const store = new Map() + let failRedisSet = false + const mockRedis = { + async set(k, val, ...rest) { + setCalls.push({ key: k, val, rest }) + if (failRedisSet) throw new Error('redis write failed') + store.set(k, val) + return 'OK' + }, + async mget(...keys) { + return keys.map((k) => (store.has(k) ? store.get(k) : null)) + }, + async del(...keys) { + let n = 0 + for (const k of keys) if (store.delete(k)) n += 1 + return n + }, + } + const listeners = new Set() + const mockCache = { + enabled: true, + hasRedis: true, + getRedisClient: () => mockRedis, + redisKey: (k) => `vm2api:${k}`, + resolveRedisKey: async (k) => `vm2api:${k}`, + onInvalidate: (fn) => { + listeners.add(fn) + return () => listeners.delete(fn) + }, + invalidate: async (payload) => { + for (const fn of listeners) fn(payload) + }, + } + + const keyAuthOk = 'jev-401-redis-ok-key' + const keyAuthFail = 'jev-401-redis-fail-key' + const t0 = 500_000 + + // 1. 401 pause writes to Redis WITHOUT PX TTL so it stays paused until manually resumed + const cfgOk = { + enabled: true, + hard_regex_enabled: false, + base_url: 'http://127.0.0.1:9', + api_keys: [keyAuthOk], + model: 'jev-latest', + timeout_ms: 500, + dedup_sec: 0, + cache: mockCache, + } + await classifyJev('auth-401-ok', cfgOk, async () => ({ ok: false, status: 401 }), t0) + await Promise.resolve() + await Promise.resolve() + assert.equal(setCalls.length, 1) + assert.deepEqual(setCalls[0].rest, [], '401 auth pause must NOT set an auto-expiring Redis TTL') + + // 2. When Redis write fails (key absent in Redis), 401 pause must NOT auto-clear after 5s grace + failRedisSet = true + const cfgFail = { + ...cfgOk, + api_keys: [keyAuthFail], + } + let calls = 0 + await classifyJev( + 'auth-401-fail-1', + cfgFail, + async () => { + calls += 1 + return { ok: false, status: 401 } + }, + t0, + ) + await Promise.resolve() + await Promise.resolve() + assert.equal(calls, 1) + + // 30 seconds later (well past 5s heal grace) with Redis still returning null -> must STILL be paused! + const stillPaused = await classifyJev( + 'auth-401-fail-2', + cfgFail, + async () => { + calls += 1 + return { ok: true, json: async () => ({ answers: { usage_policy: { noul: 0.9 } } }) } + }, + t0 + 30_000, + ) + assert.equal(calls, 1, '401 auth pause must stay paused even if Redis key is missing past 5s grace') + assert.equal(stillPaused.reason, 'unavailable') + assert.equal(stillPaused.detail, '密钥失效') + + // Only manual resume unpauses it + await resumePausedJevKeys(cfgOk, '', t0 + 31_000, { cache: mockCache }) + await resumePausedJevKeys(cfgFail, '', t0 + 31_000, { cache: mockCache }) + const afterResume = await classifyJev( + 'auth-401-fail-3', + cfgFail, + async () => { + calls += 1 + return { ok: true, json: async () => ({ answers: { usage_policy: { noul: 0.9 } } }) } + }, + t0 + 32_000, + ) + assert.equal(calls, 2) + assert.equal(afterResume.action, 'pass') +}) diff --git a/test/unit/jev-usage.test.mjs b/test/unit/jev-usage.test.mjs index 721eecc830..2116262548 100644 --- a/test/unit/jev-usage.test.mjs +++ b/test/unit/jev-usage.test.mjs @@ -7,12 +7,14 @@ import { createDatabase, openDatabase, closeDatabase } from '../../src/lib/db/da import { SettingsRepo } from '../../src/lib/db/repos/settings-repo.mjs' import { JevUsageRepo } from '../../src/lib/db/repos/jev-usage-repo.mjs' import { createPanelHandler } from '../../src/lib/admin/panel-routes.mjs' +import { authorizePanelRoute } from '../../src/lib/admin/panel-acl.mjs' import { classifyJev, publicJevKeys, resumeJevKeys } from '../../src/lib/protocol/jev-intercept.mjs' import { installJevUsageRecorder, recordJevUsage, normalizeJevUsage, jevKeyFingerprint, + jevUsageDroppedEvents, jevUsageStorageErrors, shanghaiUsageDay, isOfficialTypeSafeUrl, @@ -805,3 +807,73 @@ test('configuredKeysAsync uses async pgPool with short-TTL cache in PG mode and const sqliteAsync = await sqliteRepo.configuredKeysAsync([{ number: 1, key_fingerprint: fpA, retired: false }]) assert.deepEqual(sqliteAsync, sqliteRepo.configuredKeys([{ number: 1, key_fingerprint: fpA, retired: false }])) }) + +test('the provider usage endpoint is not exposed to non-admin panel roles', () => { + assert.equal(authorizePanelRoute('GET', '/api/panel/jev-usage', 'admin').ok, true) + assert.equal(authorizePanelRoute('GET', '/api/panel/jev-usage', 'user').ok, false) + assert.equal(authorizePanelRoute('GET', '/api/panel/jev-usage', 'super').ok, false) +}) + +test('PG batch flush failure increments jevUsageStorageErrors, re-queues failed batch for retry, and counts overflow drops', async () => { + let failPool = true + const writtenIds = [] + const mockPool = { + async connect() { + return { + async query(sql, params = []) { + const text = String(sql).trim() + if (text === 'BEGIN' || text === 'ROLLBACK' || text === 'COMMIT') return { rows: [] } + if (failPool) throw new Error('simulated pg blip') + if (text.startsWith('INSERT INTO jev_usage_events')) { + const ids = params[0] || [] + writtenIds.push(...ids) + return { rows: ids.map((id) => ({ id })), rowCount: ids.length } + } + return { rows: [], rowCount: 1 } + }, + release() {}, + } + }, + async query() { + throw new Error('simulated pg blip') + }, + } + + const errBefore = jevUsageStorageErrors() + const dropBefore = jevUsageDroppedEvents() + const repo = new JevUsageRepo( + { engine: 'postgres', pgPool: mockPool }, + { now: () => NOW, batchSize: 2, flushIntervalMs: 60_000, maxPending: 3 }, + ) + + const e1 = normalizeJevUsage(value({ request_id: 'pg-fail-1' })) + const e2 = normalizeJevUsage(value({ request_id: 'pg-fail-2' })) + const e3 = normalizeJevUsage(value({ request_id: 'pg-fail-3' })) + const e4 = normalizeJevUsage(value({ request_id: 'pg-fail-4' })) + + // Enqueue 3 events (< maxPending=3) and trigger flush while PG is failing + repo._queue.push(e1, e2, e3) + const failedFlush = await repo.flush() + assert.equal(failedFlush.flushed, 0) + assert.equal(failedFlush.errors, 1) + assert.equal(repo.flushErrors, 1) + assert.equal(jevUsageStorageErrors(), errBefore + 1, 'failed PG batch flush must increment jevUsageStorageErrors') + assert.equal(repo.droppedEvents, 0, 'failed batch within maxPending must be re-queued, not dropped') + assert.equal(repo._queue.length, 3, 'all 3 events stay queued for retry') + + // Adding a 4th event while queue is full overflows oldest (e1) -> counts both droppedEvents and storageErrors + repo.record(e4) + await Promise.resolve() + // Wait for auto-triggered flush to settle + if (repo._flushPromise) await repo._flushPromise + assert.ok(repo.droppedEvents >= 1, 'overflow must increment repo.droppedEvents') + assert.ok(jevUsageDroppedEvents() >= dropBefore + 1, 'overflow must increment jevUsageDroppedEvents') + assert.ok(jevUsageStorageErrors() >= errBefore + 2, 'overflow + flush failure must increment jevUsageStorageErrors') + + // Once PG recovers, flush drains the re-queued events cleanly + failPool = false + const recovered = await repo.close() + assert.equal(recovered.errors, 0) + assert.equal(recovered.flushed, 3) + assert.deepEqual(writtenIds, [e2.id, e3.id, e4.id]) +}) diff --git a/test/unit/pg-log-writer.test.mjs b/test/unit/pg-log-writer.test.mjs index b84536eb5c..d3291bfa4c 100644 --- a/test/unit/pg-log-writer.test.mjs +++ b/test/unit/pg-log-writer.test.mjs @@ -110,13 +110,13 @@ function parsePgTableColumnTypes(tableName) { return typeMap } -test('PG migrations 011, 012, and 014 optimize usage_logs/request_attempts/risk/jev indexes idempotently', async () => { +test('PG migrations 011, 012, and 015 optimize usage_logs/request_attempts/risk/jev indexes idempotently', async () => { const mig011 = '011_drop_duplicate_usage_logs_indexes.sql' const mig012 = '012_optimize_usage_logs_and_attempts_indexes.sql' - const mig014 = '014_optimize_risk_and_jev_indexes.sql' + const mig015 = '015_optimize_risk_and_jev_indexes.sql' const sql011 = fs.readFileSync(path.join(PG_MIGRATIONS_DIR, mig011), 'utf8') const sql012 = fs.readFileSync(path.join(PG_MIGRATIONS_DIR, mig012), 'utf8') - const sql014 = fs.readFileSync(path.join(PG_MIGRATIONS_DIR, mig014), 'utf8') + const sql015 = fs.readFileSync(path.join(PG_MIGRATIONS_DIR, mig015), 'utf8') assert.match(sql011, /DROP INDEX IF EXISTS idx_reqlog_cost_ts;/i) assert.match(sql011, /DROP INDEX IF EXISTS idx_usage_logs_request_id;/i) @@ -157,25 +157,25 @@ test('PG migrations 011, 012, and 014 optimize usage_logs/request_attempts/risk/ /CREATE INDEX IF NOT EXISTS idx_alloc_account_id_desc\s+ON account_allocations \(account_id, id DESC\);/i, ) - // 014 drops dead/superseded risk indexes, adds partial risk/expiry indexes, and sets jev_usage_totals fillfactor - assert.match(sql014, /DROP INDEX IF EXISTS idx_refusal_guards_model;/i) - assert.match(sql014, /DROP INDEX IF EXISTS idx_usage_logs_upstream_400;/i) + // 015 drops dead/superseded risk indexes, adds partial risk/expiry indexes, and sets jev_usage_totals fillfactor + assert.match(sql015, /DROP INDEX IF EXISTS idx_refusal_guards_model;/i) + assert.match(sql015, /DROP INDEX IF EXISTS idx_usage_logs_upstream_400;/i) assert.match( - sql014, + sql015, /CREATE INDEX IF NOT EXISTS idx_refusal_device_blocks_expires\s+ON refusal_device_blocks \(expires_at\)\s+WHERE expires_at IS NOT NULL;/i, ) assert.match( - sql014, + sql015, /CREATE INDEX IF NOT EXISTS idx_refusal_guards_expires\s+ON refusal_guards \(expires_at\)\s+WHERE expires_at IS NOT NULL;/i, ) assert.match( - sql014, + sql015, /CREATE INDEX IF NOT EXISTS idx_usage_logs_upstream_risk\s+ON usage_logs \(created_at DESC, id DESC\)\s+WHERE upstream_status IN \(400, 401, 403, 422\);/i, ) - assert.match(sql014, /ALTER TABLE jev_usage_totals SET \(fillfactor = 70\);/i) + assert.match(sql015, /ALTER TABLE jev_usage_totals SET \(fillfactor = 70\);/i) - // Verify SQLite migration 075 aligns indexes identically with PG 014 - const sqliteDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vm2api-sqlite-075-idx-')) + // Verify SQLite migration 076 aligns indexes identically with PG 015 + const sqliteDir = fs.mkdtempSync(path.join(os.tmpdir(), 'vm2api-sqlite-076-idx-')) try { const sqliteDb = createDatabase({ dbPath: path.join(sqliteDir, 'kin.db') }) try { @@ -185,11 +185,11 @@ test('PG migrations 011, 012, and 014 optimize usage_logs/request_attempts/risk/ .all() .map((r) => r.name), ) - assert.equal(idxNames.has('idx_refusal_guards_model'), false, 'SQLite 075 must drop idx_refusal_guards_model') + assert.equal(idxNames.has('idx_refusal_guards_model'), false, 'SQLite 076 must drop idx_refusal_guards_model') assert.equal( idxNames.has('idx_usage_logs_upstream_400'), false, - 'SQLite 075 must drop superseded idx_usage_logs_upstream_400', + 'SQLite 076 must drop superseded idx_usage_logs_upstream_400', ) assert.equal(idxNames.has('idx_refusal_device_blocks_expires'), true) assert.equal(idxNames.has('idx_refusal_guards_expires'), true) @@ -201,7 +201,7 @@ test('PG migrations 011, 012, and 014 optimize usage_logs/request_attempts/risk/ fs.rmSync(sqliteDir, { recursive: true, force: true }) } - // Verify applyPgMigrations loads and applies 011, 012, and 014 cleanly and idempotently via mock client + // Verify applyPgMigrations loads and applies 011, 012, and 015 cleanly and idempotently via mock client const appliedVersions = new Map() const executedSql = [] const client = { @@ -236,7 +236,7 @@ test('PG migrations 011, 012, and 014 optimize usage_logs/request_attempts/risk/ assert.ok( first.includes(mig011) && first.indexOf(mig012) > first.indexOf(mig011) && - first.indexOf(mig014) > first.indexOf(mig012), + first.indexOf(mig015) > first.indexOf(mig012), ) assert.ok(executedSql.some((s) => s.includes('DROP INDEX IF EXISTS idx_reqlog_cost_ts'))) assert.ok(executedSql.some((s) => s.includes('DROP INDEX IF EXISTS idx_request_attempt_request'))) diff --git a/test/unit/pg-repos-parity.test.mjs b/test/unit/pg-repos-parity.test.mjs index b747a3019d..683791a2e4 100644 --- a/test/unit/pg-repos-parity.test.mjs +++ b/test/unit/pg-repos-parity.test.mjs @@ -550,18 +550,21 @@ async function runAll22ReposScenario(db, { pgPool = null } = {}) { { principal: 'key_p1', deviceId: 'dev-abc', sessionId: 'sess-ban-1' }, { requestId: 'req_400_perm', reason: 'upstream_400:unknown', ttlMs: 10 * 60_000, now: nowMs + 2000 }, ) - // Temporary session ban visible before expiry, filtered out by list/count after expiry, and removed by pruneExpired + // Temporary session ban visible before expiry, filtered out by list/count after expiry, + // retained within the 30-day GC retention window, and pruned once past retention. devBlocks.blockSession( { principal: 'key_p1', sessionId: 'sess-temp-exp' }, { requestId: 'req_400_temp', reason: 'upstream_400:tool_pair_broken', ttlMs: 60_000, now: nowMs }, ) const beforeExpIso = new Date(nowMs + 5_000).toISOString() const afterExpIso = new Date(nowMs + 120_000).toISOString() + const afterRetentionIso = new Date(nowMs + 31 * 24 * 60 * 60 * 1000).toISOString() const countBeforeExp = devBlocks.count(beforeExpIso) const listBeforeExpLen = devBlocks.list(200, beforeExpIso).length const countAfterExp = devBlocks.count(afterExpIso) const listAfterExpLen = devBlocks.list(200, afterExpIso).length - const prunedDevices = await devBlocks.pruneExpired(afterExpIso, 100) + const prunedWithinRetention = await devBlocks.pruneExpired(afterExpIso, 100) + const prunedDevices = await devBlocks.pruneExpired(afterRetentionIso, 100) snap.devBlocks = { count: devBlocks.count(beforeExpIso), violatedKind: viol?.subject_kind, @@ -573,6 +576,7 @@ async function runAll22ReposScenario(db, { pgPool = null } = {}) { listBeforeExpLen, countAfterExp, listAfterExpLen, + prunedWithinRetention, prunedDevices, permSurvivedPrune: devBlocks.get(permAfterTemp.device_id)?.expires_at === null, } diff --git a/test/unit/refusal-guard.test.mjs b/test/unit/refusal-guard.test.mjs index fe5077665b..6debdedb26 100644 --- a/test/unit/refusal-guard.test.mjs +++ b/test/unit/refusal-guard.test.mjs @@ -1323,21 +1323,25 @@ test('list and count filter expired rows in SQL and pruneExpired performs bounde insDev.run('active-temp-1', olderAt, olderAt, 'active-temp-1', futureExp) insDev.run('active-temp-2', olderAt, olderAt, 'active-temp-2', futureExp) for (let i = 0; i < 10; i += 1) { - const expIso = new Date(baseMs - (10 - i) * 1_000).toISOString() + const expIso = new Date(baseMs - 31 * 24 * 60 * 60 * 1000 - (10 - i) * 1_000).toISOString() insDev.run(`expired-dev-${i}`, newerAt, newerAt, `expired-dev-${i}`, expIso) } + // Recently expired row (< 30d) must be retained by default GC for escalation history + const recentExpIso = new Date(baseMs - 10 * 60_000).toISOString() + insDev.run('recent-expired-dev', newerAt, newerAt, 'recent-expired-dev', recentExpIso) assert.equal(devices.count(nowIso), 3, 'count() must exclude expired device/session bans in SQL') const activeDevs = devices.list(3, nowIso) assert.equal(activeDevs.length, 3, 'list(limit) must not be crowded out by newer expired rows') assert.ok(activeDevs.every((r) => r.device_id.startsWith('active-'))) - // Bounded pruneExpired deletes in batches of 4 and never removes active/permanent rows + // Bounded pruneExpired deletes >30d expired rows in batches of 4 and preserves active, permanent, and recently expired rows assert.equal(await devices.pruneExpired(nowIso, 4), 4) assert.equal(await devices.pruneExpired(nowIso, 4), 4) assert.equal(await devices.pruneExpired(nowIso, 4), 2) assert.equal(await devices.pruneExpired(nowIso, 4), 0) - assert.equal(db.prepare('SELECT COUNT(*) AS n FROM refusal_device_blocks').get().n, 3) + assert.equal(db.prepare('SELECT COUNT(*) AS n FROM refusal_device_blocks').get().n, 4) + assert.ok(devices.get('recent-expired-dev'), 'recently expired row must survive 30d retention GC') // Same verification for RefusalGuardsRepo (fixes LIMIT-before-JS-filter bug) const insGuard = db.prepare(` @@ -1386,12 +1390,64 @@ test('list and count filter expired rows in SQL and pruneExpired performs bounde assert.equal(await new RefusalGuardsRepo(pgDb).pruneExpired(nowIso, 250), 7) assert.equal(pgQueries.length, 2) assert.match(pgQueries[0].sql, /DELETE FROM refusal_device_blocks/) + assert.equal( + pgQueries[0].params[0], + new Date(baseMs - 30 * 24 * 60 * 60 * 1000).toISOString(), + 'PG device block GC must subtract 30d retention window', + ) assert.match(pgQueries[1].sql, /DELETE FROM refusal_guards/) } finally { db.close() } }) +test('RefusalDeviceBlocksRepo.pruneExpired preserves violations escalation (1 -> 2 -> 3 permanent) and risk_device_aliases across cooldown expiry', async () => { + const db = createDatabase({ dbPath: ':memory:' }) + try { + const devices = new RefusalDeviceBlocksRepo(db) + const steps = [10, 10, 0] + const t0 = Date.parse('2026-12-01T12:00:00.000Z') + const idBoth = { principal: 'key_esc', deviceId: 'dev-esc-1', machineId: 'mach-esc-1' } + + // 1st violation -> 10m temporary ban + machineId alias bound in risk_device_aliases + const v1 = devices.recordViolation(idBoth, { requestId: 'req-1', reason: 'refusal_guard', steps, now: t0 }) + assert.equal(v1.violations, 1) + assert.ok(v1.expires_at, '1st strike should be temporary') + const aliasesAfterV1 = db.prepare('SELECT COUNT(*) AS n FROM risk_device_aliases').get().n + assert.equal(aliasesAfterV1, 1) + + // 11m later: ban expired; run periodic GC -> row & alias MUST survive + const t1 = t0 + 11 * 60_000 + assert.equal(await devices.pruneExpired(new Date(t1).toISOString(), 500), 0) + assert.equal(db.prepare('SELECT COUNT(*) AS n FROM risk_device_aliases').get().n, 1) + + // 2nd violation -> escalates to violations=2 (still 10m temporary) + const v2 = devices.recordViolation(idBoth, { requestId: 'req-2', reason: 'refusal_guard', steps, now: t1 }) + assert.equal(v2.violations, 2) + assert.ok(v2.expires_at, '2nd strike should still be temporary') + + // 11m later: ban expired again; run GC -> row & alias MUST survive + const t2 = t1 + 11 * 60_000 + assert.equal(await devices.pruneExpired(new Date(t2).toISOString(), 500), 0) + assert.equal(db.prepare('SELECT COUNT(*) AS n FROM risk_device_aliases').get().n, 1) + + // 3rd violation arriving via machineId alias only -> escalates to violations=3 (permanent: expires_at === null) + const v3 = devices.recordViolation( + { principal: 'key_esc', machineId: 'mach-esc-1' }, + { requestId: 'req-3', reason: 'refusal_guard', steps, now: t2 }, + ) + assert.equal(v3.violations, 3) + assert.equal(v3.expires_at, null, '3rd strike must escalate to permanent ban') + + // Even 31 days later, permanent ban is never pruned + const t3 = t2 + 31 * 24 * 60 * 60 * 1000 + assert.equal(await devices.pruneExpired(new Date(t3).toISOString(), 500), 0) + assert.equal(devices.get(v3.device_id)?.expires_at, null) + } finally { + db.close() + } +}) + test('RefusalGuardsRepo.remember() incrementally updates warm snapshot without double full-table rescan while still broadcasting to peers', async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-guards-remember-')) closeDatabase() diff --git a/test/unit/usage-profile.test.mjs b/test/unit/usage-profile.test.mjs index 49873d285c..889a9eec44 100644 --- a/test/unit/usage-profile.test.mjs +++ b/test/unit/usage-profile.test.mjs @@ -4,7 +4,15 @@ import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import { loadDistillRules } from '../../src/lib/core/distill-detect.mjs' +import { + loadDistillRules, + loadDistillRulesFromSettings, + saveDistillRulesToSettings, +} from '../../src/lib/core/distill-detect.mjs' +import { createDatabase } from '../../src/lib/db/database.mjs' +import { SettingsRepo } from '../../src/lib/db/repos/settings-repo.mjs' +import { MultiTierCacheClient } from '../../src/lib/cache/cache-client.mjs' +import { EntityCache } from '../../src/lib/cache/entity-cache.mjs' import { refusalGuardPolicy } from '../../src/lib/core/refusal-guard.mjs' import { readJevConfig } from '../../src/lib/protocol/jev-intercept.mjs' import { applyUsageProfile, riskPatchForProfile, routingPatchForProfile } from '../../src/lib/admin/usage-profile.mjs' @@ -157,3 +165,58 @@ test('unknown profile is rejected and a saved profile survives complete', async const reset = applyOnboardingAction(done, 'admin', 'reset') assert.equal(recordOf(reset, 'admin').profile, null) }) + +test('applyUsageProfile persists distill rules to DB SSOT and invalidates EntityCache so refresh cannot revert profile switch', async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'kin-profile-db-ssot-')) + const distillFile = path.join(dir, 'distill-rules.json') + const db = createDatabase({ dbPath: path.join(dir, 'kin.db') }) + const settings = new SettingsRepo(db) + const client = new MultiTierCacheClient({ redisConfig: null, cacheConfig: { disabled: false } }) + const entity = new EntityCache(client) + const cache = { client, entity } + t.after(() => { + db.close() + fs.rmSync(dir, { recursive: true, force: true }) + }) + + // Panel previously saved distill_rules to DB with enabled=true + await saveDistillRulesToSettings(db, { enabled: true }, cache, { file: distillFile }) + assert.equal((await loadDistillRulesFromSettings(db, cache, { file: distillFile })).enabled, true) + + // Switch to personal profile -> DB SSOT + file + memory must all reflect enabled=false + let memDistill = null + await applyUsageProfile({ + mode: 'personal', + persistRouting: () => ({ ok: true }), + settings, + db, + cache, + distillFile, + setDistill: (r) => { + memDistill = r + }, + }) + assert.equal(memDistill.enabled, false) + assert.equal(loadDistillRules(distillFile).enabled, false) + // Simulate settings cache invalidation + refreshDistillFromSettings + await entity.invalidateSettings() + const reloadedPersonal = await loadDistillRulesFromSettings(db, cache, { file: distillFile }) + assert.equal(reloadedPersonal.enabled, false, 'DB SSOT must not revert personal profile distill=false') + + // Reverse direction: switch to relay profile -> DB SSOT must turn distill back on + await applyUsageProfile({ + mode: 'relay', + persistRouting: () => ({ ok: true }), + settings, + db, + cache, + distillFile, + setDistill: (r) => { + memDistill = r + }, + }) + assert.equal(memDistill.enabled, true) + await entity.invalidateSettings() + const reloadedRelay = await loadDistillRulesFromSettings(db, cache, { file: distillFile }) + assert.equal(reloadedRelay.enabled, true, 'DB SSOT must reflect relay profile distill=true') +})