feat(audit): 收口领域写接口权限审计
This commit is contained in:
@@ -13,6 +13,8 @@ export function resolveApiBase(env: ApiEnv = process.env) {
|
||||
}
|
||||
|
||||
const API_BASE = resolveApiBase();
|
||||
const AUTH_SESSION_KEY = 'ftb_auth_session';
|
||||
const AUTH_PERSIST_KEY = 'ftb_auth_persist';
|
||||
|
||||
function isLocalOnlyApiUrl(value: string) {
|
||||
try {
|
||||
@@ -67,7 +69,7 @@ async function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
const available = await checkApi();
|
||||
if (!available) throw new Error('API 不可用');
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
headers: { 'Content-Type': 'application/json', ...options?.headers },
|
||||
headers: { 'Content-Type': 'application/json', ...resolveAuthHeaders(), ...options?.headers },
|
||||
...options,
|
||||
}).catch(() => null);
|
||||
if (!res) {
|
||||
@@ -97,7 +99,7 @@ export const api = {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}${path}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: { 'Content-Type': 'application/json', ...resolveAuthHeaders() },
|
||||
body: JSON.stringify(data),
|
||||
signal: controller.signal,
|
||||
});
|
||||
@@ -116,3 +118,36 @@ export function __resetApiAvailabilityForTests() {
|
||||
apiAvailable = null;
|
||||
probePromise = null;
|
||||
}
|
||||
|
||||
function resolveAuthHeaders(): Record<string, string> {
|
||||
const user = readStoredAuthUser();
|
||||
if (!user?.id) return {};
|
||||
return {
|
||||
'x-ftb-user-id': user.id,
|
||||
...(user.roleId ? { 'x-ftb-user-role-id': user.roleId } : {}),
|
||||
...(user.name ? { 'x-ftb-user-name': encodeURIComponent(user.name) } : {}),
|
||||
...(user.username ? { 'x-ftb-user-username': user.username } : {}),
|
||||
...(user.email ? { 'x-ftb-user-email': user.email } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function readStoredAuthUser(): { id?: string; roleId?: string; name?: string; username?: string; email?: string } | null {
|
||||
if (typeof sessionStorage === 'undefined') return null;
|
||||
const raw = safeStorageGet(sessionStorage, AUTH_SESSION_KEY)
|
||||
?? (typeof localStorage === 'undefined' ? null : safeStorageGet(localStorage, AUTH_PERSIST_KEY));
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const value = JSON.parse(raw);
|
||||
return value && typeof value === 'object' ? value : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function safeStorageGet(storage: Pick<Storage, 'getItem'>, key: string): string | null {
|
||||
try {
|
||||
return storage.getItem(key);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user