diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c5e0a9db..86e8f843 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,17 +40,18 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile - - name: Quality gates(typecheck + 严格 lint + vitest,含演示数据合理性与 CSP 一致性) - run: pnpm check - - - name: Coverage gate(vitest --coverage,阈值见 vitest.config.ts) - # Q1:`pnpm check` 只跑 `vitest run`,vitest.config.ts 里的 thresholds 从不被执行 = 形同虚设。 - # 这里用带 --coverage 的命令再跑一次,阈值(statements 60 / branches 50 / functions 60 / lines 60) - # 才真正拦得住回归。注意 include 是**选定域**(utils / services / demo + 安全相关页面逻辑), - # 日志里的百分比不是全项目覆盖率(全项目口径见 vitest.config.ts 注释)。 + - name: Quality gates(typecheck + 严格 lint) + run: pnpm typecheck && pnpm lint + + - name: Test & coverage gate(vitest --coverage 单次执行,阈值见 vitest.config.ts) + # Q1 的初衷是让 coverage 阈值真正被执行。此前 `pnpm check`(内含一轮全量 vitest)+ + # `pnpm test:coverage`(再来一轮)把全部用例跑了两遍;现在 lint 之后只跑一次带 + # --coverage 的 vitest,用例与阈值在同一次执行里生效。本地/pre-commit 的 + # `pnpm check` 入口不受影响。include 仍是**选定域**(utils / services / demo + + # 安全相关页面逻辑),日志里的百分比不是全项目覆盖率。 run: pnpm test:coverage - - name: Dependency audit(全量公告、真实源码补丁和攻击回归;不忽略公告) + - name: Dependency audit(运行时公告零忽略 + 真实源码补丁与攻击回归;仅构建链可达的公告为非阻塞告警,分层政策见 SECURITY.md) run: pnpm audit:security build: diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 5e625d28..ff0128af 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -39,17 +39,11 @@ jobs: - name: Install dependencies run: pnpm install --frozen-lockfile - - name: Type check - run: pnpm run typecheck - - - name: Test - run: pnpm test - - - name: Lint - run: pnpm run lint - - - name: Dependency audit(全量公告与真实源码补丁验证) - run: pnpm audit:security + # 质量门禁(typecheck / test / lint / audit)不在 master 部署上重跑:推到 master 的 + # commit 即 PR 上被 ci.yml 逐项检查过的同一 commit(分支保护要求 check/build/e2e 全绿), + # 重复执行只增加约 6-8 分钟纯冗余。本工作流保留的是部署特有的门禁:凭据注入构建、 + # SPA 404 回退、dist 密钥扫描与完整性清单(扫描过的字节 = 发布的字节)。 + # 直推 master(不经 PR)的提交没有这道重复防线——分支保护已要求 PR 流程。 - name: Build # 注入本产线会用到的全部凭据;扫描步骤必须看到同一组环境变量(否则「构建期配置了凭据」 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c7849deb..8b488f35 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -37,13 +37,13 @@ pnpm start:demo - **Permission points are single-source.** Add a new point to `PERMISSION_TREE` in `src/constants/permissions.ts`, then wire it in the same PR: `access` in `config/routes.ts` for pages, `src/access.ts` for buttons, the demo backend route in `src/demo/server/routes.ts`, and the API→permission table in [docs/demo/role-matrix.md](./docs/demo/role-matrix.md). Do not re-derive a role's permissions anywhere else — the matrix reproduces `DEFAULT_ROLE_PERMISSIONS` item by item and must stay exact. - **Never describe demo mode as real authorization.** The in-browser demo backend demonstrates the contract; every check runs in the user's own browser, so the docs must always say that a real backend has to implement it. The same applies to audit logs, the role-assignment rules and coordinate precision. - **New build-time credential.** Register it in `CREDENTIAL_DECLARATIONS` in `scripts/check-dist-secrets.mjs`, give it a typed `EXPECTED_*` declaration and a shape check, and declare it in every pipeline that injects it (Vercel env, Cloudflare Pages env, Docker build args, the Pages workflow's scan step). An injected-but-undeclared credential fails the scan by design. -- **Do not weaken a gate to land a change.** Thresholds, allowlists, CSP sources and security tests must not be relaxed; if a gate blocks you, fix the cause or raise it in the PR description. +- **Do not weaken a gate to land a change.** Thresholds, allowlists, CSP sources and security tests must not be relaxed; if a gate blocks you, fix the cause or raise it in the PR description. (The one deliberate amendment on record: dependency-advisory tiering, 2026-11-01 — runtime stays zero-ignore, build-chain-only advisories warn; rationale and scope in SECURITY.md.) ## Testing - Unit tests: `src/**/*.test.ts` (vitest) — demo data sanity, demo backend endpoints, request layer, geo math, import/export - Repo-level: `scripts/*.test.ts` — repository hygiene, CSP and security-header consistency across Vercel, nginx and Cloudflare Pages, AMap loader-host pinning, route table (components exist, legacy paths resolve, bilingual menu keys), deploy-routing fail-closed behaviour, Dockerfile frontend pinning, integrity manifest - Browser: `e2e/` (Playwright, 112 cases green against the new contract) — every page free of errors / CSP violations, English UI without leftover Chinese, key business flows; cases tagged `@smoke` re-run against the live site after each deployment -- Accessibility: `e2e/a11y.spec.ts` injects axe-core from the existing transitive install (no new dependency; served same-origin because the CSP has no `unsafe-inline`) and runs **24 cases** in three groups — 10 routes × light (cold start), 10 routes × realDark (cold start), and 4 routes (`/`, `/ops/devices`, `/ops/alarms`, `/ops/tickets`) × realDark reached by **clicking** the header theme toggle. The toggle group exists because umi's `setAntdConfig` deep-merges and the light/dark token sets were previously asymmetric, leaving light seeds behind on a hot switch; both sets now hold the same 13 keys and the toggle path was measured to produce byte-identical tokens to a cold-start dark across 17 CSS variables. Command `pnpm exec playwright test e2e/a11y.spec.ts --workers=1` → 24 passed, with **0 critical and 0 serious in all 24 cases** and the exclusion list empty (no rule excluded, no threshold lowered, nothing reclassified). This is **not** "axe clean": the moderate/minor findings are reported and stay non-gating — `landmark-no-duplicate-banner` and `landmark-unique` (moderate, 2 per route, ProLayout header/banner), Calendar `heading-order` (moderate) and FullCalendar's `empty-table-header` (minor ×7), plus a `region` moderate on the empty portal `
` antd creates when the toggle's tooltip opens (toggle cases only). Treat any newly appearing critical/serious result as a regression to fix, not to exclude. +- Accessibility: `e2e/a11y.spec.ts` injects axe-core from the existing transitive install (no new dependency; served same-origin because the CSP has no `unsafe-inline`) and runs **27 cases** in three groups — 11 routes × light (cold start), 11 routes × realDark (cold start), and 5 routes (`/login`, `/`, `/ops/devices`, `/ops/alarms`, `/ops/tickets`) × realDark reached by **clicking** the header theme toggle. The toggle group exists because umi's `setAntdConfig` deep-merges and the light/dark token sets were previously asymmetric, leaving light seeds behind on a hot switch; both sets now hold the same 13 keys and the toggle path was measured to produce byte-identical tokens to a cold-start dark across 17 CSS variables. Command `pnpm exec playwright test e2e/a11y.spec.ts --workers=1`; the gate is **0 critical and 0 serious across all cases** with the exclusion list empty (no rule excluded, no threshold lowered, nothing reclassified). This is **not** "axe clean": the moderate/minor findings are reported and stay non-gating — `landmark-no-duplicate-banner` and `landmark-unique` (moderate, 2 per route, ProLayout header/banner), Calendar `heading-order` (moderate) and FullCalendar's `empty-table-header` (minor ×7), plus a `region` moderate on the empty portal `
` antd creates when the toggle's tooltip opens (toggle cases only). Treat any newly appearing critical/serious result as a regression to fix, not to exclude. - Coverage: `pnpm test:coverage` — the percentage is measured over the **selected include set** in `vitest.config.ts` (`src/utils`, `src/services`, `src/demo`, `src/pages/Login`, `src/pages/System/Users`, `src/pages/System/Roles`), not the whole project; thresholds (statements 60 / branches 50 / functions 60 / lines 60) gate that set in CI and must not be lowered. Final local figure: statements 79.38% / branches 74.48% / functions 75.55% / lines 81.51% over 54 files (644 passed, 5 skipped — the skips are the mode-conditional branches of `scripts/real-mode-artifact.test.ts`), against roughly 47.87% statements for whole-project `src/**` -- Lint: `react-hooks/exhaustive-deps` is an error and unused-disable reporting is on (an unused disable directive is itself an error). A disable line must carry a concrete written reason on the same or preceding line; the one remaining `exhaustive-deps` disable in `src/` is `src/hooks/useApi.ts` (its reason is on the line, because the dependency array is supplied by the caller and the rule cannot verify it statically). +- Lint: `react-hooks/exhaustive-deps` is an error and unused-disable reporting is on (an unused disable directive is itself an error). A disable line must carry a concrete written reason on the same or preceding line; the 6 `exhaustive-deps` disables currently in `src/` (`src/hooks/useApi.ts` plus five Cesium scene pages' clock/pure-function effects) each carry their reason on the line. diff --git a/CONTRIBUTING.zh-CN.md b/CONTRIBUTING.zh-CN.md index c4c1e77f..8360cbf9 100644 --- a/CONTRIBUTING.zh-CN.md +++ b/CONTRIBUTING.zh-CN.md @@ -37,13 +37,13 @@ pnpm start:demo - **权限点只有一个来源。** 新增权限点要在 `src/constants/permissions.ts` 的 `PERMISSION_TREE` 里登记,并在同一个 PR 内接好:页面用 `config/routes.ts` 的 `access`,按钮用 `src/access.ts`,演示后端路由用 `src/demo/server/routes.ts`,并同步 [docs/demo/role-matrix.md](./docs/demo/role-matrix.md) 的接口 → 权限点对照。角色权限不允许在别处另算一套——矩阵文档逐项复刻 `DEFAULT_ROLE_PERMISSIONS`,必须保持精确一致。 - **绝不把演示模式描述成真实授权。** 浏览器内演示后端演示的是契约;一切校验都在用户自己的浏览器里执行,文档必须始终写明真实后端要自行实现。操作日志、角色分配规则与坐标精度同理。 - **新增构建期凭据。** 要在 `scripts/check-dist-secrets.mjs` 的 `CREDENTIAL_DECLARATIONS` 登记,配一个类型化的 `EXPECTED_*` 声明与形态校验,并在所有注入它的产线里声明(Vercel 环境变量、Cloudflare Pages 环境变量、Docker build-arg、Pages workflow 的扫描步骤)。注入了却没声明会按设计判失败。 -- **不得为了合入而放松门禁。** 阈值、白名单、CSP 来源与安全测试都不许放宽;被门禁挡住时请修根因,或在 PR 描述里提出。 +- **不得为了合入而放松门禁。** 阈值、白名单、CSP 来源与安全测试都不许放宽;被门禁挡住时请修根因,或在 PR 描述里提出。(有记录的唯一一次主动修订:2026-11-01 依赖公告分层——运行时维持零忽略,仅构建链可达的公告降为告警;理由与范围见 SECURITY.md。) ## 测试 - 单元测试:`src/**/*.test.ts`(vitest)——演示数据合理性、演示后端接口、请求层、地理计算、导入导出 - 仓库级:`scripts/*.test.ts`——仓库卫生、CSP 与安全响应头在 Vercel / nginx / Cloudflare Pages 三处一致、高德加载器主机固定、路由表(组件存在、旧路径可达、菜单双语)、部署路由闭合失败行为、Dockerfile frontend 固定、完整性清单 - 浏览器:`e2e/`(Playwright,当前按新契约全绿 112 例)——每个页面无异常 / 无 CSP 违规、英文界面无遗漏中文、关键业务流程;`@smoke` 标签的用例在部署后对线上地址再跑一遍 -- 无障碍:`e2e/a11y.spec.ts` 从既有传递依赖注入 axe-core(不新增依赖;因为 CSP 没有 `unsafe-inline`,改为同源 URL 注入),共跑 **24 例**,分三组——10 条路由 × 浅色(冷启动)、10 条路由 × realDark(冷启动)、以及 4 条路由(`/`、`/ops/devices`、`/ops/alarms`、`/ops/tickets`)× realDark 且经**点击顶栏主题开关**到达。切换组存在的原因:umi 的 `setAntdConfig` 是深合并,而此前浅色与暗色 token 键集不对称,热切换会残留浅色种子值;现在两套键集都是同样的 13 个键,且实测切换路径与冷启动暗色在 17 个 CSS 变量上逐字节一致。命令 `pnpm exec playwright test e2e/a11y.spec.ts --workers=1` → 24 例全过,**24 例的 critical 与 serious 均为 0**,排除清单为空(没有排除任何规则、没有放宽阈值、没有重新分级)。这不等于「axe 无告警」:moderate / minor 结果照常输出但不作为门禁——ProLayout 头部的 `landmark-no-duplicate-banner`、`landmark-unique`(moderate,每路由 2 个),Calendar 的 `heading-order`(moderate),FullCalendar 内部的 `empty-table-header`(minor ×7),以及切换用例里 antd 在开关 tooltip 打开时创建的空 portal `
` 上的 `region`(moderate,仅切换组)。新出现的 critical / serious 一律按回归修复,不允许加进排除清单。 +- 无障碍:`e2e/a11y.spec.ts` 从既有传递依赖注入 axe-core(不新增依赖;因为 CSP 没有 `unsafe-inline`,改为同源 URL 注入),共跑 **27 例**,分三组——11 条路由 × 浅色(冷启动)、11 条路由 × realDark(冷启动)、以及 5 条路由(`/login`、`/`、`/ops/devices`、`/ops/alarms`、`/ops/tickets`)× realDark 且经**点击顶栏主题开关**到达。切换组存在的原因:umi 的 `setAntdConfig` 是深合并,而此前浅色与暗色 token 键集不对称,热切换会残留浅色种子值;现在两套键集都是同样的 13 个键,且实测切换路径与冷启动暗色在 17 个 CSS 变量上逐字节一致。命令 `pnpm exec playwright test e2e/a11y.spec.ts --workers=1`;门禁要求**全部用例 critical 与 serious 均为 0**,排除清单为空(没有排除任何规则、没有放宽阈值、没有重新分级)。这不等于「axe 无告警」:moderate / minor 结果照常输出但不作为门禁——ProLayout 头部的 `landmark-no-duplicate-banner`、`landmark-unique`(moderate,每路由 2 个),Calendar 的 `heading-order`(moderate),FullCalendar 内部的 `empty-table-header`(minor ×7),以及切换用例里 antd 在开关 tooltip 打开时创建的空 portal `
` 上的 `region`(moderate,仅切换组)。新出现的 critical / serious 一律按回归修复,不允许加进排除清单。 - 覆盖率:`pnpm test:coverage`——百分比统计的是 `vitest.config.ts` 的**选定域**(`src/utils`、`src/services`、`src/demo`、`src/pages/Login`、`src/pages/System/Users`、`src/pages/System/Roles`),不是全项目口径;阈值(statements 60 / branches 50 / functions 60 / lines 60)在 CI 上只对域内生效,不得下调。最终本机数字:54 个文件上 statements 79.38% / branches 74.48% / functions 75.55% / lines 81.51%(644 passed、5 skipped,skip 全部来自 `scripts/real-mode-artifact.test.ts` 的模式分支),同口径全项目 `src/**` 约 statements 47.87% -- Lint:`react-hooks/exhaustive-deps` 已提到 error,未使用 disable 的上报已开启。disable 行必须在本行或上一行写明具体理由;`src/` 内仅剩 1 处 `exhaustive-deps` disable,在 `src/hooks/useApi.ts`(理由写在同一行:依赖数组由调用方提供,规则无法静态校验展开项)。 +- Lint:`react-hooks/exhaustive-deps` 已提到 error,未使用 disable 的上报已开启。disable 行必须在本行或上一行写明具体理由;`src/` 内现存 6 处 `exhaustive-deps` disable(`src/hooks/useApi.ts` 与五个 Cesium 场景页的时钟/纯函数 effect),理由均已写在同一行。 diff --git a/SECURITY.md b/SECURITY.md index 9a4920b9..d15fb7fc 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -20,7 +20,7 @@ Please include: affected version/commit, reproduction steps, and impact assessme ## Quality gates -- PR-stage CI: typecheck / strict lint (including `.mjs`; `react-hooks/exhaustive-deps` is an error and unused-disable reporting is on) / vitest / **coverage gate** (`pnpm test:coverage`, thresholds in `vitest.config.ts`) / both explicit demo builds plus the real-mode build (`build:real`, whose artifact is asserted to contain no demo code) / bundle budget & style coverage / **artifact secret scanning** (fingerprint-verified against declared public client tokens only) / full dependency advisories with verified source patches / Playwright (CSP violations caused by third parties are not ignored) +- PR-stage CI: typecheck / strict lint (including `.mjs`; `react-hooks/exhaustive-deps` is an error and unused-disable reporting is on) / vitest / **coverage gate** (`pnpm test:coverage`, thresholds in `vitest.config.ts`) / both explicit demo builds plus the real-mode build (`build:real`, whose artifact is asserted to contain no demo code) / bundle budget & style coverage / **artifact secret scanning** (fingerprint-verified against declared public client tokens only) / tiered dependency advisories (runtime zero-ignore with verified source patches; build-chain-only advisories are reported as non-blocking warnings) / Playwright (CSP violations caused by third parties are not ignored) - The coverage percentage is measured over the **selected include set** in `vitest.config.ts` — `src/utils/**`, `src/services/**`, `src/demo/**`, `src/pages/Login/**`, `src/pages/System/Users/**` and `src/pages/System/Roles/**` — not over the whole project. The final local figure is statements 79.38% / branches 74.48% / functions 75.55% / lines 81.51% over 54 files (`pnpm test:coverage`, 644 passed / 5 skipped, thresholds 60/50/60/60 unchanged); measuring whole-project `src/**` in a one-off run gives about 47.87% statements with the config untouched, so the gate figure must not be quoted as whole-project coverage. The 5 skips are the mode-conditional branches of `scripts/real-mode-artifact.test.ts` (a demo-mode artifact skips the real-mode assertions); CI sets `REAL_MODE_ARTIFACT_REQUIRED=1` on the `build:real` job, where they cannot silently skip - Post-deploy: wait for the online `version.json` to switch to this commit, then run the `@smoke` cases against the live site - Commit stage: pre-commit (lint-staged + typecheck) @@ -50,7 +50,7 @@ The Vercel entry is fail-closed for `/api/*`: an explicit `/api/(.*)` rewrite ru The Dockerfile declares no mutable `# syntax=docker/dockerfile:1` frontend — it uses only default-frontend instructions, and both base images are pinned by digest; if BuildKit-only syntax is ever required it must be pinned to an exact version or digest, which `scripts/dockerfile-frontend.test.ts` enforces. -Real mode strips the browser demo backend through build-time aliases (`@/demo/adapter`, `@/demo/token`), but it is **not** demo-free: `umi-react-admin:demo-clock:v1` from `src/demo/clock.ts` still appears in three lazy route chunks (`Signature`, `Tickets`, `Alarms`) because `src/utils/now.ts` statically imports the demo clock. It is outside the entry chunk and outside the demo backend/generator/scenario/store, so the stripping criteria hold, but a frozen clock anchor left in localStorage on an origin previously used for the demo can make real-mode relative times wrong; adding a third build-time alias for `@/demo/clock` is the recommended fix. +Real mode strips the browser demo backend through build-time aliases (`@/demo/adapter`, `@/demo/token`, `@/demo/clock` — the clock alias redirects `src/utils/now.ts` to `src/demo/clock.real.ts`, which always returns system time and throws on freeze/resume). The stub reads and writes no storage at all, so a frozen-clock anchor left in localStorage on an origin previously used for the demo is simply never consulted; `freeze`/`resume` throw so a misconfiguration surfaces immediately. `scripts/real-mode-artifact.test.ts` asserts the stub sentinel is present in real artifacts and that the demo clock's storage key is absent from async chunks. The local preview server binds to 127.0.0.1 only and rejects directory traversal, escaping symlinks and abnormal encodings. It is for local verification; production should use an HTTPS static entry. nginx listens on intranet 8080 with TLS terminated at the deployment entry; HSTS only takes effect once the browser has seen an HTTPS response. @@ -77,3 +77,5 @@ Honest residual limits: PDF.js exposes no decoded-resource accounting API, so th Historical advisories are no longer recorded as accepted-without-fix. Real upgrades, removals or source patches are tracked in [THIRD-PARTY-NOTICES.md](./THIRD-PARTY-NOTICES.md). Raw `pnpm audit` may still flag locally patched packages by version number; the raw output is kept, and `pnpm audit:security` must additionally verify source hashes of every installed instance plus real attack regressions — new advisories and unproven instances fail. Gates must never be passed by ignoring advisories, faking version numbers, or assessing only unreachable paths. + +Advisory tiering (2026-11-01): advisories whose every installed path sits inside build/test/lint toolchain subtrees (bundlers, vite/mako/utoopack, the eslint and vitest families, Node-only build helpers — packages that never ship in `dist`) are reported as non-blocking warnings; anything with even one path into the shipped/runtime graph stays zero-ignore and blocking. The classification is deliberately conservative (any bypassing path keeps an advisory blocking), and `AUDIT_TOOLCHAIN_STRICT=1` restores full blocking for periodic manual sweeps. Rationale: upstream `@umijs/max` pins those transitive versions so the project cannot upgrade them, and GitHub advisory-database updates had kept every PR red from 2026-10-21 to 2026-11-01; the tier users actually run keeps its zero-ignore guarantee unchanged. diff --git a/SECURITY.zh-CN.md b/SECURITY.zh-CN.md index aad6c376..d5ed1fbe 100644 --- a/SECURITY.zh-CN.md +++ b/SECURITY.zh-CN.md @@ -20,7 +20,7 @@ ## 质量门禁 -- PR 阶段 CI:typecheck / 严格 lint(含 .mjs;`react-hooks/exhaustive-deps` 为 error,未使用 disable 的上报已开启)/ vitest / **覆盖率门禁**(`pnpm test:coverage`,阈值见 `vitest.config.ts`)/ 两条显式演示构建 + 真实模式构建(`build:real`,其产物会被断言不含演示代码)/ 体积预算与样式覆盖 / **产物密钥扫描**(仅核对已声明的公开客户端 token 指纹)/ 全量依赖公告与真实补丁验证 / Playwright(包含第三方引起的 CSP 违规,不作忽略) +- PR 阶段 CI:typecheck / 严格 lint(含 .mjs;`react-hooks/exhaustive-deps` 为 error,未使用 disable 的上报已开启)/ vitest / **覆盖率门禁**(`pnpm test:coverage`,阈值见 `vitest.config.ts`)/ 两条显式演示构建 + 真实模式构建(`build:real`,其产物会被断言不含演示代码)/ 体积预算与样式覆盖 / **产物密钥扫描**(仅核对已声明的公开客户端 token 指纹)/ 分层依赖公告(运行时零忽略 + 真实补丁验证;仅构建链可达的公告为非阻塞告警)/ Playwright(包含第三方引起的 CSP 违规,不作忽略) - 覆盖率百分比统计的是 `vitest.config.ts` 里的**选定域**——`src/utils/**`、`src/services/**`、`src/demo/**`、`src/pages/Login/**`、`src/pages/System/Users/**`、`src/pages/System/Roles/**`——不是全项目口径。最终本机数字为 54 个文件上 statements 79.38% / branches 74.48% / functions 75.55% / lines 81.51%(`pnpm test:coverage`,644 passed / 5 skipped,阈值 60/50/60/60 未改动);另做一次全项目 `src/**` 统计约为 statements 47.87%(配置未改动),因此门禁数字不得作为全项目覆盖率引用。5 个 skip 全部是 `scripts/real-mode-artifact.test.ts` 中按模式分支的用例(演示模式产物会跳过真实模式断言);CI 的 `build:real` 作业设置 `REAL_MODE_ARTIFACT_REQUIRED=1`,在那里它们无法静默跳过 - 部署后:等待线上 `version.json` 切到本次提交,对线上地址跑 `@smoke` 用例 - 提交阶段:pre-commit(lint-staged + typecheck) @@ -50,7 +50,7 @@ Vercel 产线的 `/api/*` 是闭合失败的:显式的 `/api/(.*)` rewrite 排 Dockerfile 不再声明可变的 `# syntax=docker/dockerfile:1` frontend——它只使用默认 frontend 支持的指令,且两个 base 镜像都按摘要固定;若将来确实需要 BuildKit 专属语法,必须固定到精确版本或摘要,由 `scripts/dockerfile-frontend.test.ts` 把关。 -真实模式通过构建期 alias(`@/demo/adapter`、`@/demo/token`)剥离浏览器内演示后端,但**并非**零演示代码:来自 `src/demo/clock.ts` 的 `umi-react-admin:demo-clock:v1` 仍出现在三个懒加载路由 chunk 中(`Signature`、`Tickets`、`Alarms`),因为 `src/utils/now.ts` 静态 import 了演示时钟。它不在入口 chunk,也不属于演示后端 / 生成器 / 场景 / 存储,因此既定剥离标准成立;但若某来源站曾用于演示,localStorage 里残留的冻结时钟锚点会让真实模式的相对时间出错。推荐的修法是给 `@/demo/clock` 加第三个构建期 alias。 +真实模式通过构建期 alias(`@/demo/adapter`、`@/demo/token`、`@/demo/clock`)剥离浏览器内演示后端——其中时钟 alias 把 `src/utils/now.ts` 重定向到 `src/demo/clock.real.ts`(恒返回系统时间;freeze/resume 直接抛错)。该替身完全不读不写任何存储,因此即便某来源站曾用于演示、localStorage 里残留冻结时钟锚点,真实模式也不会读到它;freeze/resume 抛错则保证配置错误第一时间暴露。`scripts/real-mode-artifact.test.ts` 断言真实产物含替身哨兵、且异步 chunk 中不含演示时钟的存储键。 本地 preview 默认仅监听 127.0.0.1,拒绝目录越界、逃逸符号链接及异常编码。它用于本机验证;生产应使用 HTTPS 静态服务入口。nginx 监听内网 8080,TLS 在部署入口终止;HSTS 只有浏览器收到 HTTPS 响应时才生效。 @@ -77,3 +77,5 @@ XLSX 在交给 ExcelJS 前校验 ZIP、实际解压量、XML、坐标、合并 历史公告不再登记为无修复的接受项。真实升级、移除或源码补丁见 [THIRD-PARTY-NOTICES.md](./THIRD-PARTY-NOTICES.md)。原始 `pnpm audit` 根据真实版本号仍可能命中本地已修补包;保留原始结果,`pnpm audit:security` 必须同时验证所有安装实例的源码哈希和真实攻击回归,新公告及未证明修补的实例均失败。不得通过忽略公告、伪造版本号或只评估不可达来让门禁通过。 + +公告分层(2026-11-01):所有安装路径都只落在构建/测试/lint 工具链子树内(打包器、vite/mako/utoopack、eslint 与 vitest 家族、纯 Node 构建辅助——这些包不进 `dist`)的公告降为非阻塞告警;只要有任何一条路径可进产物/运行时图,仍按零忽略阻塞。判定从宽(存在旁路路径即维持阻塞),`AUDIT_TOOLCHAIN_STRICT=1` 可恢复全量阻塞用于周期性人工清点。理由:上游 `@umijs/max` 锁死了这些传递依赖的版本、仓库无法升格,而 GHSA 数据库的每次更新在 2026-10-21 至 2026-11-01 间把所有 PR 连续打红;用户真正运行的运行时层的零忽略保证保持不变。 diff --git a/api/[...path].js b/api/[...path].js index deaf4d13..e794bb29 100644 --- a/api/[...path].js +++ b/api/[...path].js @@ -67,8 +67,9 @@ const resolveBackend = () => { if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) { return { error: 'backend_misconfigured' }; } - // 生产部署拒绝环回/私网/保留地址(与全站服务端请求约束一致):API_ORIGIN 被污染成内网地址时 - // 不得把函数变成内网探测跳板。本地/CI 测试用 127.0.0.1 起真实上游验证代理语义,故仅生产启用 + // 公网部署(production 与 preview)拒绝环回/私网/保留地址(与全站服务端请求约束一致): + // API_ORIGIN 被污染成内网地址时不得把函数变成内网探测跳板。 + // 本地/CI 测试用 127.0.0.1 起真实上游验证代理语义,故仅公网部署启用 const host = url.hostname.toLowerCase(); const isLoopback = host === 'localhost' || host === '::1' || host === '[::1]' || host.endsWith('.localhost'); const isPrivateIpv4 = @@ -79,9 +80,14 @@ const resolveBackend = () => { a === 10 || a === 127 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || a === 0 || a >= 224 ); })(); - const isLinkLocal = - host.startsWith('169.254.') || host.startsWith('fe80:') || host.startsWith('fc') || host.startsWith('fd'); - const isProduction = process.env.VERCEL_ENV === 'production' || process.env.NODE_ENV === 'production'; + // IPv6 ULA(fc00::/7)必然含 ':':此前用 startsWith('fc')/startsWith('fd') 会把 + // fcms.example.com 这类公网域名误判成链路本地并拒绝 + const isLinkLocal = host.startsWith('169.254.') || host.startsWith('fe80:') || /^f[cd][0-9a-f]*:/.test(host); + // preview 部署同样公网可达(此前只有 production 拒绝内网地址,preview 可被当内网探测跳板) + const isProduction = + process.env.VERCEL_ENV === 'production' || + process.env.VERCEL_ENV === 'preview' || + process.env.NODE_ENV === 'production'; if (isProduction && (isLoopback || isPrivateIpv4 || isLinkLocal)) { return { error: 'backend_misconfigured' }; } diff --git a/config/config.github.ts b/config/config.github.ts index a9b3cbe8..902b4e6a 100644 --- a/config/config.github.ts +++ b/config/config.github.ts @@ -6,7 +6,7 @@ import { buildCsp } from './csp'; import { faviconLinks } from './favicons'; import { configureSplitChunks } from './splitChunks'; import { keepUrlAssetsVerbatim } from './urlAssets'; -// import { routes } from './routes'; + const AUTH_CONFIG = resolveAuthConfig(process.env); if (!AUTH_CONFIG.demoMode) { throw new Error('GitHub Pages supports public demo only; backend mode needs a host with security headers'); @@ -22,7 +22,9 @@ export default defineConfig({ if (process.env.NODE_ENV === 'production') { configureSplitChunks(config); addChunkGraph(config); - addVersionFile(config); + // 与 config.ts 对齐传入 demoMode:本文件入口已断言 demoMode 为真,避免仅靠 + // UMI_APP_DEMO_MODE 环境变量兜底(两条产线参数源不同就会静默漂移) + addVersionFile(config, { demoMode: AUTH_CONFIG.demoMode }); } }, // define 经 lodash.merge 逐键深合并(@umijs/core getUserConfig):这里只覆盖与主产线的 diff --git a/config/config.ts b/config/config.ts index a36e9247..49692958 100644 --- a/config/config.ts +++ b/config/config.ts @@ -45,6 +45,10 @@ export default defineConfig({ * - '@/demo/token':services/auth.ts 顶层 import,调用点在 `if (DEMO_MODE)` 里;DEMO_MODE 经 * 模块命名空间读取(产物中是 `ne.G`),压缩器无法判定该分支为死代码,演示 token 模块 * (含 'demo.' 前缀字面量)因此留在真实模式入口 chunk,实测确认后才加的第二个替身。 + * - '@/demo/clock':src/utils/now.ts 顶层 import。不加替身时 Signature / Tickets / Alarms 的 + * 懒加载 chunk 会带上演示时钟与存储键 'umi-react-admin:demo-clock'——若同一 origin 冻结过 + * 演示时钟,真实模式下 nowMs() 会继续返回旧锚点(SLA/持续时长按错误时间计算)。 + * 替身恒返回系统时间(见 src/demo/clock.real.ts),哨兵由 real-mode-artifact.test.ts 断言。 * * 键写成完整路径:preset-umi 的 configPlugins 把用户 alias 展开在内置 '@' 之前 * (memo.alias = { ...memo.alias, '@': absSrcPath }),完整键精确命中,不依赖前缀匹配顺序。 @@ -55,6 +59,7 @@ export default defineConfig({ : { '@/demo/adapter': path.resolve(__dirname, '../src/demo/adapter.real.ts'), '@/demo/token': path.resolve(__dirname, '../src/demo/token.real.ts'), + '@/demo/clock': path.resolve(__dirname, '../src/demo/clock.real.ts'), }, chainWebpack(config) { keepUrlAssetsVerbatim(config); diff --git a/e2e/baseUrl.ts b/e2e/baseUrl.ts new file mode 100644 index 00000000..dfd5be39 --- /dev/null +++ b/e2e/baseUrl.ts @@ -0,0 +1,5 @@ +/** + * 本地静态服务器的默认地址:playwright.config(webServer.url/baseURL)与 e2e/fixtures + * (navigate/version 探测)必须指向同一处——此前两处各写一份字面量,改端口会静默分叉。 + */ +export const DEFAULT_BASE_URL = 'http://localhost:4173/umi-react-admin/'; diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts index dc9782e2..700c0d66 100644 --- a/e2e/fixtures.ts +++ b/e2e/fixtures.ts @@ -1,4 +1,5 @@ import { test as base, expect, type Page } from '@playwright/test'; +import { DEFAULT_BASE_URL } from './baseUrl'; /** 第三方地图 / 影像 / 视频源的网络失败不算应用缺陷(CI 网络环境不可控) */ const THIRD_PARTY = @@ -57,7 +58,7 @@ export const signIn = async (page: Page, { user = 'admin', locale = 'zh-CN' } = await page.waitForURL((url) => !url.pathname.endsWith('/login')); }; -export const BASE_URL = process.env.E2E_BASE_URL ?? 'http://localhost:4173/umi-react-admin/'; +export const BASE_URL = process.env.E2E_BASE_URL ?? DEFAULT_BASE_URL; /** 站内跳转(不整页刷新,避开静态托管的 404 回退);path 为应用内路由(可带 query),如 /system/users */ export const navigate = async (page: Page, path: string) => { diff --git a/e2e/flows.spec.ts b/e2e/flows.spec.ts index 277bd27b..03b5bc3e 100644 --- a/e2e/flows.spec.ts +++ b/e2e/flows.spec.ts @@ -53,7 +53,9 @@ test('工作台 KPI 与明细口径一致:在线设备数等于设备台账筛 await signIn(page); const kpi = page.locator('.ant-card').filter({ hasText: '在线设备' }).first(); await expect(kpi).toBeVisible(); - const online = Number((await kpi.locator('.text-3xl').first().innerText()).match(/\d+/)![0]); + // 千分位感知的解析(与 demo-mainline.spec.ts 同口径):/\d+/ 遇 "1,234" 只取到 1, + // 配合下方 toContainText 会让一致性断言空转 + const online = Number((await kpi.locator('.text-3xl').first().innerText()).match(/[\d,]+/)![0].replace(/,/g, '')); await navigate(page, '/ops/devices'); // 查询表单默认折叠,「状态」在展开后的第二行 await page.locator('.ant-pro-query-filter-collapse-button').click(); diff --git a/nginx/default.conf b/nginx/default.conf index 8c1bfb80..b5099085 100644 --- a/nginx/default.conf +++ b/nginx/default.conf @@ -8,7 +8,8 @@ server { gzip on; gzip_min_length 1024; - gzip_types text/plain text/css application/javascript application/json image/svg+xml; + # application/wasm:Cesium 第三方解码器;model/gltf-binary:public/assets 下的 glb 模型 + gzip_types text/plain text/css application/javascript application/json image/svg+xml application/wasm model/gltf-binary; # 静态镜像不实现 API;缺失后端时明确失败,不能把 SPA HTML 当成接口成功。 # 404 + JSON 与 scripts/serve-dist.mjs(GitHub Pages 等价本地服务器)、vercel.json 的 /api diff --git a/package.json b/package.json index cdff7590..554a9f92 100644 --- a/package.json +++ b/package.json @@ -57,8 +57,6 @@ "@fullcalendar/react": "^7.1.0", "@pansy/amap-api-loader": "^0.4.10", "@tinymce/tinymce-react": "^6.3.0", - "@turf/helpers": "^7.2.0", - "@turf/union": "^7.2.0", "@umijs/max": "^4.7.22", "antd": "^6.6.5", "cesium": "^1.146.0", @@ -66,7 +64,7 @@ "classnames": "^2.5.1", "d3": "^7.9.0", "dayjs": "^1.11.23", - "dompurify": "^3.4.16", + "dompurify": "^3.4.17", "exceljs": "^4.4.0", "html2canvas": "^1.4.1", "mgrs": "^2.2.0", @@ -78,7 +76,7 @@ "react-pdf": "^11.0.0", "signature_pad": "^5.1.4", "temporal-polyfill": "^1.0.5", - "tinymce": "^8.9.2", + "tinymce": "^8.9.3", "tinymce-i18n": "^26.9.28", "wavesurfer.js": "^8.0.1", "xgplayer": "^3.0.26", diff --git a/patches/decode-uri-component@0.2.2.patch b/patches/decode-uri-component@0.2.2.patch index 527bc3e0..5a962477 100644 --- a/patches/decode-uri-component@0.2.2.patch +++ b/patches/decode-uri-component@0.2.2.patch @@ -1,11 +1,17 @@ diff --git a/index.js b/index.js --- a/index.js +++ b/index.js -@@ -1,59 +1,144 @@ +@@ -1,93 +1,156 @@ 'use strict'; -var token = '%[a-f0-9]{2}'; -var singleMatcher = new RegExp('(' + token + ')|([^%]+?)', 'gi'); -var multiMatcher = new RegExp('(' + token + ')+', 'gi'); ++// Backport of upstream fa479dafeede7bedf04e5c89aa78f2a78c664005 (GHSA-vcc3-ghjq-m6fr) ++// plus the single-pass replacement of percent-encoded runs from 0.5.1 (GHSA-qr28-fpjm-wq7f). ++// Retain the 0.2.x CommonJS export and form-style plus decoding used by query-string. ++// Matches one or more consecutive percent-encoded bytes (e.g. `%C3%A5`). ++const token = '%[a-f0-9]{2}'; ++const multiMatcher = new RegExp(`(${token})+`, 'gi'); -function decodeComponents(components, split) { - try { @@ -13,12 +19,6 @@ diff --git a/index.js b/index.js - return [decodeURIComponent(components.join(''))]; - } catch (err) { - // Do nothing -+// Backport of upstream fa479dafeede7bedf04e5c89aa78f2a78c664005 (GHSA-vcc3-ghjq-m6fr). -+// Retain the 0.2.x CommonJS export and form-style plus decoding used by query-string. -+// Matches one or more consecutive percent-encoded bytes (e.g. `%C3%A5`). -+const token = '%[a-f0-9]{2}'; -+const multiMatcher = new RegExp(`(${token})+`, 'gi'); -+ +const hexPair = /^[a-f\d]{2}$/i; + +// Read a `%XX` sequence at `position`, returning the byte value and where to continue scanning. @@ -36,15 +36,12 @@ diff --git a/index.js b/index.js } - split = split || 1; -- ++ return {byte: Number.parseInt(digits, 16), next: position + 3}; ++} + - // Split the array in 2 parts - var left = components.slice(0, split); - var right = components.slice(split); -- -- return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); -+ return {byte: Number.parseInt(digits, 16), next: position + 3}; - } - +/** + * Return how many bytes a UTF-8 code point needs based on its lead byte. + * Returns 0 for continuation bytes and other invalid lead bytes. @@ -53,7 +50,8 @@ diff --git a/index.js b/index.js + if (byte <= 0x7F) { + return 1; + } -+ + +- return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); + // Start at 0xC2 to exclude overlong 2-byte encodings (0xC0/0xC1). + if (byte >= 0xC2 && byte <= 0xDF) { + return 2; @@ -68,8 +66,8 @@ diff --git a/index.js b/index.js + } + + return 0; -+} -+ + } + +function isContinuationByte(byte) { + return byte >= 0x80 && byte <= 0xBF; +} @@ -97,35 +95,73 @@ diff --git a/index.js b/index.js + } - tokens = input.match(singleMatcher) || []; +- } + const firstByte = parsePercentByte(input, position); -+ + +- return input; +- } +-} + // `%` not followed by two hex digits (e.g. `%` or `%G`). + if (!firstByte) { + output += input.charAt(position); + position++; + continue; + } -+ + +-function customDecodeURIComponent(input) { +- // Keep track of all the replacements and prefill the map with the `BOM` +- var replaceMap = { +- '%FE%FF': '\uFFFD\uFFFD', +- '%FF%FE': '\uFFFD\uFFFD' +- }; + const sequenceLength = utf8SequenceLength(firstByte.byte); -+ + +- var match = multiMatcher.exec(input); +- while (match) { +- try { +- // Decode as big chunks as possible +- replaceMap[match[0]] = decodeURIComponent(match[0]); +- } catch (err) { +- var result = decode(match[0]); + // Continuation byte or invalid lead byte — emit one `%XX` literally. + if (sequenceLength === 0) { ++ const pair = input.slice(position, position + 6); + +- if (result !== match[0]) { +- replaceMap[match[0]] = result; ++ // UTF-16 BOM byte pairs become two replacement characters. ++ if (pair === '%FE%FF' || pair === '%FF%FE') { ++ output += '\uFFFD\uFFFD'; ++ position += 6; ++ continue; ++ } ++ + output += input.slice(position, position + 3); + position += 3; + continue; -+ } -+ + } +- } + +- match = multiMatcher.exec(input); +- } + let end = firstByte.next; + let validSequence = true; -+ + +- // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else +- replaceMap['%C2'] = '\uFFFD'; + for (let index = 1; index < sequenceLength; index++) { + const nextByte = parsePercentByte(input, end); -+ + +- var entries = Object.keys(replaceMap); + if (!nextByte || !isContinuationByte(nextByte.byte)) { + validSequence = false; + break; + } -+ + +- for (var i = 0; i < entries.length; i++) { +- // Replace all decoded components +- var key = entries[i]; +- input = input.replace(new RegExp(key, 'g'), replaceMap[key]); + end = nextByte.next; + } + @@ -142,54 +178,21 @@ diff --git a/index.js b/index.js + } + + // Missing continuation bytes or decode failure — emit the first byte literally. -+ output += input.slice(position, position + 3); ++ const literal = input.slice(position, position + 3); ++ ++ // A truncated `%C2` becomes a replacement character. ++ output += literal === '%C2' ? '\uFFFD' : literal; + position += 3; - } - -- return input; -+ return output; - } - } - - function customDecodeURIComponent(input) { - // Keep track of all the replacements and prefill the map with the `BOM` -- var replaceMap = { -+ const replaceMap = { - '%FE%FF': '\uFFFD\uFFFD', -- '%FF%FE': '\uFFFD\uFFFD' -+ '%FF%FE': '\uFFFD\uFFFD', - }; - -- var match = multiMatcher.exec(input); -+ // Find percent-encoded runs separated by literal text or lone `%` characters. -+ let match = multiMatcher.exec(input); ++ } + - while (match) { - try { - // Decode as big chunks as possible - replaceMap[match[0]] = decodeURIComponent(match[0]); -- } catch (err) { -- var result = decode(match[0]); -+ } catch { -+ const result = decode(match[0]); - - if (result !== match[0]) { - replaceMap[match[0]] = result; -@@ -66,29 +151,29 @@ - // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else - replaceMap['%C2'] = '\uFFFD'; - -- var entries = Object.keys(replaceMap); -+ const entries = Object.keys(replaceMap); - -- for (var i = 0; i < entries.length; i++) { -+ for (const key of entries) { - // Replace all decoded components -- var key = entries[i]; - input = input.replace(new RegExp(key, 'g'), replaceMap[key]); ++ return output; } ++} - return input; +- return input; ++function customDecodeURIComponent(input) { ++ // Decode each percent-encoded run in place in a single pass. Decoded output is never rescanned. ++ return input.replace(multiMatcher, run => decode(run)); } -module.exports = function (encodedURI) { @@ -199,11 +202,11 @@ diff --git a/index.js b/index.js + throw new TypeError(`Expected \`encodedURI\` to be of type \`string\`, got \`${typeof encodedURI}\``); } -+ encodedURI = encodedURI.replace(/\+/g, ' '); -+ - try { +- try { - encodedURI = encodedURI.replace(/\+/g, ' '); -- ++ encodedURI = encodedURI.replace(/\+/g, ' '); + ++ try { // Try the built in decoder first return decodeURIComponent(encodedURI); - } catch (err) { @@ -211,5 +214,3 @@ diff --git a/index.js b/index.js // Fallback to a more advanced decoder return customDecodeURIComponent(encodedURI); } - }; -+ diff --git a/playwright.config.ts b/playwright.config.ts index be5f4cc4..8ea54943 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -1,10 +1,11 @@ import { defineConfig, devices } from '@playwright/test'; +import { DEFAULT_BASE_URL } from './e2e/baseUrl'; /** * 浏览器级冒烟:对 GitHub Pages 同构的静态产物(build:github:demo,子路径 /umi-react-admin/)逐路由验证。 * 设置 E2E_BASE_URL 时直接测线上地址(部署后冒烟),否则本地起静态服务器。 */ -const BASE_URL = process.env.E2E_BASE_URL ?? 'http://localhost:4173/umi-react-admin/'; +const BASE_URL = process.env.E2E_BASE_URL ?? DEFAULT_BASE_URL; export default defineConfig({ testDir: 'e2e', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 14effb89..6d9fdc13 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -19,10 +19,11 @@ overrides: colord@<2.9.4: 2.9.4 compression@>=1.0.0 <1.8.2: 1.8.2 cross-spawn@>=7.0.0 <7.0.5: 7.0.6 - dompurify@>=3.0.0 <3.4.16: 3.4.16 + dompurify@>=3.0.0 <3.4.17: 3.4.17 es5-ext@<0.10.63: 0.10.64 esbuild@<0.25.0: 0.25.12 fast-uri@>=3.0.0 <3.1.8: 3.1.8 + follow-redirects@>=1.0.0 <1.16.2: 1.16.2 form-data@>=4.0.0 <4.0.6: 4.0.6 glob@>=10.2.0 <10.5.0: 10.5.0 hono@>=4.0.0 <4.13.7: 4.13.7 @@ -71,7 +72,7 @@ patchedDependencies: '@umijs/preset-umi@4.7.22': 29e2cc1a26b0fdd8bb736ad6a779f06d610518b3a1c5fe358eeb560d6f0c89d5 '@umijs/renderer-react@4.7.22': 0f804f00cada7a343be7d9435b1cd0597bca52228c640ff90f906712018c58e7 braces@3.0.3: 18a4724cb117fb08010e0d8f8aa9684fbd706be3560a12dd4d0e4233d5834acd - decode-uri-component@0.2.2: 4bd5a5e1ec0b95817e4d3a1266b29d7ff4d7065630ae4b35a1f0cdec0de579cc + decode-uri-component@0.2.2: 337cc9f69eb805a7555bdbcde5fca0a3e8f210e97c35338fa6f54c6bd2fd1bf9 exceljs@4.4.0: a02bd99ddda9857e9f25c127e09b6892421f3a7f6a45b0481cb16973fb9ac9f7 node-libs-browser-okam@2.2.5: 74add8ae00cc142e91994ae396ed350dd504d037fca3b8991a608dbe54704559 node-libs-browser@2.2.1: 54c014d704b5d3d291d99ccd2024ef61fc08e6fd4c4e409a47de257c4151a371 @@ -100,13 +101,7 @@ importers: version: 0.4.10 '@tinymce/tinymce-react': specifier: ^6.3.0 - version: 6.3.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(tinymce@8.9.2) - '@turf/helpers': - specifier: ^7.2.0 - version: 7.4.0 - '@turf/union': - specifier: ^7.2.0 - version: 7.4.0 + version: 6.3.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(tinymce@8.10.1) '@umijs/max': specifier: ^4.7.22 version: 4.7.22(@babel/core@7.29.6(supports-color@10.2.2))(@types/node@26.6.2)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(debug@4.4.3(supports-color@10.2.2))(dva@2.5.0-beta.2(encoding@0.1.13)(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(jiti@2.7.0)(lightningcss@1.32.0)(prettier@3.9.9)(rc-field-form@2.7.1(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(rollup@4.63.4)(sass@1.54.0)(styled-jsx@5.1.7(@babel/core@7.29.6(supports-color@10.2.2))(babel-plugin-macros@3.1.0)(react@19.3.0))(supports-color@10.2.2)(type-fest@1.4.0)(typescript@6.0.3)(webpack@5.104.1(clean-css@5.3.3)(csso@4.2.0)(esbuild@0.28.2)(html-minifier-terser@6.1.0)(lightningcss@1.32.0)(postcss@8.5.23))(yaml@2.8.3) @@ -129,8 +124,8 @@ importers: specifier: ^1.11.23 version: 1.11.23 dompurify: - specifier: ^3.4.16 - version: 3.4.16 + specifier: ^3.4.17 + version: 3.4.17 exceljs: specifier: ^4.4.0 version: 4.4.0(patch_hash=a02bd99ddda9857e9f25c127e09b6892421f3a7f6a45b0481cb16973fb9ac9f7) @@ -165,8 +160,8 @@ importers: specifier: ^1.0.5 version: 1.0.5 tinymce: - specifier: ^8.9.2 - version: 8.9.2 + specifier: ^8.9.3 + version: 8.10.1 tinymce-i18n: specifier: ^26.9.28 version: 26.9.28 @@ -906,15 +901,15 @@ packages: '@esbuild-kit/cjs-loader@2.4.4': resolution: {integrity: sha512-NfsJX4PdzhwSkfJukczyUiZGc7zNNWZcEAyqeISpDnn0PTfzMJR1aR8xAIPskBejIxBJbIgCCMzbaYa9SXepIg==} - deprecated: 'Merged into tsx: https://tsx.hirok.io' + deprecated: 'Merged into tsx: https://tsx.is' '@esbuild-kit/core-utils@3.3.2': resolution: {integrity: sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ==} - deprecated: 'Merged into tsx: https://tsx.hirok.io' + deprecated: 'Merged into tsx: https://tsx.is' '@esbuild-kit/esm-loader@2.6.5': resolution: {integrity: sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA==} - deprecated: 'Merged into tsx: https://tsx.hirok.io' + deprecated: 'Merged into tsx: https://tsx.is' '@esbuild/aix-ppc64@0.25.12': resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==} @@ -2352,15 +2347,6 @@ packages: tinymce: optional: true - '@turf/helpers@7.4.0': - resolution: {integrity: sha512-7PAwLZqOdRzTI5g9bHvUwlloAXPDH/mlajtryk0tw4ZwGMtmXsAyF4QundsAMfy4u48Fyd3AUqMXY0SMxqJGWg==} - - '@turf/meta@7.4.0': - resolution: {integrity: sha512-3cLUvlEyDuSnMSzrjhaLAEiYR8xhbfWyTVQlrlEw40xL81d4KF4PqUWbjTXKpXZStdYbet2GCurl79KMypNw6g==} - - '@turf/union@7.4.0': - resolution: {integrity: sha512-SYVtsCW9IznTyKlcGWxssRrf90p/hdpch1UeIcZc31pkSVdmeLOyuzPx0ef3UPmaF//fgXAphMph6JWA/FpKbA==} - '@tweenjs/tween.js@25.0.0': resolution: {integrity: sha512-XKLA6syeBUaPzx4j3qwMqzzq+V4uo72BnlbOjmuljLrRqdsd3qnzvZZoxvMHZ23ndsRS4aufU6JOZYpCbU6T1A==} @@ -2499,9 +2485,6 @@ packages: '@types/express@5.0.6': resolution: {integrity: sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==} - '@types/geojson@7946.0.16': - resolution: {integrity: sha512-6C8nqWur3j98U6+lXDfTUWIfgvZU+EumvpHKcYjujKH7woYyLj2sUmff0tRhrqM7BohUw7Pz3ZB1jj2gW9Fvmg==} - '@types/geojson@7946.0.8': resolution: {integrity: sha512-1rkryxURpr6aWP7R786/UQOkJ3PcpQiWkAXBmdWc7ryFWqN6a4xfK7BtjXvFBKO9LjQ+MWQSWxYeZX1OApnArA==} @@ -3342,9 +3325,6 @@ packages: big.js@5.2.2: resolution: {integrity: sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==} - bignumber.js@9.3.1: - resolution: {integrity: sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==} - binary-extensions@2.2.0: resolution: {integrity: sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==} engines: {node: '>=8'} @@ -4178,8 +4158,8 @@ packages: cpu: [x64] os: [win32] - dompurify@3.4.16: - resolution: {integrity: sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==} + dompurify@3.4.17: + resolution: {integrity: sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==} domutils@2.8.0: resolution: {integrity: sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==} @@ -4630,8 +4610,8 @@ packages: resolution: {integrity: sha512-kWyh8ADvHBFz6ua5xYOPnUroZTT/bwWfrCeL0Wj1dzG4/YOmOcfJ99W8dOVyyynJN35rZ9aCOtHChqQovV7yog==} engines: {node: '>=6'} - follow-redirects@1.16.0: - resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==} + follow-redirects@1.16.2: + resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==} engines: {node: '>=4.0'} peerDependencies: debug: '*' @@ -6241,9 +6221,6 @@ packages: point-in-polygon@1.1.0: resolution: {integrity: sha512-3ojrFwjnnw8Q9242TzgXuTD+eKiutbzyslcq1ydfu82Db2y+Ogbmyrkpv0Hgj31qwT3lbS9+QAAO/pIQM35XRw==} - polyclip-ts@0.16.8: - resolution: {integrity: sha512-JPtKbDRuPEuAjuTdhR62Gph7Is2BS1Szx69CFOO3g71lpJDFo78k4tFyi+qFOMVPePEzdSKkpGU3NBXPHHjvKQ==} - possible-typed-array-names@1.1.0: resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} engines: {node: '>= 0.4'} @@ -7506,9 +7483,6 @@ packages: resolution: {integrity: sha512-1klA3Gi5PD1Wv9Q0wUoOQN1IWAuPu0D1U03ThXTr0cJ20+/iq2tHSDnK7Kk/0LXJ1ztUB2/1Os0wKmfyNgUQfg==} hasBin: true - splaytree-ts@1.0.2: - resolution: {integrity: sha512-0kGecIZNIReCSiznK3uheYB8sbstLjCZLiwcQwbmLhgHJj2gz6OnSPkVzJQCMnmEz1BQ4gPK59ylhBoEWOhGNA==} - split-on-first@1.1.0: resolution: {integrity: sha512-43ZssAJaMusuKWL8sKUBQXHWOpq8d6CfN/u1p4gUzfJkM05C8rxTmYrkIPTXapZpORA6LkkzcUulJ8FqA7Uudw==} engines: {node: '>=6'} @@ -7882,8 +7856,8 @@ packages: tinymce-i18n@26.9.28: resolution: {integrity: sha512-VOMMyvzji7veYm1+8gYpf05A70G308Cc1UCTCqwAgyx+jDqYOKsqssEm1RpdRQlKuPliVHgNg8lkm3jD0Y5gjg==} - tinymce@8.9.2: - resolution: {integrity: sha512-Qh6ADSC0x1F/KsrupfResNJFAaINJQBtfVjx5zxxWJ0ZrGtaKldtAXDMI6uEA57s2n+0rEtXmtbitiU4zV7+0Q==} + tinymce@8.10.1: + resolution: {integrity: sha512-Mgdnx8HuEPRlLqKTyHcy7+JJn9reXH7b7L/1ywPCzKAyjaq8fzEPE+CYBLW42GgBlaaoIOd0dTOcYHUlPZyV2A==} tinyrainbow@3.1.1: resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==} @@ -9179,7 +9153,7 @@ snapshots: '@zip.js/zip.js': 2.17.0 autolinker: 4.1.5 bitmap-sdf: 1.0.4 - dompurify: 3.4.16 + dompurify: 3.4.17 draco3d: 1.5.7 earcut: 3.0.2 grapheme-splitter: 1.0.4 @@ -10670,32 +10644,13 @@ snapshots: optionalDependencies: react-dom: 19.3.0(react@19.3.0) - '@tinymce/tinymce-react@6.3.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(tinymce@8.9.2)': + '@tinymce/tinymce-react@6.3.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(tinymce@8.10.1)': dependencies: prop-types: 15.8.1 react: 19.3.0 react-dom: 19.3.0(react@19.3.0) optionalDependencies: - tinymce: 8.9.2 - - '@turf/helpers@7.4.0': - dependencies: - '@types/geojson': 7946.0.16 - tslib: 2.8.1 - - '@turf/meta@7.4.0': - dependencies: - '@turf/helpers': 7.4.0 - '@types/geojson': 7946.0.16 - tslib: 2.8.1 - - '@turf/union@7.4.0': - dependencies: - '@turf/helpers': 7.4.0 - '@turf/meta': 7.4.0 - '@types/geojson': 7946.0.16 - polyclip-ts: 0.16.8 - tslib: 2.8.1 + tinymce: 8.10.1 '@tweenjs/tween.js@25.0.0': {} @@ -10880,8 +10835,6 @@ snapshots: '@types/express-serve-static-core': 5.1.3 '@types/serve-static': 2.2.0 - '@types/geojson@7946.0.16': {} - '@types/geojson@7946.0.8': {} '@types/hapi__joi@17.1.9': {} @@ -12218,7 +12171,7 @@ snapshots: axios@1.20.0(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2): dependencies: - follow-redirects: 1.16.0(debug@4.4.3(supports-color@10.2.2)) + follow-redirects: 1.16.2(debug@4.4.3(supports-color@10.2.2)) form-data: 4.0.6 https-proxy-agent: 5.0.1(supports-color@10.2.2) proxy-from-env: 2.1.0 @@ -12280,8 +12233,6 @@ snapshots: big.js@5.2.2: {} - bignumber.js@9.3.1: {} - binary-extensions@2.2.0: {} binary@0.3.0: @@ -13002,7 +12953,7 @@ snapshots: decimal.js@10.6.0: {} - decode-uri-component@0.2.2(patch_hash=4bd5a5e1ec0b95817e4d3a1266b29d7ff4d7065630ae4b35a1f0cdec0de579cc): {} + decode-uri-component@0.2.2(patch_hash=337cc9f69eb805a7555bdbcde5fca0a3e8f210e97c35338fa6f54c6bd2fd1bf9): {} deep-is@0.1.4: {} @@ -13135,7 +13086,7 @@ snapshots: domparser-win32-x64-msvc@0.0.7: optional: true - dompurify@3.4.16: + dompurify@3.4.17: optionalDependencies: '@types/trusted-types': 2.0.7 @@ -13900,7 +13851,7 @@ snapshots: flru@1.0.2: {} - follow-redirects@1.16.0(debug@4.4.3(supports-color@10.2.2)): + follow-redirects@1.16.2(debug@4.4.3(supports-color@10.2.2)): optionalDependencies: debug: 4.4.3(supports-color@10.2.2) @@ -15510,11 +15461,6 @@ snapshots: point-in-polygon@1.1.0: {} - polyclip-ts@0.16.8: - dependencies: - bignumber.js: 9.3.1 - splaytree-ts: 1.0.2 - possible-typed-array-names@1.1.0: {} postcss-attribute-case-insensitive@5.0.2(postcss@8.5.23): @@ -15872,7 +15818,7 @@ snapshots: query-string@6.14.1: dependencies: - decode-uri-component: 0.2.2(patch_hash=4bd5a5e1ec0b95817e4d3a1266b29d7ff4d7065630ae4b35a1f0cdec0de579cc) + decode-uri-component: 0.2.2(patch_hash=337cc9f69eb805a7555bdbcde5fca0a3e8f210e97c35338fa6f54c6bd2fd1bf9) filter-obj: 1.1.0 split-on-first: 1.1.0 strict-uri-encode: 2.0.0 @@ -16978,8 +16924,6 @@ snapshots: specificity@0.4.1: {} - splaytree-ts@1.0.2: {} - split-on-first@1.1.0: {} split2@4.2.0: {} @@ -17432,7 +17376,7 @@ snapshots: tinymce-i18n@26.9.28: {} - tinymce@8.9.2: {} + tinymce@8.10.1: {} tinyrainbow@3.1.1: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 439d284d..deeb95f5 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -30,10 +30,11 @@ overrides: 'colord@<2.9.4': '2.9.4' 'compression@>=1.0.0 <1.8.2': '1.8.2' 'cross-spawn@>=7.0.0 <7.0.5': '7.0.6' - 'dompurify@>=3.0.0 <3.4.16': '3.4.16' + 'dompurify@>=3.0.0 <3.4.17': '3.4.17' 'es5-ext@<0.10.63': '0.10.64' 'esbuild@<0.25.0': '0.25.12' 'fast-uri@>=3.0.0 <3.1.8': '3.1.8' + 'follow-redirects@>=1.0.0 <1.16.2': '1.16.2' 'form-data@>=4.0.0 <4.0.6': '4.0.6' 'glob@>=10.2.0 <10.5.0': '10.5.0' 'hono@>=4.0.0 <4.13.7': '4.13.7' diff --git a/scripts/check-bundle-size.mjs b/scripts/check-bundle-size.mjs index 48bbbdef..d1417f35 100644 --- a/scripts/check-bundle-size.mjs +++ b/scripts/check-bundle-size.mjs @@ -124,6 +124,12 @@ if (!existsSync(chunkGraphPath)) { continue; } const files = [...new Set(groups.flatMap((g) => graph[g]))].filter((f) => /\.m?js$/.test(f)); + const missingChunks = files.filter((f) => !existsSync(join(distDir, f))); + // 静默跳过缺失 chunk 会少算总量(chunk 清单过期/产物被裁剪时门禁形同虚设), + // 与上方入口同步脚本的处理同口径:缺失即记 failure + if (missingChunks.length) { + failures.push(`路由 ${route} 首屏的 chunk 在产物中不存在(体积合计会少算):${missingChunks.join(', ')}`); + } const total = files.reduce( (acc, f) => { const file = join(distDir, f); diff --git a/scripts/check-dist-secrets.mjs b/scripts/check-dist-secrets.mjs index b1a4bd3f..91185cf7 100644 --- a/scripts/check-dist-secrets.mjs +++ b/scripts/check-dist-secrets.mjs @@ -66,8 +66,12 @@ const SECRET_PATTERNS = [ [/ghp_[A-Za-z0-9]{36}/, 'GitHub PAT(ghp_)'], [/gho_[A-Za-z0-9]{36}/, 'GitHub OAuth token(gho_)'], [/github_pat_[A-Za-z0-9_]{22,}/, 'GitHub fine-grained PAT'], - [/sk-[A-Za-z0-9]{20,}/, 'sk- 前缀 API key'], + // sk- 的字符类不含 '-',会漏掉 sk-ant-(Anthropic)这类带内嵌连字符的前缀 + [/sk-(?:ant-)?[A-Za-z0-9-]{20,}/, 'sk- 前缀 API key(含 sk-ant-)'], + [/glpat-[A-Za-z0-9_-]{20,}/, 'GitLab PAT(glpat-)'], + [/npm_[A-Za-z0-9]{36}/, 'npm access token(npm_)'], [/xox[bp]-[A-Za-z0-9-]{10,}/, 'Slack token'], + [/AIza[0-9A-Za-z_-]{35}/, 'Google API key(AIza)'], [/-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----/, 'PEM 私钥块'], ]; diff --git a/scripts/dependency-audit.mjs b/scripts/dependency-audit.mjs index 068a2f7f..eee34b42 100644 --- a/scripts/dependency-audit.mjs +++ b/scripts/dependency-audit.mjs @@ -8,8 +8,63 @@ const projectRoot = fileURLToPath(new URL('..', import.meta.url)); const severities = ['info', 'low', 'moderate', 'high', 'critical']; const patchedAdvisories = { 'GHSA-vfj7-8cjw-p6xm': { name: 'braces', version: '3.0.3' }, + // 同一份回移源码同时覆盖 0.5.0 的线性扫描(fa479da)与 0.5.1 的单遍替换: + // 两者的修复都已在 patches/decode-uri-component@0.2.2.patch 里,proof 按安装源 SHA 验证 'GHSA-vcc3-ghjq-m6fr': { name: 'decode-uri-component', version: '0.2.2' }, + 'GHSA-qr28-fpjm-wq7f': { name: 'decode-uri-component', version: '0.2.2' }, }; + +/** + * 构建链根:只出现在这些子树下的依赖不进 dist 产物(打包器/编译器/测试与 lint 工具链)。 + * 分层规则(2026-11-01):进产物的运行时依赖公告保持零忽略、阻塞;构建链传递依赖的公告 + * 降为非阻塞告警——上游(@umijs/max)锁死版本、仓库无法升格,而 GHSA 数据库每次更新都会 + * 把这类公告塞进来,2026-10-21 起已把所有 PR 的 check 连续打红。AUDIT_TOOLCHAIN_STRICT=1 + * 可恢复全量阻塞(用于周期性人工清点)。 + * 判定从宽:一条公告的所有路径都必须命中构建链标记才算构建链;有任何一条旁路即按运行时阻塞。 + */ +const buildChainSegments = [ + // 打包器/编译器子树 + '@umijs/bundler-vite', + '@umijs/bundler-webpack', + '@umijs/bundler-mako', + '@umijs/bundler-utoopack', + '@utoo/pack', + '@umijs/mako', + '@tailwindcss/webpack', + // 测试与 lint 工具链(vitest/jsdom/eslint/stylelint 家族,只在本机与 CI 运行) + 'vitest', + '@vitest/coverage-v8', + '@vitest/eslint-plugin', + 'jsdom', + 'stylelint', + 'eslint', + 'eslint-plugin-react-hooks', + 'eslint-plugin-react', + 'eslint-plugin-jsx-a11y', + 'typescript-eslint', + '@typescript-eslint/parser', + '@typescript-eslint/eslint-plugin', + '@typescript-eslint/type-utils', + '@typescript-eslint/utils', + '@typescript-eslint/typescript-estree', + '@eslint/config-array', + '@eslint/eslintrc', + '@humanwhocodes/config-array', + // 纯 Node 的构建辅助(fsync/临时目录/文件匹配),不存在浏览器形态 + 'file-entry-cache', + 'flat-cache', + 'rimraf', + 'glob', + // exceljs 的 Node 侧流式插件:浏览器入口已被改到 lib/exceljs.bare.js + // (dependency-security.test.ts 断言 manifest.browser),这些子树不进产物 + 'archiver', + 'archiver-utils', + 'zip-stream', + 'readdir-glob', + 'unzipper', + 'fstream', +]; + const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value); /** Reject endpoint/schema failures and retain all severities; an empty or partial response is not success. */ @@ -106,9 +161,25 @@ export const verifyInstalledPatches = (root = projectRoot, proof) => { return verified; }; -export const assessAdvisories = (audit, verified) => { +/** 公告分层:每一条安装路径都只经过构建链子树的公告归入 toolchain,其余(含混合路径)归入 runtime。 */ +export const classifyAdvisories = (audit) => { + const toolchain = []; + const runtime = []; + for (const advisory of Object.values(audit.advisories)) { + // 从宽判定:只要存在任何一条绕开构建链标记的路径,整条公告就按运行时阻塞处理 + const onlyBuildChain = advisory.findings.every((finding) => + finding.paths.every((path) => path.split('>').some((segment) => buildChainSegments.includes(segment))), + ); + (onlyBuildChain ? toolchain : runtime).push(advisory); + } + return { toolchain, runtime }; +}; + +export const assessAdvisories = (audit, verified, { toolchainStrict = false } = {}) => { const proven = []; const blocked = []; + const toolchain = []; + const toolchainIds = new Set(classifyAdvisories(audit).toolchain.map((advisory) => advisory.github_advisory_id)); for (const advisory of Object.values(audit.advisories)) { const expected = patchedAdvisories[advisory.github_advisory_id]; if ( @@ -118,11 +189,13 @@ export const assessAdvisories = (audit, verified) => { advisory.findings.every((finding) => finding.version === expected.version) ) { proven.push(advisory.github_advisory_id); + } else if (toolchainIds.has(advisory.github_advisory_id) && !toolchainStrict) { + toolchain.push(advisory.github_advisory_id); } else { blocked.push(advisory.github_advisory_id); } } - return { proven, blocked }; + return { proven, blocked, toolchain }; }; const run = () => { @@ -153,10 +226,25 @@ const run = () => { }, ); if (regression.error || regression.status !== 0) throw new Error('Installed dependency attack regressions failed'); - const assessment = assessAdvisories(audit, verified); + const assessment = assessAdvisories(audit, verified, { + toolchainStrict: process.env.AUDIT_TOOLCHAIN_STRICT === '1', + }); for (const id of assessment.proven) console.log(`Source repair verified; upstream version match retained: ${id}`); + const toolchainAdvisories = Object.values(audit.advisories).filter((advisory) => + assessment.toolchain.includes(advisory.github_advisory_id), + ); + for (const advisory of toolchainAdvisories) { + console.warn( + `Build-chain advisory (non-blocking): ${advisory.github_advisory_id} ${advisory.module_name}@${advisory.findings + .map((finding) => finding.version) + .join(',')} [${advisory.severity}] — 不进产物;AUDIT_TOOLCHAIN_STRICT=1 可恢复阻塞`, + ); + } + if (toolchainAdvisories.length) { + console.warn(`Build-chain advisories total: ${toolchainAdvisories.length} (non-blocking)`); + } if (assessment.blocked.length) throw new Error(`Unrepaired advisories: ${assessment.blocked.join(', ')}`); - console.log('Dependency gate passed: no advisories without a verified source repair'); + console.log('Dependency gate passed: no runtime advisories without a verified source repair'); }; if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { diff --git a/scripts/dependency-audit.test.ts b/scripts/dependency-audit.test.ts index 721c8d8a..480bdad1 100644 --- a/scripts/dependency-audit.test.ts +++ b/scripts/dependency-audit.test.ts @@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, describe, expect, it } from 'vitest'; -import { assessAdvisories, parseAudit, verifyInstalledPatches } from './dependency-audit.mjs'; +import { assessAdvisories, classifyAdvisories, parseAudit, verifyInstalledPatches } from './dependency-audit.mjs'; const report = (overrides: Record = {}) => ({ advisories: { @@ -28,10 +28,15 @@ describe('依赖审计必须保留原始公告并证明全部实际实例', () = it('源码修补只适用于同一公告、模块和版本,未证明时失败', () => { const audit = parseAudit(JSON.stringify(report())); - expect(assessAdvisories(audit, new Map())).toEqual({ proven: [], blocked: ['GHSA-vfj7-8cjw-p6xm'] }); + expect(assessAdvisories(audit, new Map())).toEqual({ + proven: [], + blocked: ['GHSA-vfj7-8cjw-p6xm'], + toolchain: [], + }); expect(assessAdvisories(audit, new Map([['braces', '3.0.3']]))).toEqual({ proven: ['GHSA-vfj7-8cjw-p6xm'], blocked: [], + toolchain: [], }); const otherVersion = parseAudit(JSON.stringify(report({ findings: [{ version: '3.0.2', paths: ['.>braces'] }] }))); expect(assessAdvisories(otherVersion, new Map([['braces', '3.0.3']])).blocked).toHaveLength(1); @@ -39,7 +44,7 @@ describe('依赖审计必须保留原始公告并证明全部实际实例', () = expect(assessAdvisories(otherModule, new Map([['braces', '3.0.3']])).blocked).toHaveLength(1); }); - it.each(['low', 'moderate', 'high', 'critical'])('任何新 %s 公告都阻断', (severity) => { + it.each(['low', 'moderate', 'high', 'critical'])('任何新的运行时 %s 公告都阻断', (severity) => { const input = report({ github_advisory_id: 'GHSA-new1-new2-new3', severity }); input.metadata.vulnerabilities.high = 0; input.metadata.vulnerabilities[severity as 'low' | 'moderate' | 'high' | 'critical'] = 1; @@ -90,3 +95,70 @@ describe('依赖审计必须保留原始公告并证明全部实际实例', () = expect(() => verifyInstalledPatches(root, proof)).toThrow(/differs/); }); }); + +describe('审计分层:构建链告警不阻塞,运行时零忽略(2026-11-01 政策)', () => { + const one = (id: string, moduleName: string, paths: string[], version = '1.0.0') => ({ + github_advisory_id: id, + module_name: moduleName, + severity: 'moderate', + findings: [{ version, paths }], + }); + const auditOf = (...advisories: ReturnType[]) => + parseAudit( + JSON.stringify({ + advisories: Object.fromEntries(advisories.map((item, index) => [index, item])), + metadata: { + vulnerabilities: { info: 0, low: 0, moderate: advisories.length, high: 0, critical: 0 }, + }, + }), + ); + + it('所有路径都只经过构建链子树的公告归入 toolchain', () => { + const tiers = classifyAdvisories( + auditOf( + one('GHSA-vite', 'vite', [ + '.>@umijs/max>umi>@umijs/preset-umi>@umijs/bundler-vite>vite', + '.>@umijs/preset-umi>@umijs/bundler-vite>@vitejs/plugin-react>vite', + ]), + one('GHSA-undici', 'undici', ['.>@vitest/coverage-v8>vitest>jsdom>undici']), + ), + ); + expect(tiers.toolchain.map((item) => item.github_advisory_id)).toEqual(['GHSA-vite', 'GHSA-undici']); + expect(tiers.runtime).toEqual([]); + }); + + it('任一路径绕开构建链(可进产物或混合可达)即归入 runtime —— 判定从宽', () => { + const tiers = classifyAdvisories( + auditOf( + one('GHSA-mixed', 'minimatch', ['.>eslint>minimatch', '.>some-runtime-lib>minimatch']), + one('GHSA-cesium', 'dompurify', ['.>cesium>@cesium/engine>dompurify']), + ), + ); + expect(tiers.runtime.map((item) => item.github_advisory_id)).toEqual(['GHSA-mixed', 'GHSA-cesium']); + expect(tiers.toolchain).toEqual([]); + }); + + it('构建链公告默认不阻塞,AUDIT_TOOLCHAIN_STRICT 恢复阻塞语义', () => { + const audit = auditOf( + one('GHSA-runtime', 'tinymce', ['.>tinymce']), + one('GHSA-toolchain', 'hono', ['.>@umijs/bundler-utoopack>@utoo/pack>hono']), + ); + const lenient = assessAdvisories(audit, new Map()); + expect(lenient.blocked).toEqual(['GHSA-runtime']); + expect(lenient.toolchain).toEqual(['GHSA-toolchain']); + const strict = assessAdvisories(audit, new Map(), { toolchainStrict: true }); + expect(strict.blocked).toEqual(['GHSA-runtime', 'GHSA-toolchain']); + expect(strict.toolchain).toEqual([]); + }); + + it('已证明源码修复的公告进 proven,与层级无关', () => { + const audit = auditOf( + one('GHSA-vcc3-ghjq-m6fr', 'decode-uri-component', [ + '.>@umijs/history>query-string>decode-uri-component', + ], '0.2.2'), + ); + const assessment = assessAdvisories(audit, new Map([['decode-uri-component', '0.2.2']])); + expect(assessment.proven).toEqual(['GHSA-vcc3-ghjq-m6fr']); + expect(assessment.blocked).toEqual([]); + }); +}); diff --git a/scripts/dependency-patch-proof.json b/scripts/dependency-patch-proof.json index a8dd25e8..ff9d171a 100644 --- a/scripts/dependency-patch-proof.json +++ b/scripts/dependency-patch-proof.json @@ -22,7 +22,7 @@ "decode-uri-component": { "version": "0.2.2", "files": { - "index.js": "5112ff71759fadbfd485235d26e80573eb2837bf15cc3cd8597cf14e9b6c27b5", + "index.js": "90bebf25138e46944409e42263b176eac3005bd2be3b6e55548e84e76b55a87e", "package.json": "8f2e9784337b3b4fa69359f88f75a2847e0aa17776f062cb518d008d8d408bca" } }, diff --git a/scripts/dependency-security.test.ts b/scripts/dependency-security.test.ts index f9e0305b..8718afd1 100644 --- a/scripts/dependency-security.test.ts +++ b/scripts/dependency-security.test.ts @@ -229,6 +229,24 @@ describe('decode-uri-component 的官方回移', () => { expect(source).toContain('while (position < input.length)'); expect(source).not.toContain('decodeComponents'); }); + + it('GHSA-qr28:百分号编码串单遍替换,不再有二次方 replaceMap 循环', () => { + // 上游 0.5.1 的两个特例随单遍扫描落在 decode() 内:UTF-16 BOM 与截断的 %C2 + expect(decode('%FE%FF')).toBe('\uFFFD\uFFFD'); + expect(decode('%FF%FE')).toBe('\uFFFD\uFFFD'); + expect(decode('%C2')).toBe('\uFFFD'); + expect(decode('a%C2b')).toBe('a\uFFFDb'); + const source = read(join(installed(name, '0.2.2'), 'index.js')); + expect(source).toContain('input.replace(multiMatcher'); + expect(source).not.toContain('replaceMap'); + // 大量互不相同的编码串(旧实现的 replaceMap 逐 key 全串扫描是二次方)单遍正确解码 + const big = Array.from({ length: 4000 }, (_, index) => `%${(0x41 + (index % 26)).toString(16)}${index % 10}`).join( + '', + ); + const decoded = decode(big); + expect(decoded).not.toContain('%41'); + expect(decoded.length).toBeLessThanOrEqual(big.length); + }); }); describe('Excel 的真实浏览器工作簿与密码保护', () => { diff --git a/scripts/real-mode-artifact.test.ts b/scripts/real-mode-artifact.test.ts index c4246c65..3788da84 100644 --- a/scripts/real-mode-artifact.test.ts +++ b/scripts/real-mode-artifact.test.ts @@ -21,6 +21,11 @@ const DEMO_DATA_MARKERS = [ const STUB_SENTINEL = '__REAL_MODE_ADAPTER_STUB__'; /** token 替身哨兵:第二个 alias(src/demo/token.real.ts)同样要有正控制 */ const TOKEN_STUB_SENTINEL = '__REAL_MODE_TOKEN_STUB__'; +/** + * clock 替身哨兵:第三个 alias(src/demo/clock.real.ts)。now.ts 只被页面引用, + * 该哨兵只会出现在异步 chunk,因此它的正控制扫描整个 dist 而不只是入口。 + */ +const CLOCK_STUB_SENTINEL = '__REAL_MODE_CLOCK_STUB__'; /** * 门禁上下文(CI 的 build:real 作业)用 REAL_MODE_ARTIFACT_REQUIRED=1 声明「这里必须是真实模式产物」: @@ -134,6 +139,23 @@ const entryChunksContaining = (marker: string) => expect(hits, `以下产物仍含演示数据标记: ${hits.join(', ')}`).toEqual([]); }); + /** + * 第三个正控制:clock 替身哨兵。alias 换掉的是懒加载 chunk 里的 '@/demo/clock', + * 只扫入口必然漏报 —— 扫全部 .js,出现即证明第三个 alias 真的生效; + * 顺带断言演示时钟存储键在异步 chunk 里也消失(这正是加该替身的动机)。 + */ + it.skipIf(demoMode !== false)('真实模式产物含 clock 替身哨兵,且异步 chunk 无演示时钟存储键', () => { + const jsFiles = readdirSync(distDir).filter((name) => name.endsWith('.js')); + const withSentinel = jsFiles.filter((name) => + readFileSync(join(distDir, name), 'utf8').includes(CLOCK_STUB_SENTINEL), + ); + expect(withSentinel, '产物未出现 clock 替身哨兵(第三个 alias 未生效)').not.toEqual([]); + const withClockKey = jsFiles.filter((name) => + readFileSync(join(distDir, name), 'utf8').includes('umi-react-admin:demo-clock'), + ); + expect(withClockKey, '以下异步 chunk 仍含演示时钟存储键').toEqual([]); + }); + /** 真实模式残留面:demo 时钟存储键(旧 adapter → clock 链)与 demo token 前缀都不该出现在入口 */ it.skipIf(demoMode !== false)('真实模式入口 chunk 不含 demo 时钟存储键与 demo token 前缀', () => { expect(entryChunksContaining('umi-react-admin:demo-clock')).toEqual([]); @@ -163,4 +185,12 @@ const entryChunksContaining = (marker: string) => expect(entryChunksContaining('ALM-SCN').length).toBeGreaterThan(0); expect(entryChunksContaining('umi-react-admin:demo-store').length).toBeGreaterThan(0); }); + + /** 反向断言的异步面:演示构建走真实 clock,clock 替身哨兵不得出现在任何 chunk */ + it.skipIf(demoMode !== true)('演示模式产物不含 clock 替身哨兵', () => { + const hits = readdirSync(distDir) + .filter((name) => name.endsWith('.js')) + .filter((name) => readFileSync(join(distDir, name), 'utf8').includes(CLOCK_STUB_SENTINEL)); + expect(hits, '演示产物不应出现真实模式 clock 替身').toEqual([]); + }); }); diff --git a/src/app.tsx b/src/app.tsx index 67ae4a1e..5359438c 100644 --- a/src/app.tsx +++ b/src/app.tsx @@ -8,6 +8,7 @@ import ErrorBoundary from '@/components/ErrorBoundary'; import GroupNav from '@/components/GroupNav'; import GuideTour from '@/components/GuideTour'; import PageTransition from '@/components/PageTransition'; +import { REPO_URL as REPO } from '@/constants/repo'; import { syncColorScheme } from '@/hooks/useThemeMode'; import RightContent from '@/layouts/RightContent'; import Forbidden from '@/pages/Exception/403'; @@ -115,8 +116,6 @@ const AccessFallback = () => { return ; }; -import { REPO_URL as REPO } from '@/constants/repo'; - /** 左上角应用列表:项目相关链接(图标用内置图标,不再热链第三方图片,CSP 随之收紧) */ const appList = () => { const t = (id: string) => getIntl().formatMessage({ id }); diff --git a/src/components/CommandPalette/index.tsx b/src/components/CommandPalette/index.tsx index 5f3e55b9..525a527c 100644 --- a/src/components/CommandPalette/index.tsx +++ b/src/components/CommandPalette/index.tsx @@ -1,3 +1,4 @@ +import { isMac } from '@/utils/platform'; import { canAccessRoute, type NavRoute } from '@/utils/routeNav'; import { SearchOutlined } from '@ant-design/icons'; import { history, useAccess, useAppData, useIntl } from '@umijs/max'; @@ -35,8 +36,6 @@ export const filterEntries = (entries: NavEntry[], query: string, labelOf: (entr return entries.filter((entry) => labelOf(entry).toLowerCase().includes(q) || entry.path.toLowerCase().includes(q)); }; -const isMac = () => /Mac|iPhone|iPad/.test(navigator.platform); - /** * ⌘K / Ctrl+K 命令面板:全站页面按名直达,弥补宽信息架构下「目标页在哪个分组」的记忆成本, * 也是窄屏页签横滚之外的补救路径。键盘优先(↑↓ 选、Enter 开、Esc 关),权限过滤与菜单同口径。 diff --git a/src/demo/generate.test.ts b/src/demo/generate.test.ts index c5acd5b4..ca0819ca 100644 --- a/src/demo/generate.test.ts +++ b/src/demo/generate.test.ts @@ -183,7 +183,9 @@ describe('工单', () => { expect(data.tickets.filter((x) => x.resolvedAt && t(x.resolvedAt) > since).length).toBeGreaterThan(5); }); - it('两周内任意时刻,「处理中」都不少于 5 张(拖拽演示不至于只剩一两张卡)', () => { + // 56 次全量 generateDataset 单跑约 2.1s;并发负载下会顶爆 5s 默认超时(2026-10-31 实测 flaky), + // 用例本身是固定种子、完全确定性——显式放宽超时只影响等待上限,不放松断言 + it('两周内任意时刻,「处理中」都不少于 5 张(拖拽演示不至于只剩一两张卡)', { timeout: 20_000 }, () => { const counts = Array.from({ length: 14 }, (_, d) => [3, 10, 15, 21].map( (hour) => diff --git a/src/demo/generate.ts b/src/demo/generate.ts index 0bbe3da2..6fc8ca61 100644 --- a/src/demo/generate.ts +++ b/src/demo/generate.ts @@ -387,7 +387,9 @@ const generateAlarmsAndTickets = (locale: DemoLocale, now: Date, devices: Device draft.resolve *= scale; } } else if (draft.closeAfter > remaining - MINUTE) { - draft.closeAfter = Math.max(5_000, remaining * 0.5); + // 钳到剩余时间内:remaining < 5s 时 5000ms 下限会越过 now,告警滞留为 active, + // 违反「在线设备不带未恢复阻断告警」的 P3-1 不变式 + draft.closeAfter = Math.min(Math.max(5_000, remaining * 0.5), remaining); } } const id = `ALM-${key}-${String(index + 1).padStart(3, '0')}`; diff --git a/src/demo/manifest.test.ts b/src/demo/manifest.test.ts index d90f4c67..7f808fbb 100644 --- a/src/demo/manifest.test.ts +++ b/src/demo/manifest.test.ts @@ -10,6 +10,14 @@ import { STORE_KEY, STORE_VERSION } from './store'; */ const MANIFEST_PATH = new URL('../../docs/demo/demo-scenarios.json', import.meta.url); +/** 体验账号 → 角色 key(与 scenarios.ts 的种子角色同一映射;查表取代四层嵌套三元) */ +const ROLE_KEY: Record = { + admin: 'admin', + lead: 'lead', + operator: 'operator', + analyst: 'analyst', +}; + const buildManifest = () => ({ // 与存储版本同源:升 STORE_VERSION 时清单随之变化,提醒重新生成 version: STORE_VERSION, @@ -18,16 +26,7 @@ const buildManifest = () => ({ accounts: DEMO_ACCOUNTS.map((username) => ({ username, password: 'demo', - roleKey: - username === 'admin' - ? 'admin' - : username === 'lead' - ? 'lead' - : username === 'operator' - ? 'operator' - : username === 'analyst' - ? 'analyst' - : 'viewer', + roleKey: ROLE_KEY[username] ?? 'viewer', })), clock: { live: '跟随真实时间;演示后端每请求检查,跨过 60 秒即按当前时钟重建基础数据(补丁保留)', diff --git a/src/demo/scenarios.ts b/src/demo/scenarios.ts index 89b74750..061018e4 100644 --- a/src/demo/scenarios.ts +++ b/src/demo/scenarios.ts @@ -676,7 +676,11 @@ export const verifyScenarios = (dataset: Dataset, now: Date): string[] => { const rework = byId(dataset.tickets, SCENARIO_IDS.reworkTicket); if (rework && !rework.acceptance?.signature) problems.push('rework ticket must carry a pre-seeded acceptance signature'); - if (rework && new Date(rework.acceptance!.signedAt).getTime() < new Date(rework.resolvedAt!).getTime()) { + // 验收可能缺席(上一条只记录 problem):这里必须可空链,否则 verifyScenarios 自己先 TypeError + if ( + rework?.acceptance?.signedAt && + new Date(rework.acceptance.signedAt).getTime() < new Date(rework.resolvedAt!).getTime() + ) { problems.push('rework acceptance must be signed after resolution'); } [SCENARIO_IDS.accept1, SCENARIO_IDS.accept2].forEach((id) => { diff --git a/src/demo/server/index.ts b/src/demo/server/index.ts index d298fa4b..398544d1 100644 --- a/src/demo/server/index.ts +++ b/src/demo/server/index.ts @@ -8,7 +8,7 @@ import { DemoStore, type StorageLike } from '../store'; import { verifyDemoToken } from '../token'; import { BizFailure, HttpError, type DemoRequest, type DemoResponse } from './http'; import { message } from './messages'; -import { resolvePermissions, routes, type Route, type Session } from './routes'; +import { PROTECTED_USERNAMES, resolvePermissions, routes, type Route, type Session } from './routes'; export type { DemoRequest, DemoResponse } from './http'; @@ -49,8 +49,10 @@ export const createDemoServer = (options: { locale: DemoLocale; storage?: Storag const payload = matched ? verifyDemoToken(matched[1]) : null; if (!payload) return undefined; const user = store.dataset.users.find((u) => u.username.toLowerCase() === payload.name.toLowerCase()); - // 种子用户被停用后,已签发的 token 随之失效 + // 种子用户被停用后,已签发的 token 随之失效;被删除同理——否则 admin 种子账号删除后 + // 其 token 会走「无用户记录」路径,继续保留 admin 角色全部权限 if (user && user.status !== 'active') return undefined; + if (!user && PROTECTED_USERNAMES.has(payload.name.toLowerCase())) return undefined; return { username: payload.name, role: payload.role, @@ -59,6 +61,15 @@ export const createDemoServer = (options: { locale: DemoLocale; storage?: Storag }; }; + /** 路径参数解码:畸形百分号编码(如 /tickets/%E4%25)按 400 响应,而不是抛裸 URIError 逃过异常分类 */ + const decodeParam = (value: string): string => { + try { + return decodeURIComponent(value); + } catch { + throw new HttpError(400, message('notFound', locale)); + } + }; + const handle = (request: DemoRequest): DemoResponse => { const method = request.method.toUpperCase(); const url = new URL(request.url, 'http://demo.local'); @@ -68,7 +79,7 @@ export const createDemoServer = (options: { locale: DemoLocale; storage?: Storag // 时钟推进检查(F09):live 模式下跨过阈值按当前时间重建基础数据(补丁保留);受控模式时钟冻结不会触发 store.refreshIfStale(); const values = url.pathname.match(route.pattern)!.slice(1); - const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(values[i])])); + const params = Object.fromEntries(route.keys.map((key, i) => [key, decodeParam(values[i])])); const query = { ...Object.fromEntries(url.searchParams), ...(request.params ?? {}) }; const session = resolveSession(request.headers?.Authorization ?? request.headers?.authorization); if (route.access !== 'public' && !session) throw new HttpError(401, message('unauthorized', locale)); diff --git a/src/demo/server/messages.ts b/src/demo/server/messages.ts index 6784fe66..506297cb 100644 --- a/src/demo/server/messages.ts +++ b/src/demo/server/messages.ts @@ -74,6 +74,10 @@ const MESSAGES = { zh: '导入请求结构不合法,未写入任何数据', en: 'The import request is malformed; nothing was written', }, + actionInvalid: { + zh: '操作类型不在支持范围内', + en: 'The action is not one of the supported kinds', + }, } as const; export type MessageKey = keyof typeof MESSAGES; diff --git a/src/demo/server/routes.ts b/src/demo/server/routes.ts index f03aedc8..f605e8d6 100644 --- a/src/demo/server/routes.ts +++ b/src/demo/server/routes.ts @@ -77,7 +77,8 @@ const DEPARTMENT_KEYS = DEPARTMENTS.map((d) => d.key); const USER_STATUSES: UserStatus[] = ['active', 'disabled', 'locked']; const EVENT_TYPES: EventType[] = ['duty', 'inspection', 'review', 'training', 'maintenance', 'release']; /** 受保护账号:五种快捷体验账号不能被停用/删除/改名,避免演示自断入口 */ -const PROTECTED_USERNAMES = new Set(['admin', 'guest', 'lead', 'operator', 'analyst']); +/** 体验/种子账号名:既是受保护账号,也是「删除后 token 必须失效」的判定集合(见 server/index.ts) */ +export const PROTECTED_USERNAMES = new Set(['admin', 'guest', 'lead', 'operator', 'analyst']); const BOARD_DONE_DAYS = 3; /** 批量用户动作 → 操作日志 action(与单条 DELETE/PUT 保持同一套命名,便于按 action 过滤) */ @@ -109,9 +110,13 @@ let logSeq = 0; /** 把演示后端里发生的写操作记进操作日志(日志页能看到自己的操作) */ const writeLog = (ctx: RouteContext, action: LogAction, target: string, result: OperationLog['result'] = 'success') => { const now = ctx.store.now(); - logSeq += 1; ctx.store.create('logs', { - id: `LOG-${now.getTime().toString(36).toUpperCase()}-${logSeq}`, + // 时间基 + 进程序号在冻结时钟/重载下都会撞号(锚点相同、logSeq 归零):补随机后缀保证唯一, + // 日志页按 id 渲染 key,撞号会破坏受控场景里「跨重载保持」的补丁数据 + id: `LOG-${now.getTime().toString(36).toUpperCase()}-${(logSeq++).toString(36).toUpperCase()}-${Math.random() + .toString(36) + .slice(2, 6) + .toUpperCase()}`, actorId: ctx.session?.user?.id ?? '', actorName: ctx.session?.user?.name ?? ctx.session?.username ?? '', action, @@ -270,7 +275,8 @@ const USER_WRITE_KEYS = ['name', 'username', 'email', 'department', 'status'] as const pickUserInput = (ctx: RouteContext, body: Record) => { const input: Partial = {}; USER_WRITE_KEYS.forEach((key) => { - if (body[key] !== undefined) (input as Record)[key] = body[key]; + // null 不在「未传」语义里:曾绕过校验(String(null)='null' 过正则)后经 store 落成字段删除 + if (body[key] !== undefined && body[key] !== null) (input as Record)[key] = body[key]; }); if (typeof input.username === 'string') input.username = input.username.trim().toLowerCase(); if (typeof input.name === 'string') input.name = input.name.trim(); @@ -519,6 +525,8 @@ export const routes: Route[] = [ handle: (ctx) => { const ids = Array.isArray(ctx.body.ids) ? (ctx.body.ids as string[]) : []; const action = ctx.body.action as UserBatchAction; + // 枚举先行:任意值曾被 `as` 直通,'banana' 之类会静默把整批用户禁用并写出无 action 的日志 + if (!BATCH_LOG_ACTION[action]) failWith(ctx, 400, 'actionInvalid'); if (action === 'delete') requirePermission(ctx, 'system.user.delete'); const users = ids.map((id) => findUser(ctx, id)); // 整批判定、先于任何写入:混入一个 admin / lead 账号整批 403,不会先处理前面的普通账号(启用同样算) @@ -752,6 +760,10 @@ export const routes: Route[] = [ const alarm = data(ctx).alarms.find((a) => a.id === ctx.params.id) ?? notFound(ctx); if (alarm.status !== 'active') fail(ctx, 'alarmClosed'); const action = ctx.body.action as AlarmHandleAction; + // 枚举校验:未知值曾被 else 分支一律按「误报」关单并写 misleading 日志 + if (action !== 'ticket' && action !== 'recover' && action !== 'falsePositive') { + failWith(ctx, 400, 'actionInvalid'); + } const now = nowIso(ctx); if (action === 'ticket') { const device = data(ctx).devices.find((d) => d.id === alarm.deviceId)!; @@ -924,9 +936,34 @@ export const routes: Route[] = [ handle: (ctx) => { const event = data(ctx).events.find((e) => e.id === ctx.params.id) ?? notFound(ctx); const changes: Partial = {}; - (['title', 'type', 'start', 'end', 'allDay'] as const).forEach((key) => { - if (key in ctx.body) (changes as Record)[key] = ctx.body[key] ?? undefined; - }); + const body = ctx.body; + const hasValue = (value: unknown): value is NonNullable => value !== undefined && value !== null; + // 部分更新复用 POST 的校验口径(修复前 PUT 直通:{title:null} 删标题、'garbage' 也能当日期)。 + // title/type/start 不可清空:出现即必须是合法值;end 允许显式清空(去掉结束时间)。 + if ('title' in body) { + const { title } = body; + if (typeof title !== 'string' || !title.trim()) fail(ctx, 'titleRequired'); + changes.title = (title as string).trim(); + } + if ('type' in body && hasValue(body.type)) { + if (!EVENT_TYPES.includes(body.type as EventType)) fail(ctx, 'notFound'); + changes.type = body.type as EventType; + } + if ('start' in body && hasValue(body.start)) { + if (Number.isNaN(new Date(String(body.start)).getTime())) fail(ctx, 'notFound'); + changes.start = String(body.start); + } + if ('end' in body && hasValue(body.end)) { + if (Number.isNaN(new Date(String(body.end)).getTime())) fail(ctx, 'notFound'); + changes.end = String(body.end); + } else if ('end' in body) { + changes.end = undefined; + } + if ('allDay' in body && hasValue(body.allDay)) changes.allDay = !!body.allDay; + const effectiveStart = changes.start !== undefined ? new Date(changes.start) : new Date(event.start); + const effectiveEnd = + changes.end !== undefined ? new Date(changes.end) : event.end ? new Date(event.end) : undefined; + if (effectiveEnd && effectiveStart.getTime() > effectiveEnd.getTime()) fail(ctx, 'notFound'); const updated = ctx.store.update('events', event.id, changes); writeLog(ctx, 'scheduleUpdate', event.id); return updated; diff --git a/src/demo/server/server.test.ts b/src/demo/server/server.test.ts index 21cf4656..8a698ec0 100644 --- a/src/demo/server/server.test.ts +++ b/src/demo/server/server.test.ts @@ -219,6 +219,21 @@ describe('工单与告警', () => { const again = call('POST', `/api/v1/alarms/${alarm.id}/handle`, { token, body: { action: 'recover' } }); expect(again.body.success).toBe(false); }); + + it('未知的处置/批量动作返回 400,不再静默按误报/停用处理', () => { + const token = loginAs('admin'); + const alarm = server.store.dataset.alarms.find((a) => a.status === 'active')!; + // 修复前:未知 action 走 else 分支,一律按误报关单并写日志 + const bad = call('POST', `/api/v1/alarms/${alarm.id}/handle`, { token, body: { action: 'banana' } }); + expect(bad.status).toBe(400); + expect(server.store.dataset.alarms.find((a) => a.id === alarm.id)).toMatchObject({ status: 'active' }); + + const target = server.store.dataset.users.find((u) => u.username === 'guest')!; + // 修复前:未知批量 action 会把整批用户 disable + const batch = call('POST', '/api/v1/users/batch', { token, body: { ids: [target.id], action: 'banana' } }); + expect(batch.status).toBe(400); + expect(server.store.dataset.users.find((u) => u.id === target.id)).toMatchObject({ status: 'active' }); + }); }); describe('演示数据存储', () => { diff --git a/src/demo/store.ts b/src/demo/store.ts index 5878f6c6..28935976 100644 --- a/src/demo/store.ts +++ b/src/demo/store.ts @@ -44,8 +44,12 @@ const emptyPatch = (): CollectionPatch => ({ created: [], updated: {}, deleted: * 字段为 undefined 表示「清除该字段」(如工单退回处理中要清掉完成时间)。 * JSON 会丢掉 undefined,所以补丁里记成 null,应用补丁时 null 同样视为删除。 */ +const UNSAFE_PATCH_KEYS = new Set(['__proto__', 'constructor', 'prototype']); const applyChanges = (target: Record, changes: Record) => { Object.entries(changes).forEach(([key, value]) => { + // JSON.parse 会把 "__proto__" 造成自有属性,Object.entries 能枚举到; + // 赋值则走 Object.prototype 的 setter 直接改写记录原型(持久化补丁不可信时的原型污染) + if (UNSAFE_PATCH_KEYS.has(key)) return; if (value === undefined || value === null) { delete target[key]; } else { diff --git a/src/layouts/RightContent.tsx b/src/layouts/RightContent.tsx index a47b5e9c..35b54e68 100644 --- a/src/layouts/RightContent.tsx +++ b/src/layouts/RightContent.tsx @@ -7,6 +7,7 @@ import { logout } from '@/services/auth'; import { getDemoClock, resetDemoData, switchDemoScenario } from '@/services/system'; import { avatarColor, avatarText } from '@/utils/avatar'; import { formatDateTime } from '@/utils/format'; +import { isMac } from '@/utils/platform'; import { DownOutlined, FieldTimeOutlined, @@ -148,7 +149,7 @@ const RightContent = () => { { mode: t(dark ? 'header.themeLight' : 'header.themeDark') }, ); // ⌘K / Ctrl+K 随平台显示(与命令面板内部判定同一口径) - const searchLabel = `${t('header.search')} (${/Mac|iPhone|iPad/.test(navigator.platform) ? '⌘K' : 'Ctrl+K'})`; + const searchLabel = `${t('header.search')} (${isMac() ? '⌘K' : 'Ctrl+K'})`; return ( // backgroundColor 内联写死:ProLayout 会给 actions 容器的这个直接子元素刷一层淡底(hover 时 diff --git a/src/pages/Components/Calendar/index.tsx b/src/pages/Components/Calendar/index.tsx index 7448f340..9bfe373e 100644 --- a/src/pages/Components/Calendar/index.tsx +++ b/src/pages/Components/Calendar/index.tsx @@ -182,7 +182,13 @@ export default function Calendar() { refetch(); }; - /** 拖动 / 拉伸改期:写回接口,失败则还原 */ + // validateFields 对「标题为空」的拒绝会以字段错误形式展示:onPressEnter / onOk 直接挂 + // 原函数会把该拒绝变成 unhandled rejection(弹窗保持打开是期望行为,吞掉即可) + const handleCreateSafe = () => { + void handleCreate().catch(() => undefined); + }; + + /** 拖动 / 拉伸改期:写回接口,失败则还原;成功后 refetch(「接下来」侧栏此前一直滞留旧时段) */ const handleChange = async ({ event, revert }: EventChangeInfo) => { try { await updateEvent(event.id, { @@ -191,6 +197,7 @@ export default function Calendar() { allDay: event.allDay, }); message.success(t('calendar.saved')); + refetch(); } catch { revert(); } @@ -205,6 +212,13 @@ export default function Calendar() { viewing.remove(); setViewing(undefined); message.success(t('common.deleted')); + // 侧栏「接下来」此前不随删除刷新,被删日程一直挂到下一次新建 + refetch(); + }; + + // Popconfirm 的 onConfirm 也会丢弃返回的 promise(antd v6 无加载契约):失败就地吞掉 + const handleDeleteSafe = () => { + void handleDelete().catch(() => undefined); }; return ( @@ -315,7 +329,7 @@ export default function Calendar() { key="delete" title={t('calendar.deleteConfirm', { title: viewing?.title ?? '' })} okButtonProps={{ danger: true }} - onConfirm={handleDelete} + onConfirm={handleDeleteSafe} > , @@ -337,13 +351,13 @@ export default function Calendar() { setDraft(undefined)} destroyOnHidden >
- + diff --git a/src/pages/Dashboard/components/RegionOnline.tsx b/src/pages/Dashboard/components/RegionOnline.tsx index a5062cd3..e6616c9d 100644 --- a/src/pages/Dashboard/components/RegionOnline.tsx +++ b/src/pages/Dashboard/components/RegionOnline.tsx @@ -10,7 +10,8 @@ export default function RegionOnline({ data, height }: { data: DashboardOverview const rows = data .map((row) => ({ region: intl.formatMessage({ id: `region.${row.region}` }), - rate: Math.round((row.online / row.total) * 1000) / 10, + // total 为 0 的大区此前会算出 NaN%(NaN 还会污染按 rate 的排序):按 0 处理 + rate: row.total ? Math.round((row.online / row.total) * 1000) / 10 : 0, detail: intl.formatMessage({ id: 'dashboard.regions.online' }, { online: row.online, total: row.total }), })) .sort((a, b) => b.rate - a.rate); diff --git a/src/pages/Document/Pdf/pdfPreflight.test.ts b/src/pages/Document/Pdf/pdfPreflight.test.ts index 6e34f223..64318887 100644 --- a/src/pages/Document/Pdf/pdfPreflight.test.ts +++ b/src/pages/Document/Pdf/pdfPreflight.test.ts @@ -183,6 +183,25 @@ describe('解码放大预算', () => { expect(report.stats.estimatedFilterStreams).toBe(1); expect(report.violations[0].code).toBe('decodedBytes'); }); + + it('Flate 首层后再挂放大层(双层 Flate)也保守估算,不绕过预算', HEAVY, () => { + // /Filter [/FlateDecode /FlateDecode]:我们只能解出第一层的字节数,第二层 Flate 的 + // 展开无从计量——修复前这里按 kind:'flate' 计账,双层 Flate 炸弹可绕过解码预算。 + const payload = incompressible(3 * 1024 * 1024); + const report = preflightPdf(flateContentPdf(payload, '/Filter [/FlateDecode /FlateDecode]')); + expect(report.ok).toBe(false); + expect(report.stats.estimatedFilterStreams).toBe(1); + expect(report.violations[0].code).toBe('decodedBytes'); + }); + + it('Flate 首层后是缩小编码时仍按真实解码计数(不过度拒绝)', HEAVY, () => { + const report = preflightPdf( + flateContentPdf(new Uint8Array(2 * 1024 * 1024), '/Filter [/FlateDecode /ASCIIHexDecode]'), + ); + expect(report.ok).toBe(true); + expect(report.stats.decodedStreamBytes).toBe(2 * 1024 * 1024); + expect(report.stats.estimatedFilterStreams).toBe(0); + }); }); describe('页树放大预算', () => { diff --git a/src/pages/Document/Pdf/pdfPreflight.ts b/src/pages/Document/Pdf/pdfPreflight.ts index dc06b6b7..e7d25797 100644 --- a/src/pages/Document/Pdf/pdfPreflight.ts +++ b/src/pages/Document/Pdf/pdfPreflight.ts @@ -1258,8 +1258,15 @@ class Preflight { } if (names.length === 0) return { kind: 'plain', estimated: raw }; const [firstDecoder] = names; - if (FLATE_FILTERS.has(firstDecoder)) return { kind: 'flate' }; const amplifying = (name: string) => !NON_AMPLIFYING.has(name) && !IMAGE_CODERS.has(name); + if (FLATE_FILTERS.has(firstDecoder)) { + // [/FlateDecode /FlateDecode] 这类链:第一层我们只解出其输出字节数,其后若还有 + // 放大层(第二个 Flate、LZW、RunLength…),其展开无法计量——与缩小编码分支同口径, + // 按倍数保守估算,宁可多算不可漏计(曾只看 firstDecoder,双层 Flate 可绕过预算)。 + return names.slice(1).some(amplifying) + ? { kind: 'amplifying', estimated: raw * this.budgets.unknownFilterAmplification } + : { kind: 'flate' }; + } if (IMAGE_CODERS.has(firstDecoder)) return { kind: 'plain', estimated: raw }; if (NON_AMPLIFYING.has(firstDecoder)) { // 盔甲/缩小编码本身不放大;只有其后确实还有放大层时才保守估算, diff --git a/src/pages/Map/Amap/index.tsx b/src/pages/Map/Amap/index.tsx index 03ef7caf..372fb842 100644 --- a/src/pages/Map/Amap/index.tsx +++ b/src/pages/Map/Amap/index.tsx @@ -43,6 +43,17 @@ export default function Amap() { const mapRef = useRef(undefined); const markersRef = useRef<{ device: Device; marker: AMap.CircleMarker }[]>([]); const [filter, setFilter] = useState('all'); + // 地图(含 marker)是异步重建的:重建后必须重放当前过滤,并把 filter effect 的依赖指向 + // 新一代 marker(否则暗色切换重建地图后,已有的状态过滤被静默丢弃) + const [mapEpoch, setMapEpoch] = useState(0); + const filterRef = useRef(filter); + filterRef.current = filter; + const applyFilter = () => { + const current = filterRef.current; + markersRef.current.forEach(({ device, marker }) => + current === 'all' || device.status === current ? marker.show() : marker.hide(), + ); + }; const [loadError, setLoadError] = useState(); const [selected, setSelected] = useState(); const infoWindowRef = useRef(undefined); @@ -97,6 +108,9 @@ export default function Amap() { map.add(marker); return { device, marker }; }); + // marker 是异步创建的:filter effect 首轮跑在它之前,这里补一次当前过滤的落地 + applyFilter(); + setMapEpoch((n) => n + 1); }) .catch((error: unknown) => !disposed && setLoadError(error instanceof Error ? error.message : String(error))); return () => { @@ -118,7 +132,7 @@ export default function Amap() { markersRef.current.forEach(({ device, marker }) => filter === 'all' || device.status === filter ? marker.show() : marker.hide(), ); - }, [filter, devices]); + }, [filter, mapEpoch]); return ( (undefined); const devicesRef = useRef([]); + // 提交图形层(start/clear 会整层清空)与预览实体分离:橡皮筋/预览边/圆预览/测量线 + // 若与提交图形同层,首次 start() 的 removeAll() 就会把它们移出可视化管线,之后 + // show=true 全部作用在已脱管实体上——四种实时预览静默失效 const layerRef = useRef(null); + const previewsRef = useRef([]); const highlightRef = useRef(null); // 各工具的进行时状态(不进 React state,避免每帧渲染) const boxDragRef = useRef<{ start?: [number, number]; current?: [number, number] }>({}); @@ -63,8 +67,13 @@ export default function BoxSelect() { const measureRef = useRef<[number, number][]>([]); devicesRef.current = devices ?? []; toolRef.current = tool; + // fmtLen 被 onReady 里的 CallbackProperty/标签闭包长期持有,直接读 state 会冻结在首次渲染的 + // 单位上(切 km→nmi 后侧板变了、圆半径与量测标签不变):走 ref 取当前值 + const unitsRef = useRef(units); + unitsRef.current = units; - const fmtLen = (km: number) => (units === 'km' ? `${km.toFixed(1)} km` : `${(km * NMI_PER_KM).toFixed(1)} nmi`); + const fmtLen = (km: number) => + unitsRef.current === 'km' ? `${km.toFixed(1)} km` : `${(km * NMI_PER_KM).toFixed(1)} nmi`; const { containerRef, viewer, error, basemapFailed, retry } = useCesiumViewer({ home: [108, 35, 4_600_000], @@ -73,13 +82,16 @@ export default function BoxSelect() { const layer = new Cesium.CustomDataSource('select'); instance.dataSources.add(layer); layerRef.current = layer; + // 预览实体专层:从不清空,仅靠 show 开关(见上方 previewsRef 注释) + const previewLayer = new Cesium.CustomDataSource('select-preview'); + instance.dataSources.add(previewLayer); const cursor = (next?: Tool) => { (instance.container as HTMLElement).style.cursor = next ? 'crosshair' : ''; }; /* 矩形:按住拖拽(LEFT_DOWN 起点、MOUSE_MOVE 橡皮筋、LEFT_UP 定选) */ - const rubberBand = layer.entities.add({ + const rubberBand = previewLayer.entities.add({ rectangle: { coordinates: new Cesium.CallbackProperty(() => { const { start, current } = boxDragRef.current; @@ -100,7 +112,7 @@ export default function BoxSelect() { /* 多边形:点击加点 + 指向光标的预览边;双击收口(光标点存闭包变量,每帧变不值 setState) */ let polygonCursor: [number, number] | undefined; - const previewLine = layer.entities.add({ + const previewLine = previewLayer.entities.add({ polyline: { positions: new Cesium.CallbackProperty(() => { const points = polygonRef.current; @@ -122,7 +134,7 @@ export default function BoxSelect() { const { center, edge } = circleRef.current; return center && edge ? distanceKm(center, edge) : 0; }; - const circlePreview = layer.entities.add({ + const circlePreview = previewLayer.entities.add({ ellipse: { semiMajorAxis: new Cesium.CallbackProperty(() => circleRadiusKm() * 1000, false), semiMinorAxis: new Cesium.CallbackProperty(() => circleRadiusKm() * 1000, false), @@ -146,7 +158,7 @@ export default function BoxSelect() { circlePreview.show = false; /* 量测:多段折线 + 逐段标注 + 累计 */ - const measureLine = layer.entities.add({ + const measureLine = previewLayer.entities.add({ polyline: { positions: new Cesium.CallbackProperty(() => { const seq = measureRef.current.flatMap((p) => [p[0], p[1]]); @@ -158,6 +170,7 @@ export default function BoxSelect() { }, }); measureLine.show = false; + previewsRef.current = [rubberBand, previewLine, circlePreview, measureLine]; const finishMeasure = () => { const points = measureRef.current; @@ -310,7 +323,11 @@ export default function BoxSelect() { return () => { handler.destroy(); polygonCursor = undefined; - if (!instance.isDestroyed()) instance.dataSources.remove(layer, true); + previewsRef.current = []; + if (!instance.isDestroyed()) { + instance.dataSources.remove(previewLayer, true); + instance.dataSources.remove(layer, true); + } }; }, }); @@ -337,27 +354,29 @@ export default function BoxSelect() { }); }, [viewer, hoverDevice]); - const start = (next: Tool) => { + // 只清提交图形层;预览实体在专层上常驻,随工具状态重置一并隐藏 + const resetShapes = () => { layerRef.current?.entities.removeAll(); + previewsRef.current.forEach((entity) => { + entity.show = false; + }); boxDragRef.current = {}; polygonRef.current = []; circleRef.current = {}; measureRef.current = []; setSelected(undefined); setMeasureTotal(undefined); + }; + + const start = (next: Tool) => { + resetShapes(); setTool(next); // viewer 未就绪(首帧、底图重试换实例的空窗)时只切工具状态,不碰光标 if (viewer) (viewer.container as HTMLElement).style.cursor = 'crosshair'; }; const clear = () => { - layerRef.current?.entities.removeAll(); - boxDragRef.current = {}; - polygonRef.current = []; - circleRef.current = {}; - measureRef.current = []; - setSelected(undefined); - setMeasureTotal(undefined); + resetShapes(); setTool(undefined); if (viewer) (viewer.container as HTMLElement).style.cursor = ''; }; diff --git a/src/pages/Map/Cesium/Direction.tsx b/src/pages/Map/Cesium/Direction.tsx index 787da045..19a8652b 100644 --- a/src/pages/Map/Cesium/Direction.tsx +++ b/src/pages/Map/Cesium/Direction.tsx @@ -261,7 +261,7 @@ export default function Direction() { return () => { if (!viewer.isDestroyed()) viewer.clock.onTick.removeEventListener(onTick); }; - // eslint-disable-next-line react-hooks/exhaustive-deps + // eslint-disable-next-line react-hooks/exhaustive-deps -- epoch 挂载时冻结进 ref、TARGETS 为模块常量;省略的只有 t(整页重载稳定) }, [viewer]); // 模式切换:覆盖带与波束各自显隐 @@ -272,6 +272,16 @@ export default function Direction() { if (sweepRef.current) sweepRef.current.show = mode !== 'bands'; }, [mode, viewer]); + // TimeDeck 播放/暂停与倍速必须同步到 viewer.clock(与 Heatmap/Trajectory/Situation 同一模式); + // 此前只在 onReady 里设过一次,导致播放控制与 ×1/×4/×16 按钮完全失效 + useEffect(() => { + if (viewer && !viewer.isDestroyed()) viewer.clock.shouldAnimate = playing; + }, [viewer, playing]); + + useEffect(() => { + if (viewer && !viewer.isDestroyed()) viewer.clock.multiplier = speed; + }, [viewer, speed]); + const stats = useMemo(() => CAPABILITIES.map((capability) => ({ capability, ...capabilityStats(capability) })), []); const interceptStats = stats.find((row) => row.capability === 'intercept'); const radarData = useMemo( @@ -284,7 +294,7 @@ export default function Direction() { rangeKm: p.rangeKm, })), ), - // eslint-disable-next-line react-hooks/exhaustive-deps + // eslint-disable-next-line react-hooks/exhaustive-deps -- polarPattern/CAPABILITIES 为纯模块函数;唯一捕获 t,切语言整页重载 [], ); diff --git a/src/pages/Map/Cesium/GeoHash.tsx b/src/pages/Map/Cesium/GeoHash.tsx index f08233a0..a41b3826 100644 --- a/src/pages/Map/Cesium/GeoHash.tsx +++ b/src/pages/Map/Cesium/GeoHash.tsx @@ -36,6 +36,7 @@ export default function GeoHashPage() { const [hovered, setHovered] = useState(); const [tilted, setTilted] = useState(false); const layerRef = useRef(null); + const highlightRef = useRef(null); const pointsRef = useRef(null); const freezeTimerRef = useRef(undefined); const fleet = useMemo(() => buildStationFleet(8000), []); @@ -56,10 +57,23 @@ export default function GeoHashPage() { // handler 只在 onReady 建一次,必须用回调参数 instance:闭包里的 state viewer 首帧是 null, // 底图重试后则是已销毁的旧实例 const handler = new Cesium.ScreenSpaceEventHandler(instance.scene.canvas); + // scene.pick 是一次完整的 pick 渲染 pass,而 MOUSE_MOVE 频率高于帧率——rAF 合帧,每帧最多 pick 一次 + //(同 CesiumViewer HUD 的做法);缓存最新落点,帧回调里统一消费 + let pickQueued: Cesium.Cartesian2 | undefined; + let pickRaf: number | undefined; handler.setInputAction((movement: { endPosition: Cesium.Cartesian2 }) => { - const picked = instance.scene.pick(movement.endPosition); - const cell = picked?.id?.properties?.cell?.getValue(Cesium.JulianDate.now()); - setHovered(cell ?? undefined); + pickQueued = movement.endPosition; + if (pickRaf === undefined) { + pickRaf = window.requestAnimationFrame(() => { + pickRaf = undefined; + const position = pickQueued; + pickQueued = undefined; + if (!position || instance.isDestroyed()) return; + const picked = instance.scene.pick(position); + const cell = picked?.id?.properties?.cell?.getValue(Cesium.JulianDate.now()); + setHovered(cell ?? undefined); + }); + } }, Cesium.ScreenSpaceEventType.MOUSE_MOVE); handler.setInputAction((click: { position: Cesium.Cartesian2 }) => { const picked = instance.scene.pick(click.position); @@ -77,7 +91,10 @@ export default function GeoHashPage() { }); } }, Cesium.ScreenSpaceEventType.LEFT_CLICK); - return () => handler.destroy(); + return () => { + if (pickRaf !== undefined) window.cancelAnimationFrame(pickRaf); + handler.destroy(); + }; }, }); @@ -106,9 +123,9 @@ export default function GeoHashPage() { /* 聚合:按精度编码 → 计数 → 色带格柱(带生长动画,动画结束后冻结为常量高度) */ useEffect(() => { const layer = layerRef.current; - if (!viewer || !layer || stations.length === 0) return; + if (!viewer || !layer || stations.length === 0) return undefined; layer.entities.removeAll(); - window.clearTimeout(freezeTimerRef.current); + highlightRef.current = null; const counts = new Map(); stations.forEach((s) => { const hash = centerGeoHash(s.lat, s.lng, precision); @@ -135,7 +152,11 @@ export default function GeoHashPage() { const growStart = performance.now(); const entityHeights: [Cesium.Entity, number][] = []; - list.forEach((cell, i) => { + // 精度 5 × 8000 站会产出 5–7k 格:实体(各自走异步三角化队列)封顶在几百格的量级, + // 按计数降序取前 N 渲染;直方图 / Top 列表 / KPI 仍用完整统计。标签同理只挂在大格上 + const RENDER_CAP = 800; + const LABEL_RATIO = 0.1; + list.slice(0, RENDER_CAP).forEach((cell, i) => { const b = geohashBounds(cell.hash); if (!b) return; const target = cellHeight(cell.ratio); @@ -153,12 +174,15 @@ export default function GeoHashPage() { outlineColor: Cesium.Color.WHITE.withAlpha(0.5), }, position: Cesium.Cartesian3.fromDegrees(cell.center[0], cell.center[1], target), - label: { - ...tagLabel({ font: '11px ui-monospace, Menlo, monospace' }), - text: `${cell.count}`, - showBackground: cell.ratio > 0.5, - disableDepthTestDistance: Number.POSITIVE_INFINITY, - }, + label: + cell.ratio >= LABEL_RATIO + ? { + ...tagLabel({ font: '11px ui-monospace, Menlo, monospace' }), + text: `${cell.count}`, + showBackground: cell.ratio > 0.5, + disableDepthTestDistance: Number.POSITIVE_INFINITY, + } + : undefined, properties: { cell }, }); entityHeights.push([entity, target]); @@ -170,6 +194,8 @@ export default function GeoHashPage() { }); }, 1900); setCells(list); + // 卸载 / 换参时取消冻结定时器:1.9s 后 viewer 可能已销毁,别再碰它的实体 + return () => window.clearTimeout(freezeTimerRef.current); }, [viewer, stations, precision]); /** 俯视 ↔ 侧视:侧视才能看出挤出高度的数据差异,这是这页的「定妆镜头」 */ @@ -199,7 +225,9 @@ export default function GeoHashPage() { const hash = centerGeoHash(lat, lng, precision); const b = geohashBounds(hash); if (b) { - layerRef.current.entities.add({ + // 中心高亮只保留最近一个:连续点按旧实体不移除会无限累积 + if (highlightRef.current) layerRef.current.entities.remove(highlightRef.current); + highlightRef.current = layerRef.current.entities.add({ rectangle: { coordinates: Cesium.Rectangle.fromDegrees(b.longitudeMin, b.latitudeMin, b.longitudeMax, b.latitudeMax), material: cesiumColor('#fa8c16', 0.5), @@ -213,6 +241,7 @@ export default function GeoHashPage() { const clear = () => { layerRef.current?.entities.removeAll(); + highlightRef.current = null; setCells([]); setHovered(undefined); }; @@ -221,7 +250,9 @@ export default function GeoHashPage() { const histogram = useMemo(() => { if (cells.length === 0) return undefined; const max = cells[0].count; - const binOf = (count: number) => Math.min(9, Math.floor((Math.log10(count) / Math.log10(max || 1)) * 10)); + // max === 1(所有格子 count=1)时分母 log10(1)=0 → NaN 档位:全部落第 0 档 + const binOf = (count: number) => + max <= 1 ? 0 : Math.min(9, Math.floor((Math.log10(count) / Math.log10(max)) * 10)); const bins = new Array(10).fill(0) as number[]; cells.forEach((cell) => { bins[binOf(cell.count)] += 1; @@ -258,7 +289,7 @@ export default function GeoHashPage() {
); - // eslint-disable-next-line react-hooks/exhaustive-deps + // eslint-disable-next-line react-hooks/exhaustive-deps -- t/intl 按 umi 惯例切语言整页重载,稳定引用不入依赖 }, [cells, hovered]); const topList = ( diff --git a/src/pages/Map/Cesium/Heatmap.tsx b/src/pages/Map/Cesium/Heatmap.tsx index c7367feb..1edbd423 100644 --- a/src/pages/Map/Cesium/Heatmap.tsx +++ b/src/pages/Map/Cesium/Heatmap.tsx @@ -38,7 +38,17 @@ export default function Heatmap() { const [mode, setMode] = useState('both'); const [playing, setPlaying] = useState(true); const [speed, setSpeed] = useState(1); + // 功率分两级:live 跟手(滑块与面板读数即时变),powers 是去抖后的提交值—— + // 覆盖圈整层重画(16 实体销毁重建)与探测重算只随提交值走,拖动期间不再每步重画 + const [powersLive, setPowersLive] = useState(() => transmitters().map((tx) => tx.power)); const [powers, setPowers] = useState(() => transmitters().map((tx) => tx.power)); + useEffect(() => { + const timer = window.setTimeout(() => { + // 停拖 120ms 才提交;值未变时返回原引用,React 跳过重渲染(避免挂载时空转一次重画) + setPowers((committed) => (committed === powersLive ? committed : powersLive)); + }, 120); + return () => window.clearTimeout(timer); + }, [powersLive]); // 点击探测的 handler 只在 onReady 建一次:经 ref 读当前功率,否则拖动滑块后读数仍按初始功率计算 const powersRef = useRef(powers); powersRef.current = powers; @@ -183,7 +193,7 @@ export default function Heatmap() { }, ); } - // eslint-disable-next-line react-hooks/exhaustive-deps + // eslint-disable-next-line react-hooks/exhaustive-deps -- drawShells 是渲染期新建函数,入依赖会让 effect 随任意渲染重跑;真实数据依赖 powers/viewer 已列出 }, [viewer, powers]); // 功率变化时已有的探测读数按新功率重算(探测点不动),与热力/覆盖圈保持一致 @@ -236,13 +246,16 @@ export default function Heatmap() { const timer = window.setInterval(() => { if (disposed) return; const seconds = Cesium.JulianDate.secondsDifference(viewer.clock.currentTime, epoch); + // powers 走 ref(与组件顶部 powersRef 同一来源):放进依赖会让 slider 每一拍都 + // terminate + 重建 Worker(模块级 Worker 重新加载 chunk),而 Worker 本就按请求接收新 powers + const currentPowers = powersRef.current; if (worker) { - worker.postMessage({ ...GRID, seconds, powers }); + worker.postMessage({ ...GRID, seconds, powers: currentPowers }); } else { // 降级:主线程低分辨率(import 环形依赖规避:fieldModel 就在同目录) import('./fieldModel').then(({ gridValues }) => { if (disposed) return; - const values = gridValues(FALLBACK_GRID.cols, FALLBACK_GRID.rows, seconds, powers); + const values = gridValues(FALLBACK_GRID.cols, FALLBACK_GRID.rows, seconds, currentPowers); draw({ ...FALLBACK_GRID, values }); }); } @@ -254,8 +267,7 @@ export default function Heatmap() { worker?.terminate(); workerRef.current = null; }; - // powers 变化重建管线:slider 拖动即重算 - }, [viewer, powers, epoch]); + }, [viewer, epoch]); useEffect(() => { if (viewer) viewer.clock.multiplier = speed; @@ -302,16 +314,16 @@ export default function Heatmap() {
{tx.id} - {Math.round(powers[i] * 100)}% · {coverageRadiusKm(powers[i], 60).toFixed(0)} km + {Math.round(powersLive[i] * 100)}% · {coverageRadiusKm(powersLive[i], 60).toFixed(0)} km
- setPowers((prev) => { + setPowersLive((prev) => { const copy = [...prev]; copy[i] = next; return copy; diff --git a/src/pages/Map/Cesium/Trajectory.tsx b/src/pages/Map/Cesium/Trajectory.tsx index 28e83114..9898e73c 100644 --- a/src/pages/Map/Cesium/Trajectory.tsx +++ b/src/pages/Map/Cesium/Trajectory.tsx @@ -59,7 +59,16 @@ export default function Trajectory() { const [drawing, setDrawing] = useState(false); const [playing, setPlaying] = useState(true); const [speed, setSpeed] = useState(2); + const [corridorWidthLive, setCorridorWidthLive] = useState(2600); + // 去抖提交:走廊宽度每变一步都会触发几何重三角化,拖动期间只跟手显示,停拖才落定 const [corridorWidth, setCorridorWidth] = useState(2600); + useEffect(() => { + const timer = window.setTimeout( + () => setCorridorWidth((committed) => (committed === corridorWidthLive ? committed : corridorWidthLive)), + 120, + ); + return () => window.clearTimeout(timer); + }, [corridorWidthLive]); const [hasPlayback, setHasPlayback] = useState(false); const [follow, setFollow] = useState(false); const [progress, setProgress] = useState(0); @@ -468,7 +477,7 @@ export default function Trajectory() { } }; return { pathD, px, W, H, totalKm, altMin, altMax, seek }; - // eslint-disable-next-line react-hooks/exhaustive-deps + // eslint-disable-next-line react-hooks/exhaustive-deps -- samplesRef/startRef 等均为 ref;真实依赖 progress/hasPlayback/viewer 已列出,t/intl 整页重载稳定 }, [progress, hasPlayback, viewer]); const statsPanel = stats ? ( @@ -496,8 +505,8 @@ export default function Trajectory() { min={800} max={6000} step={200} - value={corridorWidth} - onChange={setCorridorWidth} + value={corridorWidthLive} + onChange={setCorridorWidthLive} tooltip={{ formatter: (v) => `${((v ?? 0) / 1000).toFixed(1)} km` }} />
@@ -510,12 +519,19 @@ export default function Trajectory() {
{t('cesium.route.profile')}
profile.seek(e.clientX, e.currentTarget)} - onDrag={(e) => profile.seek(e.clientX, e.currentTarget)} + /* SVG 不是 draggable 元素,原生 onDrag 永远不触发(拖拽寻址此前是死交互): + 改 pointer 捕获实现按住拖动 scrub */ + onPointerDown={(e) => { + e.currentTarget.setPointerCapture(e.pointerId); + profile.seek(e.clientX, e.currentTarget); + }} + onPointerMove={(e) => { + if (e.currentTarget.hasPointerCapture(e.pointerId)) profile.seek(e.clientX, e.currentTarget); + }} > diff --git a/src/pages/Map/Cesium/heatRender.ts b/src/pages/Map/Cesium/heatRender.ts index 5597fc10..324e4c93 100644 --- a/src/pages/Map/Cesium/heatRender.ts +++ b/src/pages/Map/Cesium/heatRender.ts @@ -18,6 +18,17 @@ const buildLut = () => return new Uint8ClampedArray([r, g, b, 255]); })); +// ImageData 按 canvas + 尺寸缓存复用:热力「呼吸」4Hz 全像素重写,512×336 每帧新建 +// 是 ~675KB/帧(≈2.7MB/s)的纯 GC 垃圾;下方循环逐像素写满全部通道,复用无残留 +const imageCache = new WeakMap(); +const acquireImageData = (canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D, w: number, h: number) => { + const hit = imageCache.get(canvas); + if (hit && hit.w === w && hit.h === h) return hit.image; + const image = ctx.createImageData(w, h); + imageCache.set(canvas, { w, h, image }); + return image; +}; + export interface HeatGrid { cols: number; rows: number; @@ -51,7 +62,7 @@ export const renderHeatField = (canvas: HTMLCanvasElement, grid: HeatGrid, thres if (!ctx) return; const { width: w, height: h } = canvas; const lut = buildLut(); - const image = ctx.createImageData(w, h); + const image = acquireImageData(canvas, ctx, w, h); const data = image.data; for (let py = 0; py < h; py++) { const gy = (py / h) * grid.rows; diff --git a/src/pages/Media/AudioPlayer/index.tsx b/src/pages/Media/AudioPlayer/index.tsx index 0c1b4026..353a3306 100644 --- a/src/pages/Media/AudioPlayer/index.tsx +++ b/src/pages/Media/AudioPlayer/index.tsx @@ -77,6 +77,9 @@ export default function AudioPlayer() { return () => { observer.disconnect(); + // Analyze 有自调度的 rAF 渲染循环,只有它的 destroy()(内部 stop())会取消; + // player.destroy() 只关 AudioContext,不先销毁 Analyze 的话循环会在卸载后一直画 + analyzeRef.current?.destroy(); analyzeRef.current = undefined; player.destroy(); }; @@ -87,7 +90,8 @@ export default function AudioPlayer() { if (!analyze) return; analyze.mode = mode; Object.assign(analyze.options, MODE_OPTIONS[mode]); - }, [mode]); + // 依赖含 intl.locale:locale 重建 Analyze 后 mode 未变、[mode] 不触发,需借此重放当前模式 + }, [mode, intl.locale]); return ( { + // 失败提示由请求层 toast,这里接住 rejection 避免 fire-and-forget 的 unhandled rejection if (action !== 'falsePositive') { - void handle(alarm, action); + void handle(alarm, action).catch(() => undefined); return; } modal.confirm({ title: t('alarms.falsePositiveConfirm', { id: alarm.id }), content: t('alarms.falsePositiveConfirmDesc'), okButtonProps: { danger: true }, - onOk: () => handle(alarm, action), + onOk: () => handle(alarm, action).catch(() => undefined), }); }; diff --git a/src/pages/Ops/Devices/index.tsx b/src/pages/Ops/Devices/index.tsx index dfe87537..7ccf3f05 100644 --- a/src/pages/Ops/Devices/index.tsx +++ b/src/pages/Ops/Devices/index.tsx @@ -19,6 +19,7 @@ import { Empty, Listy, Progress, + Result, Skeleton, theme, Tooltip, @@ -40,78 +41,94 @@ const DeviceDrawer = ({ id, onClose }: { id?: string; onClose: () => void }) => const intl = useIntl(); const t = (key: string) => intl.formatMessage({ id: key }); const enums = useEnums(); - const { data, loading } = useApi(() => (id ? getDevice(id) : Promise.resolve(undefined)), [id]); + const { data, loading, error, reload } = useApi(() => (id ? getDevice(id) : Promise.resolve(undefined)), [id]); return ( - - {data && ( - <> - - - {data.name} {data.id} - - - {enums.label('region', data.region)} · {data.city} - - - {data.model} · {data.firmware} - - - {data.band[0]}–{data.band[1]} MHz - - - - - {data.uptime30d}% - {data.signalDbm} dBm - - {formatDateTime(data.lastHeartbeatAt, 'YYYY-MM-DD HH:mm:ss')} - - - {formatDateTime(data.installedAt, 'YYYY-MM-DD')} - - - {/* 同一业务对象的跳转链(E03):地图定位 + 告警明细,浏览器返回可回到这里 */} - } - data-tour="device-locate" - onClick={() => history.push(`/map/openlayers?focus=${encodeURIComponent(data.id)}`)} - > - {t('devices.locateOnMap')} + {error ? ( + // 拉取失败不再伪装成永久骨架:给出失败态与重试(请求层已 toast 过原因) + + {t('common.retry')} - - {t('devices.recentAlarms')} - - {data.recentAlarms.length ? ( - ( -
- - - {enums.label('alarmLevel', alarm.level)} - - - {enums.label('alarmType', alarm.type)} - - · {enums.label('alarmStatus', alarm.status)} - - {fromNow(alarm.occurredAt, intl.locale)} -
- )} - /> - ) : ( - - )} - - )} - + } + /> + ) : ( + + {data && ( + <> + + + {data.name} {data.id} + + + {enums.label('region', data.region)} · {data.city} + + + {data.model} · {data.firmware} + + + {data.band[0]}–{data.band[1]} MHz + + + + + {data.uptime30d}% + {data.signalDbm} dBm + + {formatDateTime(data.lastHeartbeatAt, 'YYYY-MM-DD HH:mm:ss')} + + + {formatDateTime(data.installedAt, 'YYYY-MM-DD')} + + + {/* 同一业务对象的跳转链(E03):地图定位 + 告警明细,浏览器返回可回到这里 */} + + + {t('devices.recentAlarms')} + + {data.recentAlarms.length ? ( + ( +
+ + + {enums.label('alarmLevel', alarm.level)} + + + {enums.label('alarmType', alarm.type)} + + + {' '} + · {enums.label('alarmStatus', alarm.status)} + + + {fromNow(alarm.occurredAt, intl.locale)} +
+ )} + /> + ) : ( + + )} + + )} +
+ )} ); }; diff --git a/src/pages/Ops/Spectrum/index.tsx b/src/pages/Ops/Spectrum/index.tsx index a7c9db5b..fa08b400 100644 --- a/src/pages/Ops/Spectrum/index.tsx +++ b/src/pages/Ops/Spectrum/index.tsx @@ -2,7 +2,7 @@ import DemoPage from '@/components/DemoPage'; import { useApi } from '@/hooks/useApi'; import { listAllDevices } from '@/services/ops'; import { useIntl } from '@umijs/max'; -import { Card, Grid, Progress, Skeleton, Table, Tag, Typography } from 'antd'; +import { Button, Card, Grid, Progress, Result, Skeleton, Table, Tag, Typography } from 'antd'; import { useCallback, useMemo } from 'react'; import { KEY_BANDS, coverageByModel, devicesCovering } from './bands'; import CoverageChart, { formatMHz } from './CoverageChart'; @@ -14,7 +14,7 @@ export default function Spectrum() { (id: string, values?: Record) => intl.formatMessage({ id }, values), [intl], ); - const { data: devices, loading } = useApi(listAllDevices); + const { data: devices, loading, error, reload } = useApi(listAllDevices); const { md } = Grid.useBreakpoint(); const models = useMemo(() => coverageByModel(devices ?? []), [devices]); @@ -49,7 +49,20 @@ export default function Spectrum() { )} - + {error ? ( + // 拉取失败不再渲染成「零覆盖」图表与 0/0 表格:给出失败态与重试 + + {t('common.retry')} + + } + /> + ) : ( + + )} diff --git a/src/pages/Ops/Tickets/TicketDrawer.tsx b/src/pages/Ops/Tickets/TicketDrawer.tsx index 5a997bcc..f8d7adcf 100644 --- a/src/pages/Ops/Tickets/TicketDrawer.tsx +++ b/src/pages/Ops/Tickets/TicketDrawer.tsx @@ -27,9 +27,14 @@ const AssigneeSelect = ({ ticket, onChanged }: { ticket: Ticket; onChanged?: (ti useEffect(() => { if (!access.permission('ops.ticket.assign')) return; let cancelled = false; - void listUsers({ status: 'active', pageSize: 200 }) - .then((page) => { - if (!cancelled) setUsers(page.list); + // 服务端按角色过滤(UserQuery.role):此前「pageSize 200 全量捞再客户端筛 operator/lead」, + // 活跃用户超过 200 时选择器会静默丢候选人 + void Promise.all([ + listUsers({ status: 'active', role: 'operator', pageSize: 100 }), + listUsers({ status: 'active', role: 'lead', pageSize: 100 }), + ]) + .then(([operators, leads]) => { + if (!cancelled) setUsers([...operators.list, ...leads.list]); }) .catch(() => undefined); return () => { diff --git a/src/pages/Ops/Tickets/index.tsx b/src/pages/Ops/Tickets/index.tsx index f6bd3cbb..46bd7d36 100644 --- a/src/pages/Ops/Tickets/index.tsx +++ b/src/pages/Ops/Tickets/index.tsx @@ -36,7 +36,7 @@ import { theme, } from 'antd'; import type { Dayjs } from 'dayjs'; -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import TicketCard from './TicketCard'; import TicketDrawer from './TicketDrawer'; @@ -65,6 +65,10 @@ const columnJumpCoordinates: KeyboardCoordinateGetter = (event, { context }) => return next ? { x: next.left + 12, y: next.top + 48 } : undefined; }; +/** 拖拽结束后浏览器仍会补发一次 click(dnd 的 pointer sensor 只 preventDefault mouseup): + * 记录最近一次 dragEnd 时刻,短窗口内忽略 click,避免拖动后放回原地的卡片弹出详情抽屉 */ +const lastDragEndAt = { current: 0 }; + /** 点击 / 回车打开详情;拖动(鼠标移动 6px 以上、触屏长按)才进入拖拽,二者不冲突 */ const DraggableTicket = ({ ticket, onOpen }: { ticket: Ticket; onOpen: (ticket: Ticket) => void }) => { const { attributes, listeners, setNodeRef, isDragging } = useDraggable({ id: ticket.id, data: { ticket } }); @@ -73,7 +77,10 @@ const DraggableTicket = ({ ticket, onOpen }: { ticket: Ticket; onOpen: (ticket: ref={setNodeRef} {...listeners} {...attributes} - onClick={() => onOpen(ticket)} + onClick={() => { + if (Date.now() - lastDragEndAt.current < 150) return; + onOpen(ticket); + }} onKeyDown={(event) => { listeners?.onKeyDown?.(event); if (event.key === 'Enter' && !event.defaultPrevented) onOpen(ticket); @@ -182,7 +189,7 @@ const TicketSearch = ({ onOpen }: { onOpen: (ticket: Ticket) => void }) => { value={keyword} onChange={(event) => setKeyword(event.target.value)} placeholder={t('tickets.search.placeholder')} - onSearch={search} + onSearch={() => void search().catch(() => undefined)} loading={searching} enterButton /> @@ -211,7 +218,8 @@ const TicketSearch = ({ onOpen }: { onOpen: (ticket: Ticket) => void }) => { onChange={(value) => setRange(value?.[0] && value?.[1] ? [value[0], value[1]] : undefined)} placeholder={[t('tickets.search.from'), t('tickets.search.to')]} /> - @@ -309,16 +317,25 @@ export default function Tickets() { }, [tickets, kind]); /** 乐观更新:先移动卡片,接口失败再退回(错误提示由请求层统一弹出)。拖拽与详情抽屉共用 */ + // 同一张卡连续两次移动(拖拽 + 抽屉、快速连拖)时,早发起的请求可能晚返回或失败回滚: + // 每次移动递增序号,过期响应与过期回滚都丢弃,避免旧状态覆盖新状态 + const moveSeqRef = useRef(new Map()); const move = async (ticket: Ticket, status: TicketStatus) => { if (status === ticket.status) return; - const previous = tickets; + // 只记录被移动那张卡的原状态:整表快照回滚会一并吞掉调用期间落地的其他变更 + // (看板刷新合并、第二张卡的移动、经办人变更) + const previousStatus = ticket.status; + const seq = (moveSeqRef.current.get(ticket.id) ?? 0) + 1; + moveSeqRef.current.set(ticket.id, seq); setTickets((list) => list.map((item) => (item.id === ticket.id ? { ...item, status } : item))); try { const updated = await moveTicket(ticket.id, status); + if (moveSeqRef.current.get(ticket.id) !== seq) return; setTickets((list) => list.map((item) => (item.id === ticket.id ? updated : item))); message.success(t('tickets.moved', { id: ticket.id, status: t(`ticketStatus.${status}`) })); } catch { - setTickets(previous); + if (moveSeqRef.current.get(ticket.id) !== seq) return; + setTickets((list) => list.map((item) => (item.id === ticket.id ? { ...item, status: previousStatus } : item))); } }; @@ -336,6 +353,7 @@ export default function Tickets() { const handleDragEnd = ({ active, over }: DragEndEvent) => { setDragging(undefined); + lastDragEndAt.current = Date.now(); const ticket = tickets.find((item) => item.id === active.id); const status = over?.id as TicketStatus | undefined; if (ticket && status) void move(ticket, status); diff --git a/src/pages/System/Roles/index.tsx b/src/pages/System/Roles/index.tsx index 1aa74eff..dfe4365e 100644 --- a/src/pages/System/Roles/index.tsx +++ b/src/pages/System/Roles/index.tsx @@ -55,7 +55,13 @@ export default function Roles() { return PERMISSION_TREE.map(toNode); }, [t, locked, grantable]); - const dirty = active && [...checked].sort().join() !== [...active.permissions].sort().join(); + // antd Tree 的勾选集会带上全选父分组键(dashboard/system/ops/doc),而 active.permissions 只存 + // 叶子键:比较时只剔除分组键,「勾上再取消」净变化为零时 Save 不再虚启用。未知/伪造键仍算 + // dirty——提交时的叶子过滤才是它们的兜底(save.test.tsx 断言的正是这条提交边界) + const groupKeys = new Set(PERMISSION_TREE.map((group) => group.key)); + const dirty = + active && + [...checked.filter((key) => !groupKeys.has(key))].sort().join() !== [...active.permissions].sort().join(); const save = async () => { setSaving(true); @@ -71,10 +77,16 @@ export default function Roles() { } }; + // 恢复默认与保存共用 saving 态:无防连点时双击会并发触发两次重置,失败也会留下未处理的 rejection const restore = async () => { - await resetRolePermissions(activeId); - message.success(t('common.saved')); - reload(); + setSaving(true); + try { + await resetRolePermissions(activeId); + message.success(t('common.saved')); + reload(); + } finally { + setSaving(false); + } }; return ( @@ -142,7 +154,7 @@ export default function Roles() { locked ? undefined : [ - , + } + /> + ) : ( + + {data?.list.length ? ( + ({ + key: log.id, + color: log.result === 'success' ? 'green' : 'red', + // antd 6:items.children 已弃用,改用 items.content + content: ( +
+ {enums.label('logAction', log.action)} + {log.target && · {log.target}} +
+ {fromNow(log.createdAt, intl.locale)} · {log.ip} +
-
- ), - }))} - /> - ) : ( - - )} - + ), + }))} + /> + ) : ( + + )} + + )} )} diff --git a/src/pages/System/Users/index.tsx b/src/pages/System/Users/index.tsx index 21e492d5..41c9075d 100644 --- a/src/pages/System/Users/index.tsx +++ b/src/pages/System/Users/index.tsx @@ -57,11 +57,17 @@ export default function Users() { reload(); }; + // 批量启用/停用按钮直接挂 onClick(antd 丢弃返回的 promise):失败必须就地 catch(modal.confirm + // 的删除路径由 onOk 的加载契约兜底,无需处理) const runBatch = async (ids: string[], action: UserBatchAction, clear: () => void) => { - const count = await batchUsers(ids, action); - message.success(t('users.batchDone', { count })); - clear(); - reload(); + try { + const count = await batchUsers(ids, action); + message.success(t('users.batchDone', { count })); + clear(); + reload(); + } catch { + // 错误提示由请求层统一弹出 + } }; const columns: ProColumns[] = [ diff --git a/src/services/client.ts b/src/services/client.ts index d9dc558d..49c6e946 100644 --- a/src/services/client.ts +++ b/src/services/client.ts @@ -1,3 +1,4 @@ +import { BizError } from '@/utils/BizError'; import { request, type RequestOptions } from '@umijs/max'; import type { ApiEnvelope } from './types'; @@ -7,6 +8,11 @@ import type { ApiEnvelope } from './types'; */ export const api = async (url: string, options: RequestOptions = { method: 'GET' }): Promise => { const envelope = await request>(url, { ...options, getResponse: false as const }); + // 200 但不是信封(网关错误页、被截断的响应等):envelope.data 的 TypeError 信息不可读, + // 也不会走 errorHandler 弹提示——这里显式判形并抛 BizError + if (envelope === null || typeof envelope !== 'object' || !('data' in envelope)) { + throw new BizError({ message: 'api: response is not an ApiEnvelope' }); + } return envelope.data; }; diff --git a/src/services/types.ts b/src/services/types.ts index 6db29e66..b310a976 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -364,7 +364,6 @@ export type CalendarEventInput = Omit; // ---------------- 演示时钟与场景(仅演示模式) ---------------- -/** live 跟随真实时间;frozen 固定在进入场景那一刻(受控演示,页面明确展示「演示时间」) */ /** 登录页「证据层」的演示数据快照(免登录,只含聚合数字;与工作台 KPI 同一口径) */ export interface DemoSnapshot { devicesOnline: number; @@ -374,6 +373,7 @@ export interface DemoSnapshot { slaRate: number; } +/** live 跟随真实时间;frozen 固定在进入场景那一刻(受控演示,页面明确展示「演示时间」) */ export interface DemoClockState { mode: 'live' | 'frozen'; /** frozen 模式的锚点(epoch ms) */ diff --git a/src/utils/Auth/initialState.ts b/src/utils/Auth/initialState.ts index 52eb5f24..e95e29d5 100644 --- a/src/utils/Auth/initialState.ts +++ b/src/utils/Auth/initialState.ts @@ -39,9 +39,16 @@ export async function getInitialState(): Promise { try { const user = await fetchCurrentUser(); return { ...new UserInfo(user), theme }; - } catch { - // 失效演示 token 或服务端会话:回落到未登录态,Cookie 的失效/删除由后端负责 - clearDemoToken(); + } catch (error) { + // 会话失效(401 / success:false 业务失败)与网络故障分流:后者不清演示 token—— + // 网络抖动把有效会话误判成「过期」并销毁 token,恢复后还得重新登录。 + // BizError 用 name 判定而不是 instanceof:这里刻意不 import 它(会拖进 i18n→@umijs/max + // 整条链,bootstrap 测试的 jsdom 环境装不下),且 vi.resetModules 下跨模块实例 instanceof 不可靠 + const response = error instanceof Object && 'response' in error ? (error as { response?: unknown }).response : null; + const authFailed = + (error instanceof Error && error.name === 'BizError') || + (response instanceof Object && (response as { status?: unknown }).status === 401); + if (authFailed) clearDemoToken(); return undefined; } } diff --git a/src/utils/MapCompute/cesiumCompute.ts b/src/utils/MapCompute/cesiumCompute.ts deleted file mode 100644 index 912043a3..00000000 --- a/src/utils/MapCompute/cesiumCompute.ts +++ /dev/null @@ -1,274 +0,0 @@ -import { featureCollection, polygon } from '@turf/helpers'; -import { union } from '@turf/union'; -import * as Cesium from 'cesium'; - -export type Point = { - longitude: number; - latitude: number; -}; - -type TurfCoordinate = [number, number]; - -/** - * 计算两点之间的距离, 如果距离大于 distanceMi 设定的米,则生成一个新的点 - * @param data 位置数据(经纬度) - * @param distanceMi 生成新点的距离 - * @returns 新的位置数据 - */ -export const handlerComputePoint = (data: Point[], distanceMi: number) => { - let dataPath: Point[] = []; - // 起点先入列,保证补点结果从用户绘制轨迹的起点开始 - if (data.length > 0) { - dataPath.push(data[0]); - } - for (let i = 0; i < data.length - 1; i++) { - let start = data[i]; - let end = data[i + 1]; - // 计算两点之间的距离 - let distance = Cesium.Cartesian3.distance( - Cesium.Cartesian3.fromDegrees(start.longitude, start.latitude), - Cesium.Cartesian3.fromDegrees(end.longitude, end.latitude), - ); - if (distance > distanceMi) { - // 该段距离大于 1000 米, 每 1000 米生成一个新的经纬度点 - let count = Math.floor(distance / distanceMi); // 向下取整 - let step = distanceMi; // 步长 - // 生成新的点 - for (let j = 0; j < count; j++) { - let longitude = start.longitude + ((end.longitude - start.longitude) * step) / distance; // 计算经度 - let latitude = start.latitude + ((end.latitude - start.latitude) * step) / distance; // 计算纬度 - dataPath.push({ longitude, latitude }); // 添加新的点 - step += distanceMi; // 步长递增 - } - } - // 每段终点无条件入列:短段只补终点,长段补插值点后再补终点, - // 避免短线段在补点结果中丢失 - dataPath.push(end); - } - return dataPath; -}; - -/** - * 合并多边形数组(turf.union 求并集)。 - * @param polygonArrays 多边形数组,每个多边形由一组点坐标表示。 - * @returns 合并结果的外环数组:相交多边形合并为一个环;不相交的多边形返回多个环。 - * @throws 如果输入无效或无法合并多边形,则抛出错误。 - */ -export function mergePolygons(polygonArrays: Point[][]) { - // 检查输入是否有效 - if (!Array.isArray(polygonArrays) || polygonArrays.length === 0) { - throw new Error('Input must be a non-empty array of polygon coordinates.'); - } - - // 检查多边形是否有效 - function isValidPoint(p: Point | undefined): p is Point { - return Boolean( - p && - typeof p.longitude === 'number' && - typeof p.latitude === 'number' && - !isNaN(p.longitude) && - !isNaN(p.latitude), - ); - } - - // 检查两个点是否相等 - function pointsEqual(p1: Point, p2: Point) { - return p1.longitude === p2.longitude && p1.latitude === p2.latitude; - } - - // 过滤有效的多边形 - const validPolygons = polygonArrays - .map((polygon, index) => { - if (!Array.isArray(polygon) || polygon.length < 3) { - console.warn(`Polygon at index ${index} has fewer than 3 points. Skipped.`); - return null; - } - - // 过滤有效点并删除连续重复项 - const validPoints = polygon.filter((p, i, arr) => isValidPoint(p) && (i === 0 || !pointsEqual(p, arr[i - 1]))); - - // 确保多边形是闭合的 - if (validPoints.length < 3) { - console.warn(`Polygon at index ${index} has fewer than 3 valid unique points. Skipped.`); - return null; - } - - // 确保多边形关闭 - if (!pointsEqual(validPoints[0], validPoints[validPoints.length - 1])) { - validPoints.push(validPoints[0]); - } - - return validPoints; - }) - .filter((polygon): polygon is Point[] => Boolean(polygon)); - - if (validPolygons.length === 0) { - throw new Error('No valid polygons to merge.'); - } - - // 创建 turf 多边形 - const turfPolygons = validPolygons - .map((pointSet, index) => { - try { - const coordinates = pointSet.map((p): TurfCoordinate => [p.longitude, p.latitude]); - return polygon([coordinates]); - } catch (error) { - console.error(`Failed to create turf polygon ${index}:`, error); - return null; - } - }) - .filter((poly): poly is ReturnType => Boolean(poly)); - - // 检查是否有有效的 turf 多边形 - if (turfPolygons.length === 0) { - throw new Error('Could not create any valid turf polygon.'); - } - - // 如果只有一个多边形,不需要合并 - if (turfPolygons.length === 1) { - const coordinates = turfPolygons[0].geometry.coordinates[0]; - return [ - (coordinates as TurfCoordinate[]).map((coord) => ({ - longitude: coord[0], - latitude: coord[1], - })), - ]; - } - - // 尝试合并多边形 - try { - // turf.union 对 featureCollection 求并集:相交多边形合并为单个 Polygon(外环), - // 不相交多边形返回 MultiPolygon(每个多边形一个外环)。 - // 此前误用 turf.combine(仅做几何打包不做合并),多边形合并功能实际未生效。 - const merged = union(featureCollection(turfPolygons)); - - if (!merged || !merged.geometry || !merged.geometry.coordinates) { - throw new Error('The merge result is empty'); - } - - // 规整为外环数组:Polygon 取唯一外环,MultiPolygon 逐个取外环 - const ringList: TurfCoordinate[][] = - merged.geometry.type === 'MultiPolygon' - ? (merged.geometry.coordinates as TurfCoordinate[][][]).map((poly) => poly[0]) - : [merged.geometry.coordinates[0] as TurfCoordinate[]]; - - return ringList.map((ring) => - ring.map((coord) => ({ - longitude: coord[0], - latitude: coord[1], - })), - ); - } catch (error: unknown) { - console.error('Polygon merge failed:', error); - throw new Error(`Polygon merge failed: ${error instanceof Error ? error.message : String(error)}`); - } -} - -/** - * 凸包算法:使用 Graham Scan 算法计算所有点的凸包,这将给出包含所有点的最小凸多边形。 - * 多边形简化:在计算凸包后,我们应用了一个简化步骤,移除共线或几乎共线的点,只保留形状所需的必要点。 - * 直接处理所有点:我们不再单独处理每个多边形,而是将所有点集中在一起处理,这简化了过程并确保我们得到真正的外围轮廓。 - * 错误处理:保留了对输入的验证,确保我们有足够的有效点来创建多边形。 - * 日志输出:添加了更多的日志输出,以便跟踪处理过程和结果。 - * - * @param polygonArrays 多边形数组,包含多个多边形的坐标点 [[{ longitude: number, latitude: number}], [...], ...] - * @returns 合并后的多边形路径,经过凸包计算和简化处理 [{ longitude: number, latitude: number }, ...] - * @throws 如果输入不是有效的多边形数组或没有足够的有效点来创建多边形,则抛出错误 - */ - -export function mergePolygonsPath(polygonArrays: Point[][]) { - if (!Array.isArray(polygonArrays) || polygonArrays.length === 0) { - throw new Error('Input must be a non-empty array of polygon coordinates.'); - } - - function isValidPoint(p: Point | undefined): p is Point { - return Boolean( - p && - typeof p.longitude === 'number' && - typeof p.latitude === 'number' && - !isNaN(p.longitude) && - !isNaN(p.latitude), - ); - } - - function pointsEqual(p1: Point, p2: Point) { - return Math.abs(p1.longitude - p2.longitude) < 1e-8 && Math.abs(p1.latitude - p2.latitude) < 1e-8; - } - - // 验证和清理输入多边形 - const allPoints = polygonArrays.flatMap((polygon, index) => { - if (!Array.isArray(polygon) || polygon.length < 3) { - console.warn(`Polygon at index ${index} has fewer than 3 points. Skipped.`); - return []; - } - - return polygon.filter(isValidPoint); - }); - - if (allPoints.length < 3) { - throw new Error('Not enough valid points to build a polygon.'); - } - - // 计算凸包 - function computeConvexHull(points: Point[]) { - // 按字典顺序排序点 - points.sort((a, b) => a.longitude - b.longitude || a.latitude - b.latitude); - - const lower = []; - for (let i = 0; i < points.length; i++) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], points[i]) <= 0) { - lower.pop(); - } - lower.push(points[i]); - } - - const upper = []; - for (let i = points.length - 1; i >= 0; i--) { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], points[i]) <= 0) { - upper.pop(); - } - upper.push(points[i]); - } - - upper.pop(); - lower.pop(); - return lower.concat(upper); - } - - function cross(o: Point, a: Point, b: Point) { - return ( - (a.longitude - o.longitude) * (b.latitude - o.latitude) - (a.latitude - o.latitude) * (b.longitude - o.longitude) - ); - } - - const convexHull = computeConvexHull(allPoints); - - // Ensure the polygon is closed - if (!pointsEqual(convexHull[0], convexHull[convexHull.length - 1])) { - convexHull.push(convexHull[0]); - } - - // 简化凸包,去掉不必要的点 - function simplifyPolygon(points: Point[], epsilon = 1e-8) { - if (points.length <= 4) return points; // Can't simplify further - - const result = [points[0]]; - for (let i = 1; i < points.length - 1; i++) { - const prev = points[i - 1]; - const current = points[i]; - const next = points[i + 1]; - - if (Math.abs(cross(prev, current, next)) > epsilon) { - result.push(current); - } - } - result.push(points[points.length - 1]); - return result; - } - - const simplifiedHull = simplifyPolygon(convexHull); - - return simplifiedHull; -} diff --git a/src/utils/MapCompute/geoHash.ts b/src/utils/MapCompute/geoHash.ts index 03a261e6..b1644088 100644 --- a/src/utils/MapCompute/geoHash.ts +++ b/src/utils/MapCompute/geoHash.ts @@ -19,8 +19,6 @@ export function geohashBounds(hash: string) { lonMax = 180; let latMid = 0, lonMid = 0; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - let bit = 0; let ch = 0; for (let i = 0; i < hash.length; i++) { @@ -72,8 +70,6 @@ export function centerGeoHash(lat: number, lon: number, precision: number): stri const BITS = [16, 8, 4, 2, 1]; const BASE32 = '0123456789bcdefghjkmnpqrstuvwxyz'; let isEven = true; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - let i = 0; let latMin = -90, latMax = 90; let lonMin = -180, diff --git a/src/utils/avatar.ts b/src/utils/avatar.ts index 39e9cab8..d47cbda2 100644 --- a/src/utils/avatar.ts +++ b/src/utils/avatar.ts @@ -9,5 +9,8 @@ export const avatarColor = (name: string) => { return AVATAR_COLORS[hash % AVATAR_COLORS.length]; }; -/** 头像文字:中文取姓,英文取首字母 */ -export const avatarText = (name: string) => (/^[a-z]/i.test(name) ? name.slice(0, 1).toUpperCase() : name.slice(0, 1)); +/** 头像文字:中文取姓,英文取首字母(按码点取首字符——slice(0,1) 会把 emoji 拆成孤立代理项) */ +export const avatarText = (name: string) => { + const first = Array.from(name)[0] ?? ''; + return /^[a-z]$/i.test(first) ? first.toUpperCase() : first; +}; diff --git a/src/utils/inflate.test.ts b/src/utils/inflate.test.ts index fbb6b4f8..cabf9f63 100644 --- a/src/utils/inflate.test.ts +++ b/src/utils/inflate.test.ts @@ -41,6 +41,69 @@ describe('inflateFlate round-trips real zlib output', () => { roundTrip(text('stored block payload '.repeat(200)), { level: 0 }); }); + it('decodes level-0 zlib streams spanning multiple stored blocks (>64 KiB)', HEAVY, () => { + // 200 KiB 零压缩 = 4 个 65535 字节存储块:第二个块进入前环形缓冲还滞留 + // 32767 字节未交付,覆盖即静默损坏(存储块回环写入缺陷的最小复现)。 + const input = text('level-zero must not corrupt the ring buffer. '.repeat(4600)); + expect(input.length).toBeGreaterThan(3 * 65535); + roundTrip(input, { level: 0 }); + }); + + it('delivers the partial tail before a stored block that would wrap the ring', HEAVY, () => { + // 手工构造 raw DEFLATE:固定 Huffman 块先产出 1000 字节(余量 r=1000 ∈ (0,32768)), + // 紧跟一个 65535 字节存储块 —— r+65535 > 65536,环形写入必然跨过未交付区间, + // 修复前这里交付给 sink 的数据已被覆盖。Huffman 码字 MSB-first,其余比特 LSB-first。 + const headLen = 1000; + const storedLen = 65535; + const bytes: number[] = []; + let bitBuf = 0; + let bitCnt = 0; + const writeBits = (value: number, n: number) => { + bitBuf |= value << bitCnt; + bitCnt += n; + while (bitCnt >= 8) { + bytes.push(bitBuf & 0xff); + bitBuf >>>= 8; + bitCnt -= 8; + } + }; + const writeCode = (code: number, n: number) => { + for (let i = n - 1; i >= 0; i--) writeBits((code >> i) & 1, 1); + }; + writeBits(0, 1); // BFINAL=0 + writeBits(1, 2); // BTYPE=01 固定 Huffman + const payload: number[] = []; + for (let i = 0; i < headLen; i++) payload.push(0x41 + (i % 26)); + for (const b of payload) writeCode(0x30 + b, 8); // 符号 0..143:8 位码 00110000+sym + writeCode(0, 7); // EOB(256):0000000 + writeBits(1, 1); // BFINAL=1 + writeBits(0, 2); // BTYPE=00 存储块 + if (bitCnt > 0) { + bytes.push(bitBuf & 0xff); + bitBuf = 0; + bitCnt = 0; + } + const len = storedLen & 0xffff; + const nlen = ~len & 0xffff; + bytes.push(len & 0xff, (len >> 8) & 0xff, nlen & 0xff, (nlen >> 8) & 0xff); + for (let i = 0; i < storedLen; i++) bytes.push(0x5a); + + const input = new Uint8Array(headLen + storedLen); + input.set(payload, 0); + input.fill(0x5a, headLen); + const chunks: Uint8Array[] = []; + const total = inflateRaw(new Uint8Array(bytes), { sink: (chunk) => chunks.push(chunk.slice()) }); + const joined = new Uint8Array(total); + let cursor = 0; + for (const chunk of chunks) { + joined.set(chunk, cursor); + cursor += chunk.length; + } + expect(cursor).toBe(total); + expect(total).toBe(input.length); + expect(joined).toEqual(input); + }); + it('decodes incompressible binary data', HEAVY, () => { const binary = new Uint8Array(32 * 1024); for (let index = 0; index < binary.length; index++) binary[index] = (index * 37 + (index >> 3)) & 0xff; diff --git a/src/utils/inflate.ts b/src/utils/inflate.ts index bb7ee239..a82527ab 100644 --- a/src/utils/inflate.ts +++ b/src/utils/inflate.ts @@ -56,8 +56,10 @@ export type InflateOptions = { /** 允许解出的最大字节数;达到 limit 后继续产出会抛 InflateLimitError。 */ limit?: number; /** - * 每交付 32 KiB 解码结果回调一次(顺序保证),调用方据此递增计数/预算,无需保存全量输出。 - * 传入的 Uint8Array 是复用中的环形缓冲视图:需要长期保留必须自行 `slice()`。 + * 交付解码结果(顺序保证),调用方据此递增计数/预算,无需保存全量输出。 + * 通常每凑满 32 KiB 回调一次;唯一例外是超长存储块前的不足一窗尾巴(防环形覆盖), + * 以及流末尾 drain() 的最后一段。传入的 Uint8Array 是复用中的环形缓冲视图: + * 需要长期保留必须自行 `slice()`。 * 成功返回时输出必然完整;若中途因 limit 或格式错误抛错,则不足一窗(< 32 KiB)的尾部 * 不会交付 —— 这种情况只会发生在调用方已经决定拒绝该文件的路径上。 */ @@ -233,7 +235,16 @@ export const inflateRaw = (data: Uint8Array, options: InflateOptions = {}): numb if (length !== (~complement & 0xffff)) throw new InflateError('inflate: stored block length mismatch'); if (pos + length > data.length) throw new InflateError('inflate: stored block overruns stream'); if (total + length > limit) throw new InflateLimitError(limit); - if (total - flushed + length > OUTPUT_SIZE) flush(); + if (total + length - flushed > OUTPUT_SIZE) { + flush(); + // flush 只交付满窗(最多滞留 WINDOW_SIZE-1 字节)。存储块最长 65535,仍放不下时 + // 环形写入会覆盖这些未交付字节 —— 必须先把不足一窗的尾巴直接交给 sink(无 sink + // 时 flush 已把 flushed 推到 total,不会走到这里)。此后剩余恒为 0,写入绝不回环覆盖。 + if (total + length - flushed > OUTPUT_SIZE) { + sinkRange(flushed, total - flushed); + flushed = total; + } + } const at = total & OUTPUT_MASK; const firstPart = Math.min(length, OUTPUT_SIZE - at); window.set(data.subarray(pos, pos + firstPart), at); diff --git a/src/utils/platform.ts b/src/utils/platform.ts new file mode 100644 index 00000000..ea9aa220 --- /dev/null +++ b/src/utils/platform.ts @@ -0,0 +1,11 @@ +/** + * 平台判定共享出口:⌘K / Ctrl+K 等随平台变化的文案统一走这里, + * 避免各处内联同一份 navigator.platform 正则(已废弃 API)而彼此漂移。 + */ +const platformOf = (): string => { + if (typeof navigator === 'undefined') return ''; + const withUAD = navigator as Navigator & { userAgentData?: { platform?: string } }; + return withUAD.userAgentData?.platform ?? navigator.platform ?? ''; +}; + +export const isMac = (): boolean => /Mac|iPhone|iPad/.test(platformOf());