Merge branch 'dev' into snow
# Conflicts: # backend/app/api/chat.py # backend/app/services/admin/permission_service.py # backend/app/services/knowledge_cleaning/dify_sync_service.py # backend/app/services/knowledge_cleaning/settings_service.py # backend/tests/test_dify_sync_process_rule.py # docker-compose.yml # docs/funclist.md # frontend/package-lock.json # frontend/src/config.ts # frontend/src/features/admin/components/AdminNav.vue # frontend/src/features/admin/constants/modules.ts # frontend/src/features/admin/stores/admin-nav.store.ts # frontend/src/features/chat/components/messages/ChatMessageBubble.vue # frontend/src/features/user/views/UserProfilePage.vue # frontend/src/locales/en/admin.json # frontend/src/locales/en/auth.json # frontend/src/locales/en/errors.json # frontend/src/locales/th/admin.json # frontend/src/locales/th/auth.json # frontend/src/locales/th/errors.json # frontend/src/locales/zh-CN/admin.json # frontend/src/locales/zh-CN/auth.json # frontend/src/locales/zh-CN/errors.json # frontend/src/locales/zh-TW/admin.json # frontend/src/locales/zh-TW/auth.json # frontend/src/locales/zh-TW/errors.json
This commit is contained in:
commit
ca9c174f29
2050 files changed
+511839
-42320
No files matched your search
@@ -10,6 +10,7 @@ export const AGENT_CODE_GENERIC = 'generic';
|
||||
export const AGENT_CODE_SHIPPING_NOTICE = 'shipping_notice';
|
||||
export const AGENT_CODE_FILE_CHECK = 'file_check';
|
||||
export const AGENT_CODE_PROCUREMENT_CONTRACT_REVIEW = 'procurement_contract_review';
|
||||
export const AGENT_CODE_IN_TRANSIT_TRANSFER = 'in_transit_transfer';
|
||||
|
||||
export interface AgentRegistryCapabilities {
|
||||
streaming?: boolean;
|
||||
|
||||
@@ -1,19 +1,22 @@
|
||||
/**
|
||||
* shared/utils/auth.ts
|
||||
* 用途:统一封装登录态、记住我偏好、登录页账号密码自动回填、跨标签登出同步等认证相关本地存储能力。
|
||||
* 用途:统一封装登录态、记住我偏好、登录页账号密码自动回填、跨标签登出同步,以及 401 是否表示会话失效的判断。
|
||||
* 依赖:浏览器 localStorage/sessionStorage、Casdoor refresh 接口。
|
||||
* 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理,既支持 30 天免登录,也支持按业务确认方案回填账号密码。
|
||||
* 逻辑:把“认证凭据”和“登录页自动回填资料”分开管理;改密等业务 401 不得触发全局登出。
|
||||
*/
|
||||
export type FeaturePermissions = {
|
||||
training_hr_manage?: boolean;
|
||||
'contract_payment.access'?: boolean;
|
||||
[key: string]: boolean | undefined;
|
||||
};
|
||||
|
||||
export interface AuthUser {
|
||||
id?: number;
|
||||
username?: string;
|
||||
real_name?: string;
|
||||
employee_id?: string;
|
||||
role?: string;
|
||||
feature_permissions?: {
|
||||
training_hr_manage?: boolean;
|
||||
[key: string]: boolean | undefined;
|
||||
};
|
||||
feature_permissions?: FeaturePermissions;
|
||||
token?: string;
|
||||
access_token?: string;
|
||||
refresh_token?: string;
|
||||
@@ -107,6 +110,27 @@ export const getStoredAuthUser = (): AuthUser | null => {
|
||||
return null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 就地更新当前登录用户的若干字段,不改变 remember / expiry 所在存储。
|
||||
* 核心逻辑:按 sessionStorage → localStorage 找到现有 payload,合并 partial 后写回同一位置。
|
||||
* @param partial - 需要覆盖的用户字段(如首页刷新得到的 feature_permissions)
|
||||
* @returns 合并后的用户;当前没有登录态时返回 null
|
||||
*/
|
||||
export const patchStoredAuthUser = (partial: Partial<AuthUser>): AuthUser | null => {
|
||||
const candidates: Array<[Storage, string]> = [
|
||||
[sessionStorage, AUTH_USER_KEY],
|
||||
[localStorage, AUTH_USER_KEY],
|
||||
];
|
||||
for (const [storage, key] of candidates) {
|
||||
const payload = readStoredAuthPayload(storage, key);
|
||||
if (!payload?.user) continue;
|
||||
const nextUser = { ...payload.user, ...partial };
|
||||
storage.setItem(key, JSON.stringify({ ...payload, user: nextUser }));
|
||||
return nextUser;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
export const getAuthToken = (): string => {
|
||||
const user = getStoredAuthUser();
|
||||
const token = user?.access_token || user?.token;
|
||||
@@ -306,6 +330,25 @@ export const initAuthSync = (): void => {
|
||||
}
|
||||
};
|
||||
|
||||
const BUSINESS_UNAUTHORIZED_CODES = new Set([
|
||||
'CASDOOR_INVALID_CREDENTIALS',
|
||||
'AUTH_INCORRECT_CURRENT_PASSWORD',
|
||||
'AUTH_INCORRECT_PASSWORD',
|
||||
'AUTH_PASSWORD_UNCHANGED',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 判断 API 401 是否表示登录会话失效,从而需要清 token 并跳转登录页。
|
||||
* 核心逻辑:空错误码按会话失效处理;改密/凭据类业务码即使历史接口返回 401 也不清会话。
|
||||
* @param code - 后端 envelope error.code
|
||||
* @returns true 时由全局 fetch 包装派发 hxops:unauthorized
|
||||
*/
|
||||
export function isSessionUnauthorizedError(code?: string | null): boolean {
|
||||
const raw = String(code || '').trim();
|
||||
if (!raw) return true;
|
||||
return !BUSINESS_UNAUTHORIZED_CODES.has(raw.replace(/\./g, '_').toUpperCase());
|
||||
}
|
||||
|
||||
let _refreshing: Promise<string | null> | null = null;
|
||||
|
||||
export const refreshAccessToken = async (): Promise<string | null> => {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* shared/utils/casdoor.ts
|
||||
* Casdoor OAuth 错误文案解析。
|
||||
* 用途:把 Casdoor / 改密相关 BusinessError 映射为登录与个人中心可读文案。
|
||||
* 依赖:BusinessError、vue-i18n t()。
|
||||
* 逻辑:优先用稳定 error.code;个人中心改密与管理端用户编辑共用同一套码。
|
||||
*/
|
||||
import type { BusinessError } from '@/shared/api/client';
|
||||
|
||||
@@ -10,9 +12,20 @@ function cleanText(value: unknown): string {
|
||||
return typeof value === 'string' ? value.trim() : String(value ?? '').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 BusinessError 取出可映射的 Casdoor / 改密错误码。
|
||||
* 核心逻辑:优先稳定 code,其次 details.error_code,最后从英文原文兜底。
|
||||
* @param err - requestJson 抛出的业务错误
|
||||
* @returns 用于文案映射的错误码
|
||||
*/
|
||||
export function pickCasdoorErrorCode(err: BusinessError): string {
|
||||
const code = cleanText(err.code);
|
||||
if (code.startsWith('CASDOOR_') || code === 'ACCOUNT_DISABLED' || code === 'AUTH.INCORRECT_CURRENT_PASSWORD') {
|
||||
if (
|
||||
code.startsWith('CASDOOR_')
|
||||
|| code === 'ACCOUNT_DISABLED'
|
||||
|| code === 'AUTH.INCORRECT_CURRENT_PASSWORD'
|
||||
|| code === 'AUTH.PASSWORD_UNCHANGED'
|
||||
) {
|
||||
return code;
|
||||
}
|
||||
const detailsCode = cleanText(err.details?.error_code);
|
||||
@@ -24,6 +37,13 @@ export function pickCasdoorErrorCode(err: BusinessError): string {
|
||||
return code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Casdoor / 改密错误转为当前语言用户可见文案。
|
||||
* 核心逻辑:按 pickCasdoorErrorCode 查 i18n;未知码回退原始 message。
|
||||
* @param err - 业务错误
|
||||
* @param t - vue-i18n t 函数
|
||||
* @returns 用户可见错误文案
|
||||
*/
|
||||
export function resolveCasdoorErrorMessage(err: BusinessError, t: TranslateFn): string {
|
||||
const errorCode = pickCasdoorErrorCode(err);
|
||||
const keyMap: Record<string, string> = {
|
||||
@@ -39,6 +59,7 @@ export function resolveCasdoorErrorMessage(err: BusinessError, t: TranslateFn):
|
||||
CASDOOR_SET_PASSWORD_FAILED: 'login.casdoorErrors.setPasswordFailed',
|
||||
CASDOOR_USER_NOT_IN_IDP: 'login.casdoorErrors.userNotInIdp',
|
||||
'AUTH.INCORRECT_CURRENT_PASSWORD': 'login.casdoorErrors.incorrectCurrentPassword',
|
||||
'AUTH.PASSWORD_UNCHANGED': 'login.casdoorErrors.passwordUnchanged',
|
||||
'VALIDATION.INVALID_PARAM': 'login.casdoorErrors.stateExpired',
|
||||
};
|
||||
const key = keyMap[errorCode];
|
||||
@@ -46,6 +67,7 @@ export function resolveCasdoorErrorMessage(err: BusinessError, t: TranslateFn):
|
||||
const raw = cleanText(err.message);
|
||||
if (raw === 'Incorrect username or password') return t('login.casdoorErrors.invalidCredentials');
|
||||
if (raw === 'Incorrect current password') return t('login.casdoorErrors.incorrectCurrentPassword');
|
||||
if (raw === 'New password must differ from the current password') return t('login.casdoorErrors.passwordUnchanged');
|
||||
if (raw === 'Invalid or expired Casdoor state') return t('login.casdoorErrors.stateExpired');
|
||||
return raw || t('login.casdoorErrors.authFailed');
|
||||
}
|
||||
@@ -31,3 +31,40 @@ export function formatLocalDateTime(iso?: string | null): string {
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format an API timestamp as `YYYY-MM-DD HH:mm:ss`, preserving the source wall-clock time.
|
||||
* Use for OA-sourced naive timestamps (e.g. contract archive date) where the stored value is the
|
||||
* local time as shown on the source page and must NOT be shifted by the browser timezone.
|
||||
* Backend may serialize microseconds (e.g. `...26.660127`); they are trimmed for reliable parsing.
|
||||
* Empty values return `-`; invalid dates fall back to the original string for troubleshooting.
|
||||
*
|
||||
* @param iso - API timestamp string.
|
||||
* @returns Wall-clock display text.
|
||||
*/
|
||||
export function formatNaiveDateTime(iso?: string | null): string {
|
||||
if (!iso) return '-';
|
||||
const normalized = iso.replace(/(\.\d{3})\d+/, '$1');
|
||||
const d = new Date(normalized);
|
||||
if (Number.isNaN(d.getTime())) return iso;
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format an API timestamp as `YYYY-MM-DD`, preserving the source wall-clock day.
|
||||
* Use for OA-sourced naive timestamps (e.g. contract archive date) where only the date is
|
||||
* meaningful and the trailing time part must not be shown. Parsing mirrors formatNaiveDateTime.
|
||||
* Empty values return `-`; invalid dates fall back to the original string for troubleshooting.
|
||||
*
|
||||
* @param iso - API timestamp string.
|
||||
* @returns Wall-clock date text (`YYYY-MM-DD`).
|
||||
*/
|
||||
export function formatNaiveDate(iso?: string | null): string {
|
||||
if (!iso) return '-';
|
||||
const normalized = iso.replace(/(\.\d{3})\d+/, '$1');
|
||||
const d = new Date(normalized);
|
||||
if (Number.isNaN(d.getTime())) return iso;
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* shared/utils/download.test.ts
|
||||
* 用途:校验 Content-Disposition 解析与单次 blob 下载不会拼出怪名。
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
parseContentDispositionFilename,
|
||||
sanitizeDownloadFilename,
|
||||
triggerBlobDownload,
|
||||
} from './download';
|
||||
|
||||
describe('parseContentDispositionFilename', () => {
|
||||
it('prefers RFC 5987 filename* over ASCII fallback', () => {
|
||||
// 断言:Werkzeug/Flask 中文名会留下 ASCII 回退段,必须取 filename*。
|
||||
const encoded = encodeURIComponent('企业文化.docx');
|
||||
const disposition = `attachment; filename="download.docx"; filename*=UTF-8''${encoded}`;
|
||||
expect(parseContentDispositionFilename(disposition)).toBe('企业文化.docx');
|
||||
});
|
||||
|
||||
it('does not concatenate unquoted ASCII fallback with filename*', () => {
|
||||
// 断言:旧实现会得到 `docx; filename_=UTF-8''企业文化.docx`。
|
||||
const encoded = encodeURIComponent('企业文化.docx');
|
||||
const disposition = `inline; filename=docx; filename*=UTF-8''${encoded}`;
|
||||
expect(parseContentDispositionFilename(disposition)).toBe('企业文化.docx');
|
||||
});
|
||||
|
||||
it('reads quoted filename when filename* is absent', () => {
|
||||
expect(parseContentDispositionFilename('attachment; filename="report.pdf"')).toBe('report.pdf');
|
||||
});
|
||||
|
||||
it('returns undefined for empty header', () => {
|
||||
expect(parseContentDispositionFilename('')).toBeUndefined();
|
||||
expect(parseContentDispositionFilename(null)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeDownloadFilename', () => {
|
||||
it('keeps only the last path segment', () => {
|
||||
expect(sanitizeDownloadFilename('dir/企业文化.docx')).toBe('企业文化.docx');
|
||||
});
|
||||
});
|
||||
|
||||
describe('triggerBlobDownload', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('clicks a single anchor with the original filename', () => {
|
||||
// 断言:一次下载只产生一个 a[download],文件名与源文件一致。
|
||||
const clicks: string[] = [];
|
||||
const createObjectURL = vi.fn(() => 'blob:http://localhost/fake');
|
||||
const revokeObjectURL = vi.fn();
|
||||
vi.stubGlobal('URL', { createObjectURL, revokeObjectURL });
|
||||
|
||||
const originalCreateElement = document.createElement.bind(document);
|
||||
vi.spyOn(document, 'createElement').mockImplementation((tagName: string) => {
|
||||
const el = originalCreateElement(tagName);
|
||||
if (tagName === 'a') {
|
||||
vi.spyOn(el, 'click').mockImplementation(() => {
|
||||
clicks.push(el.download);
|
||||
});
|
||||
}
|
||||
return el;
|
||||
});
|
||||
|
||||
triggerBlobDownload(new Blob(['hello']), '企业文化.docx');
|
||||
|
||||
expect(createObjectURL).toHaveBeenCalledTimes(1);
|
||||
expect(clicks).toEqual(['企业文化.docx']);
|
||||
expect(document.body.querySelectorAll('a')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* shared/utils/download.ts
|
||||
* 用途:浏览器受控下载的文件名解析与单次触发,避免 blob URL 被 window.open 再下一份。
|
||||
* 依赖:无业务模块;仅使用 DOM URL / a[download]。
|
||||
* 逻辑:requestBlob、知识库源文件等调用;Content-Disposition 优先 RFC 5987 filename*。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 去掉路径与非法换行,得到可写入 a[download] 的纯文件名。
|
||||
* 核心逻辑:只保留最后一段路径分量,避免把目录或响应头片段写进保存名。
|
||||
* @param filename - 原始或解析得到的文件名
|
||||
* @param fallback - 清洗后为空时的回退名
|
||||
* @returns 可安全用作下载名的字符串
|
||||
*/
|
||||
export function sanitizeDownloadFilename(filename: string, fallback = 'download'): string {
|
||||
const name = String(filename || '').replace(/\\/g, '/').split('/').pop()?.trim() || '';
|
||||
const cleaned = name.replace(/[\r\n"]/g, '');
|
||||
return cleaned || fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 Content-Disposition 解析下载文件名,优先 RFC 5987 的 filename*。
|
||||
* 核心逻辑:先取 filename*=UTF-8'',再取带引号或到分号为止的 filename=。
|
||||
* 不能用贪婪的 filename="?([^"]+)"?,否则会把 `filename=docx; filename*=UTF-8''原名.docx` 整段当成文件名。
|
||||
* @param disposition - 响应头原文
|
||||
* @returns 解码后的文件名;无法解析时返回 undefined
|
||||
*/
|
||||
export function parseContentDispositionFilename(
|
||||
disposition: string | null | undefined,
|
||||
): string | undefined {
|
||||
const value = String(disposition || '');
|
||||
if (!value) return undefined;
|
||||
|
||||
const utf8Match = value.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);
|
||||
const quotedMatch = value.match(/filename\s*=\s*"([^"]+)"/i);
|
||||
const unquotedMatch = value.match(/filename\s*=\s*([^;]+)/i);
|
||||
const raw = (utf8Match?.[1] || quotedMatch?.[1] || unquotedMatch?.[1] || '').trim();
|
||||
if (!raw) return undefined;
|
||||
|
||||
let decoded = raw;
|
||||
try {
|
||||
decoded = decodeURIComponent(raw);
|
||||
} catch {
|
||||
decoded = raw;
|
||||
}
|
||||
const name = sanitizeDownloadFilename(decoded, '');
|
||||
return name || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用 blob 触发一次浏览器下载,保存名使用给定文件名。
|
||||
* 核心逻辑:只创建一条 a[download] 并 click;禁止 window.open blob URL,
|
||||
* 因为 docx 等无法预览的类型会再下一份 UUID 名文件,且 noopener 使 open 返回 null 导致双下载。
|
||||
* @param blob - 文件内容
|
||||
* @param filename - 保存文件名,应与源文件名一致
|
||||
*/
|
||||
export function triggerBlobDownload(blob: Blob, filename: string): void {
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = objectUrl;
|
||||
link.download = sanitizeDownloadFilename(filename);
|
||||
link.rel = 'noopener';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* shared/utils/id.test.ts
|
||||
* 用途:校验 createRandomUuid 在缺少 randomUUID 时仍可生成可用 ID。
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createRandomUuid } from './id';
|
||||
|
||||
describe('createRandomUuid', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('uses crypto.randomUUID when available', () => {
|
||||
// 断言:安全上下文走原生 API。
|
||||
vi.stubGlobal('crypto', {
|
||||
randomUUID: () => '11111111-2222-4333-8444-555555555555',
|
||||
});
|
||||
expect(createRandomUuid()).toBe('11111111-2222-4333-8444-555555555555');
|
||||
});
|
||||
|
||||
it('falls back when randomUUID is missing (HTTP non-secure context)', () => {
|
||||
// 断言:模拟内网 HTTP,无 randomUUID 也不抛错,且返回非空串。
|
||||
vi.stubGlobal('crypto', {
|
||||
getRandomValues: (bytes: Uint8Array) => {
|
||||
for (let i = 0; i < bytes.length; i += 1) bytes[i] = i;
|
||||
return bytes;
|
||||
},
|
||||
});
|
||||
const value = createRandomUuid();
|
||||
expect(value).toMatch(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* shared/utils/id.ts
|
||||
* 用途:生成客户端随机 ID(会话号、operation_id、幂等键等)。
|
||||
* 依赖:Web Crypto(优先);无安全上下文时回退到 getRandomValues / Math.random。
|
||||
* 逻辑:HTTP 内网(如 192.168.x)不是 secure context,`crypto.randomUUID` 不可用,
|
||||
* 直接调用会在 Vue setup 阶段抛 TypeError 导致白屏;统一走本工具避免分叉。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 生成 UUID 风格随机串;优先 `crypto.randomUUID`,HTTP 等非安全上下文自动降级。
|
||||
* 核心逻辑:secure context 用原生 API;否则用 getRandomValues 拼 RFC4122 v4;再不行用时间戳+随机。
|
||||
* @returns 形如 `xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx` 的字符串(降级路径不保证密码学强度)
|
||||
*/
|
||||
export function createRandomUuid(): string {
|
||||
const webCrypto = globalThis.crypto;
|
||||
if (webCrypto && typeof webCrypto.randomUUID === 'function') {
|
||||
return webCrypto.randomUUID();
|
||||
}
|
||||
if (webCrypto && typeof webCrypto.getRandomValues === 'function') {
|
||||
const bytes = new Uint8Array(16);
|
||||
webCrypto.getRandomValues(bytes);
|
||||
// noUncheckedIndexedAccess 下 Uint8Array 下标为 number | undefined
|
||||
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
|
||||
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
|
||||
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||
}
|
||||
return `fallback-${Date.now().toString(16)}-${Math.random().toString(16).slice(2, 10)}`;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* shared/utils/redirect.ts
|
||||
* 登录回跳目标解析:企微提醒卡片等深链场景下,登录页按 redirect 参数原样回跳。
|
||||
* 依赖:无。被 app/router/guards.ts(守卫放行/跳转)与 features/auth(登录成功后回跳)共用。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 校验并解析登录后回跳目标(企微提醒卡片等深链场景)。
|
||||
* AI 触发时机:路由守卫拦截未登录访问时,以及密码/OAuth 登录成功后决定跳转目标时调用。
|
||||
* 核心逻辑:仅接受站内相对路径(以 / 开头且不以 // 开头),拒绝外链与协议相对地址,防开放重定向。
|
||||
* @param raw - 待校验的 redirect 参数(可能为 string | string[] | undefined)
|
||||
* @returns 安全的站内路径;不合法时返回 null
|
||||
*/
|
||||
export function resolveSafeRedirect(raw: unknown): string | null {
|
||||
const value = Array.isArray(raw) ? String(raw[0] ?? '') : String(raw ?? '');
|
||||
if (!value.startsWith('/') || value.startsWith('//')) return null;
|
||||
return value;
|
||||
}
|
||||
Reference in new issue
Block a user