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)),
}
}
@@ -662,7 +662,7 @@ export default function WorkerLoginPage() {
<Alert
showIcon
type="info"
message="验证账号密码后,可删除旧设备。所有 PC 和手机合计最多同时在线 3 台。"
message="验证账号密码后,可删除旧设备。PC 和手机分别最多同时在线 3 台。"
style={{ marginBottom: 16 }}
/>
<Table
@@ -38,6 +38,7 @@ export function WorkerProfileAccountModals({
setDevicesOpen,
devices,
maxDevices,
deviceCounts,
devicesLoading,
removeWorkerDevice,
passwordOpen,
@@ -60,6 +61,7 @@ export function WorkerProfileAccountModals({
setDevicesOpen: (open: boolean) => void
devices: WorkerSessionDevice[]
maxDevices: number
deviceCounts: { pc: number; mobile: number }
devicesLoading: boolean
removeWorkerDevice: (device: WorkerSessionDevice) => Promise<void>
passwordOpen: boolean
@@ -88,7 +90,7 @@ export function WorkerProfileAccountModals({
<Alert
showIcon
type="info"
message={`所有设备合计最多同时在线 ${maxDevices} 台,删除旧设备后才能在新设备登录。`}
message={`PC 和手机分别最多同时在线 ${maxDevices}(当前 PC ${deviceCounts.pc} 台、手机 ${deviceCounts.mobile} 台),删除对应旧设备后才能登录。`}
/>
<Table<WorkerSessionDevice>
size="small"
@@ -658,6 +658,7 @@ export default function WorkerProfilePage() {
setDevicesOpen={setDevicesOpen}
devices={devicesQuery.data?.data.items || []}
maxDevices={devicesQuery.data?.data.maxDevices || 3}
deviceCounts={devicesQuery.data?.data.deviceCounts || { pc: 0, mobile: 0 }}
devicesLoading={devicesQuery.isLoading || devicesQuery.isFetching}
removeWorkerDevice={removeWorkerDevice}
passwordOpen={passwordOpen}
+9 -5
View File
@@ -94,7 +94,7 @@ export function loginWorkerBySmsCode(payload: { phone: string; code: string }) {
}
export function fetchWorkerSessions() {
return apiGet<{ maxDevices: number; items: WorkerSessionDevice[] }>('/api/v1/worker/auth/devices')
return apiGet<WorkerDeviceLimitsResponse>('/api/v1/worker/auth/devices')
}
export function deleteWorkerSession(sessionId: string) {
@@ -102,10 +102,14 @@ export function deleteWorkerSession(sessionId: string) {
}
export function manageWorkerSessions(payload: { username: string; password: string }) {
return apiPost<{ maxDevices: number; items: WorkerSessionDevice[] }>(
'/api/v1/worker/auth/devices/manage/list',
payload,
)
return apiPost<WorkerDeviceLimitsResponse>('/api/v1/worker/auth/devices/manage/list', payload)
}
export type WorkerDeviceLimitsResponse = {
maxDevices: number
maxDevicesByType: { pc: number; mobile: number }
deviceCounts: { pc: number; mobile: number }
items: WorkerSessionDevice[]
}
export function deleteWorkerSessionWithCredentials(payload: {