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
@@ -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)),
}
}