Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
475 changes: 253 additions & 222 deletions src/lib/admin/panel-routes.mjs

Large diffs are not rendered by default.

17 changes: 14 additions & 3 deletions src/lib/core/panel-2fa.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
*/

import crypto from 'node:crypto'
import { getDb } from '../db/database.mjs'
import { SettingsRepo } from '../db/repos/settings-repo.mjs'
import { decryptString, encryptString } from '../db/secure.mjs'
import { DEFAULT_OPTIONS, buildOtpauthUri, generateSecret, matchCounter, normalizeSecret } from './totp.mjs'
Expand Down Expand Up @@ -100,11 +101,21 @@ export function isTwoFactorEnabled(username) {

/** Batch form of {@link isTwoFactorEnabled} for the user list. */
export function twoFactorEnabledFor(usernames = []) {
const repo = settings()
const out = new Map()
if (!Array.isArray(usernames) || !usernames.length) return out
const rows = getDb().prepare("SELECT key, value FROM settings WHERE key LIKE 'panel_2fa:%'").all()
const enabledKeys = new Set()
for (const row of rows) {
try {
const rec = row?.value ? JSON.parse(row.value) : null
if (rec && typeof rec === 'object' && rec.enabled && rec.secret) {
enabledKeys.add(String(row.key))
}
} catch {}
}
for (const name of usernames) {
const rec = loadRecord(name, repo)
out.set(name, !!(rec?.enabled && rec?.secret))
const trimmed = String(name || '').trim()
out.set(name, !!trimmed && enabledKeys.has(twoFactorKey(trimmed)))
}
return out
}
Expand Down
33 changes: 32 additions & 1 deletion src/lib/db/repos/api-endpoints-repo.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -94,13 +94,15 @@ export class ApiEndpointsRepo {
)
this._delEp = db.prepare('DELETE FROM api_endpoints WHERE id = ?')
this._listKeys = db.prepare('SELECT * FROM api_endpoint_keys WHERE endpoint_id = ? ORDER BY created_at, id')
this._listAllKeys = db.prepare('SELECT * FROM api_endpoint_keys ORDER BY created_at, id')
this._getKey = db.prepare('SELECT * FROM api_endpoint_keys WHERE id = ?')
this._insKey = db.prepare(
`INSERT INTO api_endpoint_keys (${KEY_COLS.join(',')}) VALUES (${KEY_COLS.map(() => '?').join(',')})`,
)
this._delKey = db.prepare('DELETE FROM api_endpoint_keys WHERE id = ?')
this._delKeysEp = db.prepare('DELETE FROM api_endpoint_keys WHERE endpoint_id = ?')
this._listModels = db.prepare('SELECT * FROM api_endpoint_models WHERE endpoint_id = ? ORDER BY sort, id')
this._listAllModels = db.prepare('SELECT * FROM api_endpoint_models ORDER BY sort, id')
this._insModel = db.prepare(
`INSERT INTO api_endpoint_models (${MODEL_COLS.join(',')}) VALUES (${MODEL_COLS.map(() => '?').join(',')})`,
)
Expand All @@ -112,7 +114,36 @@ export class ApiEndpointsRepo {
}

listHydrated() {
return this._listEp.all().map((row) => this.hydrate(rowEp(row)))
const endpoints = this._listEp.all()
if (!endpoints.length) return []
const keysByEp = new Map()
for (const row of this._listAllKeys.all()) {
const key = rowKey(row)
let list = keysByEp.get(key.endpoint_id)
if (!list) {
list = []
keysByEp.set(key.endpoint_id, list)
}
list.push(key)
}
const modelsByEp = new Map()
for (const row of this._listAllModels.all()) {
const model = rowModel(row)
let list = modelsByEp.get(model.endpoint_id)
if (!list) {
list = []
modelsByEp.set(model.endpoint_id, list)
}
list.push(model)
}
return endpoints.map((row) => {
const ep = rowEp(row)
return {
...ep,
api_key_entries: keysByEp.get(ep.id) || [],
models: modelsByEp.get(ep.id) || [],
}
})
}

getHydrated(id) {
Expand Down
50 changes: 45 additions & 5 deletions src/lib/db/repos/settings-repo.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,27 @@
* Used for: legacy_import_done, backup_schedule, proxy_pool_config, active_vm …
*/

import { getDb } from '../database.mjs'
import { DB_INSTANCE_ID, getDb, isDbOpen } from '../database.mjs'
import { getCacheRuntime } from '../../cache/index.mjs'

let lastPrimaryDbId = null

function cloneSettingValue(value) {
if (value === null || typeof value !== 'object') return value
return structuredClone(value)
}

function isPrimaryDb(db) {
if (!isDbOpen() || db !== getDb()) return false
const dbId = db?.[DB_INSTANCE_ID] || null
if (dbId && lastPrimaryDbId && dbId !== lastPrimaryDbId) {
getCacheRuntime()
.entity.invalidateSettings()
.catch(() => {})
}
if (dbId) lastPrimaryDbId = dbId
return true
}

export class SettingsRepo {
constructor(db = getDb()) {
Expand All @@ -17,18 +37,33 @@ export class SettingsRepo {
this._all = db.prepare('SELECT key, value, updated_at FROM settings ORDER BY key')
}

get(key, fallback = null) {
_readParsedEntry(key) {
const row = this._get.get(key)
if (!row) return fallback
if (!row) return { found: false, value: null }
try {
return JSON.parse(row.value)
return { found: true, value: JSON.parse(row.value) }
} catch {
return fallback
return { found: false, value: null }
}
}

get(key, fallback = null) {
if (key != null && key !== '' && isPrimaryDb(this.db)) {
const entry = getCacheRuntime().entity.getSettingSync(String(key), () => this._readParsedEntry(key))
if (!entry || !entry.found) return fallback
Comment on lines +50 to +53

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Agentic Security Review
Severity: MEDIUM

PostgreSQL 下 SettingsRepo.get 把 {found, value} 写入 entity:setting:<rawKey>,与已有的 readCachedSettingSync / readCachedSettingAsync / distill 读取器共享同一键,但那些读取器写入的是 {value} 或 {__missing: true}。

热路径先填充缓存后,后续 SettingsRepo.get 会因 !entry.found 误判为 miss 并返回 fallback。jevInterceptSnapshot 与 applyJevPatch 走这条路,面板 GET 可能展示默认/空策略,PUT 会按默认值 merge 后 settings.set 持久化,从而擦掉已配置的 JEV intercept / refusal 等安全控制。

Impact: 在 PG + EntityCache 开启时,安全策略可被误读为默认并被管理端写回库,导致 intercept/refusal 等控制失效。

Fix in Cursor Fix in Web

Reviewed by Cursor Security Reviewer for commit ae85938. Configure here.

return cloneSettingValue(entry.value)
}
const entry = this._readParsedEntry(key)
return entry.found ? entry.value : fallback
}

set(key, value) {
this._set.run(key, JSON.stringify(value), new Date().toISOString())
if (isPrimaryDb(this.db)) {
getCacheRuntime()
.entity.invalidateSettings()
.catch(() => {})
}
return value
}

Expand All @@ -38,6 +73,11 @@ export class SettingsRepo {

remove(key) {
this._del.run(key)
if (isPrimaryDb(this.db)) {
getCacheRuntime()
.entity.invalidateSettings()
.catch(() => {})
}
}

all() {
Expand Down
30 changes: 27 additions & 3 deletions src/lib/db/repos/statistics-repo.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -290,9 +290,13 @@ export class StatisticsRepo {
acc.output_tokens += num(row.output_tokens)
acc.cache_read_tokens += cacheRead
acc.cache_creation_tokens += cacheCreation
acc.cache_creation_5m_tokens += num(row.cache_creation_5m_tokens)
acc.cache_creation_1h_tokens += num(row.cache_creation_1h_tokens)
acc.prompt_tokens += input + cacheRead + cacheCreation
acc.total_duration_ms += num(row.total_duration_ms)
acc.duration_count += num(row.duration_count)
acc.total_ttft_ms += num(row.total_ttft_ms)
acc.ttft_count += num(row.ttft_count)
}
const addTail = (row) => {
if (!row) return
Expand Down Expand Up @@ -325,8 +329,12 @@ export class StatisticsRepo {
COALESCE(SUM(output_tokens), 0) AS output_tokens,
COALESCE(SUM(cache_read_tokens), 0) AS cache_read_tokens,
COALESCE(SUM(cache_creation_tokens), 0) AS cache_creation_tokens,
COALESCE(SUM(cache_creation_5m_tokens), 0) AS cache_creation_5m_tokens,
COALESCE(SUM(cache_creation_1h_tokens), 0) AS cache_creation_1h_tokens,
COALESCE(SUM(total_duration_ms), 0) AS total_duration_ms,
COALESCE(SUM(duration_count), 0) AS duration_count
COALESCE(SUM(duration_count), 0) AS duration_count,
COALESCE(SUM(total_ttft_ms), 0) AS total_ttft_ms,
COALESCE(SUM(ttft_count), 0) AS ttft_count
FROM usage_dashboard_daily
WHERE bucket_date >= ?::date AND bucket_date < ?::date
`)
Expand All @@ -344,8 +352,12 @@ export class StatisticsRepo {
COALESCE(SUM(output_tokens), 0) AS output_tokens,
COALESCE(SUM(cache_read_tokens), 0) AS cache_read_tokens,
COALESCE(SUM(cache_creation_tokens), 0) AS cache_creation_tokens,
COALESCE(SUM(cache_creation_5m_tokens), 0) AS cache_creation_5m_tokens,
COALESCE(SUM(cache_creation_1h_tokens), 0) AS cache_creation_1h_tokens,
COALESCE(SUM(total_duration_ms), 0) AS total_duration_ms,
COALESCE(SUM(duration_count), 0) AS duration_count
COALESCE(SUM(duration_count), 0) AS duration_count,
COALESCE(SUM(total_ttft_ms), 0) AS total_ttft_ms,
COALESCE(SUM(ttft_count), 0) AS ttft_count
FROM usage_dashboard_hourly
WHERE bucket_start >= ?::timestamptz AND bucket_start < ?::timestamptz
`)
Expand Down Expand Up @@ -436,8 +448,14 @@ export class StatisticsRepo {
COALESCE(SUM(output_tokens), 0) AS output_tokens,
COALESCE(SUM(cache_read_tokens), 0) AS cache_read_tokens,
COALESCE(SUM(cache_creation_tokens), 0) AS cache_creation_tokens,
COALESCE(SUM(cache_creation_5m_tokens), 0) AS cache_creation_5m_tokens,
COALESCE(SUM(cache_creation_1h_tokens), 0) AS cache_creation_1h_tokens,
COALESCE(SUM(total_cost), 0) AS cost,
COALESCE(SUM(actual_cost), 0) AS actual_cost
COALESCE(SUM(actual_cost), 0) AS actual_cost,
COALESCE(SUM(total_duration_ms), 0) AS total_duration_ms,
COALESCE(SUM(duration_count), 0) AS duration_count,
COALESCE(SUM(total_ttft_ms), 0) AS total_ttft_ms,
COALESCE(SUM(ttft_count), 0) AS ttft_count
FROM usage_dashboard_hourly_models
WHERE bucket_start >= ?::timestamptz AND bucket_start < ?::timestamptz
GROUP BY 1
Expand Down Expand Up @@ -515,9 +533,15 @@ export class StatisticsRepo {
cur.output_tokens += num(row.output_tokens)
cur.cache_read_tokens += cacheRead
cur.cache_creation_tokens += cacheCreation
cur.cache_creation_5m_tokens += num(row.cache_creation_5m_tokens)
cur.cache_creation_1h_tokens += num(row.cache_creation_1h_tokens)
cur.prompt_tokens += input + cacheRead + cacheCreation
cur.cost += num(row.cost)
cur.actual_cost += num(row.actual_cost)
cur.total_duration_ms += num(row.total_duration_ms)
cur.duration_count += num(row.duration_count)
cur.total_ttft_ms += num(row.total_ttft_ms)
cur.ttft_count += num(row.ttft_count)
}

for (const row of tailRows) {
Expand Down
Loading
Loading