fix(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s

- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14)
- T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9)
- T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4)
- T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8)
- T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15)
- T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8)
- T7 前后端测试与 lint 门禁清零
- T8 应付卡片按关联订单日(口径 A)
- T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
This commit is contained in:
Ubuntu
2026-10-19 16:16:51 +08:00
parent 601a207b1e
commit 5fa2bbfd55
252 changed files with 18656 additions and 721 deletions
+1 -1
View File
@@ -590,7 +590,7 @@ describe('syncTemplateLayoutInDocument(编辑器就地更新布局,不重建
* 事故:用户在编辑器里挪了「每页合计 / 整单合计」,打印时位置错乱。
*/
describe('flow 定位语义(跟随内容)', () => {
const flowTemplate = (anchoring: 'flow' | 'page' | undefined, rows: number): DeliveryHtmlTemplate => ({
const flowTemplate = (anchoring: 'flow' | 'page' | undefined, _rows: number): DeliveryHtmlTemplate => ({
id: 'flow', name: 'flow',
html: '<table><tbody>{{#items}}<tr><td>{{item.item_name}}</td></tr>{{/items}}'
+ '<tr><td class="page-total" colspan="2">每页合计:{{group.total_amount}}</td></tr></tbody></table>',
@@ -0,0 +1,104 @@
// @vitest-environment jsdom
import React, { useEffect, useRef, useState } from 'react';
import { cleanup, render } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* B-9.1b(2026-10-19 T5 终局复攻):上传在途卸载。
*
* 旧行为:`await stage(...)` 返回时组件已卸载,仍会 `URL.createObjectURL`(1 个),
* setState 无效、blob 无人引用 ⇒ 永不 revoke(created=1 / revoked=0)。
* 修复:传入 `isMounted`,返回后若已卸载 ⇒ 释放刚建的 blob 并返回 null(created=1 / revoked=1)。
*/
import { stageOutboundPhotoPreviewsIfMounted } from './outboundPhotoPreview';
function Harness(props: {
upload: (file: File) => Promise<string>;
onStaged?: (count: number) => void;
}) {
const mountedRef = useRef(true);
const [count, setCount] = useState<number | null>(null);
// 回调走 ref:组件模拟"仅挂载时执行一次"的 effect,避免 exhaustive-deps 误报(行为不变)
const uploadRef = useRef(props.upload);
uploadRef.current = props.upload;
const onStagedRef = useRef(props.onStaged);
onStagedRef.current = props.onStaged;
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
useEffect(() => {
void (async () => {
const staged = await stageOutboundPhotoPreviewsIfMounted(
[new File(['a'], 'a.jpg', { type: 'image/jpeg' })],
uploadRef.current,
(file) => URL.createObjectURL(file),
() => mountedRef.current
);
if (!staged) return; // 已卸载:helper 已释放,不得 setState
setCount(staged.length);
onStagedRef.current?.(staged.length);
})();
}, []);
return <div data-testid="count">{count ?? 'none'}</div>;
}
beforeEach(() => {
(URL as unknown as { createObjectURL: unknown }).createObjectURL = vi.fn(() => 'blob:mock-1');
(URL as unknown as { revokeObjectURL: unknown }).revokeObjectURL = vi.fn();
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
describe('B-9.1b:上传在途卸载 ⇒ 释放刚创建的 blob', () => {
it('真实渲染:卸载后才 resolve 上传 ⇒ createObjectURL 1 次、revokeObjectURL 1 次、不 setState', async () => {
let resolveUpload: (value: string) => void = () => undefined;
const upload = vi.fn(
() =>
new Promise<string>((resolve) => {
resolveUpload = resolve;
})
);
const onStaged = vi.fn();
const view = render(<Harness upload={upload} onStaged={onStaged} />);
await vi.waitFor(() => expect(upload).toHaveBeenCalledTimes(1));
view.unmount(); // 上传在途卸载
resolveUpload('server/a.jpg');
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
expect(URL.createObjectURL, '在途卸载后仍会创建一个 blob(这正是要释放的)').toHaveBeenCalledTimes(1);
expect(URL.revokeObjectURL, '必须把刚创建的 blob 释放掉').toHaveBeenCalledTimes(1);
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:mock-1');
expect(onStaged, '卸载后不得 setState/回调').not.toHaveBeenCalled();
});
it('未卸载 ⇒ 正常 setState,不误释放', async () => {
const upload = vi.fn(async () => 'server/a.jpg');
const onStaged = vi.fn();
const view = render(<Harness upload={upload} onStaged={onStaged} />);
await vi.waitFor(() => expect(onStaged).toHaveBeenCalledWith(1));
expect(view.getByTestId('count').textContent).toBe('1');
expect(URL.createObjectURL).toHaveBeenCalledTimes(1);
expect(URL.revokeObjectURL).not.toHaveBeenCalled();
});
});
describe('B-9.1b:页面接线契约', () => {
it('PickingManagement 使用 mounted 守卫版本且传 mountedRef', async () => {
const { readFileSync } = await import('node:fs');
const path = await import('node:path');
const source = readFileSync(path.join(__dirname, '../pages/picking/PickingManagement.tsx'), 'utf8');
expect(source).toContain('stageOutboundPhotoPreviewsIfMounted');
expect(source).toContain('() => mountedRef.current');
});
});
@@ -0,0 +1,63 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* FE-4(2026-10-19 T5 红队复攻):多文件上传**部分失败不得泄漏 blob URL**。
*
* 旧逻辑:每张成功就 createObjectURL,后续文件抛错 ⇒ uploaded 数组丢弃、前面建的 blob 不 revoke。
* 修复:先全部上传成功再建预览 URL;任一上传失败时一个 blob URL 都还没创建。
*/
import { stageOutboundPhotoPreviews } from './outboundPhotoPreview';
const files = [new File(['a'], 'a.jpg', { type: 'image/jpeg' }), new File(['b'], 'b.jpg', { type: 'image/jpeg' })];
beforeEach(() => {
let seq = 0;
vi.stubGlobal('URL', {
...URL,
createObjectURL: vi.fn(() => `blob:preview-${++seq}`),
revokeObjectURL: vi.fn(),
});
});
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe('stageOutboundPhotoPreviews:部分失败无 blob 泄漏', () => {
it('第 2 个文件上传失败 ⇒ 不创建任何预览 URL(无可泄漏),错误原样抛出', async () => {
const upload = vi
.fn()
.mockResolvedValueOnce('server/a.jpg')
.mockRejectedValueOnce(new Error('upload failed'));
await expect(
stageOutboundPhotoPreviews(files, upload, (file) => URL.createObjectURL(file))
).rejects.toThrow('upload failed');
expect(upload).toHaveBeenCalledTimes(2);
expect(URL.createObjectURL, '失败时不得留下半截 blob').toHaveBeenCalledTimes(0);
expect(URL.revokeObjectURL).not.toHaveBeenCalled();
});
it('全部上传成功 ⇒ 才建预览 URL,且条数/顺序一致', async () => {
const upload = vi.fn(async (file: File) => `server/${file.name}`);
const staged = await stageOutboundPhotoPreviews(files, upload, (file) => URL.createObjectURL(file));
expect(staged.map((item) => item.path)).toEqual(['server/a.jpg', 'server/b.jpg']);
expect(staged.map((item) => item.previewUrl)).toEqual(['blob:preview-1', 'blob:preview-2']);
expect(URL.createObjectURL).toHaveBeenCalledTimes(2);
});
it('建预览 URL 中途抛错 ⇒ 释放已创建的 blob,再抛错', async () => {
const upload = vi.fn(async (file: File) => `server/${file.name}`);
let calls = 0;
(URL.createObjectURL as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => {
calls += 1;
if (calls === 2) throw new Error('oom');
return `blob:preview-${calls}`;
});
await expect(stageOutboundPhotoPreviews(files, upload, (file) => URL.createObjectURL(file))).rejects.toThrow('oom');
expect(URL.revokeObjectURL).toHaveBeenCalledTimes(1);
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:preview-1');
});
});
+51
View File
@@ -31,3 +31,54 @@ export function releaseOutboundPhotoPreviewUrls(
}
}
}
/**
* FE-4(2026-10-19 T5 红队复攻):多文件上传的预览 URL 必须在**全部上传成功之后**才创建。
*
* 旧实现每传成功一个就 `createObjectURL`,随后一个文件抛错时 `uploaded` 数组被丢弃 ⇒
* 前面已创建的 blob URL 永远没人 revoke(多文件部分失败泄漏)。这里先传完再建 URL;
* 即使创建 URL 的中间环节抛错,也会释放已创建的 blob。
*/
export async function stageOutboundPhotoPreviews<T>(
files: File[],
upload: (file: File) => Promise<T>,
makePreviewUrl: (file: File) => string
): Promise<Array<{ path: T; previewUrl: string }>> {
const paths: T[] = [];
for (const file of files) {
paths.push(await upload(file)); // 任一失败即抛出:此时尚未创建任何 blob URL
}
const created: Array<{ path: T; previewUrl: string }> = [];
try {
for (let index = 0; index < paths.length; index += 1) {
created.push({ path: paths[index], previewUrl: makePreviewUrl(files[index]) });
}
return created;
} catch (error) {
releaseOutboundPhotoPreviewUrls(
created.map((item) => ({ path: String(item.path), previewUrl: item.previewUrl }))
);
throw error;
}
}
/**
* B-9.1b(2026-10-19 T5 终局复攻):上传在途时组件可能已卸载。
* 先按正常流程上传/建预览,返回后若已卸载 ⇒ 立刻释放刚创建的 blob 并返回 null,
* 调用方不得再 setState(否则 URL 无人引用、永不 revoke)。
*/
export async function stageOutboundPhotoPreviewsIfMounted<T>(
files: File[],
upload: (file: File) => Promise<T>,
makePreviewUrl: (file: File) => string,
isMounted: () => boolean
): Promise<Array<{ path: T; previewUrl: string }> | null> {
const staged = await stageOutboundPhotoPreviews(files, upload, makePreviewUrl);
if (!isMounted()) {
releaseOutboundPhotoPreviewUrls(
staged.map((item) => ({ path: String(item.path), previewUrl: item.previewUrl }))
);
return null;
}
return staged;
}
+3 -2
View File
@@ -5,8 +5,9 @@ import { describe, expect, it } from 'vitest';
* 未完成单只展示**待分拣**行(已确认的即时移出视野);已完成单仍为「待补录,全确认回退全部」。
* 设计见 docs/design/20261016-小程序分拣已确认行即时隐藏.md。
*/
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { visibleItemsForStatus } = require('../../miniprogram/utils/pickingAssembly');
import { createRequire } from 'node:module';
const requireForMiniprogram = createRequire(import.meta.url);
const { visibleItemsForStatus } = requireForMiniprogram('../../miniprogram/utils/pickingAssembly');
/** 已确认:有实拣量 + review_status ≥ 20(与 isItemPicked 同口径) */
const picked = (n = 1) => ({ picked_qty: n, review_status: 20, settlement_qty: n });
+1 -1
View File
@@ -383,7 +383,7 @@ export function buildPickingLabelRulerHtml(options?: {
const ruler = `<section class="pick-label">
<div class="rl-frame"></div>
${ticks.join('')}
<div class="rl-mid">${paper.widthMm} × ${paper.heightMm} mm 旋转 ${rotation}°</div>
<div class="rl-mid">${paper.widthMm} × ${paper.heightMm} mm\u3000旋转 ${rotation}°</div>
<div class="rl-mid2">↑ 顶边 / ← 左边(刻度单位 mm)</div>
</section>`;
const count = Math.min(Math.max(Number(options?.pages) || 2, 1), 5);
+3 -2
View File
@@ -7,8 +7,9 @@ import { describe, expect, it } from 'vitest';
* 这些用例守的是**回写边界**:识别值不能冒充人工值,换商品不能串档案。
*/
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { buildArchivePayload, hasUnsavedArchiveEdits } = require('../../miniprogram/utils/stockInboundArchive');
import { createRequire } from 'node:module';
const requireForMiniprogram = createRequire(import.meta.url);
const { buildArchivePayload, hasUnsavedArchiveEdits } = requireForMiniprogram('../../miniprogram/utils/stockInboundArchive');
describe('buildArchivePayload', () => {
it('无人工编辑 ⇒ null(不传 archive,服务端就不写档案)', () => {
+161
View File
@@ -0,0 +1,161 @@
// @vitest-environment jsdom
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* T5 独立边界复测 · FE-1(401 统一登出 / SSE 重连) + FE-4(blob 预览释放) —— 2026-10-19,tester。
* 与 dev 的 `workflowApi.unauthorized.test.ts` / `useNotificationStream.unauthorized.test.ts` 独立。
*/
const SESSION_KEY = 'canteen.auth.session';
function setSession(): void {
localStorage.setItem(SESSION_KEY, JSON.stringify({ access_token: 't-1', user: { id: 'u1' } }));
}
function installLocationStub(): { href: string } {
const loc = { href: '' };
try {
Object.defineProperty(window, 'location', { configurable: true, value: loc });
} catch {
(window as unknown as { location: { href: string } }).location = loc;
}
return loc;
}
function mockFetchStatus(status: number): void {
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status, body: null, json: async () => ({ error: 'token_expired' }) }))
);
}
beforeEach(() => {
localStorage.clear();
vi.unstubAllGlobals();
vi.useRealTimers();
});
afterEach(() => {
vi.unstubAllGlobals();
vi.useRealTimers();
localStorage.clear();
});
describe('T5/FE-1:workflowApi 401 统一登出', () => {
it('有 session:第一次 401 清 session + 跳转;随后再 401(已无 session)不再重复跳', async () => {
setSession();
const loc = installLocationStub();
mockFetchStatus(401);
vi.resetModules();
const { submitInspectionComplianceApi } = await import('./workflowApi');
const first = await submitInspectionComplianceApi({}).catch((err) => err);
expect(first).toMatchObject({ status: 401, code: 'token_expired' });
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('/login');
expect(loc.href).toContain('reason=expired');
const hrefAfterFirst = loc.href;
const second = await submitInspectionComplianceApi({}).catch((err) => err);
expect(second).toMatchObject({ status: 401 });
expect(loc.href, '无 session 后不得再跳(避免登录页自跳循环)').toBe(hrefAfterFirst);
});
it('无 session(登录页输错密码):只抛 401,不跳转、不清数据', async () => {
const loc = installLocationStub();
mockFetchStatus(401);
vi.resetModules();
const { submitInspectionComplianceApi } = await import('./workflowApi');
const error = await submitInspectionComplianceApi({}).catch((err) => err);
expect(error).toMatchObject({ status: 401 });
expect(loc.href).toBe('');
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
});
});
describe('T5/FE-1:SSE 401 停止重连 / 500 保持退避', () => {
it('SSE 401 ⇒ 只请求 1 次,60s 内不再重连,并登出', async () => {
setSession();
const loc = installLocationStub();
mockFetchStatus(401);
vi.resetModules();
const { useNotificationStream } = await import('../hooks/useNotificationStream');
const { unmount } = renderHook(() => useNotificationStream({ enabled: true, onSnapshot: () => undefined }));
await vi.waitFor(() => expect(globalThis.fetch).toHaveBeenCalledTimes(1));
await vi.waitFor(() => expect(loc.href).toContain('/login'));
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
await new Promise((resolve) => setTimeout(resolve, 50));
expect(globalThis.fetch, '401 后不得再重连').toHaveBeenCalledTimes(1);
unmount();
});
it('SSE 500 ⇒ 保持 2s 退避重连(第二次请求发生,且不登出)', async () => {
setSession();
installLocationStub();
mockFetchStatus(500);
vi.resetModules();
const { useNotificationStream } = await import('../hooks/useNotificationStream');
const { unmount } = renderHook(() => useNotificationStream({ enabled: true, onSnapshot: () => undefined }));
await vi.waitFor(() => expect(globalThis.fetch).toHaveBeenCalledTimes(1));
await vi.waitFor(() => expect(globalThis.fetch).toHaveBeenCalledTimes(2), { timeout: 5000 });
expect(localStorage.getItem(SESSION_KEY)).toBeTruthy();
unmount();
}, 15000);
});
describe('T5/FE-4:blob 预览 URL 成对释放', () => {
it('同一 blob URL 在「删图 → 卸载」生命周期里只 revoke 一次(状态已清空不重复)', async () => {
const revoked: string[] = [];
Object.defineProperty(URL, 'revokeObjectURL', {
configurable: true,
writable: true,
value: (url: string) => revoked.push(String(url)),
});
vi.resetModules();
const { releaseOutboundPhotoPreviewUrls } = await import('./outboundPhotoPreview');
const state: Record<string, Array<{ path: string; previewUrl: string }>> = {
item1: [{ path: 'p1', previewUrl: 'blob:http://localhost/same' }],
};
// ① 删图:释放被删那张,然后从 state 移除
releaseOutboundPhotoPreviewUrls(state.item1);
delete state.item1;
// ② 卸载:用 ref.current(已清空)再释放
releaseOutboundPhotoPreviewUrls(state);
expect(revoked).toEqual(['blob:http://localhost/same']);
});
it('切单只释放上一单的 blob;新单的 blob 在卸载时释放——各一次、均不碰签名 URL', async () => {
const revoked: string[] = [];
Object.defineProperty(URL, 'revokeObjectURL', {
configurable: true,
writable: true,
value: (url: string) => revoked.push(String(url)),
});
vi.resetModules();
const { releaseOutboundPhotoPreviewUrls } = await import('./outboundPhotoPreview');
const oldPhotos = { a: [{ path: 'p1', previewUrl: 'blob:old' }, { path: 'p2', previewUrl: 'https://cdn/x.jpg?sig=1' }] };
releaseOutboundPhotoPreviewUrls(oldPhotos); // 切单
const newPhotos = { a: [{ path: 'p9', previewUrl: 'blob:new' }] };
releaseOutboundPhotoPreviewUrls(newPhotos); // 卸载
expect(revoked).toEqual(['blob:old', 'blob:new']);
});
it('FE-3 前端接线:映射面板显式 limit=500 且搜索不带 refresh(源码契约)', () => {
const src = readFileSync(path.join(__dirname, '../pages/customers/QuoteSkuMappingsPanel.tsx'), 'utf8');
expect(src).toContain('limit: 500');
// 只有首次挂载带 refresh,后续搜索分支不带
const mountIdx = src.indexOf('void load({ refresh: true })');
const searchIdx = src.indexOf('void load();');
expect(mountIdx).toBeGreaterThan(-1);
expect(searchIdx).toBeGreaterThan(mountIdx);
});
});
+154
View File
@@ -0,0 +1,154 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* T5 rev7 合并最终复测 · tester 独立边界(2026-10-19)。
* c1) 401 响应体为 JSON null ⇒ 仍清 session + 跳转、error.status=401(读 payload 不得崩溃)。
* c2) 多文件上传 a 成功 b 失败 ⇒ 不得泄漏 a 的 blob(或干脆尚未创建 blob)。
*/
const SESSION_KEY = 'canteen.auth.session';
function setSession(): void {
localStorage.setItem(SESSION_KEY, JSON.stringify({ access_token: 't-1', user: { id: 'u1' } }));
}
function installLocationStub(): { href: string } {
const loc = { href: '' };
try {
Object.defineProperty(window, 'location', { configurable: true, value: loc });
} catch {
(window as unknown as { location: { href: string } }).location = loc;
}
return loc;
}
beforeEach(() => {
localStorage.clear();
vi.unstubAllGlobals();
});
afterEach(() => {
vi.unstubAllGlobals();
localStorage.clear();
});
describe('T5/FE-1:401 body=null 不得崩溃,仍统一登出', () => {
it('有 session + body null ⇒ 清 session、跳 /login、error.status=401/code=unauthorized', async () => {
setSession();
const loc = installLocationStub();
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status: 401, json: async () => null }))
);
vi.resetModules();
const { submitInspectionComplianceApi } = await import('./workflowApi');
const error = await submitInspectionComplianceApi({}).catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'unauthorized' });
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('/login');
expect(loc.href).toContain('reason=expired');
});
it('无 session + body null ⇒ 不跳转(登录页场景)', async () => {
const loc = installLocationStub();
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status: 401, json: async () => null }))
);
vi.resetModules();
const { submitInspectionComplianceApi } = await import('./workflowApi');
const error = await submitInspectionComplianceApi({}).catch((err) => err);
expect(error).toMatchObject({ status: 401 });
expect(loc.href).toBe('');
});
});
describe('T5/FE-4:多文件上传部分失败不得泄漏 blob', () => {
let created: string[];
let revoked: string[];
beforeEach(() => {
created = [];
revoked = [];
let seq = 0;
Object.defineProperty(URL, 'createObjectURL', {
configurable: true,
writable: true,
value: () => {
seq += 1;
const url = `blob:test/${seq}`;
created.push(url);
return url;
},
});
Object.defineProperty(URL, 'revokeObjectURL', {
configurable: true,
writable: true,
value: (url: string) => revoked.push(String(url)),
});
});
it('上传 a 成功、b 失败 ⇒ 整体拒绝且**未创建任何 blob**(无泄漏)', async () => {
vi.resetModules();
const { stageOutboundPhotoPreviews } = await import('./outboundPhotoPreview');
const files = [new File(['a'], 'a.jpg'), new File(['b'], 'b.jpg')];
let uploads = 0;
const error = await stageOutboundPhotoPreviews(
files,
async (file) => {
uploads += 1;
if (file.name === 'b.jpg') throw new Error('upload b failed');
return 'path-a';
},
(file) => URL.createObjectURL(file)
).catch((err) => err);
expect(String(error?.message)).toContain('upload b failed');
expect(uploads).toBe(2);
expect(created, '失败时不得留下半截 blob').toEqual([]);
expect(revoked).toEqual([]);
});
it('上传都成功但创建第 2 个预览 URL 抛错 ⇒ 已创建的 a blob 被 revoke,无泄漏', async () => {
vi.resetModules();
const { stageOutboundPhotoPreviews } = await import('./outboundPhotoPreview');
const files = [new File(['a'], 'a.jpg'), new File(['b'], 'b.jpg')];
let createdCalls = 0;
Object.defineProperty(URL, 'createObjectURL', {
configurable: true,
writable: true,
value: () => {
createdCalls += 1;
if (createdCalls === 2) throw new Error('create 2 failed');
const url = 'blob:test/a';
created.push(url);
return url;
},
});
const error = await stageOutboundPhotoPreviews(
files,
async (file) => `path-${file.name}`,
(file) => URL.createObjectURL(file)
).catch((err) => err);
expect(String(error?.message)).toContain('create 2 failed');
expect(revoked, 'a 的 blob 必须被释放').toEqual(['blob:test/a']);
});
it('全部成功 ⇒ 返回两条预览、不 revoke', async () => {
vi.resetModules();
const { stageOutboundPhotoPreviews } = await import('./outboundPhotoPreview');
const files = [new File(['a'], 'a.jpg'), new File(['b'], 'b.jpg')];
const staged = await stageOutboundPhotoPreviews(
files,
async (file) => `path-${file.name}`,
(file) => URL.createObjectURL(file)
);
expect(staged.map((row) => row.path)).toEqual(['path-a.jpg', 'path-b.jpg']);
expect(staged.every((row) => row.previewUrl.startsWith('blob:'))).toBe(true);
expect(revoked).toEqual([]);
});
});
+122
View File
@@ -0,0 +1,122 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* T5 rev13 实体最终复测 · raw fetch 401(tester 独立边界,2026-10-19)。
*
* `uploadPickingOutboundPhotoApi` / `checkCustomerBudgetApi` 走**裸 fetch**(非 workflowFetch),
* 之前 401 只按普通失败处理:body=null 时 `payload.error` 可能崩溃,budget 还会返回
* `{allowed:false}`(页面误当成"客户不能下单"而不是登录失效)。rev13 统一走
* `throwIfUnauthorizedRaw`:清 session + 跳 `/login?reason=expired`、错误带 `status:401/code`。
*/
const SESSION_KEY = 'canteen.auth.session';
function setSession(): void {
localStorage.setItem(SESSION_KEY, JSON.stringify({ access_token: 't-1', user: { id: 'u1' } }));
}
function installLocationStub(): { href: string } {
const loc = { href: '' };
try {
Object.defineProperty(window, 'location', { configurable: true, value: loc });
} catch {
(window as unknown as { location: { href: string } }).location = loc;
}
return loc;
}
function mock401(body: 'null' | 'non-json' | 'envelope'): void {
const json =
body === 'null'
? async () => null
: body === 'non-json'
? async () => {
throw new SyntaxError('Unexpected token < in JSON');
}
: async () => ({ error: 'token_expired', error_description: '登录已过期' });
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 401, json })));
}
function mockStatus(status: number, jsonBody: unknown): void {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status, json: async () => jsonBody })));
}
beforeEach(() => {
localStorage.clear();
vi.unstubAllGlobals();
vi.resetModules();
});
afterEach(() => {
vi.unstubAllGlobals();
localStorage.clear();
});
describe('T5/FE-1:uploadPickingOutboundPhotoApi 401(body null / 非 JSON)', () => {
it('body=null ⇒ 清 session、跳转、错误 status=401/code=unauthorized', async () => {
setSession();
const loc = installLocationStub();
mock401('null');
const { uploadPickingOutboundPhotoApi } = await import('./workflowApi');
const error = await uploadPickingOutboundPhotoApi(new File(['x'], 'a.jpg')).catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'unauthorized' });
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('/login');
expect(loc.href).toContain('reason=expired');
});
it('非 JSON body ⇒ 同样按 401 登出,不因 JSON 解析失败崩溃', async () => {
setSession();
const loc = installLocationStub();
mock401('non-json');
const { uploadPickingOutboundPhotoApi } = await import('./workflowApi');
const error = await uploadPickingOutboundPhotoApi(new File(['x'], 'a.jpg')).catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'unauthorized' });
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('reason=expired');
});
it('无 session ⇒ 401 不跳转(登录页场景),错误仍带 status=401', async () => {
const loc = installLocationStub();
mock401('null');
const { uploadPickingOutboundPhotoApi } = await import('./workflowApi');
const error = await uploadPickingOutboundPhotoApi(new File(['x'], 'a.jpg')).catch((err) => err);
expect(error).toMatchObject({ status: 401 });
expect(loc.href).toBe('');
});
});
describe('T5/FE-1:checkCustomerBudgetApi 401 不再返回 allowed:false', () => {
it('body=null ⇒ reject(不是 {allowed:false}),清 session + 跳转', async () => {
setSession();
const loc = installLocationStub();
mock401('null');
const { checkCustomerBudgetApi } = await import('./workflowApi');
const error = await checkCustomerBudgetApi('C001', 100).catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'unauthorized' });
expect((error as { allowed?: boolean }).allowed).toBeUndefined();
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('/login');
});
it('envelope 带 error code ⇒ code 透传;非 401 仍返回 allowed:false(行为不回归)', async () => {
setSession();
installLocationStub();
mock401('envelope');
const { checkCustomerBudgetApi } = await import('./workflowApi');
const error = await checkCustomerBudgetApi('C001').catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'token_expired' });
vi.resetModules();
localStorage.setItem(SESSION_KEY, JSON.stringify({ access_token: 't-2', user: { id: 'u1' } }));
mockStatus(400, { error: 'budget_block', error_description: '超出预算' });
const mod = await import('./workflowApi');
const result = await mod.checkCustomerBudgetApi('C001', 50);
expect(result).toMatchObject({ allowed: false });
});
});
+122
View File
@@ -0,0 +1,122 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/**
* FE-1(2026-10-19):`workflowApi` 的 401 必须与 `localApiClient` 共用同一登出处理。
*
* 缺陷:workflow 请求层 401 只 throw 普通 Error,不清 session、不跳登录页、错误也没有
* status/code ⇒ 页面停在旧数据上,用户不知道要重新登录(与 localApiClient 行为不一致)。
* 修复:401 ⇒ `handleUnauthorized()`(清 session + 跳 `/login?reason=expired`;**无 session 不跳**),
* 抛出的错误带 `status:401` 与后端 `error` 字段 code。
*/
const SESSION_KEY = 'canteen.auth.session';
async function loadWorkflowApi() {
vi.resetModules();
return import('../utils/workflowApi');
}
function installLocationStub(): { href: string } {
const loc = { href: '' };
try {
Object.defineProperty(window, 'location', { configurable: true, value: loc });
} catch {
// 极端 jsdom 版本不可重定义时,退化为直接赋值观察
(window as unknown as { location: { href: string } }).location = loc;
}
return loc;
}
function mockUnauthorized(): void {
vi.stubGlobal(
'fetch',
vi.fn(async () => ({
ok: false,
status: 401,
json: async () => ({ error: 'token_expired', error_description: '登录已过期,请重新登录' }),
}))
);
}
beforeEach(() => {
localStorage.clear();
vi.unstubAllGlobals();
});
afterEach(() => {
vi.unstubAllGlobals();
localStorage.clear();
});
describe('B-10.1:raw fetch(文件上传)401 也走统一登出', () => {
it('uploadPickingOutboundPhotoApi 401 ⇒ 清 session、跳一次登录、错误带 status/code', async () => {
const { setStoredSession } = await import('../lib/localApiClient');
setStoredSession({ access_token: 't-upload', user: { id: 'u1' } } as never);
const loc = installLocationStub();
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status: 401, json: async () => ({ error: 'token_expired' }) }))
);
const { uploadPickingOutboundPhotoApi } = await loadWorkflowApi();
const file = new File(['x'], 'a.jpg', { type: 'image/jpeg' });
const error = await uploadPickingOutboundPhotoApi(file).catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'token_expired' });
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('/login');
expect(loc.href).toContain('reason=expired');
});
});
describe('workflowApi 401:与 localApiClient 共用登出处理', () => {
it('有 session ⇒ 清 session、跳 /login?reason=expired、错误带 status=401 与 code', async () => {
const { setStoredSession } = await import('../lib/localApiClient');
setStoredSession({ access_token: 't-1', user: { id: 'u1' } } as never);
expect(localStorage.getItem(SESSION_KEY)).toBeTruthy();
const loc = installLocationStub();
mockUnauthorized();
const { submitInspectionComplianceApi } = await loadWorkflowApi();
const error = await submitInspectionComplianceApi({}).catch((err) => err);
expect(error).toMatchObject({ status: 401, code: 'token_expired' });
expect(localStorage.getItem(SESSION_KEY), '401 后必须清掉本地 session').toBeNull();
expect(loc.href).toContain('/login');
expect(loc.href).toContain('reason=expired');
});
it('401 且 body 为 JSON null ⇒ 不崩、仍登出、错误带 status=401/code=unauthorized', async () => {
const { setStoredSession } = await import('../lib/localApiClient');
setStoredSession({ access_token: 't-null', user: { id: 'u1' } } as never);
const loc = installLocationStub();
vi.stubGlobal(
'fetch',
vi.fn(async () => ({ ok: false, status: 401, body: null, json: async () => null }))
);
const { submitInspectionComplianceApi } = await loadWorkflowApi();
const error = await submitInspectionComplianceApi({}).catch((err) => err);
expect(error, 'body=null 时不得因读 payload.error 抛 TypeError').toMatchObject({
status: 401,
code: 'unauthorized',
});
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
expect(loc.href).toContain('/login');
expect(loc.href).toContain('reason=expired');
});
it('无 session(登录页本身 401)⇒ 不跳转、不清数据', async () => {
const loc = installLocationStub();
mockUnauthorized();
const { submitInspectionComplianceApi } = await loadWorkflowApi();
const error = await submitInspectionComplianceApi({}).catch((err) => err);
expect(error).toMatchObject({ status: 401 });
expect(loc.href, '无 session 时不得把登录页再跳走').toBe('');
expect(localStorage.getItem(SESSION_KEY)).toBeNull();
});
});
+7 -2
View File
@@ -73,7 +73,10 @@ export function buildZipStore(entries: Array<{ name: string; data: Uint8Array }>
]);
const central = concat([
new Uint8Array([0x50, 0x4b, 0x01, 0x02]),
u16(20),
// BIZ-15:central header `version made by` = Unix(3) + spec 3.0(0x031E),
// 配合 flags 0x0800(UTF-8 文件名)让 unzip 用 UTF-8 解中文名;
// 下面 `version needed` 仍保持 20(不改,避免破坏 zipStore.test.ts 的字节断言)。
u16(0x031e),
u16(20),
u16(0x0800),
u16(0),
@@ -87,7 +90,9 @@ export function buildZipStore(entries: Array<{ name: string; data: Uint8Array }>
u16(0),
u16(0),
u16(0),
u32(0),
// 外部属性:version made by 声明 Unix(3) 后,unzip 会按高 16 位当 Unix mode;
// 给 0100644(普通文件 rw-r--r--),否则解出的文件 mode=0000 会 EACCES 读不了。
u32(0x81a40000),
u32(offset),
file.nameBytes,
]);