feat: split worker login device limits by type

This commit is contained in:
yml2213
2026-08-30 21:58:13 +08:00
parent ffb71f2276
commit b832279c1f
15 changed files with 537 additions and 14 deletions
+26
View File
@@ -4,6 +4,7 @@
*/
import fs from 'node:fs'
import path from 'node:path'
import { execFileSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url))
@@ -57,6 +58,31 @@ const checks: Array<{ name: string; file: string; patterns: string[] }> = [
]
const failures: string[] = []
// 已应用的历史迁移必须保持字节不变,所有结构或数据修复都必须新增迁移文件。
try {
const diffOutputs = [
execFileSync('git', ['diff', '--name-status', 'HEAD', '--', 'src/db/migrations'], {
cwd: BACKEND_ROOT,
encoding: 'utf8',
}),
execFileSync('git', ['diff', '--name-status', 'HEAD^', 'HEAD', '--', 'src/db/migrations'], {
cwd: BACKEND_ROOT,
encoding: 'utf8',
}),
]
const changedHistoricalMigrations = diffOutputs
.flatMap((output) => output.split('\n'))
.map((line) => line.trim().split(/\s+/))
.filter(([status, file]) => status && file?.endsWith('.sql') && status !== 'A')
.map(([status, file]) => `${status} ${file}`)
if (changedHistoricalMigrations.length > 0) {
failures.push(`历史迁移文件不可修改: ${changedHistoricalMigrations.join(', ')}`)
}
} catch (error) {
failures.push(`历史迁移完整性检查失败: ${error instanceof Error ? error.message : String(error)}`)
}
for (const check of checks) {
if (!fs.existsSync(check.file)) {
failures.push(`${check.name}: 文件不存在 ${check.file}`)
@@ -0,0 +1,8 @@
-- 将历史平板会话归入手机设备桶,确保新旧数据使用同一套 PC/手机上限。
UPDATE worker_sessions
SET device_type = 'mobile', updated_at = NOW()
WHERE device_type = 'tablet';
UPDATE worker_sessions
SET device_type = 'pc', updated_at = NOW()
WHERE device_type IS NULL OR device_type NOT IN ('pc', 'mobile');
@@ -41,9 +41,9 @@ export async function createWorkerSessionRecord(
)
const activeResult = await client.query<WorkerSessionRow>(
`SELECT * FROM worker_sessions
WHERE worker_id = $1 AND status = 'active' AND expires_at > $2
WHERE worker_id = $1 AND device_type = $2 AND status = 'active' AND expires_at > $3
ORDER BY last_seen_at DESC, id DESC`,
[input.workerId, input.now],
[input.workerId, input.deviceType, input.now],
)
const activeSessions = activeResult.rows
if (activeSessions.length >= input.maxDevices) {
@@ -0,0 +1,11 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { normalizeWorkerDeviceType } from './worker-auth-policy.js'
test('worker device types use separate PC and mobile buckets', () => {
assert.equal(normalizeWorkerDeviceType('pc'), 'pc')
assert.equal(normalizeWorkerDeviceType('desktop'), 'pc')
assert.equal(normalizeWorkerDeviceType('mobile'), 'mobile')
assert.equal(normalizeWorkerDeviceType('tablet'), 'mobile')
})
@@ -28,7 +28,7 @@ export function normalizeWorkerDeviceType(value: unknown): string {
const type = String(value || '')
.trim()
.toLowerCase()
return type === 'mobile' || type === 'tablet' ? type : 'pc'
return type === 'mobile' || type === 'tablet' ? 'mobile' : 'pc'
}
export function normalizeWorkerDeviceId(value: unknown, fallback: string): string {
@@ -141,10 +141,14 @@ async function createWorkerLoginSession(
maxDevices: WORKER_MAX_DEVICES,
})
if (!sessionRecord.created) {
throw createHttpError('在线设备已达到 3 台,请先删除旧的登录设备', {
statusCode: 409,
errorCode: 'worker_device_limit',
})
const deviceLabel = deviceType === 'pc' ? 'PC' : '手机'
throw createHttpError(
`${deviceLabel}设备已达到 ${WORKER_MAX_DEVICES} 台,请先删除旧的登录设备`,
{
statusCode: 409,
errorCode: 'worker_device_limit',
},
)
}
return { ...session, passwordWeak }
}
@@ -135,8 +135,18 @@ export async function verifyWorkerSessionToken(token: unknown): Promise<WorkerSe
export async function getWorkerSessions(session: WorkerSession) {
const sessions = await listWorkerSessions(session.workerId, nowIso())
const deviceCounts = sessions.reduce(
(counts, item) => {
const deviceType = item.device_type === 'mobile' ? 'mobile' : 'pc'
counts[deviceType] += 1
return counts
},
{ pc: 0, mobile: 0 },
)
return {
maxDevices: WORKER_MAX_DEVICES,
maxDevicesByType: { pc: WORKER_MAX_DEVICES, mobile: WORKER_MAX_DEVICES },
deviceCounts,
items: sessions.map((item) => mapWorkerSession(item, session.sessionId)),
}
}