fix(qa): 第五轮系统性质量保障缺陷修复 + 单元/集成测试
安全/鉴权:登出清服务端 httpOnly 令牌、登录 IP 限流前置 bcrypt、停用账号 令牌在 6 个内联 role handler 失效、admin/items 存在性 oracle 认证前置、 同意偏好 sanitize fail-closed、api-crypto 按 HTTP 方法判体。 CMS:workflow 状态更新+审计收进交互式 $transaction(失败即回滚)、编辑器 richtext 走 textarea 防换行损毁、array/object 子字段按作用域读写防污染、 about/contact/erp-upgrade 补 ISR revalidate 与路由映射。 UI/a11y:AnimatedCounter 入视口前显起点、CLS 累计上报、MetricCard 动画入 effect 并卸载取消 rAF、后台状态四态映射/搜索防抖+序号守卫/媒体单 input/ 吞错改横幅/表单 label-aria 关联。 新增对应判别性单测与 pagination/rate-limit/client-ip/sanitize/validate-content-data 等模块及 tests-integration 真库集成层。
This commit is contained in:
1 parent
040951c0a3
commit
a366bd1400
224 files changed
+8938
-5579
No files matched your search
@@ -149,6 +149,62 @@ describe('AdminApiClient', () => {
|
||||
|
||||
await expect(adminApi.request('/api/admin/models')).rejects.toThrow('模型不存在');
|
||||
});
|
||||
|
||||
// L-1:withCrypto 会把 4xx/5xx 也加密成 { data: <encrypted> } + X-Encrypted: true,
|
||||
// 解密成功后的错误信封必须按 res.ok 拒绝,且优先透出服务端自己的错误文案。
|
||||
it('rejects encrypted error envelope (403) with the server message', async () => {
|
||||
mockStorage['novalon_admin_token'] = 'test-token';
|
||||
mockDecrypt.mockResolvedValue(JSON.stringify({ error: '无权修改该内容' }));
|
||||
mockFetch.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ data: 'encrypted-error' }), {
|
||||
status: 403,
|
||||
headers: { 'Content-Type': 'application/json', 'X-Encrypted': 'true' },
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(adminApi.updateItem('item-1', { title: 'x' })).rejects.toThrow('无权修改该内容');
|
||||
expect(mockDecrypt).toHaveBeenCalledWith('encrypted-error');
|
||||
});
|
||||
|
||||
it('rejects encrypted error envelope (400) preferring message field', async () => {
|
||||
mockStorage['novalon_admin_token'] = 'test-token';
|
||||
mockEncrypt.mockResolvedValue('encrypted-data');
|
||||
mockDecrypt.mockResolvedValue(JSON.stringify({ message: '字段校验失败' }));
|
||||
mockFetch.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ data: 'encrypted-error' }), {
|
||||
status: 400,
|
||||
headers: { 'Content-Type': 'application/json', 'X-Encrypted': 'true' },
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(adminApi.createItem({ title: 'x' })).rejects.toThrow('字段校验失败');
|
||||
});
|
||||
|
||||
it('falls back to status when decrypted error envelope carries no message', async () => {
|
||||
mockStorage['novalon_admin_token'] = 'test-token';
|
||||
mockDecrypt.mockResolvedValue(JSON.stringify({ detail: 'opaque' }));
|
||||
mockFetch.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ data: 'encrypted-error' }), {
|
||||
status: 403,
|
||||
headers: { 'Content-Type': 'application/json', 'X-Encrypted': 'true' },
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(adminApi.getItems({ page: 1 })).rejects.toThrow('请求失败 (403)');
|
||||
});
|
||||
|
||||
it('resolves encrypted success response unchanged', async () => {
|
||||
mockStorage['novalon_admin_token'] = 'test-token';
|
||||
mockDecrypt.mockResolvedValue(JSON.stringify({ items: [{ id: 'a' }], total: 1 }));
|
||||
mockFetch.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ data: 'encrypted-ok' }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json', 'X-Encrypted': 'true' },
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(adminApi.getItems({ page: 1 })).resolves.toEqual({ items: [{ id: 'a' }], total: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
// ============ 公开 API 方法测试 ============
|
||||
|
||||
+30
-11
@@ -69,26 +69,31 @@ class AdminApiClient {
|
||||
throw new Error('未授权');
|
||||
}
|
||||
|
||||
// 解密响应体
|
||||
// 解密响应体(withCrypto 对非 2xx 同样加密,故错误信封解密后仍须按 res.ok 拒绝)
|
||||
const isEncryptedResponse = res.headers.get('X-Encrypted') === 'true';
|
||||
if (isEncryptedResponse) {
|
||||
let payload: unknown;
|
||||
try {
|
||||
const responseText = await res.text();
|
||||
const responseJson = JSON.parse(responseText);
|
||||
const encryptedData = responseJson.data as string;
|
||||
if (encryptedData) {
|
||||
const decryptedText = await decrypt(encryptedData);
|
||||
return JSON.parse(decryptedText) as T;
|
||||
}
|
||||
return responseJson as T;
|
||||
payload = encryptedData
|
||||
? JSON.parse(await decrypt(encryptedData))
|
||||
: responseJson;
|
||||
} catch (e) {
|
||||
// 解密失败时尝试读取原始 JSON
|
||||
// 解密失败时降级为状态码错误(响应体已被读取,无法再取明文 error)
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
throw new Error(data.error || data.message || `请求失败 (${res.status})`);
|
||||
throw new Error(`请求失败 (${res.status})`);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const error = payload as { error?: string; message?: string } | null;
|
||||
throw new Error(error?.error || error?.message || `请求失败 (${res.status})`);
|
||||
}
|
||||
|
||||
return payload as T;
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
@@ -139,8 +144,22 @@ class AdminApiClient {
|
||||
});
|
||||
}
|
||||
|
||||
async deleteItem(id: string) {
|
||||
return this.request(`/api/admin/items?id=${id}`, {
|
||||
/**
|
||||
* 状态流转的唯一通道(B-1):POST 只建草稿、PUT 拒绝改 status,publish 权限只在
|
||||
* /api/admin/items/[id]/workflow 上校验。draft→submit→review→approve→published。
|
||||
*/
|
||||
async runWorkflow(
|
||||
id: string,
|
||||
action: 'submit' | 'approve' | 'reject' | 'archive',
|
||||
reason?: string,
|
||||
) {
|
||||
return this.request<{ id?: string; status?: string }>(`/api/admin/items/${id}/workflow`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(reason ? { action, reason } : { action }),
|
||||
});
|
||||
}
|
||||
|
||||
async deleteItem(id: string) { return this.request(`/api/admin/items?id=${id}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
}
|
||||
|
||||
+66
-13
@@ -70,6 +70,32 @@ describe('Analytics', () => {
|
||||
const result = analytics.getStoredPreferences();
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
// Q-10③:localStorage 可能被篡改/写坏;同意判定必须严格,真值非布尔不得当作已同意(fail-closed)。
|
||||
it('coerces truthy non-boolean consent fields to false instead of granting', () => {
|
||||
localStorageMock.setItem(
|
||||
'novalon-cookie-preferences',
|
||||
JSON.stringify({ necessary: false, analytics: 'yes', marketing: 1, functionality: true })
|
||||
);
|
||||
const result = analytics.getStoredPreferences();
|
||||
expect(result).toEqual({
|
||||
necessary: true, // 必要类恒真,不受存储值影响
|
||||
analytics: false, // 'yes' 非严格 true ⇒ 不授予
|
||||
marketing: false, // 1 非严格 true ⇒ 不授予
|
||||
functionality: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores a non-object payload (array/number) rather than trusting it', () => {
|
||||
localStorageMock.setItem('novalon-cookie-preferences', '[1,2,3]');
|
||||
const result = analytics.getStoredPreferences();
|
||||
expect(result).toEqual({
|
||||
necessary: true,
|
||||
analytics: false,
|
||||
marketing: false,
|
||||
functionality: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('storePreferences', () => {
|
||||
@@ -88,6 +114,8 @@ describe('Analytics', () => {
|
||||
throw new Error('Storage full');
|
||||
});
|
||||
|
||||
// 本地 spy:jest.setup.js 只静音 info/debug,warn 不再是全局 mock
|
||||
const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
analytics.storePreferences({
|
||||
necessary: true,
|
||||
analytics: true,
|
||||
@@ -95,7 +123,8 @@ describe('Analytics', () => {
|
||||
functionality: true,
|
||||
});
|
||||
|
||||
expect(console.warn).toHaveBeenCalled();
|
||||
expect(warnSpy).toHaveBeenCalled();
|
||||
warnSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -153,8 +182,10 @@ describe('Analytics', () => {
|
||||
});
|
||||
|
||||
it('should not call gtag when not available', () => {
|
||||
analytics.trackEvent('click', 'engagement', 'button-1', 1);
|
||||
// No gtag available, should not throw
|
||||
expect((window as any).gtag).toBeUndefined();
|
||||
expect(() =>
|
||||
analytics.trackEvent('click', 'engagement', 'button-1', 1)
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -192,8 +223,12 @@ describe('Analytics', () => {
|
||||
});
|
||||
|
||||
it('should warn when gtag is not available', () => {
|
||||
const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
analytics.trackError('TEST', 'No gtag');
|
||||
expect(console.warn).toHaveBeenCalled();
|
||||
|
||||
expect(warnSpy).toHaveBeenCalled();
|
||||
warnSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('should set fatal to "false" string when not fatal', () => {
|
||||
@@ -205,6 +240,17 @@ describe('Analytics', () => {
|
||||
const callArgs = gtag.mock.calls[0]?.[2] as Record<string, unknown>;
|
||||
expect(callArgs?.fatal).toBe('false');
|
||||
});
|
||||
|
||||
it('should not echo tracked errors to the console', () => {
|
||||
const gtag = jest.fn();
|
||||
(window as any).gtag = gtag;
|
||||
const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
|
||||
|
||||
analytics.trackError('API_ERROR', 'Failed to fetch', true);
|
||||
|
||||
expect(logSpy).not.toHaveBeenCalled();
|
||||
logSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('trackPageView', () => {
|
||||
@@ -221,7 +267,8 @@ describe('Analytics', () => {
|
||||
});
|
||||
|
||||
it('should not throw when gtag is not available', () => {
|
||||
analytics.trackPageView('/', 'Home');
|
||||
expect((window as any).gtag).toBeUndefined();
|
||||
expect(() => analytics.trackPageView('/', 'Home')).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -326,28 +373,34 @@ describe('Analytics', () => {
|
||||
const callArgs = gtag.mock.calls[0]?.[2] as Record<string, unknown>;
|
||||
expect(callArgs?.value).toBe(1);
|
||||
});
|
||||
|
||||
it('should keep an explicit value of 0', () => {
|
||||
const gtag = jest.fn();
|
||||
(window as any).gtag = gtag;
|
||||
|
||||
analytics.trackConversion('zero_value_conversion', 0);
|
||||
|
||||
const callArgs = gtag.mock.calls[0]?.[2] as Record<string, unknown>;
|
||||
expect(callArgs?.value).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('trackOutboundLink', () => {
|
||||
it('should call gtag with outbound link data', () => {
|
||||
it('should send exactly one outbound_click event', () => {
|
||||
const gtag = jest.fn();
|
||||
(window as any).gtag = gtag;
|
||||
|
||||
analytics.trackOutboundLink('https://example.com', 'Example');
|
||||
|
||||
// 旧实现同时发 outbound_click 与 click,GA4 里每次外跳被双计。
|
||||
expect(gtag).toHaveBeenCalledTimes(1);
|
||||
expect(gtag).toHaveBeenCalledWith('event', 'outbound_click', {
|
||||
event_category: 'engagement',
|
||||
event_label: 'https://example.com',
|
||||
event_value: undefined,
|
||||
send_to: 'G-TEST123',
|
||||
});
|
||||
|
||||
expect(gtag).toHaveBeenCalledWith('event', 'click', {
|
||||
event_category: 'outbound',
|
||||
event_label: 'https://example.com',
|
||||
transport_type: 'beacon',
|
||||
send_to: 'G-TEST123',
|
||||
});
|
||||
expect(gtag).not.toHaveBeenCalledWith('event', 'click', expect.anything());
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+25
-15
@@ -26,13 +26,35 @@ export function getDefaultPreferences(): CookiePreferences {
|
||||
return { ...DEFAULT_PREFERENCES };
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 localStorage 里可能被篡改/半截的原始值收敛为类型安全的 CookiePreferences。
|
||||
* 动机(Q-10③):`updateConsentDetailed` 用 `preferences.analytics ? 'granted' : 'denied'` 判定,
|
||||
* 而旧实现把 `JSON.parse(...) as CookiePreferences` 直接透传 ⇒ 一个 `"no"`/`1`/任意真值字符串
|
||||
* 会「意外获得」analytics/ad 同意(隐私合规上是 fail-open)。此处对四个开关做「严格 === true
|
||||
* 才算同意」的白名单式收敛,necessary 恒为真(不受存储值影响)。
|
||||
*/
|
||||
function sanitizePreferences(raw: unknown): CookiePreferences {
|
||||
const src = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
|
||||
const granted = (v: unknown): boolean => v === true;
|
||||
const pref: CookiePreferences = {
|
||||
necessary: true,
|
||||
analytics: granted(src.analytics),
|
||||
marketing: granted(src.marketing),
|
||||
functionality: granted(src.functionality),
|
||||
};
|
||||
if (typeof src.timestamp === 'number') {
|
||||
pref.timestamp = src.timestamp;
|
||||
}
|
||||
return pref;
|
||||
}
|
||||
|
||||
export function getStoredPreferences(): CookiePreferences | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
|
||||
try {
|
||||
const stored = localStorage.getItem('novalon-cookie-preferences');
|
||||
if (stored) {
|
||||
return JSON.parse(stored) as CookiePreferences;
|
||||
return sanitizePreferences(JSON.parse(stored));
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('[Analytics] Failed to read cookie preferences:', e);
|
||||
@@ -112,10 +134,6 @@ export function trackError(
|
||||
...errorData,
|
||||
send_to: GA_MEASUREMENT_ID,
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.log('[GA4] Error tracked:', errorData);
|
||||
}
|
||||
}
|
||||
|
||||
export function trackPageView(url: string, title: string): void {
|
||||
@@ -169,23 +187,15 @@ export function trackConversion(conversionLabel: string, value?: number): void {
|
||||
window.gtag('event', 'conversion', {
|
||||
send_to: GA_MEASUREMENT_ID,
|
||||
transaction_id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
||||
value: value || 1,
|
||||
value: value ?? 1,
|
||||
currency: 'CNY',
|
||||
conversion_label: conversionLabel,
|
||||
});
|
||||
}
|
||||
|
||||
export function trackOutboundLink(url: string, _linkText?: string): void {
|
||||
// 单次发送:此前同时发 outbound_click 与 click,GA4 里每次外跳被计两次。
|
||||
trackEvent('outbound_click', 'engagement', url);
|
||||
|
||||
if (typeof window !== 'undefined' && window.gtag && GA_MEASUREMENT_ID) {
|
||||
window.gtag('event', 'click', {
|
||||
event_category: 'outbound',
|
||||
event_label: url,
|
||||
transport_type: 'beacon',
|
||||
send_to: GA_MEASUREMENT_ID,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function trackScrollDepth(percentage: number, _maxScroll?: number): void {
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// @ts-nocheck
|
||||
|
||||
|
||||
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
|
||||
import { describe, it, expect, jest, beforeEach, afterEach } from '@jest/globals';
|
||||
|
||||
// ========== 全局 Mock 设置 ==========
|
||||
|
||||
@@ -239,14 +239,21 @@ type HandlerFn = (
|
||||
// ========== 测试套件 ==========
|
||||
|
||||
describe('withCrypto', () => {
|
||||
// jest.setup.js 只静音 info/debug,console.error 是真实函数;断言错误日志必须自带 spy,
|
||||
// 并在 afterEach 还原,避免把静音状态泄漏给其它套件。
|
||||
let errorSpy: ReturnType<typeof jest.spyOn>;
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
mockIsEncryptionAvailable.mockReturnValue(true);
|
||||
mockEncrypt.mockImplementation((text: string) => `enc:${text}`);
|
||||
mockDecrypt.mockImplementation(
|
||||
(text: string) => text.replace(/^enc:/, ''),
|
||||
);
|
||||
});
|
||||
afterEach(() => {
|
||||
errorSpy.mockRestore();
|
||||
});
|
||||
|
||||
// ── 未加密请求 ──────────────────────────────────────────────
|
||||
|
||||
@@ -395,6 +402,33 @@ describe('withCrypto', () => {
|
||||
expect(body).toEqual({ data: 'enc:{"params":{"id":"123"}}' });
|
||||
});
|
||||
|
||||
// Q-10①:是否有请求体应按 HTTP 方法判定,不能信任客户端可缺失/可自报的 content-length。
|
||||
// 分块传输的加密 POST 不带 content-length 头 ⇒ 旧实现判为「无 body」跳过解密、把密文交给 handler。
|
||||
it('加密 POST 无 content-length 头(分块传输)时仍解密请求体', async () => {
|
||||
const handler = jest
|
||||
.fn<HandlerFn>()
|
||||
.mockImplementation(async (req: NextRequest) => {
|
||||
const body = await (req as any).json();
|
||||
return NextResponse.json({ received: body }) as unknown as NextResponse;
|
||||
});
|
||||
const wrapped = withCrypto(handler);
|
||||
|
||||
const req = createRequest('http://localhost/api/test', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'x-encrypted': 'true',
|
||||
'content-type': 'application/json',
|
||||
// 故意省略 content-length
|
||||
},
|
||||
body: JSON.stringify({ data: 'enc:{"chunked":true}' }),
|
||||
});
|
||||
await wrapped(req);
|
||||
|
||||
expect(mockDecrypt).toHaveBeenCalledWith('enc:{"chunked":true}');
|
||||
const handlerReq = handler.mock.calls[0]?.[0] as any;
|
||||
expect(await handlerReq.json()).toEqual({ chunked: true });
|
||||
});
|
||||
|
||||
// ── 加密请求(body 解密失败) ───────────────────────────────
|
||||
|
||||
it('加密请求 body 解密失败时返回 400 错误', async () => {
|
||||
@@ -553,13 +587,18 @@ describe('withCrypto', () => {
|
||||
});
|
||||
|
||||
describe('decryptRequest', () => {
|
||||
let errorSpy: ReturnType<typeof jest.spyOn>;
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
mockIsEncryptionAvailable.mockReturnValue(true);
|
||||
mockDecrypt.mockImplementation(
|
||||
(text: string) => text.replace(/^enc:/, ''),
|
||||
);
|
||||
});
|
||||
afterEach(() => {
|
||||
errorSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('加密不可用时返回 null', async () => {
|
||||
mockIsEncryptionAvailable.mockReturnValue(false);
|
||||
|
||||
@@ -46,10 +46,13 @@ export function withCrypto<T extends Record<string, unknown> = Record<string, un
|
||||
}
|
||||
|
||||
// ---- 解密请求体 ----
|
||||
const contentLength = request.headers.get('content-length');
|
||||
const hasBody = contentLength && parseInt(contentLength) > 0;
|
||||
// 是否有请求体按 HTTP 方法判定,不看客户端可缺失/可自报的 content-length:
|
||||
// 分块传输(无 content-length 头)的加密 POST/PUT/PATCH 旧会被误判为「无 body」而跳过解密,
|
||||
// 把密文 {data:"..."} 原样交给 handler(Q-10①)。
|
||||
const method = request.method.toUpperCase();
|
||||
const mayHaveBody = method === 'POST' || method === 'PUT' || method === 'PATCH';
|
||||
|
||||
if (hasBody) {
|
||||
if (mayHaveBody) {
|
||||
try {
|
||||
const cloned = request.clone();
|
||||
const bodyText = await cloned.text();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// @ts-nocheck
|
||||
import { describe, it, expect, jest, beforeEach } from '@jest/globals';
|
||||
import { describe, it, expect, jest, beforeEach, afterEach } from '@jest/globals';
|
||||
import {
|
||||
unauthorized,
|
||||
forbidden,
|
||||
@@ -90,8 +90,14 @@ describe('badRequest', () => {
|
||||
});
|
||||
|
||||
describe('internalError', () => {
|
||||
// jest.setup.js 只静音 info/debug,console.error 是真实函数;要断言日志就得自带 spy 并还原
|
||||
let errorSpy: ReturnType<typeof jest.spyOn>;
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
afterEach(() => {
|
||||
errorSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('返回默认错误消息和 500 状态码', async () => {
|
||||
@@ -131,8 +137,13 @@ describe('success', () => {
|
||||
});
|
||||
|
||||
describe('handleApiError', () => {
|
||||
let errorSpy: ReturnType<typeof jest.spyOn>;
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
afterEach(() => {
|
||||
errorSpy.mockRestore();
|
||||
});
|
||||
|
||||
it('包含 "未授权" 的 Error 返回 unauthorized 响应', async () => {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, it, expect } from "@jest/globals";
|
||||
import { getClientIp } from "./client-ip";
|
||||
|
||||
function headersOf(init: Record<string, string>): Headers {
|
||||
return new Headers(init);
|
||||
}
|
||||
|
||||
describe("getClientIp", () => {
|
||||
it("优先取 X-Real-IP(Nginx 用 $remote_addr 覆写,客户端无法伪造)", () => {
|
||||
const headers = headersOf({
|
||||
"x-real-ip": "203.0.113.9",
|
||||
"x-forwarded-for": "1.1.1.1",
|
||||
});
|
||||
|
||||
expect(getClientIp(headers)).toBe("203.0.113.9");
|
||||
});
|
||||
|
||||
it("N-25 攻击面:伪造最左 XFF 不得改变限流桶(无 X-Real-IP 时取链尾)", () => {
|
||||
const headers = headersOf({
|
||||
"x-forwarded-for": "1.1.1.1, 2.2.2.2, 198.51.100.7",
|
||||
});
|
||||
|
||||
expect(getClientIp(headers)).toBe("198.51.100.7");
|
||||
});
|
||||
|
||||
it("逐请求轮换 XFF 时,旧实现会得到 3 个不同桶、新实现稳定为一个", () => {
|
||||
const spoofed = ["1.1.1.1", "2.2.2.2", "3.3.3.3"].map((ip) =>
|
||||
headersOf({ "x-forwarded-for": `${ip}, 198.51.100.7` }),
|
||||
);
|
||||
|
||||
const buckets = new Set(spoofed.map((h) => getClientIp(h)));
|
||||
expect(buckets.size).toBe(1);
|
||||
expect([...buckets][0]).toBe("198.51.100.7");
|
||||
});
|
||||
|
||||
it("只有一跳时取该跳", () => {
|
||||
expect(getClientIp(headersOf({ "x-forwarded-for": "198.51.100.7" }))).toBe(
|
||||
"198.51.100.7",
|
||||
);
|
||||
});
|
||||
|
||||
it("空白值等同缺失(trim 后为空 ⇒ 不成为限流键)", () => {
|
||||
expect(
|
||||
getClientIp(headersOf({ "x-forwarded-for": "198.51.100.7, , " })),
|
||||
).toBe("198.51.100.7");
|
||||
expect(getClientIp(headersOf({ "x-real-ip": " " }))).toBe("unknown");
|
||||
expect(getClientIp(headersOf({ "x-real-ip": "" }))).toBe("unknown");
|
||||
expect(getClientIp(headersOf({ "x-forwarded-for": " , " }))).toBe(
|
||||
"unknown",
|
||||
);
|
||||
});
|
||||
|
||||
it("两个头都缺失时为 unknown", () => {
|
||||
expect(getClientIp(headersOf({}))).toBe("unknown");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* 取客户端 IP 用于限流键。
|
||||
*
|
||||
* 边缘(nginx-static.conf:100-101 / nginx-static-production.conf:103-104)同时设置:
|
||||
* - `X-Real-IP: $remote_addr` ⇒ 由 Nginx **覆写**,客户端无法伪造,最可信;
|
||||
* - `X-Forwarded-For: $proxy_add_x_forwarded_for` ⇒ 语义是**追加**,
|
||||
* 因此客户端自带的 `X-Forwarded-For` 会原样保留在最左侧。
|
||||
*
|
||||
* 原实现读 `forwarded.split(',')[0]`(最左 = 客户端可控)⇒ 请求头里每次换一个
|
||||
* `X-Forwarded-For: 1.2.3.4` 就能拿到一个新的限流桶,把 contact 表单的「5 次/小时」整体绕过。
|
||||
* 这里改成:优先 `X-Real-IP`,其次取 XFF 链的**最右**一项(最近一跳由边缘写入的真实地址)。
|
||||
*/
|
||||
export function getClientIp(headers: Headers): string {
|
||||
const realIp = headers.get("x-real-ip")?.trim();
|
||||
if (realIp) return realIp;
|
||||
|
||||
const forwarded = headers.get("x-forwarded-for")?.trim();
|
||||
if (forwarded) {
|
||||
const chain = forwarded
|
||||
.split(",")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
return chain[chain.length - 1] ?? "unknown";
|
||||
}
|
||||
|
||||
return "unknown";
|
||||
}
|
||||
@@ -324,6 +324,11 @@ describe('data-server - CMS 数据访问层', () => {
|
||||
});
|
||||
|
||||
describe('Helper Functions', () => {
|
||||
// jest.spyOn 直接替换模块导出绑定;不还原会污染后续所有调用 getPublishedItems 的用例。
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('getCases should call getPublishedItems with case-study', async () => {
|
||||
const spy = jest.spyOn(dataServer, 'getPublishedItems');
|
||||
spy.mockResolvedValue([]);
|
||||
@@ -532,5 +537,93 @@ describe('data-server - CMS 数据访问层', () => {
|
||||
expect(result['home-solutions']).toHaveLength(1);
|
||||
expect(result['home-solutions']![0]!.title).toBe('Solution B');
|
||||
});
|
||||
|
||||
it('survives a dirty items column instead of throwing on .map', async () => {
|
||||
mockContentZone.findMany.mockResolvedValue([
|
||||
createZoneOverride('home-hero', null as unknown as never[]),
|
||||
createZoneOverride('home-trust', [{ itemId: 'trust-1', sortOrder: 1 }]),
|
||||
]);
|
||||
mockContentItem.findMany.mockResolvedValue([
|
||||
{ ...mockPrismaItem, id: 'trust-1', modelCode: 'hero-banner', title: 'Trust Signal' },
|
||||
]);
|
||||
|
||||
await expect(dataServer.getResolvedHomeZones()).resolves.toEqual({
|
||||
'home-hero': [],
|
||||
'home-trust': [expect.objectContaining({ title: 'Trust Signal' })],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('dirty data columns must not take down page consumers(B-4)', () => {
|
||||
it.each(['null', 'not json', '', '{"unterminated":'])('reads data %s as {}', async (raw) => {
|
||||
mockContentItem.findMany.mockResolvedValue([{ ...mockPrismaItem, data: raw }]);
|
||||
|
||||
const items = await dataServer.getPublishedItems('legal-page');
|
||||
|
||||
expect(items).toHaveLength(1);
|
||||
expect(items[0]!.data).toEqual({});
|
||||
});
|
||||
|
||||
it('handles a physically null data column without throwing', async () => {
|
||||
mockContentItem.findMany.mockResolvedValue([{ ...mockPrismaItem, data: null }]);
|
||||
|
||||
const items = await dataServer.getPublishedItems('legal-page');
|
||||
|
||||
expect(items[0]!.data).toEqual({});
|
||||
});
|
||||
|
||||
it('lets the terms page predicate run over a dirty row', async () => {
|
||||
mockContentItem.findMany.mockResolvedValue([
|
||||
{ ...mockPrismaItem, modelCode: 'legal-page', data: 'null' },
|
||||
]);
|
||||
|
||||
const items = await dataServer.getPublishedItems('legal-page');
|
||||
|
||||
// src/app/terms/page.tsx:180 与 products/page.tsx:20 直接读取 item.data.<key>
|
||||
expect(() => items.find((item) => item.data.pageType === 'terms')).not.toThrow();
|
||||
expect(items.find((item) => item.data.pageType === 'terms')).toBeUndefined();
|
||||
expect(() => items.map((item) => ({ ...item.data, id: item.data.id }))).not.toThrow();
|
||||
});
|
||||
|
||||
it('lets the single-item consumers fall back too', async () => {
|
||||
mockContentItem.findFirst.mockResolvedValue({ ...mockPrismaItem, data: 'null' });
|
||||
mockContentItem.findUnique.mockResolvedValue({ ...mockPrismaItem, data: 'bogus' });
|
||||
|
||||
const bySlug = await dataServer.getPublishedItemBySlug('legal-page', 'terms');
|
||||
const byId = await dataServer.getItemById('item-1');
|
||||
|
||||
expect(bySlug!.data).toEqual({});
|
||||
expect(byId!.data).toEqual({});
|
||||
});
|
||||
|
||||
it('degrades dirty zone and model columns to empty values', async () => {
|
||||
mockContentZone.findUnique.mockResolvedValue({
|
||||
...mockPrismaZone,
|
||||
allowedModels: 'null',
|
||||
items: 'oops',
|
||||
settings: 'null',
|
||||
});
|
||||
mockContentModel.findMany.mockResolvedValue([{ ...mockPrismaModel, fields: 'null' }]);
|
||||
|
||||
const zone = await dataServer.getZone('home-hero');
|
||||
const models = await dataServer.getContentModels();
|
||||
|
||||
expect(zone!.allowedModels).toEqual([]);
|
||||
expect(zone!.items).toEqual([]);
|
||||
expect(zone!.settings).toEqual({});
|
||||
expect(models[0]!.fields).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps page zones resolvable when a column is dirty', async () => {
|
||||
mockContentZone.findMany.mockResolvedValue([
|
||||
{ ...mockPrismaZone, allowedModels: 'null', items: 'null', settings: 'null' },
|
||||
]);
|
||||
|
||||
const zones = await dataServer.getPageZones('home');
|
||||
|
||||
expect(zones[0]!.allowedModels).toEqual([]);
|
||||
expect(zones[0]!.items).toEqual([]);
|
||||
expect(zones[0]!.settings).toEqual({});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,8 @@
|
||||
*/
|
||||
import { prisma } from '@/lib/db';
|
||||
import { cache } from 'react';
|
||||
import type { ContentItem, ContentStatus } from './types';
|
||||
import { parseCmsData } from './validate-content-data';
|
||||
import type { ContentItem, ContentStatus, ContentZoneItem, FieldDefinition } from './types';
|
||||
|
||||
// ============ 类型转换 ============
|
||||
|
||||
@@ -17,7 +18,7 @@ function toContentItem(item: Record<string, unknown>): ContentItem {
|
||||
slug: (item.slug as string | null) ?? undefined,
|
||||
locale: (item.locale as string | null) ?? 'zh-CN',
|
||||
status: item.status as ContentStatus,
|
||||
data: JSON.parse(item.data as string),
|
||||
data: parseCmsData(item.data),
|
||||
version: item.version as number,
|
||||
sortOrder: (item.sortOrder as number | null) ?? undefined,
|
||||
publishedAt: (item.publishedAt as Date | null)?.toISOString(),
|
||||
@@ -72,9 +73,9 @@ export const getPageZones = cache(async (pageCode: string) => {
|
||||
});
|
||||
return zones.map((z) => ({
|
||||
...z,
|
||||
allowedModels: JSON.parse(z.allowedModels),
|
||||
items: JSON.parse(z.items),
|
||||
settings: JSON.parse(z.settings),
|
||||
allowedModels: parseCmsData<string[]>(z.allowedModels, []),
|
||||
items: parseCmsData<ContentZoneItem[]>(z.items, []),
|
||||
settings: parseCmsData(z.settings),
|
||||
}));
|
||||
});
|
||||
|
||||
@@ -86,9 +87,9 @@ export const getZone = cache(async (code: string) => {
|
||||
if (!zone) return null;
|
||||
return {
|
||||
...zone,
|
||||
allowedModels: JSON.parse(zone.allowedModels),
|
||||
items: JSON.parse(zone.items),
|
||||
settings: JSON.parse(zone.settings),
|
||||
allowedModels: parseCmsData<string[]>(zone.allowedModels, []),
|
||||
items: parseCmsData<ContentZoneItem[]>(zone.items, []),
|
||||
settings: parseCmsData(zone.settings),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -103,7 +104,7 @@ export const getContentModels = cache(async () => {
|
||||
});
|
||||
return models.map((m) => ({
|
||||
...m,
|
||||
fields: JSON.parse(m.fields),
|
||||
fields: parseCmsData<FieldDefinition[]>(m.fields, []),
|
||||
}));
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* 只接受站内绝对路径:`//evil.com` 经 new URL 解析会跳出到站外 origin,
|
||||
* `https://evil.com`、`javascript:` 等绝对形式同理(B-6)。
|
||||
*
|
||||
* 原为 `/api/cms/draft/enable` 的私有函数;`/api/cms/draft/disable` 曾各自实现重定向而漏掉
|
||||
* 该校验(N-18),故提取共享,避免同一缺陷在姊妹路由中重复。
|
||||
*/
|
||||
export function isInternalRedirect(redirect: string): boolean {
|
||||
return redirect.startsWith('/') && !redirect.startsWith('//') && !redirect.startsWith('/\\');
|
||||
}
|
||||
+13
-1
@@ -189,11 +189,23 @@ export interface PaginatedResult<T> {
|
||||
totalPages: number;
|
||||
}
|
||||
|
||||
/** 审计日志中除工作流以外的常规写动作 */
|
||||
export type AuditCrudAction = 'create' | 'update' | 'delete' | 'publish' | 'unpublish';
|
||||
|
||||
/** 发布工作流写入审计日志的动作(与 `workflow.ts` 的 WorkflowAction 取值一致) */
|
||||
export type AuditWorkflowAction = 'submit' | 'approve' | 'reject' | 'archive';
|
||||
|
||||
export interface AuditLog {
|
||||
id: string;
|
||||
module: 'model' | 'item' | 'zone' | 'theme' | 'media';
|
||||
targetId: string;
|
||||
action: 'create' | 'update' | 'delete' | 'publish' | 'unpublish';
|
||||
/**
|
||||
* CRUD 动作 + 发布工作流动作。
|
||||
* submit/approve/reject/archive 由 `src/lib/cms/workflow.ts` 写入(`ContentItemAuditAction`),
|
||||
* 缺了它们「驳回」与「编辑」在审计日志里就不可区分(验收 §5)。
|
||||
* 列在 Prisma schema 中为自由字符串(`AuditLog.action String`),无需迁移即可容纳。
|
||||
*/
|
||||
action: AuditCrudAction | AuditWorkflowAction;
|
||||
operator: string;
|
||||
beforeData?: Record<string, unknown>;
|
||||
afterData?: Record<string, unknown>;
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import { describe, it, expect } from '@jest/globals';
|
||||
import { parseCmsData, validateContentData } from './validate-content-data';
|
||||
import { CONTENT_TYPE_CONFIGS } from './content-types';
|
||||
import type { FieldDefinition } from './types';
|
||||
|
||||
const productFields = CONTENT_TYPE_CONFIGS['product'].model.fields;
|
||||
const metricsField = productFields.find((f) => f.name === 'metrics') as FieldDefinition;
|
||||
const basisField = metricsField.fields!.find((f) => f.name === 'basis') as FieldDefinition;
|
||||
|
||||
const declared: FieldDefinition[] = [
|
||||
{ name: 'title', type: 'text', label: '标题' },
|
||||
{ name: 'body', type: 'richtext', label: '正文' },
|
||||
{ name: 'sortOrder', type: 'number', label: '排序', validation: { min: 0, max: 99 } },
|
||||
{
|
||||
name: 'slug',
|
||||
type: 'text',
|
||||
label: '标识',
|
||||
validation: { pattern: '^[a-z0-9-]+$' },
|
||||
},
|
||||
{
|
||||
name: 'color',
|
||||
type: 'select',
|
||||
label: '主题色',
|
||||
options: [
|
||||
{ label: '品牌红', value: 'brand' },
|
||||
{ label: '蓝', value: 'blue' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'items',
|
||||
type: 'array',
|
||||
label: '条目',
|
||||
fields: [
|
||||
{ name: 'label', type: 'text', label: '标签' },
|
||||
{ name: 'color', type: 'select', label: '颜色', options: [{ label: '青', value: 'teal' }] },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'seo',
|
||||
type: 'object',
|
||||
label: 'SEO',
|
||||
fields: [{ name: 'keywords', type: 'text', label: '关键词', validation: { max: 10 } }],
|
||||
},
|
||||
];
|
||||
|
||||
describe('validateContentData', () => {
|
||||
it('accepts a payload that satisfies every declared constraint', () => {
|
||||
expect(
|
||||
validateContentData(declared, {
|
||||
title: '制造业主数据治理',
|
||||
body: '<p>正文</p>',
|
||||
sortOrder: 5,
|
||||
slug: 'main-data',
|
||||
color: 'brand',
|
||||
items: [{ label: '能力一', color: 'teal' }, { label: '能力二' }],
|
||||
seo: { keywords: 'ERP,CRM' },
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects a select value outside the declared options', () => {
|
||||
const errors = validateContentData(declared, { color: 'neon-pink' });
|
||||
|
||||
expect(errors).toEqual([
|
||||
{
|
||||
path: 'color',
|
||||
rule: 'option',
|
||||
message: '主题色 的值不在声明的选项范围内',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('rejects a fabricated metric basis inside a declared array element', () => {
|
||||
const errors = validateContentData(productFields, {
|
||||
metrics: [{ value: '99.9%', label: '系统可用率', basis: 'customer-validated' }],
|
||||
});
|
||||
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(errors[0]).toMatchObject({ path: 'metrics[0].basis', rule: 'option' });
|
||||
});
|
||||
|
||||
it('documents that "verified" is itself a declared option, so enum checks cannot refuse it', () => {
|
||||
expect(basisField.options!.map((o) => o.value)).toEqual(['target', 'team-history', 'verified']);
|
||||
expect(validateContentData(productFields, { metrics: [{ basis: 'verified' }] })).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects a number above the declared max and below the declared min', () => {
|
||||
expect(validateContentData(declared, { sortOrder: 100 })[0]).toMatchObject({
|
||||
path: 'sortOrder',
|
||||
rule: 'max',
|
||||
});
|
||||
expect(validateContentData(declared, { sortOrder: -1 })[0]).toMatchObject({
|
||||
path: 'sortOrder',
|
||||
rule: 'min',
|
||||
});
|
||||
expect(validateContentData(declared, { sortOrder: 99 })).toEqual([]);
|
||||
});
|
||||
|
||||
it('treats max on a string field as a length bound and checks the declared pattern', () => {
|
||||
expect(validateContentData(declared, { seo: { keywords: 'a'.repeat(11) } })[0]).toMatchObject({
|
||||
path: 'seo.keywords',
|
||||
rule: 'max',
|
||||
});
|
||||
expect(validateContentData(declared, { slug: 'UPPER CASE!!' })[0]).toMatchObject({
|
||||
path: 'slug',
|
||||
rule: 'pattern',
|
||||
});
|
||||
});
|
||||
|
||||
it('ignores keys the model never declares', () => {
|
||||
expect(
|
||||
validateContentData(declared, {
|
||||
undeclaredProof: '已通过 ISO 认证',
|
||||
metrics: [{ basis: 'anything-goes' }],
|
||||
color: 'brand',
|
||||
}),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('ignores absent and emptied fields instead of enforcing them', () => {
|
||||
expect(validateContentData(declared, {})).toEqual([]);
|
||||
expect(validateContentData(declared, { title: null, color: undefined })).toEqual([]);
|
||||
});
|
||||
|
||||
it('stays permissive when there is nothing to validate against', () => {
|
||||
expect(validateContentData([], { color: 'neon-pink' })).toEqual([]);
|
||||
expect(validateContentData(null, { color: 'neon-pink' })).toEqual([]);
|
||||
expect(validateContentData(undefined, { anything: true })).toEqual([]);
|
||||
expect(validateContentData(declared, null)).toEqual([]);
|
||||
expect(validateContentData(declared, 'not-an-object')).toEqual([]);
|
||||
expect(validateContentData([{} as FieldDefinition], { title: 'x' })).toEqual([]);
|
||||
});
|
||||
|
||||
it('collects every violation instead of stopping at the first one', () => {
|
||||
const errors = validateContentData(declared, {
|
||||
color: 'neon-pink',
|
||||
sortOrder: 500,
|
||||
slug: 'Bad Slug',
|
||||
items: [{ color: 'teal' }, { color: 'magenta' }],
|
||||
});
|
||||
|
||||
expect(errors.map((e) => e.path).sort()).toEqual(
|
||||
['color', 'items[1].color', 'slug', 'sortOrder'].sort(),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not crash on a malformed declared pattern', () => {
|
||||
const broken: FieldDefinition[] = [
|
||||
{ name: 'code', type: 'text', label: '编码', validation: { pattern: '([unclosed' } },
|
||||
];
|
||||
|
||||
expect(validateContentData(broken, { code: 'abc' })).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseCmsData(B-4)', () => {
|
||||
it.each([
|
||||
['the literal string null', 'null'],
|
||||
['truncated JSON', '{"pageType":"terms"'],
|
||||
['non-JSON text', 'not json'],
|
||||
['a bare number', '123'],
|
||||
['a bare string', '"terms"'],
|
||||
['an empty column', ''],
|
||||
])('returns {} for %s', (_label: string, raw: string) => {
|
||||
expect(parseCmsData(raw)).toEqual({});
|
||||
});
|
||||
|
||||
it('returns {} for missing values rather than null', () => {
|
||||
expect(parseCmsData(null)).toEqual({});
|
||||
expect(parseCmsData(undefined)).toEqual({});
|
||||
});
|
||||
|
||||
it('keeps valid objects and arrays intact', () => {
|
||||
expect(parseCmsData('{"pageType":"terms"}')).toEqual({ pageType: 'terms' });
|
||||
expect(parseCmsData('["hero-banner"]')).toEqual(['hero-banner']);
|
||||
expect(parseCmsData('[]')).toEqual([]);
|
||||
});
|
||||
|
||||
it('lets array columns fall back to [] so downstream .map keeps working', () => {
|
||||
expect(parseCmsData('null', [])).toEqual([]);
|
||||
expect(parseCmsData('bogus', [])).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { FieldDefinition } from './types';
|
||||
|
||||
/**
|
||||
* CMS 内容列的读取/写入守卫(B-4、B-3),无 prisma / react 依赖,页面与 API 路由共用。
|
||||
*/
|
||||
|
||||
/**
|
||||
* CMS 的 JSON 列(ContentItem.data / ContentZone.items / ContentModel.fields 等)
|
||||
* 可能是 null、非法 JSON 或基础类型。单个脏值不应让整页渲染或 SSG 中断(B-4),
|
||||
* 与 media-service.ts 的 parseDerivatives 同族守卫:无法归一为对象/数组时回落到空值。
|
||||
* 数组列需显式传入 `[]` 作为回落值,否则下游 `.map` 会二次抛错。
|
||||
*/
|
||||
export function parseCmsData<T = Record<string, unknown>>(raw: unknown, fallback?: T): T {
|
||||
const empty = (fallback ?? {}) as T;
|
||||
if (typeof raw !== 'string') return empty;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
return parsed !== null && typeof parsed === 'object' ? (parsed as T) : empty;
|
||||
} catch {
|
||||
return empty;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入侧内容校验(B-3)。
|
||||
*
|
||||
* 只执行 `ContentModel.fields` 已声明的约束:未声明的键一律放行,未填的键不判必填,
|
||||
* 以免改变既有载荷形态(seed 与页面组件依赖宽松结构)。
|
||||
* 声明了 `options` 即视为枚举 —— `select`/`dropdown` 与带 `options` 的 `text` 字段
|
||||
* 在 content-types.ts 中同义(如 news 的 category、legal-page 的 pageType)。
|
||||
*/
|
||||
export interface ContentFieldError {
|
||||
path: string;
|
||||
rule: 'option' | 'min' | 'max' | 'pattern';
|
||||
message: string;
|
||||
}
|
||||
|
||||
const STRING_TYPES: readonly FieldDefinition['type'][] = ['text', 'textarea', 'richtext'];
|
||||
|
||||
export function validateContentData(
|
||||
fields: FieldDefinition[] | null | undefined,
|
||||
data: unknown,
|
||||
): ContentFieldError[] {
|
||||
const errors: ContentFieldError[] = [];
|
||||
validateFields(fields, data, '', errors);
|
||||
return errors;
|
||||
}
|
||||
|
||||
function validateFields(
|
||||
fields: FieldDefinition[] | null | undefined,
|
||||
value: unknown,
|
||||
prefix: string,
|
||||
errors: ContentFieldError[],
|
||||
): void {
|
||||
if (!Array.isArray(fields) || fields.length === 0) return;
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) return;
|
||||
|
||||
const record = value as Record<string, unknown>;
|
||||
for (const field of fields) {
|
||||
if (!Object.prototype.hasOwnProperty.call(record, field.name)) continue;
|
||||
const raw = record[field.name];
|
||||
if (raw === null || raw === undefined) continue;
|
||||
validateField(field, raw, prefix ? `${prefix}.${field.name}` : field.name, errors);
|
||||
}
|
||||
}
|
||||
|
||||
function validateField(
|
||||
field: FieldDefinition,
|
||||
value: unknown,
|
||||
path: string,
|
||||
errors: ContentFieldError[],
|
||||
): void {
|
||||
const label = field.label || field.name;
|
||||
|
||||
if (Array.isArray(field.options) && field.options.length > 0) {
|
||||
const allowed = field.options.map((option) => option.value);
|
||||
if (!allowed.includes(value as (typeof allowed)[number])) {
|
||||
errors.push({ path, rule: 'option', message: `${label} 的值不在声明的选项范围内` });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const validation = field.validation;
|
||||
|
||||
if (field.type === 'number' && typeof value === 'number' && validation) {
|
||||
if (typeof validation.min === 'number' && value < validation.min) {
|
||||
errors.push({ path, rule: 'min', message: `${label} 不得小于 ${validation.min}` });
|
||||
}
|
||||
if (typeof validation.max === 'number' && value > validation.max) {
|
||||
errors.push({ path, rule: 'max', message: `${label} 不得大于 ${validation.max}` });
|
||||
}
|
||||
}
|
||||
|
||||
if (STRING_TYPES.includes(field.type) && typeof value === 'string' && validation) {
|
||||
if (typeof validation.min === 'number' && value.length < validation.min) {
|
||||
errors.push({ path, rule: 'min', message: `${label} 长度不得少于 ${validation.min}` });
|
||||
}
|
||||
if (typeof validation.max === 'number' && value.length > validation.max) {
|
||||
errors.push({ path, rule: 'max', message: `${label} 长度不得超过 ${validation.max}` });
|
||||
}
|
||||
if (typeof validation.pattern === 'string') {
|
||||
let matched: boolean;
|
||||
try {
|
||||
matched = new RegExp(validation.pattern).test(value);
|
||||
} catch {
|
||||
matched = true;
|
||||
}
|
||||
if (!matched) {
|
||||
errors.push({ path, rule: 'pattern', message: `${label} 不符合声明的格式` });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.isArray(field.fields) || field.fields.length === 0) return;
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((element, index) => {
|
||||
validateFields(field.fields, element, `${path}[${index}]`, errors);
|
||||
});
|
||||
} else if (typeof value === 'object') {
|
||||
validateFields(field.fields, value, path, errors);
|
||||
}
|
||||
}
|
||||
+136
-25
@@ -3,7 +3,8 @@ import type { ContentItem } from './types';
|
||||
|
||||
// ─── Mock @/lib/db 提供可控的 prisma 实例 ──────────────────────────────
|
||||
const mockContentItemFindUnique = jest.fn<(args: unknown) => Promise<unknown | null>>();
|
||||
const mockContentItemUpdate = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
const mockContentItemUpdateMany = jest.fn<(args: unknown) => Promise<{ count: number }>>();
|
||||
const mockContentItemFindUniqueOrThrow = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
const mockAuditLogCreate = jest.fn<(args: unknown) => Promise<unknown>>();
|
||||
const mockNotifyReviewers = jest.fn<(item: ContentItem, actor: { userId: string; username: string }) => Promise<number>>();
|
||||
const mockNotifyCreator = jest.fn<
|
||||
@@ -19,11 +20,33 @@ jest.mock('@/lib/db', () => ({
|
||||
prisma: {
|
||||
contentItem: {
|
||||
findUnique: mockContentItemFindUnique,
|
||||
update: mockContentItemUpdate,
|
||||
updateMany: mockContentItemUpdateMany,
|
||||
findUniqueOrThrow: mockContentItemFindUniqueOrThrow,
|
||||
},
|
||||
auditLog: {
|
||||
create: mockAuditLogCreate,
|
||||
},
|
||||
// 交互式事务:进入前对「库」做快照,回调抛出即回滚快照,让回滚可被断言(Q-10②)。
|
||||
// 数组形态 $transaction([a,b]) 是并行提交,无法承载「更新→读回→审计」的写后读依赖,
|
||||
// 因此谓词只接函数入参——非函数调用直接判红而不是静默走旁路。
|
||||
$transaction: jest.fn(async (fn: unknown) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error('workflow 需要交互式 $transaction(写后读依赖),不接受数组形态');
|
||||
}
|
||||
const snapshot = storedItem;
|
||||
try {
|
||||
return await fn({
|
||||
contentItem: {
|
||||
updateMany: mockContentItemUpdateMany,
|
||||
findUniqueOrThrow: mockContentItemFindUniqueOrThrow,
|
||||
},
|
||||
auditLog: { create: mockAuditLogCreate },
|
||||
});
|
||||
} catch (err) {
|
||||
storedItem = snapshot;
|
||||
throw err;
|
||||
}
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -66,11 +89,44 @@ function createMockItem(status: ContentItem['status'], overrides: Partial<Conten
|
||||
} as ContentItem;
|
||||
}
|
||||
|
||||
/** 「数据库」里当前的行 */
|
||||
let storedItem: ContentItem | null = null;
|
||||
|
||||
/** 把条目放进「数据库」,findUnique / findUniqueOrThrow 都读到这一份行 */
|
||||
function stubStoredItem(item: ContentItem | null) {
|
||||
storedItem = item;
|
||||
mockContentItemFindUnique.mockImplementation(async () => item);
|
||||
mockContentItemFindUniqueOrThrow.mockImplementation(async () => {
|
||||
if (!item) throw new Error('Row not found');
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
let consoleErrorSpy: jest.Spied<typeof console.error>;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockContentItemUpdate.mockImplementation(async (args: unknown) => {
|
||||
const { data, where } = args as { data: Record<string, unknown>; where: { id: string } };
|
||||
return { id: where.id, ...data };
|
||||
consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
stubStoredItem(null);
|
||||
|
||||
// 条件更新:只有 where.status 仍等于库里的当前状态才命中 1 行,
|
||||
// 并按 data.version.increment 原子自增后写回(模拟数据库语义)
|
||||
mockContentItemUpdateMany.mockImplementation(async (args: unknown) => {
|
||||
const { where, data } = args as {
|
||||
where: { id: string; status: ContentItem['status'] };
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
if (!storedItem || storedItem.status !== where.status || storedItem.id !== where.id) {
|
||||
return { count: 0 };
|
||||
}
|
||||
const increment = (data.version as { increment: number } | undefined)?.increment ?? 0;
|
||||
const next = {
|
||||
...storedItem,
|
||||
...data,
|
||||
version: storedItem.version + increment,
|
||||
} as unknown as ContentItem;
|
||||
stubStoredItem(next);
|
||||
return { count: 1 };
|
||||
});
|
||||
mockAuditLogCreate.mockResolvedValue({ id: 'log-1' });
|
||||
mockNotifyReviewers.mockResolvedValue(1);
|
||||
@@ -101,29 +157,34 @@ describe('isValidTransition', () => {
|
||||
});
|
||||
|
||||
describe('submitForReview', () => {
|
||||
it('transitions draft to review and increments version', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(createMockItem('draft'));
|
||||
it('transitions draft to review and lets the database increment the version', async () => {
|
||||
stubStoredItem(createMockItem('draft'));
|
||||
|
||||
const result = await submitForReview('item-1', mockUser);
|
||||
|
||||
expect(result.status).toBe('review');
|
||||
expect(result.version).toBe(2);
|
||||
expect(mockContentItemUpdate).toHaveBeenCalledWith(
|
||||
// 关键:不再传绝对值 item.version + 1,而是交给数据库自增(验收 B-5)
|
||||
expect(mockContentItemUpdateMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { id: 'item-1' },
|
||||
where: { id: 'item-1', status: 'draft' },
|
||||
data: expect.objectContaining({
|
||||
status: 'review',
|
||||
version: 2,
|
||||
version: { increment: 1 },
|
||||
updatedBy: 'editor',
|
||||
}),
|
||||
})
|
||||
);
|
||||
const data = mockContentItemUpdateMany.mock.calls[0]![0] as unknown as {
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
expect(data.data).not.toHaveProperty('version', 2);
|
||||
expect(mockAuditLogCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
module: 'item',
|
||||
targetId: 'item-1',
|
||||
action: 'update',
|
||||
action: 'submit',
|
||||
operator: 'editor',
|
||||
}),
|
||||
})
|
||||
@@ -140,31 +201,38 @@ describe('submitForReview', () => {
|
||||
});
|
||||
|
||||
it('throws for illegal transition', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(createMockItem('published'));
|
||||
stubStoredItem(createMockItem('published'));
|
||||
await expect(submitForReview('item-1', mockUser)).rejects.toThrow(
|
||||
'当前状态 published 不允许提交审核'
|
||||
);
|
||||
expect(mockContentItemUpdateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('approve', () => {
|
||||
it('transitions review to published and sets publishedAt', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(createMockItem('review'));
|
||||
stubStoredItem(createMockItem('review'));
|
||||
|
||||
const result = await approve('item-1', mockReviewer);
|
||||
|
||||
expect(result.status).toBe('published');
|
||||
expect(result.version).toBe(2);
|
||||
expect(mockContentItemUpdate).toHaveBeenCalledWith(
|
||||
expect(mockContentItemUpdateMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { id: 'item-1', status: 'review' },
|
||||
data: expect.objectContaining({
|
||||
status: 'published',
|
||||
publishedAt: expect.any(Date),
|
||||
version: 2,
|
||||
version: { increment: 1 },
|
||||
updatedBy: 'reviewer',
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect(mockAuditLogCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({ action: 'approve' }),
|
||||
})
|
||||
);
|
||||
expect(mockNotifyCreator).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'item-1', title: '测试内容' }),
|
||||
'review_approved',
|
||||
@@ -173,16 +241,55 @@ describe('approve', () => {
|
||||
});
|
||||
|
||||
it('throws for non-review item', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(createMockItem('draft'));
|
||||
stubStoredItem(createMockItem('draft'));
|
||||
await expect(approve('item-1', mockReviewer)).rejects.toThrow(
|
||||
'当前状态 draft 不允许审核通过'
|
||||
);
|
||||
});
|
||||
|
||||
it('still succeeds and logs when the notification fails', async () => {
|
||||
stubStoredItem(createMockItem('review'));
|
||||
mockNotifyCreator.mockRejectedValueOnce(new Error('SQLITE_BUSY'));
|
||||
|
||||
const result = await approve('item-1', mockReviewer);
|
||||
|
||||
// 流转已成功:通知失败不得把它变成 500(验收 B-5),但必须留下日志
|
||||
expect(result.status).toBe('published');
|
||||
expect(result.version).toBe(2);
|
||||
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
|
||||
expect(consoleErrorSpy.mock.calls[0]![0]).toContain('通知发送失败');
|
||||
expect(consoleErrorSpy.mock.calls[0]![1]).toBeInstanceOf(Error);
|
||||
});
|
||||
|
||||
it('aborts the transition when another writer already changed the status', async () => {
|
||||
stubStoredItem(createMockItem('review'));
|
||||
// 条件更新命中 0 行 = 并发下 status 已不是刚读到的值(status TOCTOU)
|
||||
mockContentItemUpdateMany.mockResolvedValueOnce({ count: 0 });
|
||||
|
||||
await expect(approve('item-1', mockReviewer)).rejects.toThrow('当前状态已被其他操作改变');
|
||||
expect(mockAuditLogCreate).not.toHaveBeenCalled();
|
||||
expect(mockNotifyCreator).not.toHaveBeenCalled();
|
||||
expect(consoleErrorSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rolls the status back when the audit log write fails, instead of committing an unaudited transition', async () => {
|
||||
stubStoredItem(createMockItem('review'));
|
||||
mockAuditLogCreate.mockRejectedValueOnce(new Error('write conflict'));
|
||||
|
||||
await expect(approve('item-1', mockReviewer)).rejects.toThrow('write conflict');
|
||||
// 修复前:updateMany 与 auditLog.create 是两条独立写,审计失败时状态已落库,
|
||||
// 出现「已发布但无审计」的静默不一致,且调用方收到 500 会以为流转没发生。
|
||||
expect(storedItem).not.toBeNull();
|
||||
expect(storedItem!.status).toBe('review');
|
||||
expect(storedItem!.version).toBe(1);
|
||||
// 通知不得在事务提交前发出
|
||||
expect(mockNotifyCreator).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('reject', () => {
|
||||
it('transitions review back to draft', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(createMockItem('review'));
|
||||
it('transitions review back to draft and records a distinguishable audit action', async () => {
|
||||
stubStoredItem(createMockItem('review'));
|
||||
|
||||
const result = await reject('item-1', mockReviewer, '需要补充数据来源');
|
||||
|
||||
@@ -191,6 +298,7 @@ describe('reject', () => {
|
||||
expect(mockAuditLogCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
action: 'reject',
|
||||
afterData: expect.stringContaining('需要补充数据来源'),
|
||||
}),
|
||||
})
|
||||
@@ -204,7 +312,7 @@ describe('reject', () => {
|
||||
});
|
||||
|
||||
it('throws for non-review item', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(createMockItem('published'));
|
||||
stubStoredItem(createMockItem('published'));
|
||||
await expect(reject('item-1', mockReviewer)).rejects.toThrow(
|
||||
'当前状态 published 不允许驳回'
|
||||
);
|
||||
@@ -212,13 +320,18 @@ describe('reject', () => {
|
||||
});
|
||||
|
||||
describe('archive', () => {
|
||||
it('transitions published to archived', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(createMockItem('published'));
|
||||
it('transitions published to archived with its own audit action', async () => {
|
||||
stubStoredItem(createMockItem('published'));
|
||||
|
||||
const result = await archive('item-1', mockReviewer);
|
||||
|
||||
expect(result.status).toBe('archived');
|
||||
expect(result.version).toBe(2);
|
||||
expect(mockAuditLogCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({ action: 'archive' }),
|
||||
})
|
||||
);
|
||||
expect(mockNotifyCreator).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'item-1', title: '测试内容' }),
|
||||
'item_archived',
|
||||
@@ -227,9 +340,7 @@ describe('archive', () => {
|
||||
});
|
||||
|
||||
it('throws for non-published item', async () => {
|
||||
mockContentItemFindUnique.mockResolvedValue(createMockItem('review'));
|
||||
await expect(archive('item-1', mockReviewer)).rejects.toThrow(
|
||||
'当前状态 review 不允许归档'
|
||||
);
|
||||
stubStoredItem(createMockItem('review'));
|
||||
await expect(archive('item-1', mockReviewer)).rejects.toThrow('当前状态 review 不允许归档');
|
||||
});
|
||||
});
|
||||
+68
-31
@@ -1,7 +1,10 @@
|
||||
import { prisma } from '@/lib/db';
|
||||
import type { ContentItem, ContentStatus } from './types';
|
||||
import type { Prisma } from '@/generated/prisma/client';
|
||||
import type { AuditLog, ContentItem, ContentStatus } from './types';
|
||||
import { notifyReviewers, notifyCreator } from './notifications';
|
||||
|
||||
type PrismaTx = Prisma.TransactionClient;
|
||||
|
||||
export type WorkflowAction = 'submit' | 'approve' | 'reject' | 'archive';
|
||||
|
||||
interface WorkflowUser {
|
||||
@@ -63,12 +66,13 @@ async function transition(
|
||||
}
|
||||
|
||||
const targetStatus = TARGET_STATUS[action];
|
||||
const nextVersion = item.version + 1;
|
||||
const now = new Date();
|
||||
|
||||
const updateData: Record<string, unknown> = {
|
||||
status: targetStatus,
|
||||
version: nextVersion,
|
||||
// 由数据库自增而非读-改-写(item.version + 1):后者在并发流转下会互相覆盖版本号,
|
||||
// 与 src/app/api/admin/items/route.ts 的 { increment: 1 } 统一到同一套语义(验收 B-5)。
|
||||
version: { increment: 1 },
|
||||
updatedBy: user.username,
|
||||
updatedAt: now,
|
||||
};
|
||||
@@ -77,36 +81,69 @@ async function transition(
|
||||
updateData.publishedAt = now;
|
||||
}
|
||||
|
||||
const updated = await prisma.contentItem.update({
|
||||
where: { id: itemId },
|
||||
data: updateData,
|
||||
// 条件更新(compare-and-swap):只有 status 仍等于刚才读到的值时才写入。
|
||||
// 单条 UPDATE 在 SQLite 内是原子的,因此并发流转不会把他人刚改过的状态再覆盖一次
|
||||
// (原实现是先 findUnique 校验、再无条件 update,status 校验存在 TOCTOU 窗口)。
|
||||
//
|
||||
// 「状态更新 → 读回 → 审计」必须同事务提交:读回依赖更新的写后读,审计依赖读回的快照,
|
||||
// 因此用交互式事务。历史实现是三条独立写,审计写入失败时会留下
|
||||
// 「状态已变更但无审计记录」的静默不一致(Q-10②)。
|
||||
const { updated } = await prisma.$transaction(async (tx: PrismaTx) => {
|
||||
const { count } = await tx.contentItem.updateMany({
|
||||
where: { id: itemId, status: item.status },
|
||||
data: updateData,
|
||||
});
|
||||
|
||||
if (count === 0) {
|
||||
// 文案含「当前状态」以命中 workflow 路由的 400 分支(不是 500)
|
||||
throw new Error('当前状态已被其他操作改变,请刷新后重试');
|
||||
}
|
||||
|
||||
const after = await tx.contentItem.findUniqueOrThrow({
|
||||
where: { id: itemId },
|
||||
});
|
||||
|
||||
const afterData: Record<string, unknown> = { ...after };
|
||||
if (reason) {
|
||||
afterData.reason = reason;
|
||||
}
|
||||
|
||||
// 工作流动作即审计动作:类型标注让取值与 AuditLog['action'] 联合类型在编译期对齐
|
||||
const auditAction: AuditLog['action'] = action;
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: {
|
||||
module: 'item',
|
||||
targetId: itemId,
|
||||
// 审计动作直接记录工作流动作本身(submit/approve/reject/archive 已在
|
||||
// src/lib/cms/types.ts 的 AuditLog['action'] 联合类型中声明),
|
||||
// 使「驳回」不再与「编辑」同为 'update' 而不可区分(验收 §5)。
|
||||
// 显式标注类型:取值越出联合类型时编译期即报错,无需 as unknown as。
|
||||
action: auditAction,
|
||||
operator: user.username,
|
||||
beforeData: JSON.stringify(item),
|
||||
afterData: JSON.stringify(afterData),
|
||||
},
|
||||
});
|
||||
|
||||
return { updated: after };
|
||||
});
|
||||
|
||||
const afterData: Record<string, unknown> = { ...updated };
|
||||
if (reason) {
|
||||
afterData.reason = reason;
|
||||
}
|
||||
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
module: 'item',
|
||||
targetId: itemId,
|
||||
action: action === 'approve' || action === 'archive' ? action : 'update',
|
||||
operator: user.username,
|
||||
beforeData: JSON.stringify(item),
|
||||
afterData: JSON.stringify(afterData),
|
||||
},
|
||||
});
|
||||
|
||||
// 生成站内通知:提交审核时通知审核人;审核结果/归档时通知创建人
|
||||
if (action === 'submit') {
|
||||
await notifyReviewers(item, user);
|
||||
} else if (action === 'approve') {
|
||||
await notifyCreator(item, 'review_approved', user);
|
||||
} else if (action === 'reject') {
|
||||
await notifyCreator(item, 'review_rejected', user, reason);
|
||||
} else if (action === 'archive') {
|
||||
await notifyCreator(item, 'item_archived', user);
|
||||
// 生成站内通知:提交审核时通知审核人;审核结果/归档时通知创建人。
|
||||
// 通知失败不回滚也不上抛——流转已成功,抛错会让调用方得到 500 并误以为审批失败;
|
||||
// 但必须留下可排查的日志,不能静默吞掉(验收 B-5)。
|
||||
try {
|
||||
if (action === 'submit') {
|
||||
await notifyReviewers(item, user);
|
||||
} else if (action === 'approve') {
|
||||
await notifyCreator(item, 'review_approved', user);
|
||||
} else if (action === 'reject') {
|
||||
await notifyCreator(item, 'review_rejected', user, reason);
|
||||
} else if (action === 'archive') {
|
||||
await notifyCreator(item, 'item_archived', user);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`[cms:workflow] 通知发送失败(action=${action}, item=${itemId}):`, error);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,183 +0,0 @@
|
||||
import { describe, it, expect } from '@jest/globals';
|
||||
import { brandColors, colorValues, gradients } from './colors';
|
||||
|
||||
describe('colors', () => {
|
||||
describe('brandColors', () => {
|
||||
it('should have primary color palette', () => {
|
||||
expect(brandColors.primary).toBeDefined();
|
||||
expect(brandColors.primary[900]).toBe('#0A0A0A');
|
||||
expect(brandColors.primary[50]).toBe('#F5F5F5');
|
||||
});
|
||||
|
||||
it('should have brand color palette', () => {
|
||||
expect(brandColors.brand).toBeDefined();
|
||||
expect(brandColors.brand[600]).toBe('#C41E3A');
|
||||
expect(brandColors.brand[100]).toBe('#FEF2F4');
|
||||
});
|
||||
|
||||
it('should have neutral color palette', () => {
|
||||
expect(brandColors.neutral).toBeDefined();
|
||||
expect(brandColors.neutral[900]).toBe('#1C1C1C');
|
||||
expect(brandColors.neutral[50]).toBe('#FFFBF5');
|
||||
});
|
||||
|
||||
it('should have success color palette', () => {
|
||||
expect(brandColors.success).toBeDefined();
|
||||
expect(brandColors.success[600]).toBe('#16A34A');
|
||||
expect(brandColors.success[100]).toBe('#F0FDF4');
|
||||
});
|
||||
|
||||
it('should have warning color palette', () => {
|
||||
expect(brandColors.warning).toBeDefined();
|
||||
expect(brandColors.warning[600]).toBe('#D97706');
|
||||
expect(brandColors.warning[100]).toBe('#FFFBEB');
|
||||
});
|
||||
|
||||
it('should have info color palette', () => {
|
||||
expect(brandColors.info).toBeDefined();
|
||||
expect(brandColors.info[600]).toBe('#5C5C5C');
|
||||
expect(brandColors.info[100]).toBe('#F5F5F5');
|
||||
});
|
||||
|
||||
it('should have error color palette', () => {
|
||||
expect(brandColors.error).toBeDefined();
|
||||
expect(brandColors.error[600]).toBe('#C41E3A');
|
||||
expect(brandColors.error[100]).toBe('#FEF2F4');
|
||||
});
|
||||
|
||||
it('should have valid hex color format', () => {
|
||||
const hexPattern = /^#[0-9A-Fa-f]{6}$/;
|
||||
|
||||
Object.values(brandColors.primary).forEach(color => {
|
||||
expect(color).toMatch(hexPattern);
|
||||
});
|
||||
|
||||
Object.values(brandColors.brand).forEach(color => {
|
||||
expect(color).toMatch(hexPattern);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('colorValues', () => {
|
||||
it('should have primary colors', () => {
|
||||
expect(colorValues.primary).toBe('#1C1C1C');
|
||||
expect(colorValues.primaryHover).toBe('#0A0A0A');
|
||||
expect(colorValues.primaryLight).toBe('#3D3D3D');
|
||||
expect(colorValues.primaryLighter).toBe('#F5F5F5');
|
||||
});
|
||||
|
||||
it('should have brand colors', () => {
|
||||
expect(colorValues.brand).toBe('#C41E3A');
|
||||
expect(colorValues.brandHover).toBe('#A01830');
|
||||
expect(colorValues.brandLight).toBe('#E04A68');
|
||||
expect(colorValues.brandBg).toBe('#FEF2F4');
|
||||
});
|
||||
|
||||
it('should have text colors', () => {
|
||||
expect(colorValues.textPrimary).toBe('#1C1C1C');
|
||||
expect(colorValues.textSecondary).toBe('#3D3D3D');
|
||||
expect(colorValues.textTertiary).toBe('#5C5C5C');
|
||||
expect(colorValues.textMuted).toBe('#8C8C8C');
|
||||
});
|
||||
|
||||
it('should have background colors', () => {
|
||||
expect(colorValues.bgPrimary).toBe('#FAFAFA');
|
||||
expect(colorValues.bgSecondary).toBe('#FFFBF5');
|
||||
expect(colorValues.bgTertiary).toBe('#F5F5F5');
|
||||
expect(colorValues.bgHover).toBe('#EFEFEF');
|
||||
});
|
||||
|
||||
it('should have border colors', () => {
|
||||
expect(colorValues.border).toBe('#E5E5E5');
|
||||
expect(colorValues.borderSecondary).toBe('#D4D4D4');
|
||||
expect(colorValues.borderAccent).toBe('#1C1C1C');
|
||||
});
|
||||
|
||||
it('should have link colors', () => {
|
||||
expect(colorValues.link).toBe('#1C1C1C');
|
||||
expect(colorValues.linkHover).toBe('#C41E3A');
|
||||
});
|
||||
|
||||
it('should have status colors', () => {
|
||||
expect(colorValues.success).toBe('#16A34A');
|
||||
expect(colorValues.successBg).toBe('#F0FDF4');
|
||||
expect(colorValues.warning).toBe('#D97706');
|
||||
expect(colorValues.warningBg).toBe('#FFFBEB');
|
||||
expect(colorValues.info).toBe('#5C5C5C');
|
||||
expect(colorValues.infoBg).toBe('#F5F5F5');
|
||||
expect(colorValues.error).toBe('#C41E3A');
|
||||
expect(colorValues.errorBg).toBe('#FEF2F4');
|
||||
});
|
||||
|
||||
it('should have valid hex color format', () => {
|
||||
const hexPattern = /^#[0-9A-Fa-f]{6}$/;
|
||||
|
||||
Object.values(colorValues).forEach(color => {
|
||||
expect(color).toMatch(hexPattern);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('gradients', () => {
|
||||
it('should have primary gradient', () => {
|
||||
expect(gradients.primary).toBeDefined();
|
||||
expect(gradients.primary).toContain('linear-gradient');
|
||||
expect(gradients.primary).toContain('135deg');
|
||||
});
|
||||
|
||||
it('should have hero gradient', () => {
|
||||
expect(gradients.hero).toBeDefined();
|
||||
expect(gradients.hero).toContain('linear-gradient');
|
||||
expect(gradients.hero).toContain('180deg');
|
||||
});
|
||||
|
||||
it('should have brand gradient', () => {
|
||||
expect(gradients.brand).toBeDefined();
|
||||
expect(gradients.brand).toContain('linear-gradient');
|
||||
expect(gradients.brand).toContain('135deg');
|
||||
});
|
||||
|
||||
it('should have subtle gradient', () => {
|
||||
expect(gradients.subtle).toBeDefined();
|
||||
expect(gradients.subtle).toContain('linear-gradient');
|
||||
expect(gradients.subtle).toContain('180deg');
|
||||
});
|
||||
|
||||
it('should have card gradient', () => {
|
||||
expect(gradients.card).toBeDefined();
|
||||
expect(gradients.card).toContain('linear-gradient');
|
||||
expect(gradients.card).toContain('180deg');
|
||||
});
|
||||
|
||||
it('should have cta gradient', () => {
|
||||
expect(gradients.cta).toBeDefined();
|
||||
expect(gradients.cta).toContain('linear-gradient');
|
||||
expect(gradients.cta).toContain('135deg');
|
||||
});
|
||||
|
||||
it('should have valid gradient format', () => {
|
||||
const gradientPattern = /^linear-gradient\(/;
|
||||
|
||||
Object.values(gradients).forEach(gradient => {
|
||||
expect(gradient).toMatch(gradientPattern);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Type Exports', () => {
|
||||
it('should export BrandColor type', () => {
|
||||
const color: typeof brandColors = brandColors;
|
||||
expect(color).toBeDefined();
|
||||
});
|
||||
|
||||
it('should export ColorValue type', () => {
|
||||
const value: typeof colorValues = colorValues;
|
||||
expect(value).toBeDefined();
|
||||
});
|
||||
|
||||
it('should export Gradient type', () => {
|
||||
const gradient: typeof gradients = gradients;
|
||||
expect(gradient).toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,100 +0,0 @@
|
||||
export const brandColors = {
|
||||
primary: {
|
||||
900: '#0A0A0A',
|
||||
800: '#1C1C1C',
|
||||
700: '#2D2D2D',
|
||||
600: '#3D3D3D',
|
||||
500: '#5C5C5C',
|
||||
400: '#8C8C8C',
|
||||
300: '#B8B8B8',
|
||||
200: '#D4D4D4',
|
||||
100: '#E5E5E5',
|
||||
50: '#F5F5F5',
|
||||
},
|
||||
brand: {
|
||||
600: '#C41E3A',
|
||||
700: '#A01830',
|
||||
500: '#E04A68',
|
||||
400: '#F08C9F',
|
||||
100: '#FEF2F4',
|
||||
},
|
||||
neutral: {
|
||||
900: '#1C1C1C',
|
||||
800: '#3D3D3D',
|
||||
700: '#5C5C5C',
|
||||
600: '#8C8C8C',
|
||||
500: '#B8B8B8',
|
||||
400: '#D4D4D4',
|
||||
300: '#E5E5E5',
|
||||
200: '#F0F0F0',
|
||||
100: '#FAFAFA',
|
||||
50: '#FFFBF5',
|
||||
},
|
||||
success: {
|
||||
600: '#16A34A',
|
||||
100: '#F0FDF4',
|
||||
},
|
||||
warning: {
|
||||
600: '#D97706',
|
||||
100: '#FFFBEB',
|
||||
},
|
||||
info: {
|
||||
600: '#5C5C5C',
|
||||
100: '#F5F5F5',
|
||||
},
|
||||
error: {
|
||||
600: '#C41E3A',
|
||||
100: '#FEF2F4',
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const colorValues = {
|
||||
primary: '#1C1C1C',
|
||||
primaryHover: '#0A0A0A',
|
||||
primaryLight: '#3D3D3D',
|
||||
primaryLighter: '#F5F5F5',
|
||||
|
||||
brand: '#C41E3A',
|
||||
brandHover: '#A01830',
|
||||
brandLight: '#E04A68',
|
||||
brandBg: '#FEF2F4',
|
||||
|
||||
textPrimary: '#1C1C1C',
|
||||
textSecondary: '#3D3D3D',
|
||||
textTertiary: '#5C5C5C',
|
||||
textMuted: '#8C8C8C',
|
||||
|
||||
bgPrimary: '#FAFAFA',
|
||||
bgSecondary: '#FFFBF5',
|
||||
bgTertiary: '#F5F5F5',
|
||||
bgHover: '#EFEFEF',
|
||||
|
||||
border: '#E5E5E5',
|
||||
borderSecondary: '#D4D4D4',
|
||||
borderAccent: '#1C1C1C',
|
||||
|
||||
link: '#1C1C1C',
|
||||
linkHover: '#C41E3A',
|
||||
|
||||
success: '#16A34A',
|
||||
successBg: '#F0FDF4',
|
||||
warning: '#D97706',
|
||||
warningBg: '#FFFBEB',
|
||||
info: '#5C5C5C',
|
||||
infoBg: '#F5F5F5',
|
||||
error: '#C41E3A',
|
||||
errorBg: '#FEF2F4',
|
||||
} as const;
|
||||
|
||||
export const gradients = {
|
||||
primary: 'linear-gradient(135deg, #1C1C1C 0%, #3D3D3D 100%)',
|
||||
hero: 'linear-gradient(180deg, #FAFAFA 0%, #FFFBF5 100%)',
|
||||
brand: 'linear-gradient(135deg, #C41E3A 0%, #E04A68 100%)',
|
||||
subtle: 'linear-gradient(180deg, #FAFAFA 0%, #F5F5F5 100%)',
|
||||
card: 'linear-gradient(180deg, #FAFAFA 0%, #FFFBF5 100%)',
|
||||
cta: 'linear-gradient(135deg, #C41E3A 0%, #A01830 100%)',
|
||||
} as const;
|
||||
|
||||
export type BrandColor = typeof brandColors;
|
||||
export type ColorValue = typeof colorValues;
|
||||
export type Gradient = typeof gradients;
|
||||
@@ -128,7 +128,7 @@ export function canonicalTrustSource(source?: string | null): string | undefined
|
||||
|
||||
/**
|
||||
* 首批客户共创状态(无真实 quote 时的如实标注)。
|
||||
* 有真实客户 quote / 共创伙伴后,可在 `src/components/content/testimonials.tsx` 启用 Testimonial 区块替换本标签。
|
||||
* 有真实客户 quote / 共创伙伴后,再新建客户评价区块替换本标签(原 testimonials 占位组件因零引用已移除)。
|
||||
*/
|
||||
export const EARLY_ACCESS = {
|
||||
label: '首批客户共创中',
|
||||
|
||||
@@ -92,8 +92,12 @@ describe('DESIGN_SYSTEM', () => {
|
||||
expect(DESIGN_SYSTEM.effects.scroll.fadeInUp.initial).toEqual({ opacity: 0, y: 24 });
|
||||
expect(DESIGN_SYSTEM.effects.scroll.fadeInUp.animate).toEqual({ opacity: 1, y: 0 });
|
||||
expect(DESIGN_SYSTEM.effects.scroll.fadeInUp.viewport).toEqual({ once: true, margin: '-80px' });
|
||||
expect(DESIGN_SYSTEM.effects.scroll.fadeInUp.transition.duration).toBe(0.6);
|
||||
expect(DESIGN_SYSTEM.effects.scroll.staggerChildren.delay).toBe(0.08);
|
||||
// CONTEXT.md「动效设计四原则」:入场 180–280ms(--transition-fast … --transition-normal),
|
||||
// 子元素 stagger 30–60ms。断言区间而非具体值,令牌漂移时才会红。
|
||||
expect(DESIGN_SYSTEM.effects.scroll.fadeInUp.transition.duration).toBeGreaterThanOrEqual(0.18);
|
||||
expect(DESIGN_SYSTEM.effects.scroll.fadeInUp.transition.duration).toBeLessThanOrEqual(0.28);
|
||||
expect(DESIGN_SYSTEM.effects.scroll.staggerChildren.delay).toBeGreaterThanOrEqual(0.03);
|
||||
expect(DESIGN_SYSTEM.effects.scroll.staggerChildren.delay).toBeLessThanOrEqual(0.06);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -135,7 +139,9 @@ describe('DESIGN_SYSTEM', () => {
|
||||
expect(DESIGN_SYSTEM.components.badge).toBeDefined();
|
||||
expect(DESIGN_SYSTEM.components.badge.base).toContain('rounded-full');
|
||||
expect(DESIGN_SYSTEM.components.badge.variants).toBeDefined();
|
||||
expect(DESIGN_SYSTEM.components.badge.variants.primary).toContain('var(--color-brand)');
|
||||
// 双通道(DESIGN.md:154):底色仍走 --color-brand-bg,文字走翻转的 --color-brand-ink。
|
||||
expect(DESIGN_SYSTEM.components.badge.variants.primary).toContain('bg-[var(--color-brand-bg)]');
|
||||
expect(DESIGN_SYSTEM.components.badge.variants.primary).toContain('text-brand-ink');
|
||||
expect(DESIGN_SYSTEM.components.badge.variants.secondary).toContain('var(--color-text-secondary)');
|
||||
expect(DESIGN_SYSTEM.components.badge.variants.success).toContain('text-green-700');
|
||||
expect(DESIGN_SYSTEM.components.badge.variants.warning).toContain('text-yellow-700');
|
||||
@@ -145,7 +151,7 @@ describe('DESIGN_SYSTEM', () => {
|
||||
expect(DESIGN_SYSTEM.components.button).toBeDefined();
|
||||
expect(DESIGN_SYSTEM.components.button.primary).toContain('bg-[var(--color-brand)]');
|
||||
expect(DESIGN_SYSTEM.components.button.secondary).toContain('border-[var(--color-border-primary)]');
|
||||
expect(DESIGN_SYSTEM.components.button.ghost).toContain('text-[var(--color-brand)]');
|
||||
expect(DESIGN_SYSTEM.components.button.ghost).toContain('text-brand-ink');
|
||||
});
|
||||
|
||||
it('has metric component styles', () => {
|
||||
|
||||
@@ -80,10 +80,10 @@ export const DESIGN_SYSTEM = Object.freeze({
|
||||
initial: { opacity: 0, y: 24 },
|
||||
animate: { opacity: 1, y: 0 },
|
||||
viewport: { once: true, margin: '-80px' },
|
||||
transition: { duration: 0.6, ease: [0.16, 1, 0.3, 1] as const }, // ⚠️ P1:0.6s 超 300ms 目标
|
||||
transition: { duration: 0.28, ease: [0.22, 1, 0.36, 1] as const },
|
||||
},
|
||||
staggerChildren: {
|
||||
delay: 0.08,
|
||||
delay: 0.06,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -118,14 +118,14 @@ export const DESIGN_SYSTEM = Object.freeze({
|
||||
|
||||
components: {
|
||||
card: {
|
||||
base: 'rounded-2xl border border-[var(--color-border-primary)] overflow-hidden transition-all duration-300 bg-[var(--color-bg-primary)]',
|
||||
base: 'rounded-2xl border border-[var(--color-border-primary)] overflow-hidden transition-all duration-normal bg-[var(--color-bg-primary)]',
|
||||
hover: 'hover:border-[rgba(var(--color-brand-rgb),0.2)] hover:shadow-lg hover:-translate-y-1',
|
||||
padding: 'p-6 lg:p-8',
|
||||
},
|
||||
badge: {
|
||||
base: 'inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium',
|
||||
variants: {
|
||||
primary: 'bg-[var(--color-brand-bg)] text-[var(--color-brand)]',
|
||||
primary: 'bg-[var(--color-brand-bg)] text-brand-ink',
|
||||
secondary: 'bg-[var(--color-bg-tertiary)] text-[var(--color-text-secondary)]',
|
||||
success: 'bg-green-50 text-green-700',
|
||||
warning: 'bg-yellow-50 text-yellow-700',
|
||||
@@ -134,7 +134,7 @@ export const DESIGN_SYSTEM = Object.freeze({
|
||||
button: {
|
||||
primary: 'inline-flex items-center gap-2 px-6 py-3 text-white font-semibold rounded-lg shadow-md transition-all duration-200 bg-[var(--color-brand)] hover:brightness-110 hover:shadow-lg',
|
||||
secondary: 'inline-flex items-center gap-2 px-6 py-3 font-semibold rounded-lg border transition-all duration-200 bg-[var(--color-bg-primary)] text-[var(--color-text-secondary)] border-[var(--color-border-primary)] hover:border-[var(--color-text-hint)] hover:shadow-sm',
|
||||
ghost: 'inline-flex items-center gap-2 px-4 py-2 font-medium rounded-lg transition-colors duration-200 text-[var(--color-brand)] hover:bg-[var(--color-brand-bg)]',
|
||||
ghost: 'inline-flex items-center gap-2 px-4 py-2 font-medium rounded-lg transition-colors duration-200 text-brand-ink hover:bg-[var(--color-brand-bg)]',
|
||||
},
|
||||
metric: {
|
||||
container: 'text-center p-6 rounded-xl border bg-[var(--color-bg-section)] border-[var(--color-border-primary)]',
|
||||
|
||||
+68
-8
@@ -1,10 +1,70 @@
|
||||
// @ts-nocheck
|
||||
import { describe, it, expect } from '@jest/globals';
|
||||
import { describe, it, expect, jest, beforeEach, afterEach } from '@jest/globals';
|
||||
|
||||
// PrismaClient is already mocked in jest.setup.js
|
||||
describe('db', () => {
|
||||
it('should export prisma instance', async () => {
|
||||
const { prisma } = await import('./db');
|
||||
expect(prisma).toBeDefined();
|
||||
// PrismaClient 由本文件的 mock 提供:只需暴露 $queryRaw,即可断言真实下发的 PRAGMA。
|
||||
const mockQueryRaw = jest.fn<(parts: readonly string[]) => Promise<unknown>>();
|
||||
|
||||
jest.mock('@/generated/prisma/client', () => ({
|
||||
PrismaClient: jest.fn().mockImplementation(() => ({
|
||||
$queryRaw: mockQueryRaw,
|
||||
})),
|
||||
}));
|
||||
|
||||
type DbModule = typeof import('./db');
|
||||
|
||||
/** 重新求值模块(导入即触发一次 PRAGMA 下发),返回全新的 db 实例 */
|
||||
async function loadFreshDb(): Promise<DbModule> {
|
||||
delete (globalThis as unknown as { prisma?: unknown }).prisma;
|
||||
jest.resetModules();
|
||||
return (await import('./db')) as DbModule;
|
||||
}
|
||||
|
||||
let consoleErrorSpy: jest.Spied<typeof console.error>;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
mockQueryRaw.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
consoleErrorSpy.mockRestore();
|
||||
});
|
||||
|
||||
describe('SQLite 并发默认值(验收 B-5)', () => {
|
||||
it('导入 src/lib/db 即把 journal_mode 切到 WAL 并设置 busy_timeout', async () => {
|
||||
await loadFreshDb();
|
||||
|
||||
expect(mockQueryRaw).toHaveBeenCalledTimes(2);
|
||||
expect(mockQueryRaw.mock.calls[0]![0][0]).toBe('PRAGMA journal_mode=WAL');
|
||||
expect(mockQueryRaw.mock.calls[1]![0][0]).toBe('PRAGMA busy_timeout=5000');
|
||||
});
|
||||
});
|
||||
|
||||
it('applySqliteConcurrencyDefaults 幂等:重复调用不重复下发 PRAGMA', async () => {
|
||||
const db = await loadFreshDb();
|
||||
|
||||
await db.applySqliteConcurrencyDefaults();
|
||||
await db.applySqliteConcurrencyDefaults();
|
||||
|
||||
expect(mockQueryRaw).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('PRAGMA 失败只记录日志,既不抛出也不掩盖', async () => {
|
||||
mockQueryRaw.mockRejectedValueOnce(new Error('SQLITE_CANTOPEN: unable to open database file'));
|
||||
|
||||
const db = await loadFreshDb();
|
||||
|
||||
await expect(db.applySqliteConcurrencyDefaults()).resolves.toBeUndefined();
|
||||
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
|
||||
expect(consoleErrorSpy.mock.calls[0]![0]).toContain('WAL');
|
||||
expect((consoleErrorSpy.mock.calls[0]![1] as Error).message).toContain('SQLITE_CANTOPEN');
|
||||
// 第一条 PRAGMA 失败后不再尝试第二条(连接本身已不可用)
|
||||
expect(mockQueryRaw).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('导出的 prisma 仍是同一个客户端实例,且带 $queryRaw 能力', async () => {
|
||||
const db = await loadFreshDb();
|
||||
|
||||
expect(db.prisma).toBeDefined();
|
||||
expect(typeof db.prisma.$queryRaw).toBe('function');
|
||||
});
|
||||
});
|
||||
+37
-1
@@ -8,4 +8,40 @@ export const prisma = globalForPrisma.prisma ?? new PrismaClient();
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
globalForPrisma.prisma = prisma;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SQLite 并发默认值调优(验收 B-5)。
|
||||
*
|
||||
* 实测(@prisma/client 6.19.3 + 生成客户端 src/generated/prisma,对临时库文件跑 `PRAGMA` 读回):
|
||||
* - journal_mode 默认 'delete'(rollback journal)⇒ 同一时刻只允许一个写者,
|
||||
* 并发写会立刻 SQLITE_BUSY;WAL 允许「一读多写」并显著缩小写锁窗口。
|
||||
* - busy_timeout 默认已是 5000(并非 0),此处仍显式设置以固定预期、不依赖引擎默认值。
|
||||
* - datasource URL 上的查询参数(`?journal_mode=WAL&busy_timeout=…`)在本版本被**静默忽略**:
|
||||
* `file:<db>?journal_mode=WAL` 与 `file:<db>?totally_bogus=1` 都读回 journal_mode='delete',
|
||||
* 故不能靠改 DATABASE_URL 解决(该结论也意味着「改 .env/schema.prisma」并非正确方向)。
|
||||
* - `$on('beforeConnect')` 在本生成客户端不可用:`$on` 只接受 LogLevel
|
||||
* (src/generated/prisma/internal/class.ts:128 + prismaNamespace.ts:1515),
|
||||
* `beforeConnect` 仅存在于 binary 运行时(node_modules/@prisma/client/runtime/binary.js)。
|
||||
* - `PRAGMA journal_mode=WAL` 对**库文件**持久生效(新客户端实例不再执行 PRAGMA 仍读回 'wal'),
|
||||
* 因此进程内执行一次即可覆盖后续连接;busy_timeout 是连接级设置,但 SQLite 的默认值已足够。
|
||||
*
|
||||
* 失败只记录不上抛:数据库不可用时真正的业务查询会给出更准确的错误,
|
||||
* 不能让一个 PRAGMA 失败把整个模块导入变成 rejection。
|
||||
*/
|
||||
let sqliteTuning: Promise<void> | null = null;
|
||||
|
||||
export function applySqliteConcurrencyDefaults(): Promise<void> {
|
||||
if (!sqliteTuning) {
|
||||
sqliteTuning = (async () => {
|
||||
await prisma.$queryRaw`PRAGMA journal_mode=WAL`;
|
||||
await prisma.$queryRaw`PRAGMA busy_timeout=5000`;
|
||||
})().catch((error: unknown) => {
|
||||
console.error('Failed to apply SQLite WAL/busy_timeout pragmas:', error);
|
||||
});
|
||||
}
|
||||
return sqliteTuning;
|
||||
}
|
||||
|
||||
// 模块首次被导入即尽力开启 WAL(等价于「连接时设置」,因为 Prisma 会在此处隐式建立连接)。
|
||||
void applySqliteConcurrencyDefaults();
|
||||
@@ -1,132 +0,0 @@
|
||||
import { describe, it, expect } from '@jest/globals';
|
||||
import {
|
||||
getGradientStyle,
|
||||
getGlowStyle,
|
||||
getBorderGradientStyle,
|
||||
getTextGradientStyle,
|
||||
getHeroGradientStyle,
|
||||
getCTAGradientStyle,
|
||||
} from './gradients';
|
||||
|
||||
describe('gradients', () => {
|
||||
describe('getGradientStyle', () => {
|
||||
it('should return primary gradient style', () => {
|
||||
const style = getGradientStyle('primary');
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('linear-gradient');
|
||||
});
|
||||
|
||||
it('should return hero gradient style', () => {
|
||||
const style = getGradientStyle('hero');
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('linear-gradient');
|
||||
});
|
||||
|
||||
it('should return brand gradient style', () => {
|
||||
const style = getGradientStyle('brand');
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('linear-gradient');
|
||||
});
|
||||
|
||||
it('should return subtle gradient style', () => {
|
||||
const style = getGradientStyle('subtle');
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('linear-gradient');
|
||||
});
|
||||
|
||||
it('should return card gradient style', () => {
|
||||
const style = getGradientStyle('card');
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('linear-gradient');
|
||||
});
|
||||
|
||||
it('should return cta gradient style', () => {
|
||||
const style = getGradientStyle('cta');
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('linear-gradient');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getGlowStyle', () => {
|
||||
it('should return primary glow style with default opacity', () => {
|
||||
const style = getGlowStyle('primary');
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('radial-gradient');
|
||||
expect(style.background).toContain('0, 94, 184');
|
||||
});
|
||||
|
||||
it('should return brand glow style with default opacity', () => {
|
||||
const style = getGlowStyle('brand');
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('radial-gradient');
|
||||
expect(style.background).toContain('196, 30, 58');
|
||||
});
|
||||
|
||||
it('should return glow style with custom opacity', () => {
|
||||
const style = getGlowStyle('primary', 0.5);
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('0.5');
|
||||
});
|
||||
|
||||
it('should return glow style with zero opacity', () => {
|
||||
const style = getGlowStyle('brand', 0);
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('0)');
|
||||
});
|
||||
|
||||
it('should return glow style with full opacity', () => {
|
||||
const style = getGlowStyle('primary', 1);
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('1)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getBorderGradientStyle', () => {
|
||||
it('should return border gradient style', () => {
|
||||
const style = getBorderGradientStyle();
|
||||
expect(style).toHaveProperty('borderImage');
|
||||
expect(style.borderImage).toContain('linear-gradient');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getTextGradientStyle', () => {
|
||||
it('should return primary text gradient style', () => {
|
||||
const style = getTextGradientStyle('primary');
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style).toHaveProperty('WebkitBackgroundClip');
|
||||
expect(style).toHaveProperty('WebkitTextFillColor');
|
||||
expect(style).toHaveProperty('backgroundClip');
|
||||
expect(style.WebkitBackgroundClip).toBe('text');
|
||||
expect(style.WebkitTextFillColor).toBe('transparent');
|
||||
});
|
||||
|
||||
it('should return brand text gradient style', () => {
|
||||
const style = getTextGradientStyle('brand');
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('linear-gradient');
|
||||
});
|
||||
|
||||
it('should default to primary gradient', () => {
|
||||
const style = getTextGradientStyle();
|
||||
expect(style).toHaveProperty('background');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getHeroGradientStyle', () => {
|
||||
it('should return hero gradient style', () => {
|
||||
const style = getHeroGradientStyle();
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('linear-gradient');
|
||||
expect(style.background).toContain('180deg');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getCTAGradientStyle', () => {
|
||||
it('should return CTA gradient style', () => {
|
||||
const style = getCTAGradientStyle();
|
||||
expect(style).toHaveProperty('background');
|
||||
expect(style.background).toContain('linear-gradient');
|
||||
expect(style.background).toContain('135deg');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import { gradients } from './colors';
|
||||
|
||||
export const getGradientStyle = (type: keyof typeof gradients) => {
|
||||
return {
|
||||
background: gradients[type],
|
||||
};
|
||||
};
|
||||
|
||||
export const getGlowStyle = (color: 'primary' | 'brand', opacity: number = 0.1) => {
|
||||
const colorMap = {
|
||||
primary: '0, 94, 184',
|
||||
brand: '196, 30, 58',
|
||||
};
|
||||
const colorValue = colorMap[color];
|
||||
return {
|
||||
background: `radial-gradient(circle, rgba(${colorValue}, ${opacity}) 0%, transparent 70%)`,
|
||||
};
|
||||
};
|
||||
|
||||
export const getBorderGradientStyle = () => {
|
||||
return {
|
||||
borderImage: `${gradients.primary} 1`,
|
||||
};
|
||||
};
|
||||
|
||||
export const getTextGradientStyle = (type: 'primary' | 'brand' = 'primary') => {
|
||||
return {
|
||||
background: gradients[type],
|
||||
WebkitBackgroundClip: 'text',
|
||||
WebkitTextFillColor: 'transparent',
|
||||
backgroundClip: 'text',
|
||||
};
|
||||
};
|
||||
|
||||
export const getHeroGradientStyle = () => {
|
||||
return {
|
||||
background: gradients.hero,
|
||||
};
|
||||
};
|
||||
|
||||
export const getCTAGradientStyle = () => {
|
||||
return {
|
||||
background: gradients.cta,
|
||||
};
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect, beforeAll } from '@jest/globals';
|
||||
import { describe, it, expect, beforeAll, jest } from '@jest/globals';
|
||||
import sharp from 'sharp';
|
||||
import {
|
||||
isImage,
|
||||
@@ -84,12 +84,41 @@ describe('image-processor', () => {
|
||||
expect(derivatives.avif!.url).toMatch(/\.avif$/);
|
||||
});
|
||||
|
||||
// 派生命名原先只用 `image-${Date.now()}`(原图则走 generateUniqueFileName 带随机后缀),
|
||||
// 同一毫秒内的两次上传会算出同名路径 ⇒ saveDerivative 互相覆盖。
|
||||
it('does not reuse derivative names within the same millisecond', async () => {
|
||||
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000);
|
||||
try {
|
||||
const a = await generateDerivatives(testPng, 'image/png');
|
||||
const b = await generateDerivatives(testPng, 'image/png');
|
||||
|
||||
expect(a.thumbnail!.path).not.toBe(b.thumbnail!.path);
|
||||
expect(a.webp!.path).not.toBe(b.webp!.path);
|
||||
expect(a.avif!.path).not.toBe(b.avif!.path);
|
||||
expect(a.webp!.url).not.toBe(b.webp!.url);
|
||||
} finally {
|
||||
nowSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps original aspect ratio for thumbnail', async () => {
|
||||
const derivatives = await generateDerivatives(testPng, 'image/png');
|
||||
const thumb = derivatives.thumbnail!;
|
||||
expect(thumb.width / thumb.height).toBeCloseTo(800 / 600, 1);
|
||||
});
|
||||
|
||||
// 缩略图被声明为 `.webp`(buildDerivative 用 ext='webp'),但旧实现对 thumbnailBuffer
|
||||
// 只 `.resize().toBuffer()` 而不调 `.webp()` ⇒ 字节其实是输入格式(PNG/JPEG),
|
||||
// 落盘文件内容与其 `.webp` 扩展名和 image/webp MIME 不符。
|
||||
it('encodes the thumbnail as real WebP bytes regardless of input format', async () => {
|
||||
const fromPng = await generateDerivatives(testPng, 'image/png');
|
||||
const fromJpeg = await generateDerivatives(testJpeg, 'image/jpeg');
|
||||
|
||||
expect((await sharp(fromPng.thumbnail!.buffer).metadata()).format).toBe('webp');
|
||||
expect((await sharp(fromJpeg.thumbnail!.buffer).metadata()).format).toBe('webp');
|
||||
expect(fromPng.thumbnail!.path).toMatch(/-thumbnail\.webp$/);
|
||||
});
|
||||
|
||||
it('returns empty derivatives for non-image files', async () => {
|
||||
const derivatives = await generateDerivatives(txtBuffer, 'text/plain');
|
||||
expect(Object.keys(derivatives)).toHaveLength(0);
|
||||
|
||||
@@ -72,12 +72,13 @@ export async function generateDerivatives(
|
||||
return {};
|
||||
}
|
||||
|
||||
const originalName = `image-${Date.now()}`;
|
||||
const originalName = `image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const derivatives: GeneratedDerivatives = {};
|
||||
|
||||
// 缩略图
|
||||
const thumbnailBuffer = await sharp(buffer)
|
||||
.resize(THUMBNAIL_SIZE, THUMBNAIL_SIZE, { fit: 'inside', withoutEnlargement: true })
|
||||
.webp({ quality: 80 })
|
||||
.toBuffer();
|
||||
const thumbnailMeta = await sharp(thumbnailBuffer).metadata();
|
||||
derivatives.thumbnail = buildDerivative(
|
||||
|
||||
@@ -44,14 +44,38 @@ jest.mock('@/lib/db', () => ({
|
||||
|
||||
import { uploadMedia, deleteMedia, getMediaById, listMedia } from './media-service';
|
||||
|
||||
// uploadMedia 现要求真实魔数(验收 A-4),故夹具带合法文件头
|
||||
const PNG_BYTES = Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
Buffer.from('fake-png-body'),
|
||||
]);
|
||||
const PDF_BYTES = Buffer.concat([Buffer.from('%PDF-1.7\n', 'ascii'), Buffer.from('fake-pdf-body')]);
|
||||
|
||||
describe('media-service', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('uploadMedia', () => {
|
||||
it('HTML 载荷在落盘前即被拒绝(验收 A-4 服务层收口)', async () => {
|
||||
const html = Buffer.from('<html><script>alert(1)</script></html>');
|
||||
await expect(
|
||||
uploadMedia({ name: 'evil.html', buffer: html, mimeType: 'text/html', size: html.length }, 'editor')
|
||||
).rejects.toThrow('不允许的文件类型');
|
||||
expect(mockStorageSave).not.toHaveBeenCalled();
|
||||
expect(mockMediaAssetCreate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('内容伪装成 .png 的 HTML 同样被拒绝', async () => {
|
||||
const html = Buffer.from('<html><body>x</body></html>');
|
||||
await expect(
|
||||
uploadMedia({ name: 'attack.png', buffer: html, mimeType: 'image/png', size: html.length }, 'editor')
|
||||
).rejects.toThrow();
|
||||
expect(mockStorageSave).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uploads image and creates MediaAsset with derivatives', async () => {
|
||||
const pngBuffer = Buffer.from('fake-png');
|
||||
const pngBuffer = PNG_BYTES;
|
||||
mockStorageSave
|
||||
.mockResolvedValueOnce({ path: 'public/uploads/original.png', url: '/uploads/original.png' })
|
||||
.mockResolvedValueOnce({ path: 'public/uploads/thumb.webp', url: '/uploads/thumb.webp' })
|
||||
@@ -98,7 +122,7 @@ describe('media-service', () => {
|
||||
});
|
||||
|
||||
it('uploads non-image file without generating derivatives', async () => {
|
||||
const pdfBuffer = Buffer.from('fake-pdf');
|
||||
const pdfBuffer = PDF_BYTES;
|
||||
mockStorageSave.mockResolvedValueOnce({ path: 'public/uploads/file.pdf', url: '/uploads/file.pdf' });
|
||||
mockMediaAssetCreate.mockResolvedValue({ id: 'asset-2' });
|
||||
|
||||
@@ -136,7 +160,7 @@ describe('media-service', () => {
|
||||
mockMediaAssetCreate.mockResolvedValue({ id: 'asset-3' });
|
||||
|
||||
await uploadMedia(
|
||||
{ name: 'key.png', buffer: Buffer.from('x'), mimeType: 'image/png', size: 100 },
|
||||
{ name: 'key.png', buffer: PNG_BYTES, mimeType: 'image/png', size: 100 },
|
||||
'editor'
|
||||
);
|
||||
|
||||
@@ -154,7 +178,7 @@ describe('media-service', () => {
|
||||
mockMediaAssetCreate.mockResolvedValue({ id: 'asset-4' });
|
||||
|
||||
await uploadMedia(
|
||||
{ name: 'broken.png', buffer: Buffer.from('not-really-png'), mimeType: 'image/png', size: 100 },
|
||||
{ name: 'broken.png', buffer: PNG_BYTES, mimeType: 'image/png', size: 100 },
|
||||
'editor'
|
||||
);
|
||||
|
||||
@@ -171,7 +195,22 @@ describe('media-service', () => {
|
||||
});
|
||||
|
||||
describe('deleteMedia', () => {
|
||||
it('deletes original file and all derivatives then removes db record', async () => {
|
||||
let callOrder: string[];
|
||||
let consoleErrorSpy: jest.Spied<typeof console.error>;
|
||||
|
||||
beforeEach(() => {
|
||||
callOrder = [];
|
||||
consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
mockStorageDelete.mockImplementation(async (filePath: string) => {
|
||||
callOrder.push(`file:${filePath}`);
|
||||
});
|
||||
mockMediaAssetDelete.mockImplementation(async () => {
|
||||
callOrder.push('db:delete');
|
||||
return { id: 'asset-1' };
|
||||
});
|
||||
});
|
||||
|
||||
it('removes the db record first, then the original file and all derivatives', async () => {
|
||||
mockMediaAssetFindUnique.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
path: 'public/uploads/original.png',
|
||||
@@ -190,14 +229,54 @@ describe('media-service', () => {
|
||||
expect(mockStorageDelete).toHaveBeenCalledWith('public/uploads/original-webp.webp');
|
||||
expect(mockStorageDelete).toHaveBeenCalledWith('public/uploads/original-avif.avif');
|
||||
expect(mockMediaAssetDelete).toHaveBeenCalledWith({ where: { id: 'asset-1' } });
|
||||
// 顺序即修复点:先删记录,DB 失败时不会留下「指向已删文件的资产行」(验收 §5)
|
||||
expect(callOrder[0]).toBe('db:delete');
|
||||
expect(callOrder).toEqual([
|
||||
'db:delete',
|
||||
'file:public/uploads/original.png',
|
||||
'file:public/uploads/thumb.webp',
|
||||
'file:public/uploads/original-webp.webp',
|
||||
'file:public/uploads/original-avif.avif',
|
||||
]);
|
||||
});
|
||||
|
||||
it('throws when media asset not found', async () => {
|
||||
mockMediaAssetFindUnique.mockResolvedValue(null);
|
||||
await expect(deleteMedia('missing')).rejects.toThrow('文件不存在');
|
||||
expect(mockMediaAssetDelete).not.toHaveBeenCalled();
|
||||
expect(mockStorageDelete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('only deletes original file when derivatives JSON is invalid', async () => {
|
||||
it('leaves every file on disk when the db delete fails', async () => {
|
||||
mockMediaAssetFindUnique.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
path: 'public/uploads/original.png',
|
||||
derivatives: JSON.stringify({ thumbnail: { path: 'public/uploads/thumb.webp' } }),
|
||||
});
|
||||
mockMediaAssetDelete.mockRejectedValue(new Error('SQLITE_BUSY'));
|
||||
|
||||
await expect(deleteMedia('asset-1')).rejects.toThrow('SQLITE_BUSY');
|
||||
expect(mockStorageDelete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('logs a manual-cleanup trail instead of failing after the record is gone', async () => {
|
||||
mockMediaAssetFindUnique.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
path: 'public/uploads/original.png',
|
||||
derivatives: JSON.stringify({ thumbnail: { path: 'public/uploads/thumb.webp' } }),
|
||||
});
|
||||
const denied = Object.assign(new Error('operation not permitted'), { code: 'EPERM' });
|
||||
mockStorageDelete.mockRejectedValueOnce(denied);
|
||||
|
||||
await expect(deleteMedia('asset-1')).resolves.toBeUndefined();
|
||||
|
||||
expect(mockStorageDelete).toHaveBeenCalledTimes(2);
|
||||
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
|
||||
expect(consoleErrorSpy.mock.calls[0]![0]).toContain('public/uploads/original.png');
|
||||
expect(consoleErrorSpy.mock.calls[0]![1]).toBe(denied);
|
||||
});
|
||||
|
||||
it('still deletes the original file but logs when derivatives JSON is invalid', async () => {
|
||||
mockMediaAssetFindUnique.mockResolvedValue({
|
||||
id: 'asset-2',
|
||||
path: 'public/uploads/original.png',
|
||||
@@ -209,6 +288,10 @@ describe('media-service', () => {
|
||||
expect(mockStorageDelete).toHaveBeenCalledTimes(1);
|
||||
expect(mockStorageDelete).toHaveBeenCalledWith('public/uploads/original.png');
|
||||
expect(mockMediaAssetDelete).toHaveBeenCalledWith({ where: { id: 'asset-2' } });
|
||||
// 空 catch 已换成可排查的日志:否则派生文件永远无人知晓
|
||||
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
|
||||
expect(consoleErrorSpy.mock.calls[0]![0]).toContain('derivatives');
|
||||
expect(consoleErrorSpy.mock.calls[0]![0]).toContain('asset-2');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -2,11 +2,10 @@ import path from 'path';
|
||||
import { prisma } from '@/lib/db';
|
||||
import { getStorageProvider } from './storage';
|
||||
import { generateDerivatives, getImageMetadata, isImage } from './image-processor';
|
||||
import { assertUploadAllowed } from './upload-policy';
|
||||
import type { UploadMediaInput, ListMediaOptions, MediaDerivatives, StoredFile, StoredDerivative, GeneratedDerivatives } from './types';
|
||||
|
||||
function generateUniqueFileName(originalName: string): string {
|
||||
const ext = path.extname(originalName) || '';
|
||||
const baseName = path.basename(originalName, ext) || 'file';
|
||||
function generateUniqueFileName(baseName: string, ext: string): string {
|
||||
const timestamp = Date.now();
|
||||
const random = Math.random().toString(36).slice(2, 10);
|
||||
return `${baseName}-${timestamp}-${random}${ext}`;
|
||||
@@ -14,10 +13,11 @@ function generateUniqueFileName(originalName: string): string {
|
||||
|
||||
async function saveOriginalFile(
|
||||
provider: ReturnType<typeof getStorageProvider>,
|
||||
input: UploadMediaInput
|
||||
input: UploadMediaInput,
|
||||
policy: ReturnType<typeof assertUploadAllowed>
|
||||
): Promise<StoredFile> {
|
||||
const fileName = generateUniqueFileName(input.name);
|
||||
return provider.save(fileName, input.buffer, input.mimeType);
|
||||
const fileName = generateUniqueFileName(policy.baseName, policy.ext);
|
||||
return provider.save(fileName, input.buffer, policy.mimeType);
|
||||
}
|
||||
|
||||
async function saveDerivative(
|
||||
@@ -34,21 +34,29 @@ async function saveDerivative(
|
||||
* 图片会自动生成缩略图、WebP、AVIF 派生格式并持久化
|
||||
*/
|
||||
export async function uploadMedia(input: UploadMediaInput, createdBy: string) {
|
||||
// 落盘前必须先过白名单与魔数:一旦写入 public/uploads/ 即可以同源 URL 被取回
|
||||
const policy = assertUploadAllowed({
|
||||
name: input.name,
|
||||
buffer: input.buffer,
|
||||
mimeType: input.mimeType,
|
||||
size: input.size,
|
||||
});
|
||||
|
||||
const provider = getStorageProvider();
|
||||
const original = await saveOriginalFile(provider, input);
|
||||
const original = await saveOriginalFile(provider, input, policy);
|
||||
|
||||
let width = 0;
|
||||
let height = 0;
|
||||
let derivatives: MediaDerivatives = {};
|
||||
|
||||
if (isImage(input.mimeType)) {
|
||||
if (isImage(policy.mimeType)) {
|
||||
const metadata = await getImageMetadata(input.buffer);
|
||||
if (metadata) {
|
||||
width = metadata.width;
|
||||
height = metadata.height;
|
||||
}
|
||||
|
||||
const generated: GeneratedDerivatives = await generateDerivatives(input.buffer, input.mimeType);
|
||||
const generated: GeneratedDerivatives = await generateDerivatives(input.buffer, policy.mimeType);
|
||||
const savedDerivatives: MediaDerivatives = {};
|
||||
|
||||
for (const key of Object.keys(generated) as Array<keyof MediaDerivatives>) {
|
||||
@@ -74,7 +82,7 @@ export async function uploadMedia(input: UploadMediaInput, createdBy: string) {
|
||||
name: input.name,
|
||||
path: original.path,
|
||||
url: original.url,
|
||||
mimeType: input.mimeType,
|
||||
mimeType: policy.mimeType,
|
||||
size: input.size,
|
||||
width,
|
||||
height,
|
||||
@@ -87,7 +95,11 @@ export async function uploadMedia(input: UploadMediaInput, createdBy: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除媒体资源:清理原始文件及所有派生格式,然后删除数据库记录
|
||||
* 删除媒体资源:先删数据库记录,再清理原始文件与所有派生格式
|
||||
*
|
||||
* 顺序刻意如此(验收 §5):原实现先删文件后删记录,DB 失败即留下「指向已删文件的资产行」,
|
||||
* 前端与 CMS 会持续取回一个 404 资源。反序后最坏情况退化为「文件残留」,
|
||||
* 每条残留都会带路径写入日志,可据此人工回收。
|
||||
*/
|
||||
export async function deleteMedia(id: string) {
|
||||
const existing = await prisma.mediaAsset.findUnique({ where: { id } });
|
||||
@@ -106,15 +118,24 @@ export async function deleteMedia(id: string) {
|
||||
pathsToDelete.push(derivative.path);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// derivatives 字段不是有效 JSON 时仅删除原始文件
|
||||
}
|
||||
|
||||
for (const filePath of pathsToDelete) {
|
||||
await provider.delete(filePath);
|
||||
} catch (error) {
|
||||
// 不再空 catch:derivatives 非法时派生文件路径已无法枚举,必须留下可排查的记录,
|
||||
// 否则这些文件永远无人知晓(验收 §5)。
|
||||
console.error(
|
||||
`[media] asset=${id} 的 derivatives 不是合法 JSON,跳过派生文件枚举(可能有残留文件需人工清理):`,
|
||||
error
|
||||
);
|
||||
}
|
||||
|
||||
await prisma.mediaAsset.delete({ where: { id } });
|
||||
|
||||
for (const filePath of pathsToDelete) {
|
||||
try {
|
||||
await provider.delete(filePath);
|
||||
} catch (error) {
|
||||
console.error(`[media] asset=${id} 文件删除失败,需人工清理 path=${filePath}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -72,6 +72,44 @@ describe('LocalStorageProvider', () => {
|
||||
provider.delete(path.join(tempDir, 'not-exist.txt'))
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('deletes a file addressed relative to the storage directory', async () => {
|
||||
const result = await provider.save('relative-delete.txt', Buffer.from('x'), 'text/plain');
|
||||
const relative = path.relative(tempDir, result.path);
|
||||
|
||||
await provider.delete(relative);
|
||||
|
||||
await expect(fs.access(result.path)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('refuses to delete an absolute path outside the storage directory', async () => {
|
||||
const outsideDir = await fs.mkdtemp(path.join(os.tmpdir(), 'media-outside-'));
|
||||
const outsideFile = path.join(outsideDir, 'keep-me.txt');
|
||||
await fs.writeFile(outsideFile, 'do not delete');
|
||||
|
||||
await expect(provider.delete(outsideFile)).rejects.toThrow(/outside the storage directory/);
|
||||
await expect(fs.readFile(outsideFile)).resolves.toEqual(Buffer.from('do not delete'));
|
||||
|
||||
await fs.rm(outsideDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('refuses to delete through ../ traversal', async () => {
|
||||
const nested = path.join(tempDir, 'nested');
|
||||
await fs.mkdir(nested, { recursive: true });
|
||||
const providerInNested = new LocalStorageProvider(nested, '/test-uploads');
|
||||
const outsideFile = path.join(tempDir, 'secret.txt');
|
||||
await fs.writeFile(outsideFile, 'still here');
|
||||
|
||||
await expect(providerInNested.delete('../secret.txt')).rejects.toThrow(
|
||||
/outside the storage directory/
|
||||
);
|
||||
await expect(fs.readFile(outsideFile)).resolves.toEqual(Buffer.from('still here'));
|
||||
});
|
||||
|
||||
it('refuses to delete the storage directory itself', async () => {
|
||||
await expect(provider.delete(tempDir)).rejects.toThrow(/outside the storage directory/);
|
||||
await expect(fs.stat(tempDir)).resolves.toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('S3StorageProvider', () => {
|
||||
|
||||
@@ -26,9 +26,30 @@ export class LocalStorageProvider implements StorageProvider {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 把入参路径解析为 baseDir 内的绝对路径;越界即拒绝。
|
||||
*
|
||||
* delete() 目前只被喂库内路径(`deleteMedia` 传 MediaAsset.path / derivatives.path),
|
||||
* 但它是文件系统边界,不能依赖调用方的自律(验收 §5):
|
||||
* `../` 逃逸、绝对路径、指向 baseDir 自身都必须失败。
|
||||
* 绝对路径仍可命中 baseDir 内的同一文件,故 `save()` 返回的绝对路径不受影响。
|
||||
*/
|
||||
private resolveContainedPath(filePath: string): string {
|
||||
const baseDir = path.resolve(this.baseDir);
|
||||
const resolved = path.resolve(baseDir, filePath);
|
||||
const relative = path.relative(baseDir, resolved);
|
||||
|
||||
if (relative === '' || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
||||
throw new Error(`Refusing to delete path outside the storage directory: ${filePath}`);
|
||||
}
|
||||
|
||||
return resolved;
|
||||
}
|
||||
|
||||
async delete(filePath: string): Promise<void> {
|
||||
const resolved = this.resolveContainedPath(filePath);
|
||||
try {
|
||||
await fs.unlink(filePath);
|
||||
await fs.unlink(resolved);
|
||||
} catch (error) {
|
||||
// 文件可能已被删除,忽略 ENOENT
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
import {
|
||||
evaluateUpload,
|
||||
assertUploadAllowed,
|
||||
sniffMimeTypes,
|
||||
toSafeBaseName,
|
||||
isInlineSafeImage,
|
||||
MAX_UPLOAD_BYTES,
|
||||
UploadPolicyError,
|
||||
} from './upload-policy';
|
||||
|
||||
const PNG = Buffer.concat([
|
||||
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
||||
Buffer.from('IHDR-rest-of-a-png-file', 'ascii'),
|
||||
]);
|
||||
const JPEG = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.alloc(64, 1)]);
|
||||
const GIF = Buffer.concat([Buffer.from('GIF89a', 'ascii'), Buffer.alloc(32)]);
|
||||
const WEBP = Buffer.concat([
|
||||
Buffer.from('RIFF', 'ascii'),
|
||||
Buffer.from([0x10, 0, 0, 0]),
|
||||
Buffer.from('WEBP', 'ascii'),
|
||||
Buffer.alloc(16),
|
||||
]);
|
||||
const AVIF = Buffer.concat([
|
||||
Buffer.from([0, 0, 0, 0x1e]),
|
||||
Buffer.from('ftyp', 'ascii'),
|
||||
Buffer.from('avif', 'ascii'),
|
||||
Buffer.alloc(16),
|
||||
]);
|
||||
const PDF = Buffer.concat([Buffer.from('%PDF-1.7\n', 'ascii'), Buffer.alloc(64)]);
|
||||
const ZIP = Buffer.concat([Buffer.from([0x50, 0x4b, 0x03, 0x04]), Buffer.alloc(64)]);
|
||||
const OLE2 = Buffer.concat([
|
||||
Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]),
|
||||
Buffer.alloc(64),
|
||||
]);
|
||||
const HTML = Buffer.from('<html><script>alert(document.domain)</script></html>', 'utf8');
|
||||
|
||||
describe('sniffMimeTypes', () => {
|
||||
it('识别常见图片与文档容器', () => {
|
||||
expect(sniffMimeTypes(PNG)).toEqual(['image/png']);
|
||||
expect(sniffMimeTypes(JPEG)).toEqual(['image/jpeg']);
|
||||
expect(sniffMimeTypes(GIF)).toEqual(['image/gif']);
|
||||
expect(sniffMimeTypes(WEBP)).toEqual(['image/webp']);
|
||||
expect(sniffMimeTypes(AVIF)).toEqual(['image/avif']);
|
||||
expect(sniffMimeTypes(PDF)).toEqual(['application/pdf']);
|
||||
});
|
||||
|
||||
it('ZIP 与 OLE2 容器只给出候选集合而非单一类型', () => {
|
||||
expect(sniffMimeTypes(ZIP)).toContain('application/zip');
|
||||
expect(sniffMimeTypes(ZIP).length).toBeGreaterThan(1);
|
||||
expect(sniffMimeTypes(OLE2)).toContain('application/msword');
|
||||
});
|
||||
|
||||
it('HTML / 未知内容返回空集合', () => {
|
||||
expect(sniffMimeTypes(HTML)).toEqual([]);
|
||||
expect(sniffMimeTypes(Buffer.alloc(0))).toEqual([]);
|
||||
expect(sniffMimeTypes(Buffer.from('random bytes here'))).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('evaluateUpload:同源脚本执行面(验收 A-4)', () => {
|
||||
it('拒绝 .html:即使客户端把 MIME 报成 image/png', () => {
|
||||
expect(evaluateUpload({ name: 'evil.html', buffer: HTML, mimeType: 'image/png' })).toMatchObject({
|
||||
ok: false,
|
||||
});
|
||||
expect(evaluateUpload({ name: 'evil.htm', buffer: HTML, mimeType: 'text/html' }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('拒绝 .svg(同源可直接执行脚本),尽管前端 accept="image/*" 会放行选择', () => {
|
||||
const svg = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>');
|
||||
const verdict = evaluateUpload({ name: 'logo.svg', buffer: svg, mimeType: 'image/svg+xml' });
|
||||
expect(verdict.ok).toBe(false);
|
||||
});
|
||||
|
||||
it('拒绝可执行与脚本类扩展名', () => {
|
||||
for (const name of ['x.js', 'x.mjs', 'x.jsx', 'x.php', 'x.phar', 'x.exe', 'x.sh', 'x.xhtml', 'x.xml', 'x.html5']) {
|
||||
expect(evaluateUpload({ name, buffer: PNG, mimeType: 'image/png' }).ok).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('拒绝无扩展名与双扩展名伪装', () => {
|
||||
expect(evaluateUpload({ name: 'LICENSE', buffer: PNG, mimeType: 'image/png' }).ok).toBe(false);
|
||||
expect(evaluateUpload({ name: 'invoice.pdf.html', buffer: HTML, mimeType: 'text/html' }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('内容伪装:扩展名 .png 但字节是 HTML 时被拒', () => {
|
||||
const verdict = evaluateUpload({ name: 'banner.png', buffer: HTML, mimeType: 'image/png' });
|
||||
expect(verdict.ok).toBe(false);
|
||||
expect(verdict).toMatchObject({ ok: false, reason: expect.stringContaining('识别') });
|
||||
});
|
||||
|
||||
it('真实 PNG 头 + .png 后缀,但声明 MIME 为 text/html 时被拒', () => {
|
||||
expect(evaluateUpload({ name: 'banner.png', buffer: PNG, mimeType: 'text/html' }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('声明 MIME 与扩展名不一致时被拒', () => {
|
||||
expect(evaluateUpload({ name: 'a.png', buffer: PNG, mimeType: 'application/pdf' }).ok).toBe(false);
|
||||
expect(evaluateUpload({ name: 'a.pdf', buffer: PDF, mimeType: 'image/png' }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('拒绝空文件与超限文件', () => {
|
||||
expect(evaluateUpload({ name: 'a.png', buffer: Buffer.alloc(0), mimeType: 'image/png' }).ok).toBe(false);
|
||||
const verdict = evaluateUpload({
|
||||
name: 'a.png',
|
||||
buffer: PNG,
|
||||
mimeType: 'image/png',
|
||||
size: MAX_UPLOAD_BYTES + 1,
|
||||
});
|
||||
expect(verdict).toMatchObject({ ok: false, reason: expect.stringContaining('10MB') });
|
||||
});
|
||||
});
|
||||
|
||||
describe('evaluateUpload:合法上传不被误伤', () => {
|
||||
it('放行真实图片', () => {
|
||||
for (const [name, buffer, mimeType] of [
|
||||
['photo.png', PNG, 'image/png'],
|
||||
['photo.jpg', JPEG, 'image/jpeg'],
|
||||
['anim.gif', GIF, 'image/gif'],
|
||||
['modern.webp', WEBP, 'image/webp'],
|
||||
['next-gen.avif', AVIF, 'image/avif'],
|
||||
] as const) {
|
||||
expect(evaluateUpload({ name, buffer, mimeType })).toMatchObject({ ok: true, mimeType });
|
||||
}
|
||||
});
|
||||
|
||||
it('放行办公文档(ZIP 与 OLE2 容器)', () => {
|
||||
expect(
|
||||
evaluateUpload({
|
||||
name: 'whitepaper.docx',
|
||||
buffer: ZIP,
|
||||
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
}).ok
|
||||
).toBe(true);
|
||||
expect(evaluateUpload({ name: 'deck.ppt', buffer: OLE2, mimeType: 'application/vnd.ms-powerpoint' }).ok).toBe(
|
||||
true
|
||||
);
|
||||
expect(evaluateUpload({ name: 'bundle.zip', buffer: ZIP, mimeType: 'application/zip' }).ok).toBe(true);
|
||||
});
|
||||
|
||||
it('扩展名大小写不敏感', () => {
|
||||
expect(evaluateUpload({ name: 'LOGO.PNG', buffer: PNG, mimeType: 'image/png' })).toMatchObject({
|
||||
ok: true,
|
||||
ext: '.png',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('文件名归一化', () => {
|
||||
it('剥离路径穿越与目录成分', () => {
|
||||
expect(toSafeBaseName('../../../etc/passwd')).toBe('passwd');
|
||||
expect(toSafeBaseName('..%2f..%2fwindows')).not.toContain('/');
|
||||
expect(evaluateUpload({ name: '../../uploads/x.png', buffer: PNG, mimeType: 'image/png' })).toMatchObject({
|
||||
ok: true,
|
||||
baseName: 'x',
|
||||
});
|
||||
});
|
||||
|
||||
it('非 ASCII 与特殊字符收敛为安全 slug,空名回落 file', () => {
|
||||
expect(evaluateUpload({ name: '产品 发布!!图.png', buffer: PNG, mimeType: 'image/png' })).toMatchObject({
|
||||
baseName: 'file',
|
||||
});
|
||||
expect(toSafeBaseName('a b/c.png')).toBe('c');
|
||||
expect(toSafeBaseName('....hidden')).toBe('file'); // 纯点号词干收敛到兜底名
|
||||
expect(toSafeBaseName('x'.repeat(200)).length).toBeLessThanOrEqual(60);
|
||||
});
|
||||
|
||||
it('isInlineSafeImage 只对图片放行内联渲染', () => {
|
||||
expect(isInlineSafeImage('image/png')).toBe(true);
|
||||
expect(isInlineSafeImage('application/pdf')).toBe(false);
|
||||
expect(isInlineSafeImage('application/zip')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('assertUploadAllowed', () => {
|
||||
it('合法输入返回判定结果,非法输入抛 UploadPolicyError', () => {
|
||||
expect(assertUploadAllowed({ name: 'a.png', buffer: PNG, mimeType: 'image/png' })).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
expect(() => assertUploadAllowed({ name: 'a.html', buffer: HTML, mimeType: 'text/html' })).toThrow(
|
||||
UploadPolicyError
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import path from 'path';
|
||||
|
||||
/**
|
||||
* 上传落盘白名单与内容嗅探(验收 A-4)。
|
||||
*
|
||||
* 客户端可控的 file.type / file.name 一律不作为可信输入:扩展名与魔数都必须落在
|
||||
* 白名单交集内,实际 MIME 取嗅探结果。HTML/SVG/XHTML 等可在同源直接执行脚本的类型
|
||||
* 被整体排除,即使前端 accept="image/*" 允许选择 svg 也会在此拒绝。
|
||||
*/
|
||||
|
||||
export const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
|
||||
|
||||
const EXTENSION_TO_MIMES: Record<string, string[]> = {
|
||||
'.png': ['image/png'],
|
||||
'.jpg': ['image/jpeg'],
|
||||
'.jpeg': ['image/jpeg'],
|
||||
'.gif': ['image/gif'],
|
||||
'.webp': ['image/webp'],
|
||||
'.avif': ['image/avif'],
|
||||
'.bmp': ['image/bmp'],
|
||||
'.ico': ['image/vnd.microsoft.icon', 'image/x-icon'],
|
||||
'.pdf': ['application/pdf'],
|
||||
'.zip': ['application/zip', 'application/x-zip-compressed'],
|
||||
'.docx': ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
|
||||
'.xlsx': ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
|
||||
'.pptx': ['application/vnd.openxmlformats-officedocument.presentationml.presentation'],
|
||||
'.doc': ['application/msword'],
|
||||
'.xls': ['application/vnd.ms-excel'],
|
||||
'.ppt': ['application/vnd.ms-powerpoint'],
|
||||
};
|
||||
|
||||
function startsWith(buffer: Buffer, bytes: number[], offset = 0): boolean {
|
||||
if (buffer.length < offset + bytes.length) return false;
|
||||
return bytes.every((byte, i) => buffer[offset + i] === byte);
|
||||
}
|
||||
|
||||
function ascii(buffer: Buffer, offset: number, length: number): string {
|
||||
return buffer.subarray(offset, offset + length).toString('ascii');
|
||||
}
|
||||
|
||||
/** 返回该 buffer 在魔数上**可能**是哪些 MIME;ZIP 与 OLE2 容器无法凭魔数细分,故给出集合。 */
|
||||
export function sniffMimeTypes(buffer: Buffer): string[] {
|
||||
if (startsWith(buffer, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return ['image/png'];
|
||||
if (startsWith(buffer, [0xff, 0xd8, 0xff])) return ['image/jpeg'];
|
||||
if (ascii(buffer, 0, 6) === 'GIF87a' || ascii(buffer, 0, 6) === 'GIF89a') return ['image/gif'];
|
||||
if (ascii(buffer, 0, 4) === 'RIFF' && ascii(buffer, 8, 4) === 'WEBP') return ['image/webp'];
|
||||
if (ascii(buffer, 4, 4) === 'ftyp' && ['avif', 'avis', 'mif1', 'msf1'].includes(ascii(buffer, 8, 4))) {
|
||||
return ['image/avif'];
|
||||
}
|
||||
if (ascii(buffer, 0, 2) === 'BM') return ['image/bmp'];
|
||||
if (startsWith(buffer, [0x00, 0x00, 0x01, 0x00])) return ['image/vnd.microsoft.icon', 'image/x-icon'];
|
||||
if (ascii(buffer, 0, 5) === '%PDF-') return ['application/pdf'];
|
||||
if (startsWith(buffer, [0x50, 0x4b, 0x03, 0x04]) || startsWith(buffer, [0x50, 0x4b, 0x05, 0x06])) {
|
||||
return [
|
||||
'application/zip',
|
||||
'application/x-zip-compressed',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
];
|
||||
}
|
||||
if (startsWith(buffer, [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1])) {
|
||||
return ['application/msword', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint'];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/** 该 MIME 在响应头里应使用的规范值:非图片一律走下载型分发。 */
|
||||
export function isInlineSafeImage(mimeType: string): boolean {
|
||||
return mimeType.startsWith('image/');
|
||||
}
|
||||
|
||||
export function toSafeBaseName(originalName: string): string {
|
||||
const base = path.basename(originalName, path.extname(originalName));
|
||||
const slug = base.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^[-.]+/, '').slice(0, 60);
|
||||
return slug.length > 0 ? slug : 'file';
|
||||
}
|
||||
|
||||
export type UploadVerdict =
|
||||
| { ok: true; mimeType: string; ext: string; baseName: string }
|
||||
| { ok: false; reason: string };
|
||||
|
||||
export class UploadPolicyError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'UploadPolicyError';
|
||||
}
|
||||
}
|
||||
|
||||
export function evaluateUpload(input: {
|
||||
name: string;
|
||||
buffer: Buffer;
|
||||
mimeType: string;
|
||||
size?: number;
|
||||
}): UploadVerdict {
|
||||
if (!input.name || typeof input.name !== 'string') {
|
||||
return { ok: false, reason: '文件名缺失' };
|
||||
}
|
||||
|
||||
const size = input.size ?? input.buffer.length;
|
||||
if (size === 0 || input.buffer.length === 0) {
|
||||
return { ok: false, reason: '文件为空' };
|
||||
}
|
||||
if (size > MAX_UPLOAD_BYTES) {
|
||||
return { ok: false, reason: `文件大小不能超过 ${Math.floor(MAX_UPLOAD_BYTES / 1024 / 1024)}MB` };
|
||||
}
|
||||
|
||||
const ext = path.extname(input.name).toLowerCase();
|
||||
const allowedByExt = EXTENSION_TO_MIMES[ext];
|
||||
if (!allowedByExt) {
|
||||
return { ok: false, reason: `不允许的文件类型:${ext || '(无扩展名)'}` };
|
||||
}
|
||||
|
||||
const sniffed = sniffMimeTypes(input.buffer);
|
||||
if (sniffed.length === 0) {
|
||||
return { ok: false, reason: '无法识别的文件内容' };
|
||||
}
|
||||
|
||||
// 扩展名白名单 ∩ 魔数结果,三者(含客户端声明)必须一致,否则视为伪装上传
|
||||
const agreed = allowedByExt.filter((mime) => sniffed.includes(mime));
|
||||
if (agreed.length === 0) {
|
||||
return { ok: false, reason: '文件内容与扩展名不符' };
|
||||
}
|
||||
if (!allowedByExt.includes(input.mimeType)) {
|
||||
return { ok: false, reason: '声明的类型与扩展名不符' };
|
||||
}
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
mimeType: agreed.includes(input.mimeType) ? input.mimeType : agreed[0]!,
|
||||
ext,
|
||||
baseName: toSafeBaseName(input.name),
|
||||
};
|
||||
}
|
||||
|
||||
export function assertUploadAllowed(input: {
|
||||
name: string;
|
||||
buffer: Buffer;
|
||||
mimeType: string;
|
||||
size?: number;
|
||||
}): Extract<UploadVerdict, { ok: true }> {
|
||||
const verdict = evaluateUpload(input);
|
||||
if (!verdict.ok) throw new UploadPolicyError(verdict.reason);
|
||||
return verdict;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, it, expect } from '@jest/globals';
|
||||
import { parsePagination } from './pagination';
|
||||
|
||||
const sp = (qs: string) => new URLSearchParams(qs);
|
||||
|
||||
describe('parsePagination', () => {
|
||||
it('defaults to page 1 / given size when params absent', () => {
|
||||
expect(parsePagination(sp(''))).toEqual({ page: 1, pageSize: 10 });
|
||||
expect(parsePagination(sp(''), { defaultPageSize: 20 })).toEqual({ page: 1, pageSize: 20 });
|
||||
});
|
||||
|
||||
it('parses valid positive integers', () => {
|
||||
expect(parsePagination(sp('page=3&pageSize=25'))).toEqual({ page: 3, pageSize: 25 });
|
||||
});
|
||||
|
||||
// Q-7 的核心:非数字必须回落到安全默认,而不是产生 NaN → Prisma skip:NaN → 500。
|
||||
it('falls back to defaults for non-numeric, zero, negative inputs', () => {
|
||||
expect(parsePagination(sp('page=abc&pageSize=xyz'))).toEqual({ page: 1, pageSize: 10 });
|
||||
expect(parsePagination(sp('page=0&pageSize=0'))).toEqual({ page: 1, pageSize: 10 });
|
||||
expect(parsePagination(sp('page=-5&pageSize=-1'))).toEqual({ page: 1, pageSize: 10 });
|
||||
});
|
||||
|
||||
it('clamps pageSize to the max (blocks unbounded full-table reads)', () => {
|
||||
expect(parsePagination(sp('pageSize=100000'), { maxPageSize: 100 })).toEqual({
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
});
|
||||
});
|
||||
|
||||
it('floors fractional values', () => {
|
||||
expect(parsePagination(sp('page=2.9&pageSize=8.7'))).toEqual({ page: 2, pageSize: 8 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
// 分页参数解析:把 URL 上任意字符串收敛为安全、有界的 page/pageSize。
|
||||
// 动机(Q-7):此前各列表路由用 `parseInt(sp.get('page') || '1')` 直接算 `skip/take`——
|
||||
// · `?page=abc` → NaN → Prisma `skip: NaN` 抛错 → 500(应是安全默认,不是崩);
|
||||
// · `?page=0` / 负数 → 负 skip → 抛错;
|
||||
// · `?pageSize=100000` → 无界 `take`,任何有权读取者都能整表拉取大 `data` JSON。
|
||||
// 放在 src/lib(覆盖率棘轮内)供列表路由复用,避免每处各写一份(副本会漂移)。
|
||||
export interface Pagination {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
export interface ParsePaginationOptions {
|
||||
/** 缺省每页条数(参数缺失或非正时) */
|
||||
defaultPageSize?: number;
|
||||
/** 每页上限,超出即夹取 */
|
||||
maxPageSize?: number;
|
||||
}
|
||||
|
||||
export function parsePagination(
|
||||
searchParams: URLSearchParams,
|
||||
options: ParsePaginationOptions = {}
|
||||
): Pagination {
|
||||
const { defaultPageSize = 10, maxPageSize = 100 } = options;
|
||||
|
||||
const rawPage = Number.parseInt(searchParams.get('page') ?? '', 10);
|
||||
const rawSize = Number.parseInt(searchParams.get('pageSize') ?? '', 10);
|
||||
|
||||
const page = Number.isFinite(rawPage) && rawPage >= 1 ? Math.floor(rawPage) : 1;
|
||||
|
||||
let pageSize = Number.isFinite(rawSize) && rawSize >= 1 ? Math.floor(rawSize) : defaultPageSize;
|
||||
if (pageSize > maxPageSize) pageSize = maxPageSize;
|
||||
|
||||
return { page, pageSize };
|
||||
}
|
||||
+116
-1
@@ -4,6 +4,7 @@ jest.mock('@/lib/db', () => ({
|
||||
prisma: {
|
||||
userRole: { findMany: jest.fn() },
|
||||
permission: { findMany: jest.fn() },
|
||||
user: { findUnique: jest.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -11,7 +12,15 @@ jest.unmock('./permissions');
|
||||
|
||||
import { NextRequest } from 'next/server';
|
||||
import { prisma } from '@/lib/db';
|
||||
import { hasPermission, checkUserPermission, requirePermission } from './permissions';
|
||||
import {
|
||||
hasPermission,
|
||||
checkUserPermission,
|
||||
requirePermission,
|
||||
privilegedRolesInPlay,
|
||||
isPrivilegedRole,
|
||||
mayChangeCredentials,
|
||||
PRIVILEGED_ROLE_CODES,
|
||||
} from './permissions';
|
||||
import type { Permission, PermissionSuccess, PermissionFailure } from './permissions';
|
||||
|
||||
jest.mock('@/lib/auth', () => ({
|
||||
@@ -30,6 +39,9 @@ const mockUserRoleFindMany = prisma.userRole.findMany as jest.MockedFunction<
|
||||
const mockPermissionFindMany = prisma.permission.findMany as jest.MockedFunction<
|
||||
(args: unknown) => Promise<unknown[]>
|
||||
>;
|
||||
const mockUserFindUnique = prisma.user.findUnique as unknown as jest.MockedFunction<
|
||||
(args: unknown) => Promise<{ status: number } | null>
|
||||
>;
|
||||
|
||||
describe('hasPermission', () => {
|
||||
it('returns true when user has super_admin role', () => {
|
||||
@@ -70,6 +82,8 @@ describe('hasPermission', () => {
|
||||
describe('checkUserPermission', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
// N-20:checkUserPermission 现在先核验账号状态,活跃账号是所有既有用例的前提。
|
||||
mockUserFindUnique.mockResolvedValue({ status: 1 });
|
||||
});
|
||||
|
||||
it('returns true when user role has permission', async () => {
|
||||
@@ -97,6 +111,31 @@ describe('checkUserPermission', () => {
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('denies a disabled account even though its role grants the permission (N-20)', async () => {
|
||||
mockUserFindUnique.mockResolvedValue({ status: 0 });
|
||||
mockUserRoleFindMany.mockResolvedValue([{ roleCode: 'content_editor' }]);
|
||||
mockPermissionFindMany.mockResolvedValue([
|
||||
{ roleCode: 'content_editor', modelCode: 'news', action: 'create' },
|
||||
]);
|
||||
|
||||
await expect(checkUserPermission('user-1', 'news', 'create')).resolves.toBe(false);
|
||||
expect(mockUserRoleFindMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('denies an account whose row no longer exists', async () => {
|
||||
mockUserFindUnique.mockResolvedValue(null);
|
||||
|
||||
await expect(checkUserPermission('user-1', 'news', 'create')).resolves.toBe(false);
|
||||
});
|
||||
|
||||
// 状态校验必须早于 super_admin 短路,否则被停用的超管令牌仍可在 24h 有效期内畅通无阻。
|
||||
it('denies a disabled super_admin instead of short-circuiting on role', async () => {
|
||||
mockUserFindUnique.mockResolvedValue({ status: 0 });
|
||||
mockUserRoleFindMany.mockResolvedValue([{ roleCode: 'super_admin' }]);
|
||||
|
||||
await expect(checkUserPermission('user-1', 'news', 'create')).resolves.toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('requirePermission', () => {
|
||||
@@ -104,6 +143,8 @@ describe('requirePermission', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
// N-20:checkUserPermission 现在先核验账号状态,活跃账号是所有既有用例的前提。
|
||||
mockUserFindUnique.mockResolvedValue({ status: 1 });
|
||||
});
|
||||
|
||||
it('returns user when authenticated and authorized', async () => {
|
||||
@@ -144,3 +185,77 @@ describe('requirePermission', () => {
|
||||
expect((result as PermissionFailure).response.status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PRIVILEGED_ROLE_CODES / isPrivilegedRole', () => {
|
||||
it('特权集合只有 super_admin,与 hasPermission 的全权语义一致', () => {
|
||||
expect([...PRIVILEGED_ROLE_CODES]).toEqual(['super_admin']);
|
||||
expect(isPrivilegedRole('super_admin')).toBe(true);
|
||||
expect(isPrivilegedRole('content_admin')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 账号级特权护栏(验收 A-1 / A-2)。口径来自 ACCEPTANCE_REVIEW_2026-09-21.md §A-2:
|
||||
* 「目标持有 super_admin 时同样要求调用者为 super_admin」—— 判定挂在账号的前后状态上,
|
||||
* 与「调用者本次是否提交 roleCodes」无关,故省略 roleCodes(resulting === current)也须拦下。
|
||||
*/
|
||||
describe('privilegedRolesInPlay', () => {
|
||||
it('调用者自身是 super_admin ⇒ 任何方向都不拦', () => {
|
||||
expect(privilegedRolesInPlay(['super_admin'], ['super_admin'], ['super_admin'])).toEqual([]);
|
||||
expect(privilegedRolesInPlay(['super_admin'], [], ['super_admin'])).toEqual([]);
|
||||
});
|
||||
|
||||
it('授予方向:非超管把 super_admin 加进账号 ⇒ 拦下', () => {
|
||||
expect(privilegedRolesInPlay(['content_admin'], ['super_admin'], ['content_editor'])).toEqual([
|
||||
'super_admin',
|
||||
]);
|
||||
});
|
||||
|
||||
it('撤销方向:非超管把 super_admin 摘掉(降级)⇒ 同样拦下', () => {
|
||||
expect(privilegedRolesInPlay(['content_admin'], ['readonly'], ['super_admin'])).toEqual([
|
||||
'super_admin',
|
||||
]);
|
||||
});
|
||||
|
||||
it('状态未变动方向:非超管只改资料,resulting 回落到账号现有角色 ⇒ 仍拦下(策略而非疏漏)', () => {
|
||||
const currentRoles = ['super_admin'];
|
||||
// 调用者省略 body.roleCodes 时 users/route.ts 传入 resultingRoleCodes === targetRoleCodes
|
||||
expect(privilegedRolesInPlay(['content_admin'], currentRoles, currentRoles)).toEqual([
|
||||
'super_admin',
|
||||
]);
|
||||
});
|
||||
|
||||
it('建号方向:POST 无变更前状态([])时按授予结果判定', () => {
|
||||
expect(privilegedRolesInPlay(['content_admin'], ['super_admin'], [])).toEqual(['super_admin']);
|
||||
expect(privilegedRolesInPlay(['content_admin'], ['content_editor'], [])).toEqual([]);
|
||||
});
|
||||
|
||||
it('前后均不含特权角色 ⇒ 放行,且结果去重', () => {
|
||||
expect(
|
||||
privilegedRolesInPlay(['content_admin'], ['content_admin', 'readonly'], ['content_admin'])
|
||||
).toEqual([]);
|
||||
expect(
|
||||
privilegedRolesInPlay(
|
||||
['reviewer'],
|
||||
['super_admin', 'super_admin'],
|
||||
['super_admin', 'readonly']
|
||||
)
|
||||
).toEqual(['super_admin']);
|
||||
});
|
||||
|
||||
it('自定义特权角色名不参与判定(护栏范围由 PRIVILEGED_ROLE_CODES 定义)', () => {
|
||||
expect(privilegedRolesInPlay(['content_admin'], ['audit_admin'], [])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mayChangeCredentials', () => {
|
||||
it('自助(目标是本人)始终允许,非超管不得改他人', () => {
|
||||
expect(mayChangeCredentials(['content_admin'], true)).toBe(true);
|
||||
expect(mayChangeCredentials(['readonly'], true)).toBe(true);
|
||||
expect(mayChangeCredentials(['content_admin'], false)).toBe(false);
|
||||
});
|
||||
|
||||
it('super_admin 可改他人凭据;判定与 roleCodes 是否提交无关', () => {
|
||||
expect(mayChangeCredentials(['super_admin'], false)).toBe(true);
|
||||
});
|
||||
});
|
||||
+83
-3
@@ -35,6 +35,15 @@ export async function checkUserPermission(
|
||||
modelCode: string,
|
||||
action: PermissionAction
|
||||
): Promise<boolean> {
|
||||
// 访问令牌有效期 24h(`src/lib/auth.ts:7`),而 B-7 的账号状态校验只加在 `/api/auth/refresh` 上
|
||||
// ⇒ 被停用/删除的账号在令牌过期前仍能通过每一个 guarded 路由(N-20)。
|
||||
// 必须早于下面的 super_admin 短路,否则超管令牌被停用时仍放行。
|
||||
const account = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { status: true },
|
||||
});
|
||||
if (!account || account.status === 0) return false;
|
||||
|
||||
const userRoles = await prisma.userRole.findMany({
|
||||
where: { userId },
|
||||
});
|
||||
@@ -56,10 +65,32 @@ export async function checkUserPermission(
|
||||
return hasPermission(roleCodes, modelCode, action, permissions);
|
||||
}
|
||||
|
||||
/**
|
||||
* 认证请求 **并** 确认账号未被停用。返回 payload 或 null(null ⇒ 调用方 unauthorized)。
|
||||
*
|
||||
* 为什么需要它:`authenticateRequest` 只验 JWT 签名,不看 `User.status`。N-20 把状态校验加在
|
||||
* `checkUserPermission` 里,但 `admin/users` 与 `admin/roles` 这 6 个 handler 走的是「authenticateRequest
|
||||
* + 内联 role 数组」而非 `requirePermission`,于是停用的 super_admin 在其 ≤24h 令牌有效期内仍能
|
||||
* 列/建/改/删用户与改权限矩阵(Q-4,与 N-20 同族,只是绕开了那个已修的收口)。
|
||||
* 用 `count` 而非 `findUnique` 以避开各 handler 内已有的 username 查询语义。
|
||||
*/
|
||||
export async function authenticateActiveRequest(
|
||||
request: NextRequest
|
||||
): Promise<JwtPayload | null> {
|
||||
const user = authenticateRequest(request);
|
||||
if (!user) return null;
|
||||
|
||||
const active = await prisma.user.count({
|
||||
where: { id: user.userId, status: 1 },
|
||||
});
|
||||
if (active === 0) return null;
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
export interface PermissionSuccess {
|
||||
user: JwtPayload;
|
||||
}
|
||||
|
||||
export interface PermissionFailure {
|
||||
response: NextResponse;
|
||||
}
|
||||
@@ -68,8 +99,7 @@ export interface PermissionFailure {
|
||||
* 校验请求是否已认证并具备指定权限
|
||||
* 通过返回 { user },失败返回 { response }
|
||||
*/
|
||||
export async function requirePermission(
|
||||
request: NextRequest,
|
||||
export async function requirePermission( request: NextRequest,
|
||||
modelCode: string,
|
||||
action: PermissionAction
|
||||
): Promise<PermissionSuccess | PermissionFailure> {
|
||||
@@ -85,3 +115,53 @@ export async function requirePermission(
|
||||
|
||||
return { user };
|
||||
}
|
||||
|
||||
// ============ 账号与角色变更授权(验收 A-1 / A-2) ============
|
||||
|
||||
/**
|
||||
* 特权角色:授予它等于交付不受限管理能力,撤销它等于把他人踢出管理面,
|
||||
* 因此两个方向都必须由同等级调用者操作。与 hasPermission 的 super_admin 全权语义保持一致。
|
||||
*/
|
||||
export const PRIVILEGED_ROLE_CODES: readonly string[] = ['super_admin'];
|
||||
|
||||
export function isPrivilegedRole(roleCode: string): boolean {
|
||||
return PRIVILEGED_ROLE_CODES.includes(roleCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* 账号级特权护栏:返回调用者无权经手的特权角色。
|
||||
*
|
||||
* 口径来源 ACCEPTANCE_REVIEW_2026-09-21.md §A-2「修复」行:
|
||||
* 「改密/停用他人须 super_admin;**目标持有 super_admin 时同样要求调用者为 super_admin**」——
|
||||
* 条件写在「目标持有」上,而不是写在「本次请求是否改角色」上。故本函数取
|
||||
* 「变更前 currentRoleCodes ∪ 变更后 resultingRoleCodes」两个状态求并集:
|
||||
*
|
||||
* - 撤销方向必须并入,否则 `roleCodes: ['readonly']` 覆盖掉目标原有的 super_admin 即降级,
|
||||
* 与授予 super_admin 是同一类越权,只是方向相反;
|
||||
* - 「调用者省略 roleCodes」同样要判定(此时 resultingRoleCodes === currentRoleCodes):
|
||||
* 非超管改超管的昵称/手机号依然是对这个账号的写操作。这是**裁定过的策略而非疏漏**,
|
||||
* 不可因为「角色没变」就放行 —— 详见 users/route.ts PUT 护栏处的注释。
|
||||
*
|
||||
* 返回空数组表示调用者有权完成该次写操作。
|
||||
*
|
||||
* @param callerRoleCodes 调用者角色
|
||||
* @param resultingRoleCodes 写入后该账号的角色集(未提交 roleCodes 时即目标现有角色)
|
||||
* @param currentRoleCodes 写入前该账号的角色集(POST 建号时为 [])
|
||||
*/
|
||||
export function privilegedRolesInPlay(
|
||||
callerRoleCodes: string[],
|
||||
resultingRoleCodes: string[],
|
||||
currentRoleCodes: string[]
|
||||
): string[] {
|
||||
if (callerRoleCodes.includes('super_admin')) return [];
|
||||
const inPlay = new Set([...resultingRoleCodes, ...currentRoleCodes]);
|
||||
return [...inPlay].filter(isPrivilegedRole);
|
||||
}
|
||||
|
||||
/**
|
||||
* 改密与启停属账号接管面(A-2):`?id=` 由调用者提供,若不校验目标身份,
|
||||
* content_admin 可直接替换超管口令或停用超管后登录。自助改密仍允许。
|
||||
*/
|
||||
export function mayChangeCredentials(callerRoleCodes: string[], isTargetSelf: boolean): boolean {
|
||||
return isTargetSelf || callerRoleCodes.includes('super_admin');
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, it, expect } from '@jest/globals';
|
||||
import { createMemoryRateLimiter } from './rate-limit';
|
||||
|
||||
describe('createMemoryRateLimiter', () => {
|
||||
it('allows max requests then limits the max+1th within the window', () => {
|
||||
const clock = 1_000;
|
||||
const limiter = createMemoryRateLimiter({ windowMs: 1000, max: 3, now: () => clock });
|
||||
|
||||
expect(limiter.isLimited('ip')).toBe(false); // 1
|
||||
expect(limiter.isLimited('ip')).toBe(false); // 2
|
||||
expect(limiter.isLimited('ip')).toBe(false); // 3
|
||||
expect(limiter.isLimited('ip')).toBe(true); // 4 -> over max
|
||||
expect(limiter.isLimited('ip')).toBe(true); // 5 -> still limited
|
||||
});
|
||||
|
||||
it('tracks keys independently', () => {
|
||||
const clock = 0;
|
||||
const limiter = createMemoryRateLimiter({ windowMs: 100, max: 1, now: () => clock });
|
||||
expect(limiter.isLimited('a')).toBe(false);
|
||||
expect(limiter.isLimited('a')).toBe(true);
|
||||
expect(limiter.isLimited('b')).toBe(false); // 不同 key 独立
|
||||
});
|
||||
|
||||
it('resets the count once the window expires', () => {
|
||||
let clock = 0;
|
||||
const limiter = createMemoryRateLimiter({ windowMs: 100, max: 1, now: () => clock });
|
||||
expect(limiter.isLimited('ip')).toBe(false); // count=1, resetAt=100
|
||||
expect(limiter.isLimited('ip')).toBe(true); // count=2 > 1
|
||||
clock = 101; // 超过 resetAt
|
||||
expect(limiter.isLimited('ip')).toBe(false); // 新窗口,count=1
|
||||
});
|
||||
|
||||
it('reset() clears all buckets', () => {
|
||||
const clock = 0;
|
||||
const limiter = createMemoryRateLimiter({ windowMs: 100, max: 1, now: () => clock });
|
||||
expect(limiter.isLimited('ip')).toBe(false);
|
||||
expect(limiter.isLimited('ip')).toBe(true);
|
||||
limiter.reset();
|
||||
expect(limiter.isLimited('ip')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
// 进程内内存限流器。语义与旧的 contact 内联实现一致:窗口内首次请求计数为 1,
|
||||
// 超过 max 后判为受限。时钟可注入以便测试确定性;`reset()` 供测试隔离跨用例状态。
|
||||
// 放在 src/lib(覆盖率棘轮内)——这是可复用、可 grep 的安全控制,而非散落在各路由的副本。
|
||||
export interface RateLimiterOptions {
|
||||
/** 滑动窗口的固定长度(毫秒) */
|
||||
windowMs: number;
|
||||
/** 窗口内允许的最大请求数;第 max+1 次起判为受限 */
|
||||
max: number;
|
||||
/** 当前时间来源,测试可注入 */
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
export interface RateLimiter {
|
||||
isLimited(key: string): boolean;
|
||||
reset(): void;
|
||||
}
|
||||
|
||||
export function createMemoryRateLimiter({
|
||||
windowMs,
|
||||
max,
|
||||
now = Date.now,
|
||||
}: RateLimiterOptions): RateLimiter {
|
||||
const buckets = new Map<string, { count: number; resetAt: number }>();
|
||||
|
||||
return {
|
||||
isLimited(key: string): boolean {
|
||||
const ts = now();
|
||||
const record = buckets.get(key);
|
||||
|
||||
if (!record || ts > record.resetAt) {
|
||||
buckets.set(key, { count: 1, resetAt: ts + windowMs });
|
||||
return false;
|
||||
}
|
||||
|
||||
record.count += 1;
|
||||
return record.count > max;
|
||||
},
|
||||
reset(): void {
|
||||
buckets.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { sanitizeRichText } from './sanitize';
|
||||
|
||||
describe('sanitizeRichText', () => {
|
||||
describe('输入边界', () => {
|
||||
it('非字符串输入返回空串', () => {
|
||||
expect(sanitizeRichText(undefined)).toBe('');
|
||||
expect(sanitizeRichText(null)).toBe('');
|
||||
expect(sanitizeRichText(42)).toBe('');
|
||||
expect(sanitizeRichText({ html: 'x' })).toBe('');
|
||||
});
|
||||
|
||||
it('保留合法富文本结构', () => {
|
||||
const html = '<h2>标题</h2><p>段落<strong>强调</strong><em>斜体</em></p><ul><li>项</li></ul>';
|
||||
expect(sanitizeRichText(html)).toBe(html);
|
||||
});
|
||||
});
|
||||
|
||||
describe('脚本与事件处理器(验收 A-3)', () => {
|
||||
it('丢弃 <script> 及其内容', () => {
|
||||
const out = sanitizeRichText('<p>正常</p><script>alert(1)</script>');
|
||||
expect(out).not.toContain('alert');
|
||||
expect(out).not.toContain('<script');
|
||||
expect(out).toContain('<p>正常</p>');
|
||||
});
|
||||
|
||||
it('剔除任意 on* 事件属性', () => {
|
||||
const out = sanitizeRichText(
|
||||
'<img src="https://cdn.example.com/a.png" onerror="alert(1)"><p onclick="alert(2)">x</p>'
|
||||
);
|
||||
expect(out).not.toMatch(/on(error|load|click|mouse)/i);
|
||||
expect(out).not.toContain('alert');
|
||||
});
|
||||
|
||||
it('剔除 <style> 与 iframe / object / embed', () => {
|
||||
const out = sanitizeRichText(
|
||||
'<style>body{display:none}</style><iframe src="https://evil.example.com"></iframe>' +
|
||||
'<object data="x"></object><embed src="y">'
|
||||
);
|
||||
expect(out).not.toContain('display:none');
|
||||
expect(out).not.toMatch(/<(iframe|object|embed)/i);
|
||||
});
|
||||
|
||||
it('SVG 内嵌脚本被整体移除', () => {
|
||||
expect(sanitizeRichText('<svg><script>alert(2)</script></svg>')).not.toContain('alert');
|
||||
});
|
||||
|
||||
it('属性内的伪协议与外站脚本源被移除', () => {
|
||||
expect(sanitizeRichText('<a href="javascript:alert(1)">t</a>')).not.toContain('javascript:');
|
||||
expect(sanitizeRichText('<a href="data:text/html;base64,PHNjcmlwdD4=">t</a>')).not.toContain('data:');
|
||||
expect(sanitizeRichText('<a href="vbscript:msgbox(1)">t</a>')).not.toContain('vbscript:');
|
||||
});
|
||||
|
||||
it('嵌套/畸形标签无法绕过(标签名大小写与内联拆分)', () => {
|
||||
expect(sanitizeRichText('<ScRiPt>alert(1)</ScRiPt>')).not.toContain('alert');
|
||||
expect(sanitizeRichText('<img src="x" onerror=alert(1)>')).not.toContain('alert');
|
||||
expect(sanitizeRichText('<<script>alert(1)//<//script>')).not.toContain('alert');
|
||||
});
|
||||
|
||||
it('深嵌套受 nestingLimit 约束,不产生无界输出', () => {
|
||||
const deep = '<div>'.repeat(500) + 'x' + '</div>'.repeat(500);
|
||||
const out = sanitizeRichText(deep);
|
||||
expect(out.length).toBeLessThan(deep.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe('链接协议与 tabnabbing', () => {
|
||||
it('保留 http/https/mailto/tel 与站内相对链接', () => {
|
||||
expect(sanitizeRichText('<a href="https://novalon.cn">a</a>')).toContain('href="https://novalon.cn"');
|
||||
expect(sanitizeRichText('<a href="/terms">a</a>')).toContain('href="/terms"');
|
||||
expect(sanitizeRichText('<a href="mailto:hi@novalon.cn">a</a>')).toContain('mailto:hi@novalon.cn');
|
||||
expect(sanitizeRichText('<a href="tel:+8610000000">a</a>')).toContain('tel:+8610000000');
|
||||
});
|
||||
|
||||
it('target=_blank 自动补 rel=noopener noreferrer', () => {
|
||||
const out = sanitizeRichText('<a href="https://x.cn" target="_blank">a</a>');
|
||||
expect(out).toContain('target="_blank"');
|
||||
expect(out).toContain('rel="noopener noreferrer"');
|
||||
});
|
||||
|
||||
it('协议相对形式 //host 被拒绝', () => {
|
||||
expect(sanitizeRichText('<a href="//evil.example.com">a</a>')).not.toContain('//evil.example.com');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CMS 富文本所需能力不被过度阉割', () => {
|
||||
it('保留 class 与排版类标签', () => {
|
||||
const out = sanitizeRichText(
|
||||
'<h3 class="text-lg">t</h3><blockquote><p>q</p></blockquote><ol><li>1</li></ol><table><tbody><tr><td>c</td></tr></tbody></table><hr><br>'
|
||||
);
|
||||
expect(out).toContain('<h3 class="text-lg">t</h3>');
|
||||
expect(out).toContain('<blockquote>');
|
||||
expect(out).toContain('<ol><li>1</li></ol>');
|
||||
expect(out).toContain('<table>');
|
||||
expect(out).toContain('<hr');
|
||||
expect(out).toContain('<br');
|
||||
});
|
||||
|
||||
it('保留合法图片源但拒绝 javascript:/data:', () => {
|
||||
expect(sanitizeRichText('<img src="https://cdn.example.com/a.png" alt="a">')).toContain(
|
||||
'src="https://cdn.example.com/a.png"'
|
||||
);
|
||||
expect(sanitizeRichText('<img src="javascript:alert(1)">')).not.toContain('javascript:');
|
||||
});
|
||||
|
||||
it('丢弃未声明的属性(data-*、style、form 相关)', () => {
|
||||
const out = sanitizeRichText('<p data-token="x" style="color:red" contenteditable="true">y</p>');
|
||||
expect(out).toBe('<p>y</p>');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import sanitizeHtml from 'sanitize-html';
|
||||
|
||||
/**
|
||||
* CMS 富文本渲染端净化(验收 A-3)。
|
||||
* 白名单而非黑名单:新增的危险标签默认被丢弃,无需跟进上游漏洞库。
|
||||
*/
|
||||
const ALLOWED_TAGS = [
|
||||
'a', 'abbr', 'b', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup',
|
||||
'dd', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
|
||||
'hr', 'i', 'img', 'li', 'mark', 'ol', 'p', 'pre', 's', 'small', 'span', 'strong',
|
||||
'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'u', 'ul',
|
||||
];
|
||||
|
||||
const ALLOWED_ATTRIBUTES: Record<string, string[]> = {
|
||||
a: ['href', 'title', 'target', 'rel'],
|
||||
img: ['src', 'alt', 'title', 'width', 'height'],
|
||||
col: ['span', 'width'],
|
||||
td: ['colspan', 'rowspan'],
|
||||
th: ['colspan', 'rowspan'],
|
||||
ol: ['start', 'type'],
|
||||
'*': ['class'],
|
||||
};
|
||||
|
||||
// 无 javascript/data/vbscript:伪协议在属性层即被剔除(探针实测 href 整体消失)
|
||||
const ALLOWED_SCHEMES = ['http', 'https', 'mailto', 'tel'];
|
||||
|
||||
const OPTIONS: sanitizeHtml.IOptions = {
|
||||
allowedTags: ALLOWED_TAGS,
|
||||
allowedAttributes: ALLOWED_ATTRIBUTES,
|
||||
allowedSchemes: ALLOWED_SCHEMES,
|
||||
// 协议相对 URL(//evil.example.com)等价于跟随页面协议外跳,一并拒绝
|
||||
allowProtocolRelative: false,
|
||||
// 危险标签连同其内容整体丢弃;recursiveEscape 会把 <script> 作为可见文本泄漏给读者
|
||||
disallowedTagsMode: 'discard',
|
||||
nonTextTags: ['script', 'style', 'textarea', 'title', 'noscript', 'iframe', 'object', 'embed', 'svg', 'math'],
|
||||
nestingLimit: 50,
|
||||
transformTags: {
|
||||
a: (tagName, attribs) => ({
|
||||
tagName,
|
||||
attribs:
|
||||
attribs.target === '_blank'
|
||||
? { ...attribs, rel: 'noopener noreferrer' }
|
||||
: attribs,
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
export function sanitizeRichText(html: unknown): string {
|
||||
if (typeof html !== 'string' || html.length === 0) return '';
|
||||
return sanitizeHtml(html, OPTIONS);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, it, expect } from '@jest/globals';
|
||||
import { readFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
/**
|
||||
* 口径字段反漂移守卫。
|
||||
*
|
||||
* 背景:数据口径 `basis` 由 src/lib/cms/content-types.ts 的 metricBasisField 声明,
|
||||
* 但 prisma/seed.ts 里为 page 型模型**另写了一份字段定义**,并通过
|
||||
* `contentModel.upsert({ fields: JSON.stringify(config.model.fields) })` 落库;
|
||||
* 后台表单读的是库里这份 ⇒ 种子少写一个 basis,编辑者就永远无法为该指标声明口径。
|
||||
*
|
||||
* 两侧格式不同(content-types 一行一个键、种子把 name/type 写在同一行),
|
||||
* 故归属判定用「整源索引 + 最近的前置数组头」,不做逐行正则。
|
||||
*/
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..', '..');
|
||||
const CONTENT_TYPES = readFileSync(path.join(ROOT, 'src/lib/cms/content-types.ts'), 'utf8');
|
||||
const SEED = readFileSync(path.join(ROOT, 'prisma/seed.ts'), 'utf8');
|
||||
|
||||
const BASIS_VALUES = ['target', 'team-history', 'verified'];
|
||||
|
||||
/** 返回「子字段里出现过 marker 的数组字段名」集合 */
|
||||
function arrayFieldsCarrying(source: string, marker: RegExp): string[] {
|
||||
const headers: { name: string; at: number }[] = [];
|
||||
for (const m of source.matchAll(/name:\s*'([a-zA-Z]+)',\s*type:\s*'array'/g)) {
|
||||
headers.push({ name: m[1] as string, at: m.index as number });
|
||||
}
|
||||
const found = new Set<string>();
|
||||
for (const m of source.matchAll(new RegExp(marker, 'g'))) {
|
||||
const at = m.index as number;
|
||||
let owner: string | null = null;
|
||||
for (const h of headers) {
|
||||
if (h.at < at) owner = h.name;
|
||||
else break;
|
||||
}
|
||||
if (owner) found.add(owner);
|
||||
}
|
||||
return [...found];
|
||||
}
|
||||
|
||||
const typedWithBasis = arrayFieldsCarrying(CONTENT_TYPES, /\.\.\.metricBasisField/);
|
||||
const seedWithBasis = arrayFieldsCarrying(SEED, /name:\s*'basis'/);
|
||||
// 种子里「含指标子字段」的数组字段名(value/label/metric 三元组)
|
||||
const seedMetricArrays = arrayFieldsCarrying(SEED, /name:\s*'(?:value|metric)',\s*type:\s*'text'/);
|
||||
|
||||
describe('seed 的指标数组必须与 content-types 一样声明数据口径 basis', () => {
|
||||
it('两侧解析都真的看到了东西(防「匹配零」的假绿)', () => {
|
||||
expect(typedWithBasis.length).toBeGreaterThan(0);
|
||||
expect(seedMetricArrays.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('content-types 带 basis 的字段名,种子若也定义则必须同样带 basis', () => {
|
||||
const overlapping = seedMetricArrays.filter((n) => typedWithBasis.includes(n));
|
||||
expect(overlapping.length).toBeGreaterThan(0);
|
||||
|
||||
const missing = overlapping.filter((n) => !seedWithBasis.includes(n));
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
|
||||
it('种子声明 basis 时,其选项值必须与 content-types 同一套(防自造第三套口径标签)', () => {
|
||||
for (const value of BASIS_VALUES) {
|
||||
expect(CONTENT_TYPES).toContain(`value: '${value}'`);
|
||||
}
|
||||
expect(seedWithBasis.length).toBeGreaterThan(0);
|
||||
for (const value of BASIS_VALUES) {
|
||||
expect(SEED).toContain(`value: '${value}'`);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* L-2 防漂移门禁:prisma/seed.ts 的 permissionMatrix 授予的 modelCode 必须是真实存在
|
||||
* 的权限码(hasPermission 按 modelCode 全等匹配,src/lib/permissions.ts:26)。
|
||||
* 曾出现授予 'team' / 'legal' 这类不存在的码、漏发真实页面模型,导致非 super_admin
|
||||
* 在 legal/team/contact 内容与 admin 外壳路由上被 fail-closed 拒绝。
|
||||
*/
|
||||
import { describe, it, expect } from '@jest/globals';
|
||||
import { readFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { CONTENT_TYPE_CONFIGS } from '@/lib/cms/content-types';
|
||||
|
||||
const SEED_PATH = path.resolve(__dirname, '../../prisma/seed.ts');
|
||||
const seedSource = readFileSync(SEED_PATH, 'utf8');
|
||||
|
||||
/** 权限门控使用、但 ContentModel 表中不存在对应行的外壳码 */
|
||||
const SHELL_PERMISSION_CODES = ['media', 'content-model', 'content-zone'];
|
||||
|
||||
/** 站点级配置模型,刻意仅 super_admin 可写(见 seed 注释),故不进授权数组 */
|
||||
const SUPER_ADMIN_ONLY_MODELS = ['site-config', 'navigation'];
|
||||
|
||||
function extractArray(name: string): string[] {
|
||||
const match = seedSource.match(new RegExp(`const ${name} = \\[([\\s\\S]*?)\\];`));
|
||||
if (!match?.[1]) throw new Error(`prisma/seed.ts 中应存在 const ${name} = [...] 数组`);
|
||||
return [...match[1].matchAll(/'([^']+)'/g)].map((m) => m[1]!);
|
||||
}
|
||||
|
||||
/** seed 实际创建的 ContentModel 行:CONTENT_TYPE_CONFIGS + seed.ts modelConfigs 块 */
|
||||
function realContentModelCodes(): Set<string> {
|
||||
const fromConfigs = Object.values(CONTENT_TYPE_CONFIGS).map((c) => c.model.code);
|
||||
const modelConfigsBlock = seedSource.match(/const modelConfigs = \[[\s\S]*?\n \];/);
|
||||
if (!modelConfigsBlock?.[0]) throw new Error('prisma/seed.ts 中应存在 modelConfigs 块');
|
||||
const fromSeed = [...modelConfigsBlock[0].matchAll(/code: '([^']+)'/g)].map((m) => m[1]!);
|
||||
return new Set([...fromConfigs, ...fromSeed]);
|
||||
}
|
||||
|
||||
describe('prisma/seed.ts permissionMatrix 模型码一致性', () => {
|
||||
const granted = extractArray('contentModels');
|
||||
const real = realContentModelCodes();
|
||||
|
||||
it('授权数组非空且成功解析出真实模型集合', () => {
|
||||
expect(granted.length).toBeGreaterThan(0);
|
||||
expect(real.size).toBeGreaterThanOrEqual(14);
|
||||
});
|
||||
|
||||
it('数组中每个码都是真实 ContentModel 或外壳权限码(杜绝 team/legal 式幽灵码)', () => {
|
||||
const unknown = granted.filter((code) => !real.has(code) && !SHELL_PERMISSION_CODES.includes(code));
|
||||
expect(unknown).toEqual([]);
|
||||
});
|
||||
|
||||
it('每个真实内容模型都被授予非超管角色(除刻意 super_admin 独有的站点配置)', () => {
|
||||
const missed = [...real].filter(
|
||||
(code) => !SUPER_ADMIN_ONLY_MODELS.includes(code) && !granted.includes(code),
|
||||
);
|
||||
expect(missed).toEqual([]);
|
||||
});
|
||||
|
||||
it('外壳码授权路径:media 走内容数组;content-model/content-zone 仅以 read 授予非超管角色', () => {
|
||||
expect(granted).toContain('media');
|
||||
const shellReads = extractArray('shellReadModels');
|
||||
expect(shellReads).toEqual(['content-model', 'content-zone']);
|
||||
const matrixBlock = seedSource.match(/const permissionMatrix[\s\S]*?\n \];/);
|
||||
if (!matrixBlock?.[0]) throw new Error('prisma/seed.ts 中应存在 permissionMatrix 块');
|
||||
expect(matrixBlock[0]).toContain('shellReadModels');
|
||||
// shell 码不得混进全动作数组(否则 editor 可 update content-zone、越过 super_admin 独占的 zone 编辑)
|
||||
expect(granted).not.toContain('content-model');
|
||||
expect(granted).not.toContain('content-zone');
|
||||
});
|
||||
});
|
||||
@@ -114,6 +114,32 @@ describe('utils', () => {
|
||||
expect(result).toBeGreaterThanOrEqual(-10);
|
||||
expect(result).toBeLessThanOrEqual(-1);
|
||||
});
|
||||
|
||||
// 验收 A-14:仅断言边界检不出算子错误(`*(max-min)+min` 改成 `/(max-min)+min` 时
|
||||
// 取值被压到区间一端 11% 长度内仍全绿),故须钉住映射关系与跨度。
|
||||
it('按 Math.random 的取值线性映射到区间(算子与偏移均被检验)', () => {
|
||||
const spy = jest.spyOn(Math, 'random');
|
||||
try {
|
||||
spy.mockReturnValue(0);
|
||||
expect(randomBetween(1, 10)).toBe(1);
|
||||
spy.mockReturnValue(0.5);
|
||||
expect(randomBetween(1, 10)).toBeCloseTo(5.5, 10);
|
||||
spy.mockReturnValue(0.25);
|
||||
expect(randomBetween(-8, 8)).toBeCloseTo(-4, 10);
|
||||
spy.mockReturnValue(0.999999);
|
||||
expect(randomBetween(1, 10)).toBeLessThan(10);
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('多次取样的值域跨度覆盖全区间', () => {
|
||||
const samples = Array.from({ length: 500 }, () => randomBetween(0, 100));
|
||||
const min = Math.min(...samples);
|
||||
const max = Math.max(...samples);
|
||||
expect(min).toBeLessThan(8);
|
||||
expect(max).toBeGreaterThan(92);
|
||||
});
|
||||
});
|
||||
|
||||
describe('lerp', () => {
|
||||
@@ -126,6 +152,20 @@ describe('utils', () => {
|
||||
expect(lerp(0, 10, 0)).toBe(0);
|
||||
expect(lerp(0, 10, 1)).toBe(10);
|
||||
});
|
||||
|
||||
// 验收 A-13:原用例 start 恒为 0,使 `end - start` 与 `end + start` 数值相同,
|
||||
// start 偏移量从未被检验。以下用例全部使用非零 start。
|
||||
it('非零 start 时偏移量与差值均参与计算', () => {
|
||||
expect(lerp(10, 20, 0.5)).toBe(15);
|
||||
expect(lerp(100, 200, 0.25)).toBe(125);
|
||||
expect(lerp(-10, 10, 0.5)).toBe(0);
|
||||
expect(lerp(5, 5, 0.7)).toBe(5);
|
||||
expect(lerp(20, 10, 0.5)).toBe(15);
|
||||
expect(lerp(3, 7, 0)).toBe(3);
|
||||
expect(lerp(3, 7, 1)).toBe(7);
|
||||
expect(lerp(2, 4, 2)).toBe(6);
|
||||
expect(lerp(2, 4, -1)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clamp', () => {
|
||||
|
||||
Reference in new issue
Block a user