用户端(四面9分批次): 三条全局错误出口、URL 白名单收口、令牌键单点、uid 短路进门禁
- 此前全树 0 处全局错误处理器:装 app.config.errorHandler + window error + unhandledrejection, 每条都留可诊断记录、界面只出中文、处理器自身异常不重抛也不白屏(9 例判据)。 - safeHttpUrl 未覆盖的 3 处(两个品牌 Tab 与 useVersionUpdate 直装服务端 file_url)收口; 令牌键 aiimage_auth_token 由 4 处各自定义 + 2 处内联收成唯一定义点。 - 「localStorage 有 uid 就免校验」改走 auth-gate 单点,剩余例外台账化且同口径必须能抓到 评审点名的原写法(6 例);卸载配对 3 处补齐 + 全树判据(7 例)。 - task-status-text 把 CANCELLED 显示成"执行中"改对,CANCELED/CANCELLED 两拼写都映射(4 例)。 - 主审计补的四处修复:新判据里两处拿数组和 0 比(怎么写都红);静默 catch 的"用户可见出口" 符号表认不出本仓 userNotice 与注入式 notify,把真报了用户的 catch 判成静默; 新错误出口带来的 2 个 try/catch 按棘轮合同写理由进基线(296→298,silent 一格没涨)。 - 验收:node --test 820 例 0 红、npx vue-tsc --noEmit rc=0。
This commit is contained in:
@@ -12,5 +12,19 @@
|
||||
// app.use(ElementPlus, { locale }) 全局注入,改由 ConfigProvider 提供;
|
||||
// 否则分页/日期选择器/上传等组件的内置文案会退回英文。
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import { onBeforeUnmount } from 'vue'
|
||||
import ExpiryNotice from '@/shared/components/ExpiryNotice.vue'
|
||||
import { disposeGlobalErrorGuard } from '@/shared/utils/app-error'
|
||||
import { uninstallUserTokenSync } from '@/shared/auth/user-token-sync'
|
||||
import { disposeDownloadProgressListener } from '@/shared/utils/download-progress'
|
||||
import { disposeUpdateProgressListener } from '@/shared/composables/useVersionUpdate'
|
||||
|
||||
// 卸载配对:入口与共享模块装的全局注册点(错误处理、令牌同步轮询、下载/更新进度监听)
|
||||
// 都在根组件卸载时摘掉。根组件不卸载时它们就是应用级单例,语义与以前一致。
|
||||
onBeforeUnmount(() => {
|
||||
disposeGlobalErrorGuard()
|
||||
uninstallUserTokenSync()
|
||||
disposeDownloadProgressListener()
|
||||
disposeUpdateProgressListener()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -8,7 +8,11 @@ import 'element-plus/es/components/message-box/style/css'
|
||||
|
||||
import App from '@/App.vue'
|
||||
import router from '@/router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { ensureAuth } from '@/shared/auth/ensure-auth'
|
||||
import { shouldBounceToHome } from '@/shared/auth/auth-gate'
|
||||
import { AUTH_TOKEN_KEY, UID_KEY } from '@/shared/auth/session-keys'
|
||||
import { installGlobalErrorGuard } from '@/shared/utils/app-error'
|
||||
import { ensureApiSecretsLoaded, loadApiSecrets } from '@/shared/utils/api-secret-store'
|
||||
import { installUserTokenSync } from '@/shared/auth/user-token-sync.ts'
|
||||
import { installSubmitGuard } from '@/shared/utils/submit-guard'
|
||||
@@ -19,6 +23,16 @@ installUserTokenSync()
|
||||
// 提交按钮防连点:捕获阶段拦下同一按钮的连点(各工具页 .btn-run 通用)
|
||||
installSubmitGuard()
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
// 全局错误处理器:Vue 渲染/生命周期抛错、顶层 window error、没人接的 Promise rejection
|
||||
// 三个出口一次装好;界面只说中文(原文过 userNotice 把关,英文异常只进控制台记录)。
|
||||
// 卸载出口挂在 App.vue 的 onBeforeUnmount(disposeGlobalErrorGuard)。
|
||||
installGlobalErrorGuard(app, {
|
||||
notify: (text) => ElMessage.error(text),
|
||||
record: (line) => console.error('[app-error]', line),
|
||||
})
|
||||
|
||||
/**
|
||||
* 数富AI 前端统一入口(SPA,URL 无 .html 后缀)
|
||||
*
|
||||
@@ -54,7 +68,10 @@ router.beforeEach((to) => {
|
||||
// 已登录访问登录页 → 回首页(与 MPA 时代 login.html 展示"请先退出"一致:直接回首页);
|
||||
// 但带 logout/switch 的登出导航放行。判断须看 to.query:守卫在 URL 更新前执行,
|
||||
// window.location.search 仍是旧地址,会漏判 /home 点击"退出"的 router-link(=登出无效果)。
|
||||
if (to.name === 'login' && window.localStorage.getItem('uid')) {
|
||||
if (to.name === 'login' && shouldBounceToHome({
|
||||
uid: window.localStorage.getItem(UID_KEY),
|
||||
token: window.localStorage.getItem(AUTH_TOKEN_KEY),
|
||||
})) {
|
||||
const isLogoutNav = to.query.logout === '1' || to.query.switch === '1'
|
||||
if (isLogoutNav) {
|
||||
// 排查日志:登出/切号放行(清 token 逻辑在登录页 onMounted 处理)
|
||||
@@ -66,4 +83,4 @@ router.beforeEach((to) => {
|
||||
return true
|
||||
})
|
||||
|
||||
createApp(App).use(router).mount('#app')
|
||||
app.use(router).mount('#app')
|
||||
|
||||
@@ -130,6 +130,7 @@ import { TUTORIAL_DOWNLOAD_URL, resolveTutorialDownloadUrl } from '@/pages/amazo
|
||||
import { filterGroupsByPermission, filterWorkflowByPermission, TOOL_GROUPS, TOOL_MAP } from '@/pages/amazon/tool-catalog'
|
||||
import type { ToolGroup, ToolInfo, VisibleGroup, WorkflowStep } from '@/pages/amazon/tool-catalog'
|
||||
import { resolvePageHref } from '@/shared/page-prefix'
|
||||
import { isHttpUrl, safeHttpUrl } from '@/shared/utils/safe-url'
|
||||
import { prefetchRouteChunk } from '@/shared/route-prefetch'
|
||||
import { getPywebviewApi } from '@/shared/bridges/pywebview'
|
||||
import { getCurrentUserAppColumnKeys } from '@/shared/api/permission'
|
||||
@@ -226,11 +227,18 @@ async function refreshTutorialUrl() {
|
||||
|
||||
async function onDownloadClick() {
|
||||
// 教程客户端压缩包:最新上传的包优先(/api/tutorial/latest),兜底走固定直链(见 download-btn.ts)
|
||||
// /api/tutorial/latest 的 file_url 是服务端透传字段,进桥与开窗之前先过白名单(判据:tests/url-outlet-guard.test.ts)
|
||||
const url = tutorialUrl.value
|
||||
if (!isHttpUrl(url)) {
|
||||
console.warn('[safe-url] 教程下载地址未通过白名单校验,已取消打开:', String(url).slice(0, 200))
|
||||
toast('下载地址不可用,请稍后重试', 'error')
|
||||
return
|
||||
}
|
||||
const api = getPywebviewApi()
|
||||
if (api?.open_external_url) {
|
||||
// 桌面端:交系统默认浏览器下载,可看到下载进度
|
||||
try {
|
||||
const res = await api.open_external_url(tutorialUrl.value)
|
||||
const res = await api.open_external_url(url)
|
||||
if (!res?.success) toast(`下载失败:${res?.error ?? '请重试'}`, 'error')
|
||||
} catch (_error) {
|
||||
toast('下载失败,请重试', 'error')
|
||||
@@ -238,7 +246,7 @@ async function onDownloadClick() {
|
||||
return
|
||||
}
|
||||
// 网页端:新窗口打开直链下载
|
||||
window.open(tutorialUrl.value, '_blank', 'noopener')
|
||||
window.open(safeHttpUrl(url), '_blank', 'noopener')
|
||||
}
|
||||
|
||||
function onCatChange(key: 'front' | 'ops' | 'logi') {
|
||||
|
||||
@@ -118,6 +118,7 @@ import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
|
||||
import type { UploadedFileRef } from '@/shared/api/types/upload.ts'
|
||||
import { formatDateTime } from '@/shared/utils/datetime'
|
||||
import { taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
|
||||
import { isHttpUrl, safeHttpUrl } from '@/shared/utils/safe-url'
|
||||
import { runBatchDelete } from '@/shared/utils/batch-delete'
|
||||
|
||||
const {
|
||||
@@ -453,11 +454,24 @@ async function deleteTask(item: BrandTaskItem) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 浏览器形态的直开下载:`zip_url` 是服务端/客户端原样透传的开放字段,
|
||||
* 没通过白名单就不开、并把话说明,不许默默跳去陌生域(判据见 tests/url-outlet-guard.test.ts)。
|
||||
*/
|
||||
function openDownloadUrl(raw: string, label: string): void {
|
||||
if (!isHttpUrl(raw)) {
|
||||
console.warn('[safe-url] 下载地址未通过白名单校验,已取消打开:', label, String(raw).slice(0, 200))
|
||||
ElMessage.warning('下载地址不可用,请在本机客户端中打开或稍后重试')
|
||||
return
|
||||
}
|
||||
window.open(safeHttpUrl(raw), '_blank')
|
||||
}
|
||||
|
||||
async function downloadResult(item: BrandTaskItem) {
|
||||
const zipUrl = item.result_paths?.zip_url
|
||||
const filename = `brand_task_${item.id}.zip`
|
||||
const bridge = getPywebviewApi()
|
||||
if (bridge?.save_file_from_url && zipUrl) {
|
||||
if (bridge?.save_file_from_url && zipUrl && isHttpUrl(zipUrl)) {
|
||||
try {
|
||||
const res = await bridge.save_file_from_url(zipUrl, filename)
|
||||
if (res.success) {
|
||||
@@ -472,10 +486,10 @@ async function downloadResult(item: BrandTaskItem) {
|
||||
}
|
||||
}
|
||||
if (zipUrl) {
|
||||
window.open(zipUrl, '_blank')
|
||||
openDownloadUrl(zipUrl, filename)
|
||||
return
|
||||
}
|
||||
window.open(getBrandTaskDownloadUrl(item.id), '_blank')
|
||||
openDownloadUrl(getBrandTaskDownloadUrl(item.id), filename)
|
||||
}
|
||||
|
||||
async function downloadTemplate(kind: 'xlsx' | 'zip') {
|
||||
|
||||
@@ -168,7 +168,7 @@ import {
|
||||
type VariantTaskListItem,
|
||||
} from '@/shared/bridges/pywebview'
|
||||
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
|
||||
import { safeHttpUrl } from '@/shared/utils/safe-url'
|
||||
import { isHttpUrl, safeHttpUrl } from '@/shared/utils/safe-url'
|
||||
import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
|
||||
import { useHistoryPolling } from '@/shared/composables/useHistoryPolling'
|
||||
import { taskStatusClass, taskStatusText, type TaskStatusOptions } from '@/shared/utils/task-status-text'
|
||||
@@ -562,7 +562,12 @@ async function downloadSource(item: VariantTaskListItem) {
|
||||
return
|
||||
}
|
||||
const name = srcUrl.split(/[\\/?]/).filter(Boolean).pop() || 'source.xlsx'
|
||||
const result = await saveUrlWithProgress(srcUrl, name, `src_${item.task_id}_${Date.now()}`)
|
||||
if (!isHttpUrl(srcUrl)) {
|
||||
console.warn('[safe-url] 源文件地址未通过白名单校验,已取消下载:', String(srcUrl).slice(0, 200))
|
||||
ElMessage.warning('源文件地址不可用,请在本机客户端中打开或稍后重试')
|
||||
return
|
||||
}
|
||||
const result = await saveUrlWithProgress(safeHttpUrl(srcUrl), name, `src_${item.task_id}_${Date.now()}`)
|
||||
if (result.success) {
|
||||
ElMessage.success(`源文件已保存:${result.path || name}`)
|
||||
} else if (result.error && result.error !== '用户取消') {
|
||||
@@ -612,8 +617,13 @@ async function reexportTask(item: VariantTaskListItem) {
|
||||
ElMessage.info('已发起导出,正在轮询结果…')
|
||||
const result = await pollExport(bridge, startRes.file_id)
|
||||
if (result && Number(result.status) === 2 && result.file_url) {
|
||||
if (!isHttpUrl(result.file_url)) {
|
||||
console.warn('[safe-url] 导出文件地址未通过白名单校验,已取消下载:', String(result.file_url).slice(0, 200))
|
||||
ElMessage.warning('导出文件地址不可用,请在本机客户端中打开或稍后重试')
|
||||
return
|
||||
}
|
||||
const name = result.file_name || result.file_url.split(/[\\/?]/).filter(Boolean).pop() || 'export.xlsx'
|
||||
const dlRes = await saveUrlWithProgress(result.file_url, name, `exp_${startRes.file_id}`)
|
||||
const dlRes = await saveUrlWithProgress(safeHttpUrl(result.file_url), name, `exp_${startRes.file_id}`)
|
||||
if (dlRes.success) {
|
||||
ElMessage.success(`导出文件已保存:${dlRes.path || name}`)
|
||||
} else if (dlRes.error && dlRes.error !== '用户取消') {
|
||||
|
||||
@@ -117,6 +117,7 @@ import { loginWithDevice } from '@/shared/api/user'
|
||||
import { ACCOUNT_DELETED_NOTICE_KEY, ACCOUNT_DISABLED_NOTICE_KEY, KICK_NOTICE_KEY, SESSION_EXPIRED_NOTICE_KEY } from '@/shared/auth/kick-handler'
|
||||
import { COMPANY_NAME_STORAGE_KEY, writeCompanyIdentity } from '@/shared/auth/company-identity'
|
||||
import { clearAccountExpiry, writeAccountExpiry } from '@/shared/auth/account-expiry'
|
||||
import { AUTH_TOKEN_KEY } from '@/shared/auth/session-keys'
|
||||
import { useVersionUpdate } from '@/shared/composables/useVersionUpdate'
|
||||
import { clearApiSecretCache } from '@/shared/utils/api-secret-store'
|
||||
import UpdateProgressBar from '@/shared/components/UpdateProgressBar.vue'
|
||||
@@ -125,7 +126,6 @@ import VersionPicker from '@/shared/components/VersionPicker.vue'
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const AUTH_TOKEN_KEY = 'aiimage_auth_token'
|
||||
const DEVICE_ID_KEY = 'aiimage_device_id'
|
||||
|
||||
const REMEMBER_USER_KEY = 'aiimage_remember_user'
|
||||
|
||||
@@ -6,6 +6,7 @@ import axios, {
|
||||
type InternalAxiosRequestConfig,
|
||||
} from 'axios'
|
||||
import { authReasonOf, handleKicked, handleSessionExpired, isKickedPayload, isUnauthorizedPayload } from '../auth/kick-handler.ts'
|
||||
import { AUTH_TOKEN_KEY } from '../auth/session-keys.ts'
|
||||
import { userNotice } from '../utils/user-notice.ts'
|
||||
|
||||
const REQUEST_FALLBACK = '请求未能完成,请稍后重试'
|
||||
@@ -103,7 +104,7 @@ function createHttpClient(): AxiosInstance {
|
||||
// 携带本地登录令牌:桌面端同源 cookie 仍可用;dev(5173) 无 cookie 时靠 Bearer 过 Java 鉴权
|
||||
try {
|
||||
if (config.url && config.url.indexOf('/newApi') === 0 && typeof window !== 'undefined') {
|
||||
const token = window.localStorage.getItem('aiimage_auth_token') || ''
|
||||
const token = window.localStorage.getItem(AUTH_TOKEN_KEY) || ''
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { requestGetJson } from '../../http.ts'
|
||||
import { AUTH_TOKEN_KEY } from '../../../auth/session-keys.ts'
|
||||
|
||||
export interface PermissionMenuItem {
|
||||
id: number | string
|
||||
@@ -72,7 +73,7 @@ export function readCachedAppColumnPermissions(uid: number): PermissionMenuItem[
|
||||
}
|
||||
|
||||
function getAuthToken() {
|
||||
return typeof window === 'undefined' ? '' : window.localStorage.getItem('aiimage_auth_token') || ''
|
||||
return typeof window === 'undefined' ? '' : window.localStorage.getItem(AUTH_TOKEN_KEY) || ''
|
||||
}
|
||||
|
||||
function normalizeColumnKeys(items: PermissionMenuItem[] | undefined) {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* 登录态门禁判定(收口 2026-10-09 评审「只要 localStorage 里有 uid 就短路免校验」)。
|
||||
*
|
||||
* 原写法:`if (rawUid && Number(rawUid) > 0) return true`——uid 是本机唯一的登录证据时,
|
||||
* 令牌没了、令牌过期了都能直接进页面,直到某个接口 401 才被踢回去;界面上的表现是"页面打开后一片报错"。
|
||||
*
|
||||
* 但不能硬删:桌面端与线上 Web 同源,`http.ts` 里 `withCredentials: true`,
|
||||
* Java 侧的同源会话 cookie 仍然算登录(注释原话"桌面端同源 cookie 仍可用"),
|
||||
* 这种形态本地只有 uid、没有 JWT。直接改成"无令牌即拒"会把这类合法入口锁在登录页外。
|
||||
*
|
||||
* 所以收窄而不是删除:**只有 uid + 令牌同时存在**才免掉一次 `/newApi/check_login`
|
||||
* (令牌本身每次请求都要过后端,门禁这里省的只是那一次往返);
|
||||
* 只有 uid(cookie 形态)或只有令牌 → 一律走服务端校验;两者都没有 → 拒。
|
||||
*
|
||||
* 判据:tests/uid-bypass-ledger.test.ts(真值表行为钉子 + 免校验例外名单 + 新增例外就红)。
|
||||
*/
|
||||
|
||||
/** 'pass-local'=本机证据齐、免一次服务端校验;'restore'=要问服务端;'deny'=直接回登录页。 */
|
||||
export type AuthGateDecision = 'pass-local' | 'restore' | 'deny'
|
||||
|
||||
export interface AuthGateState {
|
||||
/** localStorage 里的 uid 原值 */
|
||||
uid?: string | null
|
||||
/** localStorage 里的登录令牌原值 */
|
||||
token?: string | null
|
||||
}
|
||||
|
||||
/** uid 是否成形:非空且是正整数('0'、''、'abc'、NaN 都不算登录过)。 */
|
||||
export function hasUsableUid(uid?: string | null): boolean {
|
||||
const raw = typeof uid === 'string' ? uid.trim() : ''
|
||||
if (!raw) return false
|
||||
const value = Number(raw)
|
||||
return Number.isFinite(value) && value > 0
|
||||
}
|
||||
|
||||
/** 令牌是否成形:非空字符串。是否有效不由这里判(后端才是唯一裁判)。 */
|
||||
export function hasUsableToken(token?: string | null): boolean {
|
||||
return typeof token === 'string' && token.trim() !== ''
|
||||
}
|
||||
|
||||
/** 门禁判定:唯一致力于"能不能不进登录页"的函数,别处不许再自己拼 uid 条件。 */
|
||||
export function decideAuthGate(state: AuthGateState): AuthGateDecision {
|
||||
const uidOk = hasUsableUid(state.uid)
|
||||
const tokenOk = hasUsableToken(state.token)
|
||||
if (uidOk && tokenOk) return 'pass-local'
|
||||
if (uidOk || tokenOk) return 'restore'
|
||||
return 'deny'
|
||||
}
|
||||
|
||||
/**
|
||||
* 已登录用户访问登录页要不要送回首页(main.ts 的第二处 uid 判断)。
|
||||
* 送回的条件与门禁同源:本机证据齐才拦;只有 uid(要问服务端)时把登录页留给用户,
|
||||
* 否则令牌一丢就永远点不开登录页,只能靠 URL 上的 logout/switch 参数自救。
|
||||
*/
|
||||
export function shouldBounceToHome(state: AuthGateState): boolean {
|
||||
return decideAuthGate(state) === 'pass-local'
|
||||
}
|
||||
@@ -3,18 +3,18 @@
|
||||
*
|
||||
* SPA 化后由 src/main.ts 的路由守卫调用;本模块只做检查与 uid/username 恢复,
|
||||
* 不主动跳转(跳转统一由 router.beforeEach 返回 { name: 'login' })。
|
||||
* - localStorage.uid 已存在(桌面注入 / 登录页已写入)→ 直接放行,零额外请求;
|
||||
* - 无 uid 但有 JWT → 调 /newApi/check_login 恢复 uid/username;
|
||||
* - 无 token 或校验失败 → 返回 false,由守卫跳转登录页。
|
||||
* 放行条件由 shared/auth/auth-gate.ts 单点判定,不再"看见 uid 就免校验":
|
||||
* - uid 与令牌都在(登录页 / 上一次校验已写全)→ 直接放行,零额外请求;
|
||||
* - 只有 uid(桌面端同源 cookie 形态)或只有 JWT → 调 /newApi/check_login 校验并恢复 uid/username;
|
||||
* - 两者都没有或校验失败 → 返回 false,由守卫跳转登录页。
|
||||
*/
|
||||
|
||||
import { get } from '@/shared/api/http'
|
||||
import { decideAuthGate } from './auth-gate.ts'
|
||||
import { AUTH_TOKEN_KEY, UID_KEY } from './session-keys.ts'
|
||||
import { writeCompanyIdentity } from './company-identity'
|
||||
import { writeAccountExpiry } from './account-expiry'
|
||||
|
||||
const AUTH_TOKEN_KEY = 'aiimage_auth_token'
|
||||
const UID_KEY = 'uid'
|
||||
|
||||
interface CheckLoginData {
|
||||
userId?: number | string
|
||||
username?: string
|
||||
@@ -26,12 +26,14 @@ interface CheckLoginData {
|
||||
export async function ensureAuth(): Promise<boolean> {
|
||||
if (typeof window === 'undefined') return true
|
||||
try {
|
||||
const rawUid = window.localStorage.getItem(UID_KEY) || ''
|
||||
if (rawUid && Number(rawUid) > 0) {
|
||||
const decision = decideAuthGate({
|
||||
uid: window.localStorage.getItem(UID_KEY),
|
||||
token: window.localStorage.getItem(AUTH_TOKEN_KEY),
|
||||
})
|
||||
if (decision === 'pass-local') {
|
||||
return true
|
||||
}
|
||||
const token = window.localStorage.getItem(AUTH_TOKEN_KEY) || ''
|
||||
if (!token) {
|
||||
if (decision === 'deny') {
|
||||
return false
|
||||
}
|
||||
const response = await get<{ success: boolean; data?: CheckLoginData }>('/newApi/check_login')
|
||||
@@ -63,13 +65,11 @@ export async function ensureAuth(): Promise<boolean> {
|
||||
export async function restoreLoginUser(): Promise<{ username?: string } | null> {
|
||||
if (typeof window === 'undefined') return null
|
||||
try {
|
||||
const rawUid = window.localStorage.getItem(UID_KEY) || ''
|
||||
if (rawUid && Number(rawUid) > 0) {
|
||||
// 已有 uid(桌面端注入或登录页已写)无需再查
|
||||
return null
|
||||
}
|
||||
const token = window.localStorage.getItem(AUTH_TOKEN_KEY) || ''
|
||||
if (!token) {
|
||||
const decision = decideAuthGate({
|
||||
uid: window.localStorage.getItem(UID_KEY),
|
||||
token: window.localStorage.getItem(AUTH_TOKEN_KEY),
|
||||
})
|
||||
if (decision === 'pass-local' || decision === 'deny') {
|
||||
return null
|
||||
}
|
||||
const response = await get<{ success: boolean; data?: CheckLoginData }>('/newApi/check_login')
|
||||
|
||||
@@ -10,11 +10,7 @@
|
||||
|
||||
import { COMPANY_NAME_STORAGE_KEY } from './company-identity.ts'
|
||||
import { ACCOUNT_EXPIRY_STORAGE_KEY } from './account-expiry.ts'
|
||||
|
||||
const AUTH_TOKEN_KEY = 'aiimage_auth_token'
|
||||
const UID_KEY = 'uid'
|
||||
const USERNAME_KEY = 'username'
|
||||
const AUTO_LOGIN_KEY = 'aiimage_auto_login'
|
||||
import { AUTH_TOKEN_KEY, UID_KEY, USERNAME_KEY, AUTO_LOGIN_KEY } from './session-keys.ts'
|
||||
|
||||
/** 登录页据此标记显示"已被顶下线"警示(路由守卫会吞掉 query,故用 localStorage 兜底)。 */
|
||||
export const KICK_NOTICE_KEY = 'aiimage_kick_notice'
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* 登录态存储键的唯一出处(收口 2026-10-09 评审「令牌键名 4 处各自定义 + 2 处内联」)。
|
||||
*
|
||||
* 令牌键名以前散在 DesktopLoginPage / ensure-auth / kick-handler / user-token-sync 四份常量与
|
||||
* http.ts / permission.ts 两处内联字符串里:改名要同时命中 6 处,漏一处就是"登了又没完全登"
|
||||
* (拦截器读不到令牌、下线收口清不掉旧键)。这里只留一份定义,其余一律 import。
|
||||
*
|
||||
* 判据:tests/auth-token-key-single-source.test.ts(全树字面量清零 + 非零对照 + 分母自证)。
|
||||
*/
|
||||
|
||||
/** 登录令牌(JWT)在 localStorage 里的键名。 */
|
||||
export const AUTH_TOKEN_KEY = 'aiimage_auth_token'
|
||||
|
||||
/** 当前登录用户 id;Java 侧按它选代理池、拼公开直链的 user_id。 */
|
||||
export const UID_KEY = 'uid'
|
||||
|
||||
/** 当前登录用户名,仅用于界面展示。 */
|
||||
export const USERNAME_KEY = 'username'
|
||||
|
||||
/** 是否自动登录('0' = 关)。被顶下线/登录失效时必须关掉,否则两台机器互踢不停。 */
|
||||
export const AUTO_LOGIN_KEY = 'aiimage_auto_login'
|
||||
@@ -1,5 +1,6 @@
|
||||
import { getPywebviewApi } from '@/shared/bridges/pywebview'
|
||||
import { setUserTokenPushTarget, syncUserTokenToBridge } from '@/shared/auth/user-token-bridge'
|
||||
import { AUTH_TOKEN_KEY } from '@/shared/auth/session-keys.ts'
|
||||
|
||||
/**
|
||||
* 把登录态令牌持续同步给桌面端 Python(A1/A3)。
|
||||
@@ -7,12 +8,18 @@ import { setUserTokenPushTarget, syncUserTokenToBridge } from '@/shared/auth/use
|
||||
* 触发点:应用启动(桥可能未就绪,监听 pywebviewready 后补推)、localStorage 变化(登录/登出)、
|
||||
* 以及每 60 秒兜底轮询(同标签页内 localStorage 变化不触发 storage 事件)。
|
||||
* 网页形态(无桥)静默跳过。
|
||||
*
|
||||
* 卸载配对:三个注册点(2 个 window 监听 + 1 个轮询定时器)的句柄都留在模块里,
|
||||
* `uninstallUserTokenSync()` 逐个摘掉;由根组件 App.vue 的 onBeforeUnmount 调用,
|
||||
* 判据见 tests/listener-timer-pairing.test.ts。
|
||||
*/
|
||||
|
||||
const AUTH_TOKEN_KEY = 'aiimage_auth_token'
|
||||
const POLL_INTERVAL_MS = 60_000
|
||||
|
||||
let installed = false
|
||||
let readyHandler: (() => void) | null = null
|
||||
let storageHandler: ((event: StorageEvent) => void) | null = null
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
function readToken(): string {
|
||||
try {
|
||||
@@ -50,11 +57,34 @@ export function installUserTokenSync(): void {
|
||||
|
||||
// 桥可能晚于脚本就绪:先尝试一次,再在 ready 事件与轮询里补
|
||||
apply()
|
||||
window.addEventListener('pywebviewready', apply)
|
||||
window.addEventListener('storage', (event) => {
|
||||
readyHandler = apply
|
||||
window.addEventListener('pywebviewready', readyHandler)
|
||||
storageHandler = (event: StorageEvent) => {
|
||||
if (!event.key || event.key === AUTH_TOKEN_KEY) {
|
||||
pushNow()
|
||||
}
|
||||
})
|
||||
window.setInterval(pushNow, POLL_INTERVAL_MS)
|
||||
}
|
||||
window.addEventListener('storage', storageHandler)
|
||||
pollTimer = window.setInterval(pushNow, POLL_INTERVAL_MS)
|
||||
}
|
||||
|
||||
/** 卸载:摘掉两个监听并停掉兜底轮询(与 installUserTokenSync 配对,可重复调用)。 */
|
||||
export function uninstallUserTokenSync(): void {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
if (readyHandler) {
|
||||
window.removeEventListener('pywebviewready', readyHandler)
|
||||
readyHandler = null
|
||||
}
|
||||
if (storageHandler) {
|
||||
window.removeEventListener('storage', storageHandler)
|
||||
storageHandler = null
|
||||
}
|
||||
if (pollTimer !== null) {
|
||||
window.clearInterval(pollTimer)
|
||||
pollTimer = null
|
||||
}
|
||||
setUserTokenPushTarget(null)
|
||||
installed = false
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
import { computed, ref } from 'vue'
|
||||
import { getPywebviewApi } from '@/shared/bridges/pywebview'
|
||||
import { isHttpUrl, safeHttpUrl } from '@/shared/utils/safe-url'
|
||||
import { selectChangelogEntries, selectVersionEntry, type ClientChangelogEntry } from '@/shared/client-changelog'
|
||||
import { compareVersions, normVersion } from '@/shared/utils/version-compare'
|
||||
import {
|
||||
@@ -26,6 +27,7 @@ export type { ClientVersionItem } from '@/shared/utils/version-picker'
|
||||
|
||||
const updateProgress = ref<UpdateProgress | null>(null)
|
||||
let progressListenerBound = false
|
||||
let progressListener: ((event: Event) => void) | null = null
|
||||
|
||||
// 公开版本列表:登录页与首页共用同一份缓存(SPA 内路由切换不重复拉取)
|
||||
const versions = ref<ClientVersionItem[]>([])
|
||||
@@ -40,11 +42,22 @@ let versionListLoaded = false
|
||||
function bindProgressListener() {
|
||||
if (progressListenerBound || typeof window === 'undefined') return
|
||||
progressListenerBound = true
|
||||
window.addEventListener('pywebview-update-progress', (event) => {
|
||||
progressListener = (event: Event) => {
|
||||
const progress = normalizeUpdateProgress((event as CustomEvent<unknown>).detail)
|
||||
if (!progress) return
|
||||
updateProgress.value = progress
|
||||
})
|
||||
}
|
||||
window.addEventListener('pywebview-update-progress', progressListener)
|
||||
}
|
||||
|
||||
/** 与 bindProgressListener 配对的卸载出口(App.vue onBeforeUnmount 调用)。 */
|
||||
export function disposeUpdateProgressListener() {
|
||||
if (typeof window === 'undefined') return
|
||||
if (progressListener) {
|
||||
window.removeEventListener('pywebview-update-progress', progressListener)
|
||||
progressListener = null
|
||||
}
|
||||
progressListenerBound = false
|
||||
}
|
||||
|
||||
async function fetchJson(url: string): Promise<Record<string, unknown>> {
|
||||
@@ -178,7 +191,13 @@ export function useVersionUpdate() {
|
||||
if (!doUpdateApp) {
|
||||
// 网页/无桌面桥形态:OSS 公开直链直接下载安装包(区别于桌面端自动下载安装)
|
||||
hint.value = '开始下载安装包,若浏览器未响应请再次点击...'
|
||||
window.location.href = url
|
||||
if (!isHttpUrl(url)) {
|
||||
console.warn('[safe-url] 更新包地址未通过白名单校验,已取消下载:', String(url).slice(0, 200))
|
||||
hint.value = '更新包地址不可用,请稍后重试或在本机客户端中打开'
|
||||
updating.value = false
|
||||
return
|
||||
}
|
||||
window.location.href = safeHttpUrl(url)
|
||||
updating.value = false
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* 全局错误处理器(收口 2026-10-09 评审「全树 errorHandler / unhandledrejection / onerror 各 0 处」)。
|
||||
*
|
||||
* 这一层之前是没有的:Vue 渲染期抛错只往控制台吐,界面上什么都不说,用户读到的是"点了没反应";
|
||||
* Promise 没接住的 rejection(接口栈、桥调用)更是直接消失。这里补三个出口并一次装好:
|
||||
* ① `app.config.errorHandler`——组件渲染 / 生命周期 / watcher 抛错;
|
||||
* ② `window` 的 `error` 事件——脱离 Vue 调用栈的顶层同步异常;
|
||||
* ③ `window` 的 `unhandledrejection`——没人 catch 的 Promise。
|
||||
*
|
||||
* 三条规矩:
|
||||
* - 界面只说中文:原文一律先过 `userNotice()`(英文异常原文只进控制台记录),
|
||||
* 这条是全项目的硬规矩,见 tests/user-notice-chinese-only-guard.test.ts;
|
||||
* - 一条都不能静默:每条错误都往记录环里塞一行可诊断文本(含出处与原文),控制台同步留痕;
|
||||
* - 不许把页面搞白屏:处理器自身异常被兜住(兜法里带一次可见提示,不是空 catch),
|
||||
* 并且绝不向上重抛;提示按冷却时间去重,避免渲染循环把界面刷成弹窗瀑布。
|
||||
*
|
||||
* 装好之后返回卸载函数,`disposeGlobalErrorGuard()` 由根组件 onBeforeUnmount 调用(卸载配对)。
|
||||
*/
|
||||
|
||||
import type { ComponentPublicInstance } from 'vue'
|
||||
import { userNotice } from './user-notice.ts'
|
||||
|
||||
/** 记录环上限:再多也没人看,只是把内存当日志盘。 */
|
||||
export const APP_ERROR_RECORD_LIMIT = 20
|
||||
|
||||
/** 两条界面提示之间的最短间隔:渲染循环里的同一个错不该刷出十条弹窗。 */
|
||||
export const APP_ERROR_NOTICE_COOLDOWN_MS = 5000
|
||||
|
||||
/** 单条记录里原文的截断长度。 */
|
||||
export const APP_ERROR_RAW_TEXT_LIMIT = 400
|
||||
|
||||
/** 兜底话术:原文不是中文时给用户看的那句(口语可读,不含异常名)。 */
|
||||
export const APP_ERROR_NOTICE_TEXT = '页面出了点问题,这一步没能完成。可以先刷新页面再试一次,反复出现请把刚才的操作告诉客服。'
|
||||
|
||||
/** 错误处理器自己出问题时说的话:不能拿异常原文当提示,也不能假装没事。 */
|
||||
const GUARD_FAILURE_TEXT = '页面出了点问题,提示消息暂时显示不出来。请刷新页面后重试。'
|
||||
|
||||
/** Vue 的 app 实例上我们要碰的那一个字段(只声明用到的形状,方便测试里给个假对象)。 */
|
||||
export interface ErrorGuardApp {
|
||||
config: {
|
||||
errorHandler?: (err: unknown, instance: ComponentPublicInstance | null, info: string) => void
|
||||
}
|
||||
}
|
||||
|
||||
export interface ErrorGuardListener {
|
||||
(event: unknown): void
|
||||
}
|
||||
|
||||
/** window 的注销形状(同样只声明用到的部分)。 */
|
||||
export interface ErrorGuardHost {
|
||||
addEventListener?: (type: string, listener: ErrorGuardListener) => void
|
||||
removeEventListener?: (type: string, listener: ErrorGuardListener) => void
|
||||
}
|
||||
|
||||
export interface ErrorGuardDeps {
|
||||
/** 用户可见出口(生产接 ElMessage.error,测试里注入假函数) */
|
||||
notify: (text: string) => void
|
||||
/** 落一条可诊断记录(默认 console.error + 内存环) */
|
||||
record?: (line: string) => void
|
||||
/** 时间源,冷却判定用 */
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
let records: string[] = []
|
||||
let noticeSentAt = 0
|
||||
let suppressedSinceLastNotice = 0
|
||||
let currentDisposer: (() => void) | null = null
|
||||
|
||||
/** 内存环里的最近若干条错误(支持同学排查时可在控制台 `__aiimageAppErrors()` 直接看)。 */
|
||||
export function getAppErrorRecords(): string[] {
|
||||
return records.slice()
|
||||
}
|
||||
|
||||
/** 清空记录环(测试用;界面上没有入口,别拿它当"错误已被处理")。 */
|
||||
export function clearAppErrorRecords(): void {
|
||||
records = []
|
||||
suppressedSinceLastNotice = 0
|
||||
}
|
||||
|
||||
/** 取原文:Error 取 message,字符串原样,其余尽量给个能看的形状。 */
|
||||
export function errorRawText(reason: unknown): string {
|
||||
if (reason instanceof Error) return String(reason.message ?? '')
|
||||
if (typeof reason === 'string') return reason
|
||||
if (reason === null || reason === undefined) return ''
|
||||
try {
|
||||
return String(reason)
|
||||
} catch {
|
||||
return '[无法转成文本的错误对象]'
|
||||
}
|
||||
}
|
||||
|
||||
/** 一行可诊断记录:出处 + 原文,只进控制台和内存环,不上界面。 */
|
||||
export function describeAppError(context: string, reason: unknown): string {
|
||||
const raw = errorRawText(reason).slice(0, APP_ERROR_RAW_TEXT_LIMIT)
|
||||
return `[${context}] ${raw || '(没有错误原文)'}`
|
||||
}
|
||||
|
||||
/** 界面文案:中文主干留下,英文原文(Java 栈名、`Network Error` 这类)换成中文兜底句。 */
|
||||
export function userTextForError(reason: unknown): string {
|
||||
return userNotice(errorRawText(reason), APP_ERROR_NOTICE_TEXT)
|
||||
}
|
||||
|
||||
function defaultRecord(line: string): void {
|
||||
console.error('[app-error]', line)
|
||||
}
|
||||
|
||||
/**
|
||||
* 一条错误进出自口:记录一定落,界面提示按冷却去重。
|
||||
* 被冷却吞掉的条数记在案,下一条真提示时补一句"还有 N 次同样的问题"。
|
||||
*/
|
||||
function report(context: string, reason: unknown, deps: ErrorGuardDeps, now: () => number): void {
|
||||
const line = describeAppError(context, reason)
|
||||
records.push(line)
|
||||
if (records.length > APP_ERROR_RECORD_LIMIT) records.splice(0, records.length - APP_ERROR_RECORD_LIMIT)
|
||||
;(deps.record ?? defaultRecord)(line)
|
||||
|
||||
const at = now()
|
||||
if (at - noticeSentAt < APP_ERROR_NOTICE_COOLDOWN_MS) {
|
||||
suppressedSinceLastNotice += 1
|
||||
return
|
||||
}
|
||||
noticeSentAt = at
|
||||
const text = userTextForError(reason)
|
||||
const suffix = suppressedSinceLastNotice > 0 ? `(同样的问题这期间还出现过 ${suppressedSinceLastNotice} 次)` : ''
|
||||
suppressedSinceLastNotice = 0
|
||||
deps.notify(suffix ? `${text}${suffix}` : text)
|
||||
}
|
||||
|
||||
/** 处理器自身不许再把异常抛回框架:兜住之后再给一句中文提示,而不是空 catch。 */
|
||||
function guardRun(body: () => void, deps: ErrorGuardDeps): void {
|
||||
try {
|
||||
body()
|
||||
} catch (fatal) {
|
||||
console.error('[app-error] 错误处理器自身异常', fatal)
|
||||
deps.notify(GUARD_FAILURE_TEXT)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 装上全局错误出口。第二个参数把"界面提示"和"记录"两个出口注进来,
|
||||
* 生产在 main.ts 用 ElMessage + console,测试给假对象,判据才跑得动。
|
||||
*/
|
||||
export function installGlobalErrorGuard(
|
||||
app: ErrorGuardApp,
|
||||
deps: ErrorGuardDeps,
|
||||
host?: ErrorGuardHost,
|
||||
): () => void {
|
||||
const now = deps.now ?? Date.now
|
||||
const listenerHost = host ?? (typeof window === 'undefined' ? undefined : (window as unknown as ErrorGuardHost))
|
||||
|
||||
const handleError = (event: unknown) => {
|
||||
guardRun(() => {
|
||||
const detail = event as { message?: unknown; error?: unknown } | undefined
|
||||
report('window.error', detail && detail.error !== undefined ? detail.error : detail?.message, deps, now)
|
||||
}, deps)
|
||||
}
|
||||
|
||||
const handleRejection = (event: unknown) => {
|
||||
guardRun(() => {
|
||||
report('unhandledrejection', (event as { reason?: unknown } | undefined)?.reason, deps, now)
|
||||
}, deps)
|
||||
}
|
||||
|
||||
app.config.errorHandler = (err: unknown, _instance: unknown, info: string) => {
|
||||
guardRun(() => {
|
||||
report(`vue:${info || 'unknown'}`, err, deps, now)
|
||||
}, deps)
|
||||
}
|
||||
|
||||
listenerHost?.addEventListener?.('error', handleError)
|
||||
listenerHost?.addEventListener?.('unhandledrejection', handleRejection)
|
||||
|
||||
const dispose = () => {
|
||||
listenerHost?.removeEventListener?.('error', handleError)
|
||||
listenerHost?.removeEventListener?.('unhandledrejection', handleRejection)
|
||||
app.config.errorHandler = undefined
|
||||
if (currentDisposer === dispose) currentDisposer = null
|
||||
}
|
||||
currentDisposer = dispose
|
||||
return dispose
|
||||
}
|
||||
|
||||
/** 卸载全局错误出口(根组件 onBeforeUnmount 调用,与 installGlobalErrorGuard 配对)。 */
|
||||
export function disposeGlobalErrorGuard(): void {
|
||||
const dispose = currentDisposer
|
||||
currentDisposer = null
|
||||
dispose?.()
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { computed, reactive } from 'vue'
|
||||
|
||||
import { getPywebviewApi } from '@/shared/bridges/pywebview'
|
||||
import { isHttpUrl } from './safe-url'
|
||||
|
||||
export type DownloadProgressStatus = 'selecting' | 'running' | 'success' | 'failed' | 'cancelled'
|
||||
|
||||
@@ -98,7 +99,24 @@ export function ensureDownloadProgressListener() {
|
||||
if (progressListenerBound || typeof window === 'undefined') return
|
||||
progressListenerBound = true
|
||||
window.addEventListener('pywebview-download-progress', handlePywebviewProgress)
|
||||
}export function useDownloadProgress() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 与 ensureDownloadProgressListener 配对的卸载出口:摘掉桥事件监听并停掉清扫定时器。
|
||||
* 由根组件 App.vue 的 onBeforeUnmount 调用(判据见 tests/listener-timer-pairing.test.ts)。
|
||||
*/
|
||||
export function disposeDownloadProgressListener() {
|
||||
if (typeof window !== 'undefined' && progressListenerBound) {
|
||||
window.removeEventListener('pywebview-download-progress', handlePywebviewProgress)
|
||||
progressListenerBound = false
|
||||
}
|
||||
if (sweepTimer !== null) {
|
||||
clearInterval(sweepTimer)
|
||||
sweepTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
export function useDownloadProgress() {
|
||||
ensureDownloadProgressListener()
|
||||
const items = computed(() =>
|
||||
Object.values(progressItems)
|
||||
@@ -120,8 +138,26 @@ function buildDownloadId(filename: string) {
|
||||
return `download:${Date.now()}:${Math.random().toString(16).slice(2)}:${safeName}`
|
||||
}
|
||||
|
||||
/** 白名单不通过时的统一说法:进度条目与返回值都用这一句(中文,用户读得懂)。 */
|
||||
const UNSAFE_DOWNLOAD_URL_TEXT = '下载地址不可用,请稍后重试或在本机客户端中打开'
|
||||
|
||||
export async function saveUrlWithProgress(url: string, filename: string, id = buildDownloadId(filename)) {
|
||||
ensureDownloadProgressListener()
|
||||
// 服务端/客户端透传的 file_url、downloadUrl 是开放字段,进桥之前先过白名单:
|
||||
// 校验不过就不发起下载,原因既落进度条目也进控制台留一行可查的记录(判据:tests/url-outlet-guard.test.ts)
|
||||
if (!isHttpUrl(url)) {
|
||||
console.warn('[safe-url] 下载地址未通过白名单校验,已取消下载:', String(url).slice(0, 200))
|
||||
upsertProgress({
|
||||
id,
|
||||
filename,
|
||||
status: 'failed',
|
||||
downloaded: 0,
|
||||
total: 0,
|
||||
percent: 0,
|
||||
error: UNSAFE_DOWNLOAD_URL_TEXT,
|
||||
})
|
||||
return { success: false, error: UNSAFE_DOWNLOAD_URL_TEXT }
|
||||
}
|
||||
const api = getPywebviewApi()
|
||||
if (!api?.save_file_from_url_new) {
|
||||
upsertProgress({
|
||||
|
||||
@@ -21,3 +21,13 @@ export function safeHttpUrl(raw?: string | null): string {
|
||||
}
|
||||
return ALLOWED_PROTOCOLS.has(parsed.protocol) ? value : '#'
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定版:给"要不要跳转/下载"用。
|
||||
*
|
||||
* `safeHttpUrl` 的兜底是 `'#'`,那是写给 `a[href]` 的(点了不动);跳转与下载要先知道
|
||||
* "这地址到底能不能用",否则 `window.open('#')` 会开一张空白标签页,用户看到的比不给还糟。
|
||||
*/
|
||||
export function isHttpUrl(raw?: string | null): boolean {
|
||||
return safeHttpUrl(raw) !== '#'
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ export const TASK_STATUS_TEXT: Record<string, string> = {
|
||||
RUNNING: '执行中',
|
||||
PENDING: '等待中',
|
||||
CANCELLED: '已取消',
|
||||
CANCELED: '已取消',
|
||||
SCHEDULED: '待执行',
|
||||
QUEUED: '排队中',
|
||||
};
|
||||
@@ -44,9 +45,19 @@ export const TASK_STATUS_CLASS: Record<string, TaskStatusClassName> = {
|
||||
COMPLETED: 'success',
|
||||
FAILED: 'failed',
|
||||
CANCELLED: 'failed',
|
||||
CANCELED: 'failed',
|
||||
RUNNING: 'running',
|
||||
};
|
||||
|
||||
/**
|
||||
* 取消态词表(美式 CANCELED 与英式 CANCELLED 并存:Java 侧两种都发得出,实测 35 与 16 处)。
|
||||
* 显示面必须都认,漏一个拼写它就掉进"未命中"的兜底里,在页面上被说成"执行中"。
|
||||
*/
|
||||
export const CANCELLED_STATUS_WORDS: readonly string[] = ['CANCELLED', 'CANCELED'];
|
||||
|
||||
/** 取消态文案:三页共用(原来靠 textFallback 兜,结果被念成「执行中」)。 */
|
||||
export const CANCELLED_STATUS_TEXT = '已取消';
|
||||
|
||||
export const TASK_STATUS_TEXT_FALLBACK = '等待中';
|
||||
export const TASK_STATUS_CLASS_FALLBACK: TaskStatusClassName = 'pending';
|
||||
|
||||
@@ -77,11 +88,27 @@ export function taskStatusClass(status?: string | null, overrides?: TaskStatusOp
|
||||
/**
|
||||
* 非终态一律显示「执行中」/ running 的页面(BrandWithdrawTab、BrandPatrolDeleteTab、
|
||||
* BrandQueryAsinTab 原行为):只区分 SUCCESS/COMPLETED/FAILED 三种终态。
|
||||
*
|
||||
* 但"取消"不是"还没跑完":任务已经被撤掉了却说成执行中,用户会一直等一个不会来的结果
|
||||
* (2026-10-09 评审实测:CANCELLED 在这 3 页显示为「执行中」)。所以取消态点名,
|
||||
* 两种拼写都列,别再让它掉进 textFallback。
|
||||
*/
|
||||
export const RUNNING_UNTIL_DONE_STATUS_OPTIONS: TaskStatusOptions = {
|
||||
replace: true,
|
||||
text: { SUCCESS: '已完成', COMPLETED: '已完成', FAILED: '失败' },
|
||||
classMap: { SUCCESS: 'success', COMPLETED: 'success', FAILED: 'failed' },
|
||||
text: {
|
||||
SUCCESS: '已完成',
|
||||
COMPLETED: '已完成',
|
||||
FAILED: '失败',
|
||||
CANCELLED: CANCELLED_STATUS_TEXT,
|
||||
CANCELED: CANCELLED_STATUS_TEXT,
|
||||
},
|
||||
classMap: {
|
||||
SUCCESS: 'success',
|
||||
COMPLETED: 'success',
|
||||
FAILED: 'failed',
|
||||
CANCELLED: 'failed',
|
||||
CANCELED: 'failed',
|
||||
},
|
||||
textFallback: '执行中',
|
||||
classFallback: 'running',
|
||||
};
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, resolve, relative, sep } from 'node:path'
|
||||
import { AUTH_TOKEN_KEY, AUTO_LOGIN_KEY, UID_KEY, USERNAME_KEY } from '../src/shared/auth/session-keys.ts'
|
||||
|
||||
/**
|
||||
* 令牌键名收成 1 个常量(2026-10-09 评审安全面:`aiimage_auth_token` 有 4 处各自定义 + 2 处内联字符串)。
|
||||
*
|
||||
* 散着的键名不是风格问题:改名要同时命中 6 处,漏一处的表现是"登录成功但请求不带令牌"
|
||||
* 或"下线了但旧键还留着令牌"。这里钉三件事:值本身、唯一定义点、以及每个消费点确实 import 它。
|
||||
*
|
||||
* 键值改动要连着后端与已发布客户端一起改,所以值也钉住(不是恒绿断言,是防手滑)。
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = resolve(here, '..')
|
||||
const SRC = resolve(ROOT, 'src')
|
||||
|
||||
/** 令牌键的字面量写法(单/双引号都算,反引号也算)。 */
|
||||
const TOKEN_LITERAL = /['"`]aiimage_auth_token['"`]/
|
||||
|
||||
/** 定义点:`const|export const 名字 = 'aiimage_auth_token'`。 */
|
||||
const TOKEN_DEFINITION = /\b(?:export\s+)?const\s+[A-Za-z0-9_]+\s*=\s*['"`]aiimage_auth_token['"`]/
|
||||
|
||||
/** 应当引用统一常量的消费点(构造名做锚点,不锚行号)。 */
|
||||
const CONSUMERS: Array<{ file: string; importOf: RegExp; construct: RegExp }> = [
|
||||
{ file: 'src/shared/api/http.ts', importOf: /import\s*\{[^}]*AUTH_TOKEN_KEY[^}]*\}\s*from\s*'\.\.\/auth\/session-keys\.ts'/, construct: /localStorage\.getItem\(AUTH_TOKEN_KEY\)/ },
|
||||
{ file: 'src/shared/api/types/modules/permission.ts', importOf: /import\s*\{[^}]*AUTH_TOKEN_KEY[^}]*\}\s*from\s*'\.\.\/\.\.\/\.\.\/auth\/session-keys\.ts'/, construct: /function getAuthToken\(\)/ },
|
||||
{ file: 'src/shared/auth/ensure-auth.ts', importOf: /import\s*\{[^}]*AUTH_TOKEN_KEY[^}]*\}\s*from\s*'\.\/session-keys\.ts'/, construct: /export async function ensureAuth\(\)/ },
|
||||
{ file: 'src/shared/auth/kick-handler.ts', importOf: /import\s*\{[^}]*AUTH_TOKEN_KEY[^}]*\}\s*from\s*'\.\/session-keys\.ts'/, construct: /function clearLocalSession\(\)/ },
|
||||
{ file: 'src/shared/auth/user-token-sync.ts', importOf: /import\s*\{[^}]*AUTH_TOKEN_KEY[^}]*\}\s*from\s*'@\/shared\/auth\/session-keys\.ts'/, construct: /function readToken\(\)/ },
|
||||
{ file: 'src/pages/login/DesktopLoginPage.vue', importOf: /import\s*\{[^}]*AUTH_TOKEN_KEY[^}]*\}\s*from\s*'@\/shared\/auth\/session-keys'/, construct: /async function submitLogin|void loginWithDevice|setItem\(AUTH_TOKEN_KEY/ },
|
||||
]
|
||||
|
||||
function sourceFiles(dir: string): string[] {
|
||||
const out: string[] = []
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) out.push(...sourceFiles(full))
|
||||
else if (entry.name.endsWith('.vue') || entry.name.endsWith('.ts')) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function read(relFromRoot: string): string {
|
||||
return readFileSync(join(ROOT, ...relFromRoot.split('/')), 'utf-8')
|
||||
}
|
||||
|
||||
/** 找出"字面量出现在统一出口之外"的文件(判据与注入自证共用同一个函数)。 */
|
||||
function literalOutsideSingleSource(entries: Array<{ rel: string; source: string }>): string[] {
|
||||
return entries
|
||||
.filter(({ rel, source }) => rel !== 'src/shared/auth/session-keys.ts' && TOKEN_LITERAL.test(source))
|
||||
.map(({ rel, source }) => `${rel}: ${source.split(/\r?\n/).find((line) => TOKEN_LITERAL.test(line))?.trim().slice(0, 100)}`)
|
||||
}
|
||||
|
||||
const ENTRIES = sourceFiles(SRC).map((file) => ({
|
||||
rel: relative(ROOT, file).split(sep).join('/'),
|
||||
source: readFileSync(file, 'utf-8'),
|
||||
}))
|
||||
|
||||
test('键名常量本身:值与形状钉住(改名要连着后端和已发布客户端,不是随手能动的)', () => {
|
||||
assert.equal(AUTH_TOKEN_KEY, 'aiimage_auth_token')
|
||||
assert.equal(UID_KEY, 'uid')
|
||||
assert.equal(USERNAME_KEY, 'username')
|
||||
assert.equal(AUTO_LOGIN_KEY, 'aiimage_auto_login')
|
||||
})
|
||||
|
||||
test('全树只有 session-keys.ts 一处定义令牌键名,内联字面量清零', () => {
|
||||
const definitions = ENTRIES.filter(({ source }) => TOKEN_DEFINITION.test(source))
|
||||
assert.deepEqual(definitions.map(({ rel }) => rel), ['src/shared/auth/session-keys.ts'],
|
||||
`令牌键名的定义点应当只有一个,实测:${definitions.map(({ rel }) => rel).join(', ')}`)
|
||||
assert.deepEqual(literalOutsideSingleSource(ENTRIES), [], '这些地方还在自己写令牌键名')
|
||||
})
|
||||
|
||||
test('分母自证:扫描器真的在扫整棵树(命中数塌了就不许报"清零")', () => {
|
||||
const literalSites = ENTRIES.filter(({ source }) => TOKEN_LITERAL.test(source)).length
|
||||
assert.ok(literalSites >= 1, `全树连一处令牌键名字面量都没扫到——扫描器或目录树坏了,"零违规"不作数`)
|
||||
assert.ok(ENTRIES.length > 100, `只扫到 ${ENTRIES.length} 个源文件,分母不对`)
|
||||
const importSites = ENTRIES.filter(({ source }) => /AUTH_TOKEN_KEY/.test(source)).length
|
||||
assert.ok(importSites >= 7, `只有 ${importSites} 个文件提到 AUTH_TOKEN_KEY(定义 + 6 个消费点,下限 7)——引用没接上`)
|
||||
// 定义点自己必须带着那个值(防止有人把 session-keys 掏空来"清零"字面量)
|
||||
const sessionKeys = read('src/shared/auth/session-keys.ts')
|
||||
assert.match(sessionKeys, /export const AUTH_TOKEN_KEY = 'aiimage_auth_token'/)
|
||||
})
|
||||
|
||||
test('6 个消费点确实 import 统一常量,没有本地副本', () => {
|
||||
const problems: string[] = []
|
||||
for (const { file, importOf, construct } of CONSUMERS) {
|
||||
const source = read(file)
|
||||
if (!importOf.test(source)) problems.push(`${file} 没有 import 统一的 AUTH_TOKEN_KEY`)
|
||||
if (!construct.test(source)) problems.push(`${file} 的锚点构造没找到(改形状了,判据要跟着改)`)
|
||||
if (/\bconst\s+AUTH_TOKEN_KEY\s*=/.test(source)) problems.push(`${file} 还留着自己的 AUTH_TOKEN_KEY 定义`)
|
||||
}
|
||||
assert.deepEqual(problems, [], problems.join('\n'))
|
||||
})
|
||||
|
||||
test('注入自证:往消费点塞一条内联字面量一定被判红', () => {
|
||||
const target = ENTRIES.find(({ rel }) => rel === 'src/shared/api/http.ts')
|
||||
assert.ok(target, 'http.ts 没进分母')
|
||||
const anchor = 'const token = window.localStorage.getItem(AUTH_TOKEN_KEY) || \'\''
|
||||
assert.equal(target.source.split(anchor).length - 1, 1, '锚点不唯一,注入自证不作数')
|
||||
const injected = target.source.replace(anchor, "const token = window.localStorage.getItem('aiimage_auth_token') || ''")
|
||||
assert.notEqual(injected, target.source, '注入没生效,这条自证是假的')
|
||||
assert.deepEqual(literalOutsideSingleSource([{ rel: target.rel, source: injected }]), [`${target.rel}: ${injected.split(/\r?\n/).find((l) => TOKEN_LITERAL.test(l))?.trim().slice(0, 100)}`],
|
||||
'内联字面量没被抓出来')
|
||||
// 合法写法(引用常量)必须放得过
|
||||
assert.deepEqual(literalOutsideSingleSource([{ rel: target.rel, source: target.source }]), [])
|
||||
})
|
||||
@@ -24,7 +24,14 @@ const BASELINE = {
|
||||
// 同一批另两处(pywebview addEventListener 的外层兜底、isSessionExpiredNav 的外层兜底)挡的是
|
||||
// 不可能发生的事(内层 lsGet 已自带兜底、URLSearchParams 对字符串永不抛),本轮直接摘掉,
|
||||
// 所以这里只 +1 而不是 +3。静默数 silent 一格没动(仍 <=84),逐文件台账也对平。
|
||||
blocks: 296,
|
||||
blocks: 298,
|
||||
// 298 = 296 + 全局错误出口 app-error.ts 的两支新 try/catch(10-09 装 app.config.errorHandler /
|
||||
// window.onerror / unhandledrejection 时引入),两支都不是"吞":
|
||||
// ① String(reason) 对无 toString 的对象/Symbol 会抛,兜法返回一句中文占位文本,
|
||||
// 该文本随后可见(进界面提示 + 内存环 + 控制台);
|
||||
// ② guardRun 挡的是"处理器自己崩了把页面带白屏",兜法是 console.error + 一次中文提示,
|
||||
// 且刻意不向上重抛(重抛会让 Vue 再进一次同一个处理器)。
|
||||
// silent 一格没涨(两支都有用户可见出口),台账无需新增条目。
|
||||
silent: 84,
|
||||
/** 逐文件台账:只钉总数与文件数两个标量的棘轮,会被「A 加一条 + B 减一条」整段绕过。 */
|
||||
perFile: {
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, resolve, relative, sep } from 'node:path'
|
||||
import {
|
||||
APP_ERROR_NOTICE_COOLDOWN_MS,
|
||||
APP_ERROR_NOTICE_TEXT,
|
||||
APP_ERROR_RECORD_LIMIT,
|
||||
clearAppErrorRecords,
|
||||
describeAppError,
|
||||
disposeGlobalErrorGuard,
|
||||
errorRawText,
|
||||
getAppErrorRecords,
|
||||
installGlobalErrorGuard,
|
||||
userTextForError,
|
||||
} from '../src/shared/utils/app-error.ts'
|
||||
import type { ErrorGuardApp } from '../src/shared/utils/app-error.ts'
|
||||
|
||||
/**
|
||||
* 全局错误处理器(2026-10-09 评审稳定面 5.0 的第一条:全树 `app.config.errorHandler`、
|
||||
* `unhandledrejection`、`window.onerror` 各 0 处;非零对照 `router.onError` 恰 1 处)。
|
||||
*
|
||||
* 这条判据主要跑行为:造一个假 app 与假 window 把三个出口装上,然后真去触发它们,
|
||||
* 看"用户看到的话"和"可诊断的记录"是否都出来——静态计数只能证明代码在场,证明不了它会响。
|
||||
* 静态那半边留给接线(main.ts 装了、App.vue 卸了),同样配非零对照与注入自证。
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = resolve(here, '..')
|
||||
const SRC = resolve(ROOT, 'src')
|
||||
|
||||
const CJK = /[㐀-䶿一-鿿]/
|
||||
|
||||
interface FakeHost {
|
||||
added: Array<{ type: string; listener: (event: never) => void }>
|
||||
removed: string[]
|
||||
emit: (type: string, event: unknown) => void
|
||||
}
|
||||
|
||||
/** 每个假世界自己的时钟起点:模块级冷却状态会跨用例,起点不隔开就会互相吃掉提示。 */
|
||||
let worldSeq = 0
|
||||
|
||||
function makeWorld() {
|
||||
const notices: string[] = []
|
||||
const lines: string[] = []
|
||||
const listeners = new Map<string, Array<(event: never) => void>>()
|
||||
const removed: string[] = []
|
||||
worldSeq += 1
|
||||
let clock = worldSeq * 10_000_000
|
||||
const host = {
|
||||
addEventListener: (type: string, listener: (event: never) => void) => {
|
||||
listeners.set(type, [...(listeners.get(type) ?? []), listener])
|
||||
},
|
||||
removeEventListener: (type: string) => {
|
||||
removed.push(type)
|
||||
listeners.delete(type)
|
||||
},
|
||||
}
|
||||
const app: ErrorGuardApp = { config: {} }
|
||||
const emit = (type: string, event: unknown) => {
|
||||
for (const listener of listeners.get(type) ?? []) (listener as (e: unknown) => void)(event)
|
||||
}
|
||||
const advance = (ms: number) => { clock += ms }
|
||||
const dispose = installGlobalErrorGuard(app, {
|
||||
notify: (text) => notices.push(text),
|
||||
record: (line) => lines.push(line),
|
||||
now: () => clock,
|
||||
}, host)
|
||||
const fakeHost: FakeHost = {
|
||||
added: [...listeners.entries()].map(([type, ls]) => ({ type, listener: ls[0] })),
|
||||
removed,
|
||||
emit,
|
||||
}
|
||||
return { app, notices, lines, dispose, advance, fakeHost, listenerTypes: () => [...listeners.keys()].sort() }
|
||||
}
|
||||
|
||||
function sourceFiles(dir: string): string[] {
|
||||
const out: string[] = []
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) out.push(...sourceFiles(full))
|
||||
else if (entry.name.endsWith('.vue') || entry.name.endsWith('.ts')) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const ENTRIES = sourceFiles(SRC).map((file) => ({
|
||||
rel: relative(ROOT, file).split(sep).join('/'),
|
||||
source: readFileSync(file, 'utf-8'),
|
||||
}))
|
||||
|
||||
function read(rel: string): string {
|
||||
return ENTRIES.find((e) => e.rel === rel)?.source ?? readFileSync(join(ROOT, ...rel.split('/')), 'utf-8')
|
||||
}
|
||||
|
||||
/** 三个出口的在场判据(装配面)。`from` 用于注入自证:把装配删掉就该判红。 */
|
||||
function guardWiring(source: string) {
|
||||
// `addEventListener(` 与可选链写法 `addEventListener?.(` 都算(源码里用的是后者)
|
||||
return {
|
||||
vueErrorHandler: /app\.config\.errorHandler\s*=|config\.errorHandler\s*=\s*\(?\s*(?:err|error)\b/.test(source),
|
||||
rejection: /addEventListener\??\.?\(\s*['"]unhandledrejection['"]/.test(source),
|
||||
windowError: /addEventListener\??\.?\(\s*['"]error['"]/.test(source),
|
||||
}
|
||||
}
|
||||
|
||||
test('装上的那一刻三个出口都在,卸载时全部摘掉', () => {
|
||||
clearAppErrorRecords()
|
||||
const world = makeWorld()
|
||||
assert.equal(typeof world.app.config.errorHandler, 'function', 'app.config.errorHandler 没装上')
|
||||
assert.deepEqual(world.listenerTypes(), ['error', 'unhandledrejection'], 'window 上的两个出口少一个')
|
||||
world.dispose()
|
||||
assert.equal(world.app.config.errorHandler, undefined, '卸载后 errorHandler 还挂着')
|
||||
assert.deepEqual(world.fakeHost.removed.sort(), ['error', 'unhandledrejection'], '卸载没有 removeEventListener 配对')
|
||||
})
|
||||
|
||||
test('三个出口都真的响:记录一定落,界面只说中文', () => {
|
||||
clearAppErrorRecords()
|
||||
const world = makeWorld()
|
||||
// ① Vue 渲染期抛错(英文异常原文,绝不能出现在界面上)
|
||||
world.app.config.errorHandler?.(new Error('Cannot read properties of undefined'), null, 'render')
|
||||
// 越过冷却再发第二条,避免被去重吃掉(去重本身另有用例)
|
||||
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
||||
// ② 顶层同步异常
|
||||
world.fakeHost.emit('error', { message: 'Uncaught ReferenceError: x is not defined', error: undefined })
|
||||
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
||||
// ③ 没人接的 Promise
|
||||
world.fakeHost.emit('unhandledrejection', { reason: 'Network Error' })
|
||||
|
||||
assert.equal(world.notices.length, 3, `三条错误只出声 ${world.notices.length} 次`)
|
||||
for (const text of world.notices) {
|
||||
assert.ok(CJK.test(text), `界面提示必须含中文:${text}`)
|
||||
for (const english of ['Cannot read properties', 'ReferenceError', 'Network Error', 'Uncaught']) {
|
||||
assert.ok(!text.includes(english), `英文异常原文漏到了界面上:${text}`)
|
||||
}
|
||||
}
|
||||
// 记录里必须有原文与出处(否则支持同学拿什么对后端日志)
|
||||
assert.equal(world.lines.length, 3, '记录条数与错误条数不一致,有错误被吞了')
|
||||
assert.match(world.lines[0], /^\[vue:render\] Cannot read properties of undefined/)
|
||||
assert.match(world.lines[1], /^\[window\.error\] Uncaught ReferenceError/)
|
||||
assert.match(world.lines[2], /^\[unhandledrejection\] Network Error/)
|
||||
assert.equal(getAppErrorRecords().length, 3, '内存环里也该留着这 3 条')
|
||||
})
|
||||
|
||||
test('中文原文照原样透出,不做无谓改写', () => {
|
||||
const world = makeWorld()
|
||||
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
||||
world.app.config.errorHandler?.(new Error('任务已被取消,请重新提交'), null, 'watcher')
|
||||
assert.deepEqual(world.notices, ['任务已被取消,请重新提交'])
|
||||
assert.equal(userTextForError('Similar ASIN result rows are empty'), APP_ERROR_NOTICE_TEXT)
|
||||
assert.equal(errorRawText(null), '')
|
||||
assert.equal(describeAppError('vue:x', null), '[vue:x] (没有错误原文)')
|
||||
})
|
||||
|
||||
test('同一个错在渲染循环里刷屏时:只说一次,但被压掉的条数记在案', () => {
|
||||
const world = makeWorld()
|
||||
for (let i = 0; i < 5; i += 1) {
|
||||
world.app.config.errorHandler?.(new Error(`loop ${i}`), null, 'render')
|
||||
}
|
||||
assert.equal(world.notices.length, 1, '5 条同场错误刷出了多条弹窗')
|
||||
assert.equal(world.lines.length, 5, '被去重的那几条不能连记录一起消失')
|
||||
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
||||
world.app.config.errorHandler?.(new Error('after cooldown'), null, 'render')
|
||||
assert.deepEqual(world.notices[1], `${APP_ERROR_NOTICE_TEXT}(同样的问题这期间还出现过 4 次)`)
|
||||
})
|
||||
|
||||
test('处理器自己抛了也不许把页面搞白屏:兜住、留痕、再说一句中文', () => {
|
||||
const notices: string[] = []
|
||||
const lines: string[] = []
|
||||
const boom = {
|
||||
addEventListener: () => { /* 假 window 不需要 */ },
|
||||
removeEventListener: () => { /* 同上 */ },
|
||||
}
|
||||
const app: ErrorGuardApp = { config: {} }
|
||||
installGlobalErrorGuard(app, {
|
||||
notify: (text) => {
|
||||
notices.push(text)
|
||||
if (notices.length === 1) throw new Error('弹窗组件挂了')
|
||||
},
|
||||
record: (line) => lines.push(line),
|
||||
now: () => (worldSeq += 1) * 10_000_000,
|
||||
}, boom)
|
||||
// 第一条:notify 抛错 → 处理器不得把异常抛回 Vue,否则这次渲染直接白屏
|
||||
assert.doesNotThrow(() => app.config.errorHandler?.(new Error('first'), null, 'render'))
|
||||
assert.ok(notices.some((text) => CJK.test(text)), '处理器自身异常时没给出中文提示')
|
||||
// 第二条:同样的路径再来一次,依然不抛
|
||||
assert.doesNotThrow(() => app.config.errorHandler?.(new Error('second'), null, 'render'))
|
||||
})
|
||||
|
||||
test('记录环有上限:挤掉最老的而不是无限攒', () => {
|
||||
clearAppErrorRecords()
|
||||
const world = makeWorld()
|
||||
for (let i = 0; i < APP_ERROR_RECORD_LIMIT + 8; i += 1) {
|
||||
world.advance(APP_ERROR_NOTICE_COOLDOWN_MS + 1)
|
||||
world.app.config.errorHandler?.(new Error(`e${i}`), null, 'render')
|
||||
}
|
||||
const records = getAppErrorRecords()
|
||||
assert.equal(records.length, APP_ERROR_RECORD_LIMIT, `记录环长到了 ${records.length}`)
|
||||
assert.match(records[records.length - 1], /e27/)
|
||||
assert.ok(!records.some((line) => line.includes('[vue:render] e0')), '最老的一条没被挤掉')
|
||||
})
|
||||
|
||||
test('接线钉子:main.ts 装了、App.vue 卸了,全树三个出口都在场', () => {
|
||||
const main = read('src/main.ts')
|
||||
const appVue = read('src/App.vue')
|
||||
assert.match(main, /installGlobalErrorGuard\(\s*app\s*,/, 'main.ts 没把处理器装到 app 上')
|
||||
assert.match(main, /notify:.*ElMessage\.error/s, '界面出口没接 ElMessage')
|
||||
assert.match(appVue, /onBeforeUnmount\(\(\)\s*=>\s*\{[^}]*disposeGlobalErrorGuard\(\)/, 'App.vue 没有卸载配对')
|
||||
const present = {
|
||||
vueErrorHandler: ENTRIES.filter(({ source }) => guardWiring(source).vueErrorHandler).length,
|
||||
rejection: ENTRIES.filter(({ source }) => guardWiring(source).rejection).length,
|
||||
windowError: ENTRIES.filter(({ source }) => guardWiring(source).windowError).length,
|
||||
}
|
||||
assert.ok(present.vueErrorHandler >= 1, 'app.config.errorHandler 全树 0 处——评审那条缺陷没修上')
|
||||
assert.ok(present.rejection >= 1, 'unhandledrejection 全树 0 处')
|
||||
assert.ok(present.windowError >= 1, '顶层 error 出口全树 0 处')
|
||||
// 非零对照:证明扫描器真的会数东西,而不是扫了个空
|
||||
const routerOnError = ENTRIES.filter(({ source }) => /router\.onError\(/.test(source)).length
|
||||
assert.equal(routerOnError, 1, `router.onError 对照面应为 1 处,实测 ${routerOnError}——扫描口径变了`)
|
||||
assert.ok(ENTRIES.length > 100, `只扫到 ${ENTRIES.length} 个源文件,分母不对`)
|
||||
})
|
||||
|
||||
test('注入自证:把装配删掉,接线判据立刻变红', () => {
|
||||
const main = read('src/main.ts')
|
||||
assert.ok(/installGlobalErrorGuard\(\s*app\s*,/.test(main), 'main.ts 的装配形状变了,判据要跟着改')
|
||||
const stripped = main.replace(/installGlobalErrorGuard\([\s\S]*?\n\}\)/, '/* 装配被删掉 */')
|
||||
assert.notEqual(stripped, main, '注入没生效,这条自证是假的')
|
||||
assert.ok(!/installGlobalErrorGuard\(\s*app\s*,/.test(stripped), '删掉装配后仍判成"已装",上面那条就是恒绿')
|
||||
assert.ok(!/onBeforeUnmount\(\(\)\s*=>\s*\{[^}]*disposeGlobalErrorGuard\(\)/.test(
|
||||
read('src/App.vue').replace('disposeGlobalErrorGuard()', '/* 卸载被删掉 */')), '卸载判据删掉了装配也照样绿')
|
||||
// 真装了的那份源码必须能被同口径认出来
|
||||
assert.deepEqual(guardWiring(read('src/shared/utils/app-error.ts')).vueErrorHandler, true, 'app-error.ts 里的赋值没被判成已装')
|
||||
assert.deepEqual(guardWiring(read('src/shared/utils/app-error.ts')).rejection, true, 'unhandledrejection 注册没被认出')
|
||||
})
|
||||
|
||||
test('disposeGlobalErrorGuard 走的是同一条卸载路(App.vue 里调的是它)', () => {
|
||||
const world = makeWorld()
|
||||
assert.deepEqual(world.listenerTypes(), ['error', 'unhandledrejection'])
|
||||
disposeGlobalErrorGuard()
|
||||
assert.deepEqual(world.listenerTypes(), [], 'disposeGlobalErrorGuard 没摘掉监听')
|
||||
})
|
||||
@@ -32,8 +32,12 @@ export interface CatchScan {
|
||||
silent: SilentCatch[]
|
||||
}
|
||||
|
||||
/** 用户可见提示的符号名(本仓只有 Element Plus 这一套)。 */
|
||||
const TOAST_SYMBOLS = new Set(['ElMessage', 'ElNotification', 'ElMessageBox'])
|
||||
/** 用户可见提示的符号名:Element Plus 那一套,加上本仓自己的提示出口 `userNotice`,
|
||||
* 以及注入式提示句柄(`app-error.ts` 的 `deps.notify(...)`——生产里传的就是 userNotice,
|
||||
* 扫描器看不穿注入,于是把"报了用户"误判成"只 log",这是尺子的盲区而不是代码的静默)。
|
||||
* 放宽的边界由 tests/catch-silence-ratchet.test.ts 的分母自证兜着:
|
||||
* api-secret-store.ts 与 DesktopLoginPage.vue 的静默数必须仍然 >0,抓不到就是这条规则放得太开。 */
|
||||
const TOAST_SYMBOLS = new Set(['ElMessage', 'ElNotification', 'ElMessageBox', 'userNotice', 'notify'])
|
||||
|
||||
function walk(node: any, cb: (n: any) => void): void {
|
||||
cb(node)
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
/**
|
||||
* 跳转/下载出口的白名单校验扫描器(判据在 tests/url-outlet-guard.test.ts)。
|
||||
*
|
||||
* 为什么按 AST 而不是 grep:`window.location.href = 服务端返回的 file_url` 这类口子写法差别很大
|
||||
* (`window.open(x)`、`saveUrlWithProgress(url, ...)`、`bridge.save_file_from_url(url, ...)`、
|
||||
* 先存进变量再跳),grep 只能盯一种形状;而真正要判的是
|
||||
* **"这次跳转的地址过没过白名单"**——校验可能写在同一个函数的开头,也可能被抽成本地小函数
|
||||
* (本仓的收口写法就是这样)。所以按"宿主函数"判,再把具名本地函数的守卫沿调用链传上去
|
||||
* (不动点迭代):函数改名、换排版、加参数都不会让尺子失明。
|
||||
*
|
||||
* 口径:
|
||||
* ① 出口 = `open(` / `saveUrlWithProgress(` / `save_file_from_url(` 调用、`*.location.href =` 赋值、
|
||||
* `*.location.assign(`/`*.location.replace(` 调用;
|
||||
* ② 出口任一祖先函数体里出现 `isHttpUrl(` 或 `safeHttpUrl(` → 已校验;
|
||||
* ③ 祖先函数调用了本文件里"已校验"的具名函数 → 也算已校验。
|
||||
*/
|
||||
import { createRequire } from 'node:module'
|
||||
import { extractScript, parseModule } from './task-terminal-ast-ruler.ts'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const ts = require('typescript')
|
||||
|
||||
/** 白名单校验函数名(src/shared/utils/safe-url.ts 的出口) */
|
||||
export const GUARD_NAMES = new Set(['isHttpUrl', 'safeHttpUrl'])
|
||||
|
||||
export interface UrlOutlet {
|
||||
file: string
|
||||
line: number
|
||||
/** 出口形状的名字,报错时给可读证据 */
|
||||
kind: string
|
||||
/** 最内层具名宿主函数(找不到=模块顶层) */
|
||||
host: string
|
||||
/** 命中的那条语句(截断) */
|
||||
snippet: string
|
||||
/** 是否过了白名单(按祖先函数与调用链判) */
|
||||
guarded: boolean
|
||||
}
|
||||
|
||||
export interface OutletScan {
|
||||
file: string
|
||||
outlets: UrlOutlet[]
|
||||
unguarded: UrlOutlet[]
|
||||
}
|
||||
|
||||
function walk(node: any, cb: (n: any) => void): void {
|
||||
cb(node)
|
||||
ts.forEachChild(node, (child: any) => walk(child, cb))
|
||||
}
|
||||
|
||||
/** 调用点的名字:`foo(...)` 取 foo,`a.b(...)` 取 b(`window.open` 就当 open)。 */
|
||||
function calledName(call: any): string {
|
||||
const callee = call.expression
|
||||
if (!callee) return ''
|
||||
if (ts.isIdentifier(callee)) return callee.text
|
||||
if (ts.isPropertyAccessExpression(callee) && callee.name) return callee.name.text
|
||||
return ''
|
||||
}
|
||||
|
||||
function calleeText(call: any): string {
|
||||
const callee = call.expression
|
||||
return callee && typeof callee.getText === 'function' ? callee.getText() : ''
|
||||
}
|
||||
|
||||
/** `x.location.href = ...` / `location.href = ...` 这类赋值出口。 */
|
||||
function isLocationHrefAssignment(node: any): boolean {
|
||||
if (!ts.isBinaryExpression(node)) return false
|
||||
if (node.operatorToken?.kind !== ts.SyntaxKind.EqualsToken) return false
|
||||
const left = node.left
|
||||
if (!ts.isPropertyAccessExpression(left) || left.name?.text !== 'href') return false
|
||||
const base = left.expression
|
||||
return ts.isPropertyAccessExpression(base) && base.name?.text === 'location'
|
||||
}
|
||||
|
||||
function outletKindOf(node: any): string | null {
|
||||
if (ts.isCallExpression(node)) {
|
||||
const name = calledName(node)
|
||||
if (name === 'open') return 'window.open'
|
||||
if (name === 'saveUrlWithProgress') return 'saveUrlWithProgress'
|
||||
if (name === 'save_file_from_url') return 'bridge.save_file_from_url'
|
||||
if ((name === 'assign' || name === 'replace') && /\.location$/.test(calleeText(node))) return `location.${name}`
|
||||
return null
|
||||
}
|
||||
if (isLocationHrefAssignment(node)) return 'location.href='
|
||||
return null
|
||||
}
|
||||
|
||||
function isFunctionLike(node: any): boolean {
|
||||
return ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node)
|
||||
|| ts.isArrowFunction(node) || ts.isMethodDeclaration(node)
|
||||
}
|
||||
|
||||
function functionName(node: any): string {
|
||||
if (!node) return ''
|
||||
if (node.name && typeof node.name.text === 'string') return node.name.text
|
||||
if (node.parent && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) return node.parent.name.text
|
||||
return ''
|
||||
}
|
||||
|
||||
/** 沿 parent 链收集具名宿主函数(校验常写在入口函数开头,所以整条链都算)。 */
|
||||
function hostChainOf(node: any): string[] {
|
||||
const names: string[] = []
|
||||
let cur = node
|
||||
while (cur) {
|
||||
if (isFunctionLike(cur)) {
|
||||
const name = functionName(cur)
|
||||
if (name && !names.includes(name)) names.push(name)
|
||||
}
|
||||
cur = cur.parent
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
/** 文件里具名函数 → 它(含嵌套块)调用到的名字集合。 */
|
||||
function collectCallGraph(sf: any): Map<string, string[]> {
|
||||
const graph = new Map<string, string[]>()
|
||||
walk(sf, (node: any) => {
|
||||
if (!isFunctionLike(node)) return
|
||||
const name = functionName(node)
|
||||
if (!name) return
|
||||
const calls = new Set<string>(graph.get(name) ?? [])
|
||||
walk(node, (inner: any) => {
|
||||
if (!ts.isCallExpression(inner)) return
|
||||
const called = calledName(inner)
|
||||
if (called) calls.add(called)
|
||||
})
|
||||
graph.set(name, [...calls])
|
||||
})
|
||||
return graph
|
||||
}
|
||||
|
||||
/** 哪些函数名"带白名单校验":自己调过 isHttpUrl/safeHttpUrl,或调用链上过。 */
|
||||
function guardedNamesOf(graph: Map<string, string[]>): Set<string> {
|
||||
const guarded = new Set<string>()
|
||||
for (const [name, calls] of graph) {
|
||||
if (calls.some((call) => GUARD_NAMES.has(call))) guarded.add(name)
|
||||
}
|
||||
let changed = true
|
||||
while (changed) {
|
||||
changed = false
|
||||
for (const [name, calls] of graph) {
|
||||
if (guarded.has(name)) continue
|
||||
if (calls.some((call) => guarded.has(call))) {
|
||||
guarded.add(name)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return guarded
|
||||
}
|
||||
|
||||
export function scanUrlOutlets(code: string, file: string, globallyGuarded: Set<string> = new Set()): OutletScan {
|
||||
const { script, lineOffset } = extractScript(code, file)
|
||||
const sf = parseModule(script, file)
|
||||
const guarded = guardedNamesOf(collectCallGraph(sf))
|
||||
const outlets: UrlOutlet[] = []
|
||||
walk(sf, (node: any) => {
|
||||
const kind = outletKindOf(node)
|
||||
if (!kind) return
|
||||
const hosts = hostChainOf(node)
|
||||
// 出口本身就是把守点的情况(`saveUrlWithProgress(...)` 这类收口函数):
|
||||
// 被调函数在别的模块里先校验再用地址,调用方不必重复判
|
||||
const calleeGuarded = ts.isCallExpression(node) && globallyGuarded.has(calledName(node))
|
||||
outlets.push({
|
||||
file,
|
||||
line: sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1 + lineOffset,
|
||||
kind,
|
||||
host: hosts[0] ?? '(模块顶层)',
|
||||
snippet: script.slice(node.getStart(sf), node.getEnd()).replace(/\s+/g, ' ').trim().slice(0, 90),
|
||||
guarded: calleeGuarded || hosts.some((host) => guarded.has(host)),
|
||||
})
|
||||
})
|
||||
return { file, outlets, unguarded: outlets.filter((outlet) => !outlet.guarded) }
|
||||
}
|
||||
|
||||
/** 一个文件里"导出、且自己调过白名单"的函数名(跨模块把守点)。 */
|
||||
export function exportedGuardedNames(code: string, file: string): string[] {
|
||||
const { script } = extractScript(code, file)
|
||||
const sf = parseModule(script, file)
|
||||
const graph = collectCallGraph(sf)
|
||||
const locallyGuarded = guardedNamesOf(graph)
|
||||
const exported = new Set<string>()
|
||||
walk(sf, (node: any) => {
|
||||
if (!(ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Export)) return
|
||||
if (ts.isVariableStatement(node)) {
|
||||
for (const decl of node.declarationList.declarations) {
|
||||
if (ts.isIdentifier(decl.name) && decl.initializer && isFunctionLike(decl.initializer)) exported.add(decl.name.text)
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!isFunctionLike(node)) return
|
||||
const name = functionName(node)
|
||||
if (name) exported.add(name)
|
||||
})
|
||||
return [...exported].filter(
|
||||
(name) => locallyGuarded.has(name) && (graph.get(name) ?? []).some((call) => GUARD_NAMES.has(call)),
|
||||
)
|
||||
}
|
||||
|
||||
/** 全库两遍:先把各模块的把守函数收上来,再判每个出口。 */
|
||||
export function scanAllUrlOutlets(sources: Array<{ file: string; code: string }>): OutletScan[] {
|
||||
const globallyGuarded = new Set<string>()
|
||||
for (const { file, code } of sources) {
|
||||
for (const name of exportedGuardedNames(code, file)) globallyGuarded.add(name)
|
||||
}
|
||||
return sources.map(({ file, code }) => scanUrlOutlets(code, file, globallyGuarded))
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, resolve, relative, sep } from 'node:path'
|
||||
|
||||
/**
|
||||
* 卸载配对判据(2026-10-09 评审稳定面 5.0:「卸载未配对 3 处」user-token-sync.ts 的两个监听与轮询、
|
||||
* download-progress.ts 的桥事件监听,外加 BrandShopMatchTab.vue:471 那条——本轮回读实测该处已配对,
|
||||
* 心跳走 categorized-timers、focus/visibilitychange 都在 onUnmounted 里摘了,见本文件最后一条用例)。
|
||||
*
|
||||
* 口径两条,都按"同一个注册点必须找得回它的反注册"判,不是数文件里有没有出现过 clearInterval:
|
||||
* ① 定时器:文件里 `setInterval(` 的个数 ≤ 反注册个数(`clearInterval(` / categorized-timers 的
|
||||
* `clearTimer(` / `clearCategory(` / `clearScope(`);
|
||||
* ② 监听器:每个 `(window|document).addEventListener('事件名'` 都得在同文件里有
|
||||
* `removeEventListener('事件名'`,带 `{ once: true }` 的算自反注册。
|
||||
*
|
||||
* 剩下的例外进台账(只许减),并且每个卸载出口都得真的被根组件接上——
|
||||
* 只定义不接线等于没接。
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = resolve(here, '..')
|
||||
const SRC = resolve(ROOT, 'src')
|
||||
|
||||
/** 台账:已知的、本轮判定"暂不配对"的注册点(数量只许减)。 */
|
||||
const UNPAIRED_LEDGER: Record<string, number> = {
|
||||
// 桥发现监听(pywebviewready):模块加载即绑,全应用生命周期都需要它,
|
||||
// 没有组件作用域可挂;绑之前有 pywebviewReadyBound 单次闸,不会累积。
|
||||
'src/shared/bridges/pywebview.ts': 1,
|
||||
}
|
||||
|
||||
/** 卸载出口必须被根组件接上(只定义不接线等于没接)。 */
|
||||
const WIRED_DISPOSERS = [
|
||||
'disposeGlobalErrorGuard',
|
||||
'uninstallUserTokenSync',
|
||||
'disposeDownloadProgressListener',
|
||||
'disposeUpdateProgressListener',
|
||||
]
|
||||
|
||||
const INTERVAL_REGISTER = /\bsetInterval\(/g
|
||||
const INTERVAL_TEARDOWN = /\bclearInterval\(|\bclearTimer\(|\bclearCategory\(|\bclearScope\(/g
|
||||
const LISTENER_REGISTER = /(?:window|document)\.addEventListener\??\.?\(\s*['"]([^'"]+)['"]([^\n]*)/g
|
||||
const LISTENER_TEARDOWN = /(?:window|document)\.removeEventListener\??\.?\(\s*['"]([^'"]+)['"]/g
|
||||
|
||||
interface PairingReport {
|
||||
file: string
|
||||
intervals: { registrations: number; teardowns: number }
|
||||
listeners: { event: string; line: number }[]
|
||||
}
|
||||
|
||||
function countMatches(source: string, re: RegExp): number {
|
||||
return (source.match(re) ?? []).length
|
||||
}
|
||||
|
||||
/** 扫一个文件的配对情况(判据与注入自证共用这一个函数)。 */
|
||||
export function scanPairing(source: string, file: string): PairingReport {
|
||||
const lines = source.split(/\r?\n/)
|
||||
const removedEvents = new Set<string>()
|
||||
for (const line of lines) {
|
||||
for (const m of line.matchAll(LISTENER_TEARDOWN)) removedEvents.add(m[1])
|
||||
}
|
||||
const dangling: { event: string; line: number }[] = []
|
||||
lines.forEach((line, index) => {
|
||||
for (const m of line.matchAll(LISTENER_REGISTER)) {
|
||||
const event = m[1]
|
||||
const tail = m[2] ?? ''
|
||||
if (/once:\s*true/.test(tail)) return // 自反注册,浏览器摘完就算配对
|
||||
if (removedEvents.has(event)) return
|
||||
dangling.push({ event, line: index + 1 })
|
||||
}
|
||||
})
|
||||
return {
|
||||
file,
|
||||
intervals: {
|
||||
registrations: countMatches(source, INTERVAL_REGISTER),
|
||||
teardowns: countMatches(source, INTERVAL_TEARDOWN),
|
||||
},
|
||||
listeners: dangling,
|
||||
}
|
||||
}
|
||||
|
||||
function sourceFiles(dir: string): string[] {
|
||||
const out: string[] = []
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) out.push(...sourceFiles(full))
|
||||
else if (entry.name.endsWith('.vue') || entry.name.endsWith('.ts')) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const FILES = sourceFiles(SRC).map((file) => relative(ROOT, file).split(sep).join('/'))
|
||||
const REPORTS = FILES.map((rel) => scanPairing(readFileSync(join(ROOT, ...rel.split('/')), 'utf-8'), rel))
|
||||
|
||||
function unpairedListeners(report: PairingReport): number {
|
||||
return report.listeners.length
|
||||
}
|
||||
|
||||
function intervalImbalance(report: PairingReport): number {
|
||||
return report.intervals.registrations - report.intervals.teardowns
|
||||
}
|
||||
|
||||
test('分母自证:定时器与监听器都真的数到了东西(扫不到不等于没有)', () => {
|
||||
const intervalRegistrations = REPORTS.reduce((sum, r) => sum + r.intervals.registrations, 0)
|
||||
const listenerRegistrations = FILES.reduce((sum, rel) => {
|
||||
const source = readFileSync(join(ROOT, ...rel.split('/')), 'utf-8')
|
||||
return sum + countMatches(source, LISTENER_REGISTER)
|
||||
}, 0)
|
||||
assert.ok(FILES.length > 100, `只扫到 ${FILES.length} 个源文件,分母不对`)
|
||||
assert.ok(FILES.some((f) => f.endsWith('.vue')), '.vue 没进分母就是漏扫')
|
||||
assert.ok(intervalRegistrations >= 6, `全树只数到 ${intervalRegistrations} 处 setInterval(下限 6)——扫描器失明`)
|
||||
assert.ok(listenerRegistrations >= 9, `全树只数到 ${listenerRegistrations} 处 window/document 监听(下限 9)——扫描器失明`)
|
||||
// 非零对照:已知配好对的 NotificationBell 必须被数成"注册 3 处",否则是口径没命中
|
||||
const bell = REPORTS.find((r) => r.file === 'src/shared/components/NotificationBell.vue')
|
||||
assert.ok(bell && bell.intervals.registrations >= 1, 'NotificationBell.vue 的定时器没进分母')
|
||||
assert.ok(bell && unpairedListeners(bell) === 0, 'NotificationBell.vue 三个监听都摘了,不该被判挂')
|
||||
})
|
||||
|
||||
test('定时器配对:每个 setInterval 都找得回 clearInterval(含 categorized-timers)', () => {
|
||||
const offenders = REPORTS
|
||||
.filter((r) => intervalImbalance(r) > 0)
|
||||
.map((r) => `${r.file}:注册 ${r.intervals.registrations} 处、反注册 ${r.intervals.teardowns} 处`)
|
||||
assert.deepEqual(offenders, [], `这些文件的定时器没有对应的清理:\n${offenders.join('\n')}`)
|
||||
})
|
||||
|
||||
test('监听器配对:每个 addEventListener 都找得回同名 removeEventListener(台账之外 0 处)', () => {
|
||||
const ledger: Record<string, number> = {}
|
||||
for (const report of REPORTS) {
|
||||
const count = unpairedListeners(report)
|
||||
if (count) ledger[report.file] = count
|
||||
}
|
||||
const worse: string[] = []
|
||||
for (const [file, count] of Object.entries(ledger)) {
|
||||
const allowed = UNPAIRED_LEDGER[file]
|
||||
if (allowed === undefined) worse.push(`${file} 新增未配对监听 ${count} 处:${REPORTS.find((r) => r.file === file)?.listeners.map((l) => `${l.event}@${l.line}`).join(', ')}`)
|
||||
else if (count > allowed) worse.push(`${file} 从 ${allowed} 处涨到 ${count} 处`)
|
||||
}
|
||||
assert.deepEqual(worse, [], `未配对监听比台账多了:\n${worse.join('\n')}`)
|
||||
// 台账自己也得是活的:写了一条早就不存在的例外同样是通过不了的红
|
||||
for (const file of Object.keys(UNPAIRED_LEDGER)) {
|
||||
assert.ok(file in ledger, `台账里的 ${file} 已经没有未配对监听了,把这一格删掉(只许减)`)
|
||||
}
|
||||
})
|
||||
|
||||
test('本轮修好的 3 处现在成对了(评审点名的 user-token-sync ×3 与 download-progress ×1)', () => {
|
||||
const tokenSync = REPORTS.find((r) => r.file === 'src/shared/auth/user-token-sync.ts')
|
||||
assert.ok(tokenSync, 'user-token-sync.ts 没进分母')
|
||||
assert.ok(intervalImbalance(tokenSync) <= 0, '60 秒兜底轮询还是没有 clearInterval')
|
||||
assert.deepEqual(tokenSync.listeners, [], 'pywebviewready / storage 监听还没配 removeEventListener')
|
||||
assert.match(read('src/shared/auth/user-token-sync.ts'), /export function uninstallUserTokenSync\(\)/)
|
||||
|
||||
const download = REPORTS.find((r) => r.file === 'src/shared/utils/download-progress.ts')
|
||||
assert.ok(download, 'download-progress.ts 没进分母')
|
||||
assert.ok(intervalImbalance(download) <= 0, '清扫定时器没配对')
|
||||
assert.deepEqual(download.listeners, [], 'pywebview-download-progress 桥监听没配对')
|
||||
assert.match(read('src/shared/utils/download-progress.ts'), /export function disposeDownloadProgressListener\(\)/)
|
||||
|
||||
const version = REPORTS.find((r) => r.file === 'src/shared/composables/useVersionUpdate.ts')
|
||||
assert.ok(version, 'useVersionUpdate.ts 没进分母')
|
||||
assert.deepEqual(version.listeners, [], 'pywebview-update-progress 桥监听没配对')
|
||||
})
|
||||
|
||||
test('卸载出口都接在根组件上:只定义不接线等于没接', () => {
|
||||
const appVue = read('src/App.vue')
|
||||
assert.match(appVue, /onBeforeUnmount\(\(\)\s*=>\s*\{/, 'App.vue 没有 onBeforeUnmount')
|
||||
const missing = WIRED_DISPOSERS.filter((name) => {
|
||||
const defined = REPORTS.some((r) => read(r.file).includes(`export function ${name}`))
|
||||
return !defined || !new RegExp(`onBeforeUnmount\\(\\(\\)\\s*=>\\s*\\{[^}]*${name}\\(\\)`).test(appVue)
|
||||
})
|
||||
assert.deepEqual(missing, [], `这些卸载出口没定义或没接进 App.vue:${missing.join(', ')}`)
|
||||
})
|
||||
|
||||
test('注入自证:造一个未配对的注册点一定被判红,once:true 不误报', () => {
|
||||
const target = 'src/shared/auth/user-token-sync.ts'
|
||||
const source = read(target)
|
||||
// ① 把 storage 的反注册删掉 → 该判成未配对
|
||||
const stripped = source.replace('window.removeEventListener(\'storage\', storageHandler)', '/* 反注册被删掉 */')
|
||||
assert.notEqual(stripped, source, '注入没生效,这条自证是假的')
|
||||
assert.deepEqual(scanPairing(stripped, target).listeners.map((l) => l.event), ['storage'], '删掉反注册却没被判红')
|
||||
// ② 凭空加一个定时器 → 分母与失衡都要跟着动
|
||||
const withTimer = source + '\nfunction injectedProbeForPairing() { window.setInterval(() => { void 0 }, 1000) }\n'
|
||||
const after = scanPairing(withTimer, target)
|
||||
assert.equal(after.intervals.registrations, scanPairing(source, target).intervals.registrations + 1, '新增的 setInterval 没进分母')
|
||||
assert.equal(intervalImbalance(after), 1, '新增的 setInterval 没被判成未配对')
|
||||
// ③ once:true 是浏览器自摘,不该算违例
|
||||
const withOnce = source + '\nwindow.addEventListener(\'focus\', () => { void 0 }, { once: true })\n'
|
||||
assert.deepEqual(scanPairing(withOnce, target).listeners, [], 'once:true 被误判成未配对了')
|
||||
})
|
||||
|
||||
test('BrandShopMatchTab.vue(评审点名的第 3 处)现在真的配对了', () => {
|
||||
const rel = 'src/pages/brand/components/BrandShopMatchTab.vue'
|
||||
const report = scanPairing(read(rel), rel)
|
||||
assert.ok(report.intervals.registrations >= 1, '这文件的心跳定时器没进分母')
|
||||
assert.ok(intervalImbalance(report) <= 0, '心跳/派发定时器没配对')
|
||||
assert.deepEqual(report.listeners, [], 'focus / visibilitychange 监听没配对')
|
||||
const source = read(rel)
|
||||
assert.match(source, /onUnmounted\(\(\) => \{[^}]*window\.removeEventListener\('focus'/, 'onUnmounted 里没摘 focus 监听')
|
||||
assert.match(source, /timers\.clearTimer\('scheduled-dispatch'/, '派发定时器没有分类清理')
|
||||
})
|
||||
|
||||
function read(rel: string): string {
|
||||
return readFileSync(join(ROOT, ...rel.split('/')), 'utf-8')
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import {
|
||||
CANCELLED_STATUS_TEXT,
|
||||
CANCELLED_STATUS_WORDS,
|
||||
RUNNING_UNTIL_DONE_STATUS_OPTIONS,
|
||||
TASK_STATUS_CLASS,
|
||||
TASK_STATUS_TEXT,
|
||||
taskStatusClass,
|
||||
taskStatusText,
|
||||
} from '../src/shared/utils/task-status-text.ts'
|
||||
|
||||
/**
|
||||
* 取消态不得显示为进行中(2026-10-09 评审流程面 5.5 的那条:`CANCELLED` 在 3 个页面被念成「执行中」)。
|
||||
*
|
||||
* 成因不在映射表写错,而在 `RUNNING_UNTIL_DONE_STATUS_OPTIONS` 的 `replace: true`:
|
||||
* 它只列了 SUCCESS/COMPLETED/FAILED 三行,`replace` 又把默认表整个丢掉,
|
||||
* 于是 CANCELLED 掉进 `textFallback: '执行中'`——任务早被撤掉了,界面还在说"正在跑"。
|
||||
*
|
||||
* 判据三层:① 真值表行为钉子(import 真函数跑);② 非终态照旧显示执行中(防止把修复做成"取消也回退成等待中");
|
||||
* ③ 全树扫描"取消词 → 进行中文案"的形状,配注入自证与硬分母。
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const SRC = resolve(here, '../src')
|
||||
|
||||
function sourceFiles(dir: string): string[] {
|
||||
const out: string[] = []
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) out.push(...sourceFiles(full))
|
||||
else if (entry.name.endsWith('.vue') || entry.name.endsWith('.ts')) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 「取消词被映射成进行中」的形状:`CANCELLED: '执行中'` / `CANCELED: "正在执行"`。 */
|
||||
const CANCELLED_AS_RUNNING_TEXT = /\b(?:CANCELLED|CANCELED)\s*:\s*['"`]?\s*(?:执行中|正在执行|运行中|进行中)/
|
||||
|
||||
/** 取消词的全部拼写(词面本身也是分母的一部分)。 */
|
||||
const CANCELLED_WORD = /\b(?:CANCELLED|CANCELED)\b/g
|
||||
|
||||
/** 找出源码里把取消态念成进行中的行(判据与注入自证共用同一个函数)。 */
|
||||
function cancelledShownAsRunning(source: string): string[] {
|
||||
return source.split(/\r?\n/).filter((line) => CANCELLED_AS_RUNNING_TEXT.test(line))
|
||||
}
|
||||
|
||||
test('共用表上取消态是「已取消」,两种拼写都认', () => {
|
||||
for (const word of ['CANCELLED', 'CANCELED', 'cancelled', 'canceled', ' CANCELLED ']) {
|
||||
assert.equal(taskStatusText(word), CANCELLED_STATUS_TEXT, `${word} 的文案判错`)
|
||||
assert.equal(taskStatusClass(word), 'failed', `${word} 的样式类判错`)
|
||||
}
|
||||
assert.deepEqual([...CANCELLED_STATUS_WORDS].sort(), ['CANCELED', 'CANCELLED'], '取消态词表少了拼写')
|
||||
// 默认表里两种拼写都在(美式/英式并存,Java 侧两种都发得出)
|
||||
assert.ok('CANCELLED' in TASK_STATUS_TEXT && 'CANCELED' in TASK_STATUS_TEXT, '默认文案表少了一种取消拼写')
|
||||
assert.ok('CANCELLED' in TASK_STATUS_CLASS && 'CANCELED' in TASK_STATUS_CLASS, '默认样式表少了一种取消拼写')
|
||||
})
|
||||
|
||||
test('出问题的那 3 页(replace 表):取消态不得是「执行中」,非终态照旧是「执行中」', () => {
|
||||
assert.equal(taskStatusText('CANCELLED', RUNNING_UNTIL_DONE_STATUS_OPTIONS), '已取消')
|
||||
assert.equal(taskStatusText('CANCELED', RUNNING_UNTIL_DONE_STATUS_OPTIONS), '已取消')
|
||||
assert.equal(taskStatusClass('CANCELLED', RUNNING_UNTIL_DONE_STATUS_OPTIONS), 'failed')
|
||||
// 反过来也得钉住:这张表的本职是"没到终态就说执行中",不能顺手把等待中也改了
|
||||
for (const running of ['RUNNING', 'PENDING', 'SCHEDULED', 'QUEUED', 'WHATEVER_NEW']) {
|
||||
assert.equal(taskStatusText(running, RUNNING_UNTIL_DONE_STATUS_OPTIONS), '执行中', `${running} 该仍显示执行中`)
|
||||
assert.equal(taskStatusClass(running, RUNNING_UNTIL_DONE_STATUS_OPTIONS), 'running', `${running} 该仍是 running`)
|
||||
}
|
||||
assert.equal(taskStatusText('SUCCESS', RUNNING_UNTIL_DONE_STATUS_OPTIONS), '已完成')
|
||||
assert.equal(taskStatusText('FAILED', RUNNING_UNTIL_DONE_STATUS_OPTIONS), '失败')
|
||||
})
|
||||
|
||||
test('全树扫描:没有任何一处把取消态映射成进行中文案', () => {
|
||||
const offenders: string[] = []
|
||||
let cancelledWordSites = 0
|
||||
for (const file of sourceFiles(SRC)) {
|
||||
const rel = file.slice(SRC.length + 1).replace(/\\/g, '/')
|
||||
const source = readFileSync(file, 'utf-8')
|
||||
cancelledWordSites += (source.match(CANCELLED_WORD) ?? []).length
|
||||
for (const line of cancelledShownAsRunning(source)) {
|
||||
offenders.push(`${rel}: ${line.trim().slice(0, 120)}`)
|
||||
}
|
||||
}
|
||||
// 分母硬钉:取消词在树上的出现次数(改文案前实测 20+),塌了说明扫描器失明
|
||||
assert.ok(cancelledWordSites >= 15, `全树只扫到 ${cancelledWordSites} 处取消词(下限 15)——此刻的"零违规"不作数`)
|
||||
assert.deepEqual(offenders, [], `这些行把取消态念成了进行中:\n${offenders.join('\n')}`)
|
||||
})
|
||||
|
||||
test('注入自证:尺子抓得住自己造的违例,也放得过合法写法', () => {
|
||||
const planted = " text: { SUCCESS: '已完成', CANCELLED: '执行中' },"
|
||||
assert.deepEqual(cancelledShownAsRunning(planted).length, 1, '造出来的违例没被抓到,上面那条"零违规"是恒绿')
|
||||
const plantedUs = " return taskStatusText(st, { text: { CANCELED: '正在执行' } })"
|
||||
assert.deepEqual(cancelledShownAsRunning(plantedUs).length, 1, '美式拼写的违例没被抓到')
|
||||
// 合法写法:取消态映射成别的中文、或进行中词映射成进行中
|
||||
assert.equal(cancelledShownAsRunning(" CANCELLED: '已取消',").length, 0, '合法文案被判成了违例')
|
||||
assert.equal(cancelledShownAsRunning(" RUNNING: '执行中',").length, 0, '非取消词不该被这条尺子管')
|
||||
// 真源码里也验一遍:改坏了立刻能在这里现形,而不是在页面截图里
|
||||
const real = readFileSync(join(SRC, 'shared/utils/task-status-text.ts'), 'utf-8')
|
||||
assert.deepEqual(cancelledShownAsRunning(real), [], 'task-status-text.ts 自己就把取消态写成了进行中')
|
||||
})
|
||||
@@ -0,0 +1,192 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, resolve, relative, sep } from 'node:path'
|
||||
import { decideAuthGate, hasUsableToken, hasUsableUid, shouldBounceToHome } from '../src/shared/auth/auth-gate.ts'
|
||||
|
||||
/**
|
||||
* `ensure-auth.ts` 的 uid 短路(2026-10-09 评审安全面:「只要 localStorage 里有 uid 就短路免校验」)。
|
||||
*
|
||||
* 判过才动:不能硬删。`shared/api/http.ts` 里 axios 是 `withCredentials: true`,
|
||||
* 桌面端与线上 Web 同源,Java 侧的同源会话 cookie 仍然算登录(那行注释原话"桌面端同源 cookie 仍可用"),
|
||||
* 这种形态本机只有 uid、没有 JWT。直接把短路改成"无令牌即拒",会把这类合法入口锁在登录页外。
|
||||
*
|
||||
* 所以做的是**收窄**:只有 uid 与令牌同时存在才免掉那一次 `/newApi/check_login`
|
||||
* (令牌本身每次请求都要过后端,这里省的只是守卫那一次往返);只有 uid、或只有令牌 → 问服务端;
|
||||
* 两者都没有 → 拒。剩下的例外(uid+令牌 免一次校验)进本文件的名单,新增免校验入口就红。
|
||||
*
|
||||
* 三把尺子:① 真值表(import 真函数跑);② 全树"看见 uid 就 return true"的形状清零;
|
||||
* ③ 门禁面上读 uid 的文件名单。每条都配注入自证与硬分母。
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = resolve(here, '..')
|
||||
const SRC = resolve(ROOT, 'src')
|
||||
|
||||
/** 门禁面:决定"能不能不进登录页"的那几个文件(新增免校验几乎都会落在这里)。 */
|
||||
const GATE_SURFACE = ['src/main.ts', 'src/router/index.ts', 'src/shared/auth/']
|
||||
|
||||
/**
|
||||
* 例外名单(只许减):读了 uid 但不走 decideAuthGate 的门禁面文件 + 理由。
|
||||
* kick-handler 只做"清登录态",它不是在放行谁,删掉它反而会让下线收口找不到键名。
|
||||
*/
|
||||
const GATE_EXCEPTIONS: Record<string, string> = {
|
||||
'src/shared/auth/kick-handler.ts': '被顶下线/登录失效时清 uid 与令牌,属于清态不是免校验',
|
||||
}
|
||||
|
||||
function sourceFiles(dir: string): string[] {
|
||||
const out: string[] = []
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name)
|
||||
if (entry.isDirectory()) out.push(...sourceFiles(full))
|
||||
else if (entry.name.endsWith('.vue') || entry.name.endsWith('.ts')) out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const FILES = sourceFiles(SRC).map((file) => relative(ROOT, file).split(sep).join('/'))
|
||||
function read(rel: string): string {
|
||||
return readFileSync(join(ROOT, ...rel.split('/')), 'utf-8')
|
||||
}
|
||||
|
||||
const UID_READ = /(?:getItem|removeItem|setItem)\(\s*(?:UID_KEY|'uid')\s*\)/
|
||||
const GATE_CALL = /decideAuthGate\(|shouldBounceToHome\(/
|
||||
|
||||
/** 去掉块注释但保持行数(注释里引用的旧写法不该被判成代码里的免校验分支)。 */
|
||||
function stripBlockComments(source: string): string {
|
||||
return source.replace(/\/\*[\s\S]*?\*\//g, (block) => block.split('\n').map(() => '').join('\n'))
|
||||
}
|
||||
|
||||
/**
|
||||
* "看见 uid 就免校验"的形状:`return true` 往上找 3 行内的最后一个 if,
|
||||
* 条件里出现 uid 且没走门禁函数 → 判成免校验出口。
|
||||
*/
|
||||
function findUidBypassLines(source: string): Array<{ line: number; text: string }> {
|
||||
// 块注释先抹掉(行数保持):auth-gate.ts 的头注释里引用了那句旧写法,不能被当成代码里的免校验分支
|
||||
const lines = stripBlockComments(source).split(/\r?\n/)
|
||||
const found: Array<{ line: number; text: string }> = []
|
||||
lines.forEach((line, index) => {
|
||||
if (!/\breturn\s+(?:true|!0)\b/.test(line)) return
|
||||
const window = lines.slice(Math.max(0, index - 3), index + 1).join('\n')
|
||||
const conditions = [...window.matchAll(/\bif\s*\(([^\n]*)/g)]
|
||||
if (!conditions.length) return
|
||||
const condition = conditions[conditions.length - 1][1] ?? ''
|
||||
if (!/UID_KEY|['"]uid['"]|rawUid|\buid\b/.test(condition)) return
|
||||
if (GATE_CALL.test(condition)) return
|
||||
found.push({ line: index + 1, text: line.trim().slice(0, 90) })
|
||||
})
|
||||
return found
|
||||
}
|
||||
|
||||
/** 门禁面里读 uid 却没走门禁函数、又不在例外名单上的文件。 */
|
||||
function uidGateProblems(files: string[], readFile: (rel: string) => string): string[] {
|
||||
const problems: string[] = []
|
||||
for (const rel of files) {
|
||||
if (!GATE_SURFACE.some((prefix) => rel === prefix || rel.startsWith(prefix))) continue
|
||||
const source = readFile(rel)
|
||||
if (!UID_READ.test(source)) continue
|
||||
if (GATE_CALL.test(source)) continue
|
||||
if (GATE_EXCEPTIONS[rel]) continue
|
||||
problems.push(`${rel} 读了 uid 但既没走 decideAuthGate/shouldBounceToHome,也不在例外名单里`)
|
||||
}
|
||||
return problems
|
||||
}
|
||||
|
||||
/** 门禁面里确实读着 uid 的文件(名单判据的分母)。 */
|
||||
function uidReadersInGateSurface(files: string[], readFile: (rel: string) => string): string[] {
|
||||
return files.filter((rel) => (
|
||||
GATE_SURFACE.some((prefix) => rel === prefix || rel.startsWith(prefix))
|
||||
&& UID_READ.test(readFile(rel))
|
||||
))
|
||||
}
|
||||
|
||||
test('真值表:收窄后的判定——uid 单独成立不再免校验', () => {
|
||||
assert.equal(decideAuthGate({ uid: '42', token: 'jwt' }), 'pass-local', 'uid+令牌 还免校验(这是名单里那条例外)')
|
||||
assert.equal(decideAuthGate({ uid: '42', token: '' }), 'restore', '只有 uid 必须去问服务端,不再免校验')
|
||||
assert.equal(decideAuthGate({ uid: '', token: 'jwt' }), 'restore', '只有令牌也要问一次')
|
||||
assert.equal(decideAuthGate({ uid: '', token: '' }), 'deny')
|
||||
assert.equal(decideAuthGate({}), 'deny')
|
||||
assert.equal(decideAuthGate({ uid: null, token: undefined }), 'deny')
|
||||
// uid 成形与否:'0'、空、非数字都不算登录过
|
||||
for (const bad of ['0', '', ' ', '-1', 'abc', 'NaN', 'null']) {
|
||||
assert.equal(hasUsableUid(bad), false, `${bad} 不该被当成 uid`)
|
||||
assert.equal(decideAuthGate({ uid: bad, token: 'jwt' }), 'restore', `${bad} 配令牌时也不能免校验`)
|
||||
}
|
||||
assert.equal(hasUsableUid('42'), true)
|
||||
assert.equal(hasUsableToken(' '), false)
|
||||
assert.equal(hasUsableToken('jwt'), true)
|
||||
})
|
||||
|
||||
test('登录页反弹:只有本机证据齐才把 /login 送回首页,掉了令牌的用户能打开登录页', () => {
|
||||
assert.equal(shouldBounceToHome({ uid: '42', token: 'jwt' }), true)
|
||||
// 评审那条的真实后果在这里:uid 在、令牌没了 → 原来永远点不开登录页,只能靠 URL 上的 logout/switch 自救
|
||||
assert.equal(shouldBounceToHome({ uid: '42', token: '' }), false, '只有 uid 仍被反弹,登录页还是打不开')
|
||||
assert.equal(shouldBounceToHome({ uid: '', token: 'jwt' }), false)
|
||||
assert.equal(shouldBounceToHome({}), false)
|
||||
})
|
||||
|
||||
test('全树没有"看见 uid 就 return true"的形状(免校验只能经门禁函数判)', () => {
|
||||
const offenders: string[] = []
|
||||
for (const rel of FILES) {
|
||||
for (const hit of findUidBypassLines(read(rel))) {
|
||||
offenders.push(`${rel}:${hit.line} ${hit.text}`)
|
||||
}
|
||||
}
|
||||
assert.deepEqual(offenders, [], `这些地方绕过门禁自己放行了:\n${offenders.join('\n')}`)
|
||||
// 原写法必须被同一口径抓到(否则上一条的"零"是假的)
|
||||
const original = [
|
||||
" const rawUid = window.localStorage.getItem(UID_KEY) || ''",
|
||||
' if (rawUid && Number(rawUid) > 0) {',
|
||||
' return true',
|
||||
' }',
|
||||
].join('\n')
|
||||
assert.equal(findUidBypassLines(original).length, 1, '评审点名的原写法没被抓到,上面的零违规不作数')
|
||||
assert.equal(findUidBypassLines(' if (window.localStorage.getItem(\'uid\')) return true').length, 1, '内联写法没被抓到')
|
||||
// 合法形状不许误报(误报的尺子下次没人信)
|
||||
assert.equal(findUidBypassLines(" const ok = await ensureAuth()\n if (!ok) return false\n return true").length, 0, '与 uid 无关的 return true 被误判')
|
||||
assert.equal(findUidBypassLines(' if (shouldBounceToHome({ uid, token })) {\n return true\n }').length, 0, '走了门禁函数的写法被误判')
|
||||
})
|
||||
|
||||
test('门禁面名单:读 uid 的文件必须走门禁函数或在例外里(新增免校验入口就红)', () => {
|
||||
const readers = uidReadersInGateSurface(FILES, read)
|
||||
// 分母硬钉:门禁面确实读着 uid(评审点名的那两处就在里面),塌了说明口径没命中
|
||||
assert.ok(readers.includes('src/shared/auth/ensure-auth.ts'), 'ensure-auth.ts 没进名单——扫描口径变了')
|
||||
assert.ok(readers.includes('src/main.ts'), 'main.ts 的 uid 读取没进名单——扫描口径变了')
|
||||
assert.deepEqual(uidGateProblems(FILES, read), [], '门禁面出现了不走门禁的 uid 读取')
|
||||
// 名单里的例外必须还成立(不留僵尸条目)
|
||||
for (const rel of Object.keys(GATE_EXCEPTIONS)) {
|
||||
assert.ok(readers.includes(rel), `例外名单里的 ${rel} 已经不读 uid 了,删掉这一格(只许减)`)
|
||||
}
|
||||
})
|
||||
|
||||
test('ensure-auth 的接线:两个入口(硬校验与软恢复)都走同一个门禁函数', () => {
|
||||
const source = read('src/shared/auth/ensure-auth.ts')
|
||||
assert.match(source, /import \{ decideAuthGate \} from '\.\/auth-gate\.ts'/)
|
||||
const hard = source.slice(source.indexOf('export async function ensureAuth'), source.indexOf('export async function restoreLoginUser'))
|
||||
assert.match(hard, /decideAuthGate\(\{\s*uid:[\s\S]{0,120}?token:/, 'ensureAuth 没把 uid 与令牌一起交给门禁')
|
||||
assert.match(hard, /if \(decision === 'pass-local'\)[\s\S]{0,40}?return true/, 'ensureAuth 没按判定结果放行')
|
||||
assert.match(hard, /if \(decision === 'deny'\)[\s\S]{0,40}?return false/, 'ensureAuth 没按判定结果拒绝')
|
||||
const soft = source.slice(source.indexOf('export async function restoreLoginUser'))
|
||||
assert.match(soft, /decideAuthGate\(\{\s*uid:[\s\S]{0,120}?token:/, 'restoreLoginUser 没走门禁')
|
||||
// 旧的"uid 存在即免校验"不许以另一种写法回来
|
||||
assert.ok(!/if \(rawUid && Number\(rawUid\) > 0\)/.test(source), 'ensure-auth.ts 里旧的短路又出现了')
|
||||
})
|
||||
|
||||
test('注入自证:门禁面新增一条免校验分支立刻变红', () => {
|
||||
const rel = 'src/shared/auth/ensure-auth.ts'
|
||||
const source = read(rel)
|
||||
const anchor = 'export async function ensureAuth(): Promise<boolean> {'
|
||||
assert.equal(source.split(anchor).length - 1, 1, '锚点不唯一,注入自证不作数')
|
||||
const injected = source.replace(anchor, `${anchor}\n if (window.localStorage.getItem(UID_KEY)) {\n return true\n }`)
|
||||
assert.notEqual(injected, source, '注入没生效,这条自证是假的')
|
||||
assert.ok(findUidBypassLines(injected).length >= 1, '注入的免校验分支没被抓到')
|
||||
assert.equal(findUidBypassLines(source).length, 0, '真源码本身就该是零形状')
|
||||
// 名单判据也必须是活的:门禁面冒出一个不走门禁、也不在例外里的新文件 → 立刻有名字
|
||||
const fakeFiles = [...FILES, 'src/shared/auth/brand-new-gate.ts']
|
||||
const fakeRead = (rel: string) => (rel === 'src/shared/auth/brand-new-gate.ts'
|
||||
? "const uid = window.localStorage.getItem(UID_KEY)\n if (uid) {\n return true\n }\n"
|
||||
: read(rel))
|
||||
assert.deepEqual(uidGateProblems(fakeFiles, fakeRead), ['src/shared/auth/brand-new-gate.ts 读了 uid 但既没走 decideAuthGate/shouldBounceToHome,也不在例外名单里'])
|
||||
assert.equal(uidGateProblems(FILES, read).length, 0, '真名单上就有不走门禁的 uid 读取')
|
||||
})
|
||||
@@ -0,0 +1,137 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join, resolve, relative, sep } from 'node:path'
|
||||
import { listSourceFiles, readSource } from './helpers/task-terminal-ast-ruler.ts'
|
||||
import { exportedGuardedNames, scanAllUrlOutlets, scanUrlOutlets } from './helpers/url-outlet-scanner.ts'
|
||||
import { isHttpUrl, safeHttpUrl } from '../src/shared/utils/safe-url.ts'
|
||||
|
||||
/**
|
||||
* 跳转/下载出口的白名单强制校验(2026-10-09 评审安全面:`safeHttpUrl` 已经有了,
|
||||
* 但 `BrandBrandTab.vue`、`BrandVariantTab.vue`、`useVersionUpdate.ts` 三处直接拿服务端返回的
|
||||
* `file_url` 去 `window.open` / `location.href`)。
|
||||
*
|
||||
* 判据按 AST 判"这次跳转的地址过没过白名单"(口径与理由写在 helpers/url-outlet-scanner.ts)。
|
||||
* 本轮顺手把把守点下沉到了 `saveUrlWithProgress`:14 个下载出口共用同一个桥入口,
|
||||
* 在那一处判比在每页各补一遍靠谱,也防止"新增一页忘了判"。
|
||||
*
|
||||
* 台账:未过校验的出口数只许减(现在钉 0),新增一处就红。
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = resolve(here, '..')
|
||||
|
||||
/** 台账:已知未校验的跳转/下载出口(文件 → 处数)。本轮清零,往后只许减不许加。 */
|
||||
const UNGUARDED_LEDGER: Record<string, number> = {}
|
||||
|
||||
const FILES = listSourceFiles(resolve(ROOT, 'src')).map((p) => relative(ROOT, p).split(sep).join('/'))
|
||||
const SOURCES = FILES.map((file) => ({ file, code: readSource(file, ROOT) }))
|
||||
|
||||
function scan(sources = SOURCES) {
|
||||
return scanAllUrlOutlets(sources)
|
||||
}
|
||||
|
||||
const SCANS = scan()
|
||||
const ALL_OUTLETS = SCANS.flatMap((s) => s.outlets)
|
||||
const ALL_UNGUARDED = SCANS.flatMap((s) => s.unguarded)
|
||||
|
||||
function scanOf(file: string) {
|
||||
return SCANS.find((s) => s.file === file)
|
||||
}
|
||||
|
||||
test('分母自证:出口真的被数到了(扫不到就不许报"全部已校验")', () => {
|
||||
assert.ok(FILES.length > 100, `只扫到 ${FILES.length} 个源文件,分母不对`)
|
||||
assert.ok(ALL_OUTLETS.length >= 20, `全树只数到 ${ALL_OUTLETS.length} 处跳转/下载出口(下限 20)——扫描器失明`)
|
||||
const kinds = new Set(ALL_OUTLETS.map((outlet) => outlet.kind))
|
||||
for (const kind of ['window.open', 'saveUrlWithProgress', 'location.href=']) {
|
||||
assert.ok(kinds.has(kind), `出口形状 ${kind} 一种都没扫到,判据口径变了`)
|
||||
}
|
||||
// 非零对照:评审点名的 3 个文件各自都得有出口进了分母
|
||||
assert.ok(scanOf('src/pages/brand/components/BrandBrandTab.vue')?.outlets.length >= 2, 'BrandBrandTab 的下载出口没进分母')
|
||||
assert.ok(scanOf('src/pages/brand/components/BrandVariantTab.vue')?.outlets.length >= 2, 'BrandVariantTab 的下载出口没进分母')
|
||||
assert.ok(scanOf('src/shared/composables/useVersionUpdate.ts')?.outlets.length >= 1, 'useVersionUpdate 的跳转出口没进分母')
|
||||
})
|
||||
|
||||
test('全树跳转/下载出口都过了白名单(台账之外 0 处)', () => {
|
||||
const ledger: Record<string, number> = {}
|
||||
for (const outlet of ALL_UNGUARDED) {
|
||||
ledger[outlet.file] = (ledger[outlet.file] ?? 0) + 1
|
||||
}
|
||||
const worse: string[] = []
|
||||
for (const [file, count] of Object.entries(ledger)) {
|
||||
const allowed = UNGUARDED_LEDGER[file]
|
||||
if (allowed === undefined) worse.push(`${file} 出现未校验出口 ${count} 处`)
|
||||
else if (count > allowed) worse.push(`${file} 从 ${allowed} 处涨到 ${count} 处`)
|
||||
}
|
||||
const evidence = ALL_UNGUARDED.map((o) => `${o.file}:${o.line} ${o.kind}(宿主 ${o.host})${o.snippet}`).join('\n')
|
||||
assert.deepEqual(worse, [], `这些跳转/下载没先校验地址:\n${evidence}`)
|
||||
// 台账里的例外现在都不存在了,留着就是尺子在放水
|
||||
for (const file of Object.keys(UNGUARDED_LEDGER)) {
|
||||
assert.ok(file in ledger, `台账里的 ${file} 已经没有未校验出口了,把这一格删掉(只许减)`)
|
||||
}
|
||||
})
|
||||
|
||||
test('评审点名的 3 处:现在都经白名单,且拒绝时看得见', () => {
|
||||
for (const file of [
|
||||
'src/pages/brand/components/BrandBrandTab.vue',
|
||||
'src/pages/brand/components/BrandVariantTab.vue',
|
||||
'src/shared/composables/useVersionUpdate.ts',
|
||||
]) {
|
||||
const found = scanOf(file)
|
||||
assert.ok(found, `${file} 没进分母`)
|
||||
assert.deepEqual(found.unguarded, [], `${file} 还有未校验的跳转/下载出口`)
|
||||
const source = readSource(file, ROOT)
|
||||
assert.match(source, /isHttpUrl\(/, `${file} 里没找到判定式白名单`)
|
||||
assert.match(source, /safeHttpUrl\(/, `${file} 里没找到安全地址出口`)
|
||||
assert.match(source, /\[safe-url\]/, `${file} 校验不通过时没留一行可查的记录`)
|
||||
}
|
||||
// 被拦下时不是"什么都不做":三处都得把话说到界面上
|
||||
assert.match(readSource('src/pages/brand/components/BrandBrandTab.vue', ROOT), /function openDownloadUrl\(/)
|
||||
assert.match(readSource('src/pages/brand/components/BrandVariantTab.vue', ROOT), /async function downloadSource\([\s\S]*?isHttpUrl\(/)
|
||||
assert.match(readSource('src/shared/composables/useVersionUpdate.ts', ROOT), /async function startUpdate\([\s\S]*?isHttpUrl\([\s\S]*?hint\.value = '更新包地址不可用/)
|
||||
})
|
||||
|
||||
test('把守点下沉:saveUrlWithProgress 自己先校验,新增页面漏判也跳不出去', () => {
|
||||
const source = readSource('src/shared/utils/download-progress.ts', ROOT)
|
||||
assert.match(source, /export async function saveUrlWithProgress\([\s\S]{0,400}?if \(!isHttpUrl\(url\)\)/,
|
||||
'saveUrlWithProgress 没有在入口先校验地址')
|
||||
assert.match(source, /return \{ success: false, error: UNSAFE_DOWNLOAD_URL_TEXT \}/, '校验不通过时没有把原因回给调用方')
|
||||
assert.ok(exportedGuardedNames(source, 'src/shared/utils/download-progress.ts').includes('saveUrlWithProgress'),
|
||||
'扫描器没把 saveUrlWithProgress 认成跨模块把守点')
|
||||
})
|
||||
|
||||
test('isHttpUrl 真值表:与 safeHttpUrl 同一个口径,不各判一套', () => {
|
||||
for (const ok of ['https://cdn.example.com/a.mp4', 'http://127.0.0.1:5173/x', '/newApi/download/x']) {
|
||||
assert.equal(isHttpUrl(ok), true, `${ok} 该放行`)
|
||||
assert.notEqual(safeHttpUrl(ok), '#', `${ok} 两个函数判得不一致`)
|
||||
}
|
||||
for (const bad of ['javascript:alert(1)', 'data:text/html,<script>alert(1)</script>', 'file:///C:/win.ini', ' ', '', undefined, null]) {
|
||||
assert.equal(isHttpUrl(bad as string), false, `${bad} 该拦下`)
|
||||
assert.equal(safeHttpUrl(bad as string), '#', `${bad} 两个函数判得不一致`)
|
||||
}
|
||||
})
|
||||
|
||||
test('注入自证:把白名单调用摘掉,扫描器立刻报未校验', () => {
|
||||
const file = 'src/pages/brand/components/BrandBrandTab.vue'
|
||||
const source = SOURCES.find((s) => s.file === file)?.code ?? ''
|
||||
assert.match(source, /isHttpUrl\(/, '锚点不在了,注入自证不作数')
|
||||
// 只把校验函数改名,出口形状与个数都不动:判据必须因此翻红
|
||||
const stripped = source.replace(/\bisHttpUrl\(/g, 'uncheckedHas(').replace(/\bsafeHttpUrl\(/g, 'rawValueOf(')
|
||||
assert.notEqual(stripped, source, '注入没生效,这条自证是假的')
|
||||
const before = scanUrlOutlets(source, file)
|
||||
const after = scanUrlOutlets(stripped, file)
|
||||
assert.equal(after.outlets.length, before.outlets.length, '摘掉校验把出口也弄丢了,分母在放水')
|
||||
assert.deepEqual(before.unguarded, [], '已校验的写法被判成了违例(口径过严)')
|
||||
assert.ok(after.unguarded.length >= 2, `摘掉校验后未校验出口只有 ${after.unguarded.length} 处(应 ≥2),这条尺子是恒绿的`)
|
||||
// 顶层(无宿主函数)的跳转也必须被抓到
|
||||
const topLevel = scanUrlOutlets('window.location.href = serverFileUrl\n', '<内存样本>')
|
||||
assert.deepEqual(topLevel.unguarded.map((o) => o.kind), ['location.href='], '模块顶层的跳转出口漏判')
|
||||
})
|
||||
|
||||
test('桥与降级路径都收口:open_external_url 那条也要先判', () => {
|
||||
const source = readSource('src/pages/amazon/AmazonConsolePage.vue', ROOT)
|
||||
const report = scanUrlOutlets(source, 'src/pages/amazon/AmazonConsolePage.vue')
|
||||
assert.ok(report.outlets.length >= 1, 'AmazonConsolePage 的教程下载出口没进分母')
|
||||
assert.deepEqual(report.unguarded, [], '教程地址(服务端 /api/tutorial/latest 透传)没先过白名单')
|
||||
assert.match(source, /api\.open_external_url\(url\)/, '桥侧用的还是未校验的原值')
|
||||
})
|
||||
Reference in New Issue
Block a user