文件
OmniCard/backend/test/modules/nfc/security.test.ts
wikiboss 62e0ae4435 feat: 同步管理端、用户端与后端业务,并接通线上 Web 接口
补齐平台订阅、外部登录、CRM 同步与用户端页面;Nginx 转发用户端接口,登录页使用 Google 与 Apple 标志。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 18:01:47 +08:00

326 行
10 KiB
TypeScript

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

import * as fs from 'fs';
import * as path from 'path';
import { CONTROLLER_KEY, getClassMetadata } from '@midwayjs/core';
import { BaseController, CoolCommException, CurdOption } from '@cool-midway/core';
import { NfcDeviceEntity } from '../../../src/modules/nfc/entity/device';
import { NfcSecurityService } from '../../../src/modules/nfc/service/security';
import {
AdminNfcSecurityController,
adminNfcSecurityCurdOption,
} from '../../../src/modules/nfc/controller/admin/security';
import {
AUDIT_ACTION_NFC_FREEZE,
BaseAuditLogService,
} from '../../../src/modules/base/service/audit';
/**
* CoolController 元数据(脚本路径解析为异步)
*/
interface CoolControllerMeta {
prefix?: string;
curdOption?: CurdOption;
}
/**
* 等待 CoolController 将 CRUD 配置写入类元数据
*/
async function waitCoolMeta(
target: new (...args: never[]) => unknown
): Promise<CoolControllerMeta> {
const started = Date.now();
while (Date.now() - started < 2000) {
const meta = getClassMetadata(CONTROLLER_KEY, target) as
| CoolControllerMeta
| undefined;
if (meta?.curdOption) {
return meta;
}
await new Promise<void>(resolve => setImmediate(resolve));
}
throw new Error(`${target.name} 的 CoolController 元数据未就绪`);
}
function serviceApiMethods(apis: CurdOption['serviceApis'] = []): string[] {
return apis.map(api => (typeof api === 'string' ? api : api.method));
}
interface DeviceFindWhere {
id?: number;
uid?: string;
}
/**
* 内存 Repository,覆盖 findOneBy / save
*/
class MemoryNfcDeviceRepo {
private data: NfcDeviceEntity[] = [];
private currentId = 1;
constructor(initialData: Array<Partial<NfcDeviceEntity>> = []) {
this.data = initialData.map(item => this.createEntity(item));
if (this.data.length > 0) {
this.currentId = Math.max(...this.data.map(d => Number(d.id) || 0)) + 1;
}
}
private createEntity(item: Partial<NfcDeviceEntity>): NfcDeviceEntity {
const entity = new NfcDeviceEntity();
Object.assign(entity, {
id: item.id || this.currentId++,
createTime: item.createTime || new Date(),
updateTime: new Date(),
...item,
});
return entity;
}
async findOneBy(where: DeviceFindWhere): Promise<NfcDeviceEntity | null> {
const found = this.data.find(item => {
const keys = Object.keys(where) as Array<keyof DeviceFindWhere>;
return keys.every(key => {
const expected = where[key];
return expected === undefined || item[key] === expected;
});
});
return found ? ({ ...found } as NfcDeviceEntity) : null;
}
async save(
entityOrEntities:
| Partial<NfcDeviceEntity>
| Array<Partial<NfcDeviceEntity>>
): Promise<NfcDeviceEntity | NfcDeviceEntity[]> {
if (Array.isArray(entityOrEntities)) {
const savedList: NfcDeviceEntity[] = [];
for (const item of entityOrEntities) {
savedList.push((await this.save(item)) as NfcDeviceEntity);
}
return savedList;
}
const item = entityOrEntities;
if (item.id) {
const index = this.data.findIndex(d => d.id === item.id);
if (index !== -1) {
this.data[index] = {
...this.data[index],
...item,
updateTime: new Date(),
} as NfcDeviceEntity;
return { ...this.data[index] } as NfcDeviceEntity;
}
}
const newEntity = this.createEntity(item);
this.data.push(newEntity);
return { ...newEntity } as NfcDeviceEntity;
}
}
function createService(
seed: Array<Partial<NfcDeviceEntity>> = [],
auditRecord?: jest.Mock
): NfcSecurityService {
const service = new NfcSecurityService();
service.nfcDeviceEntity = new MemoryNfcDeviceRepo(
seed
) as unknown as NfcSecurityService['nfcDeviceEntity'];
const auditService = new BaseAuditLogService();
auditService.record = (auditRecord ||
jest.fn(async dto => dto)) as unknown as BaseAuditLogService['record'];
service.baseAuditLogService = auditService;
return service;
}
function seedDevices(): Array<Partial<NfcDeviceEntity>> {
return [
{
id: 1,
uid: '04:7A:B2:8F:1C:6D:80',
cardId: 1001,
batchNo: 'B2026-01',
material: 'metal',
status: 'active',
sceneMode: 'social',
},
{
id: 2,
uid: '04:11:22:33:44:55:66',
cardId: 2002,
batchNo: 'B2026-01',
material: 'pvc',
status: 'suspended',
sceneMode: 'business',
},
{
id: 3,
uid: '04:AA:BB:CC:DD:EE:FF',
cardId: null,
batchNo: 'B2026-02',
material: 'wood',
status: 'suspended',
sceneMode: 'social',
},
{
id: 4,
uid: '04:00:00:00:00:00:01',
cardId: 4004,
batchNo: 'B2026-03',
material: 'pvc',
status: 'active',
sceneMode: 'business',
},
];
}
describe('T24 NFC 挂失冻结 API (nfc/security)', () => {
describe('1. freeze / unfreeze / reset', () => {
it('active freeze 后 status 为 suspended 且 cardId 不变', async () => {
const service = createService(seedDevices());
const frozen = await service.freeze({ uid: '04:7A:B2:8F:1C:6D:80' });
expect(frozen.status).toBe('suspended');
expect(frozen.cardId).toBe(1001);
expect(frozen.uid).toBe('04:7A:B2:8F:1C:6D:80');
});
it('已是 suspended 的 freeze 应幂等且仍保留 cardId', async () => {
const service = createService(seedDevices());
const frozen = await service.freeze({ id: 2 });
expect(frozen.status).toBe('suspended');
expect(frozen.cardId).toBe(2002);
});
it('unfreeze 有 cardId 时应回到 active', async () => {
const service = createService(seedDevices());
const restored = await service.unfreeze({ uid: '04:11:22:33:44:55:66' });
expect(restored.status).toBe('active');
expect(restored.cardId).toBe(2002);
});
it('unfreeze 无 cardId 时应回到 unbound', async () => {
const service = createService(seedDevices());
const restored = await service.unfreeze({ id: 3 });
expect(restored.status).toBe('unbound');
expect(restored.cardId == null).toBe(true);
});
it('unfreeze 非 suspended 应抛 CoolCommException', async () => {
const service = createService(seedDevices());
await expect(
service.unfreeze({ uid: '04:7A:B2:8F:1C:6D:80' })
).rejects.toThrow(CoolCommException);
});
it('reset 应清空 cardId、status 为 unbound 且 sceneMode 回 business', async () => {
const service = createService(seedDevices());
const reset = await service.reset({ uid: '04:7A:B2:8F:1C:6D:80' });
expect(reset.cardId == null).toBe(true);
expect(reset.status).toBe('unbound');
expect(reset.sceneMode).toBe('business');
});
it('按数字 id 查不到设备时应抛 CoolCommException', async () => {
const service = createService(seedDevices());
await expect(service.freeze({ id: 9999 })).rejects.toThrow(
CoolCommException
);
await expect(service.unfreeze({ id: 9999 })).rejects.toThrow(
CoolCommException
);
await expect(service.reset({ uid: 'not-exist' })).rejects.toThrow(
CoolCommException
);
});
it('freeze 成功后应写入 nfc_freeze 审计(含操作者与 uid/设备 id)', async () => {
const record = jest.fn(async dto => dto);
const service = createService(seedDevices(), record);
service.baseCtx = {
admin: { userId: 42, username: 'SecAdmin' },
} as unknown as NfcSecurityService['baseCtx'];
const frozen = await service.freeze({ uid: '04:7A:B2:8F:1C:6D:80' });
expect(frozen.status).toBe('suspended');
expect(record).toHaveBeenCalledTimes(1);
expect(record).toHaveBeenCalledWith(
expect.objectContaining({
module: 'nfc',
action: AUDIT_ACTION_NFC_FREEZE,
operatorId: 42,
operatorName: 'SecAdmin',
status: 1,
})
);
const detail = JSON.parse(String(record.mock.calls[0][0].detail));
expect(detail.uid).toBe('04:7A:B2:8F:1C:6D:80');
expect(detail.deviceId).toBe(1);
expect(detail).not.toHaveProperty('secret');
expect(detail).not.toHaveProperty('phone');
});
it('freeze 失败(设备不存在)时不得记成功审计', async () => {
const record = jest.fn(async dto => dto);
const service = createService(seedDevices(), record);
await expect(service.freeze({ id: 9999 })).rejects.toThrow(
CoolCommException
);
expect(record).not.toHaveBeenCalled();
});
});
describe('2. 后台控制器 /admin/nfc/security', () => {
const controllerFile = path.join(
__dirname,
'../../../src/modules/nfc/controller/admin/security.ts'
);
let meta: CoolControllerMeta;
let option: CurdOption;
beforeAll(async () => {
meta = await waitCoolMeta(AdminNfcSecurityController);
option = meta.curdOption as CurdOption;
});
it('文件路径应符合 /admin/nfc/security 自动路由约定', () => {
expect(fs.existsSync(controllerFile)).toBe(true);
expect(controllerFile.replace(/\\/g, '/')).toMatch(
/modules\/nfc\/controller\/admin\/security\.ts$/
);
});
it('路由前缀应为 /admin/nfc/security', () => {
expect(meta.prefix).toBe('/admin/nfc/security');
});
it('控制器应继承 BaseController,不开标准 CRUD,并绑定实体与服务', () => {
expect(AdminNfcSecurityController.prototype).toBeInstanceOf(
BaseController
);
expect(option.api).toEqual([]);
expect(option.entity).toBe(NfcDeviceEntity);
expect(option.service).toBe(NfcSecurityService);
expect(adminNfcSecurityCurdOption.api).toEqual([]);
expect(adminNfcSecurityCurdOption.entity).toBe(NfcDeviceEntity);
expect(adminNfcSecurityCurdOption.service).toBe(NfcSecurityService);
});
it('应将 freeze / unfreeze / reset 注册为 serviceApis', () => {
const methods = serviceApiMethods(option.serviceApis);
expect(methods).toEqual(['freeze', 'unfreeze', 'reset']);
expect(serviceApiMethods(adminNfcSecurityCurdOption.serviceApis)).toEqual([
'freeze',
'unfreeze',
'reset',
]);
});
});
});