feat: 增强URL基础地址验证功能 - 在app-instance/frontend/lib/api.ts中实现更严格的URL验证逻辑, 包括检查是否以斜杠开头、包含空格字符,以及使用URL构造函数进行验证 - 在app-instance/frontend/lib/auth-portal.ts中应用相同的URL验证改进, 提升认证门户的基础地址处理安全性 - 在auth-portal/src/lib/auth-client.ts中增强前端跳转URL构建功能, 添加错误处理机制并在URL构造失败时抛出相应异常 - 统一三个文件中的normalizeBaseUrl函数实现,确保一致的输入验证行为 ```
39 lines
1.3 KiB
TypeScript
39 lines
1.3 KiB
TypeScript
'use client';
|
|
|
|
const AUTH_PORTAL_URL = process.env.NEXT_PUBLIC_AUTH_PORTAL_URL?.trim();
|
|
const AUTH_PORTAL_PORT = process.env.NEXT_PUBLIC_AUTH_PORTAL_PORT?.trim() || '3081';
|
|
|
|
function normalizeBaseUrl(value?: string | null): string | null {
|
|
const trimmed = value?.trim();
|
|
if (!trimmed) return null;
|
|
if (trimmed.startsWith('/') || /\s/.test(trimmed)) return null;
|
|
const hasScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed);
|
|
const candidate = hasScheme ? trimmed : `http://${trimmed}`;
|
|
try {
|
|
const url = new URL(candidate);
|
|
return url.toString().replace(/\/+$/, '');
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function getPortalBaseUrl(): string {
|
|
const explicit = normalizeBaseUrl(AUTH_PORTAL_URL);
|
|
if (explicit) return explicit;
|
|
if (typeof window !== 'undefined') {
|
|
const url = new URL(window.location.origin);
|
|
url.port = AUTH_PORTAL_PORT;
|
|
return normalizeBaseUrl(url.toString()) || window.location.origin;
|
|
}
|
|
return `http://127.0.0.1:${AUTH_PORTAL_PORT}`;
|
|
}
|
|
|
|
export function buildAuthPortalUrl(path: '/login' | '/register', nextPath?: string | null): string {
|
|
const url = new URL(path, `${getPortalBaseUrl()}/`);
|
|
const nextValue = nextPath?.trim();
|
|
if (nextValue) {
|
|
url.searchParams.set('next', nextValue);
|
|
}
|
|
return url.toString();
|
|
}
|