mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-10-05 21:05:39 +08:00
feat: 为本地 HTTP API 增加 Token 鉴权与安全加固
- 使用 Electron safeStorage 加密存储并自动初始化 API Token - 为 health 以外的接口增加 Bearer Token 鉴权 - 限制 CORS 仅允许可信本地 Origin - 增加鉴权、Token rotation、safeStorage 和手动验收测试
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
import crypto from 'crypto'
|
||||
import { app, safeStorage } from 'electron'
|
||||
import fs from 'fs-extra'
|
||||
import path from 'path'
|
||||
import type {
|
||||
ApiTokenActionResult,
|
||||
ApiTokenRevealResult,
|
||||
ApiTokenStatus
|
||||
} from '../shared/local-api-auth'
|
||||
|
||||
const MASKED_TOKEN = '••••••••••••••••'
|
||||
const TOKEN_BYTES = 32
|
||||
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/
|
||||
|
||||
interface TokenReadResult {
|
||||
success: boolean
|
||||
token?: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
export class ApiTokenStore {
|
||||
private cachedToken: string | null = null
|
||||
|
||||
constructor(private readonly filePathOverride?: string) {}
|
||||
|
||||
private get filePath(): string {
|
||||
return this.filePathOverride || path.join(app.getPath('userData'), 'local-api-token.bin')
|
||||
}
|
||||
|
||||
getStatus(): ApiTokenStatus {
|
||||
const available = safeStorage.isEncryptionAvailable()
|
||||
if (!available) {
|
||||
return {
|
||||
available: false,
|
||||
hasToken: false,
|
||||
maskedToken: MASKED_TOKEN,
|
||||
error: '系统安全存储不可用,本地 API 已安全停用。请检查系统钥匙串或凭据服务后重试。'
|
||||
}
|
||||
}
|
||||
const result = this.read()
|
||||
return {
|
||||
available: true,
|
||||
hasToken: result.success && Boolean(result.token),
|
||||
maskedToken: MASKED_TOKEN,
|
||||
...(result.success ? {} : { error: result.error })
|
||||
}
|
||||
}
|
||||
|
||||
ensureToken(): ApiTokenActionResult {
|
||||
if (!safeStorage.isEncryptionAvailable()) {
|
||||
return {
|
||||
success: false,
|
||||
available: false,
|
||||
hasToken: false,
|
||||
maskedToken: MASKED_TOKEN,
|
||||
error: '系统安全存储不可用,本地 API 已安全停用。请检查系统钥匙串或凭据服务后重试。'
|
||||
}
|
||||
}
|
||||
const current = this.read()
|
||||
if (!current.success) return this.actionError(current.error)
|
||||
if (current.token) return this.actionSuccess()
|
||||
return this.persist(this.generateToken())
|
||||
}
|
||||
|
||||
revealToken(): ApiTokenRevealResult {
|
||||
const ensured = this.ensureToken()
|
||||
if (!ensured.success) return ensured
|
||||
return { ...ensured, token: this.cachedToken || undefined }
|
||||
}
|
||||
|
||||
rotateToken(): ApiTokenActionResult {
|
||||
if (!safeStorage.isEncryptionAvailable()) return this.ensureToken()
|
||||
return this.persist(this.generateToken())
|
||||
}
|
||||
|
||||
getTokenForAuthentication(): string | null {
|
||||
if (this.cachedToken) return this.cachedToken
|
||||
const result = this.read()
|
||||
return result.success ? result.token || null : null
|
||||
}
|
||||
|
||||
private generateToken(): string {
|
||||
return crypto.randomBytes(TOKEN_BYTES).toString('base64url')
|
||||
}
|
||||
|
||||
private read(): TokenReadResult {
|
||||
if (this.cachedToken) return { success: true, token: this.cachedToken }
|
||||
if (!safeStorage.isEncryptionAvailable()) {
|
||||
return { success: false, error: '系统安全存储不可用' }
|
||||
}
|
||||
if (!fs.existsSync(this.filePath)) return { success: true }
|
||||
try {
|
||||
const token = safeStorage.decryptString(fs.readFileSync(this.filePath))
|
||||
if (!TOKEN_PATTERN.test(token)) throw new Error('invalid token data')
|
||||
this.cachedToken = token
|
||||
return { success: true, token }
|
||||
} catch {
|
||||
return { success: false, error: '已保存的 API Token 无法从系统安全存储读取' }
|
||||
}
|
||||
}
|
||||
|
||||
private persist(token: string): ApiTokenActionResult {
|
||||
try {
|
||||
fs.ensureDirSync(path.dirname(this.filePath))
|
||||
fs.writeFileSync(this.filePath, safeStorage.encryptString(token), { mode: 0o600 })
|
||||
fs.chmodSync(this.filePath, 0o600)
|
||||
this.cachedToken = token
|
||||
return this.actionSuccess()
|
||||
} catch {
|
||||
return this.actionError('API Token 无法保存到系统安全存储')
|
||||
}
|
||||
}
|
||||
|
||||
private actionSuccess(): ApiTokenActionResult {
|
||||
return {
|
||||
success: true,
|
||||
available: true,
|
||||
hasToken: true,
|
||||
maskedToken: MASKED_TOKEN
|
||||
}
|
||||
}
|
||||
|
||||
private actionError(error?: string): ApiTokenActionResult {
|
||||
return {
|
||||
success: false,
|
||||
available: safeStorage.isEncryptionAvailable(),
|
||||
hasToken: false,
|
||||
maskedToken: MASKED_TOKEN,
|
||||
error: error || 'API Token 安全存储不可用'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const apiTokenStore = new ApiTokenStore()
|
||||
+69
-8
@@ -1,3 +1,4 @@
|
||||
import crypto from 'crypto'
|
||||
import http, { IncomingMessage, ServerResponse, Server } from 'http'
|
||||
import {
|
||||
isReady,
|
||||
@@ -12,6 +13,7 @@ import { GroupReportExportRequest } from '../shared/group-report'
|
||||
import { generateAgentGroupReport } from './services/agent-group-report-service'
|
||||
import { agentHubService } from './services/agent-hub-service'
|
||||
import { safeError, safeLog, safeWarn } from './safe-log'
|
||||
import { apiTokenStore } from './api-token-store'
|
||||
|
||||
export const DEFAULT_HTTP_HOST = '127.0.0.1'
|
||||
export const DEFAULT_HTTP_PORT = 6131
|
||||
@@ -29,6 +31,10 @@ interface RouteContext {
|
||||
body?: unknown
|
||||
}
|
||||
|
||||
export interface HttpServerOptions {
|
||||
tokenProvider?: () => string | null
|
||||
}
|
||||
|
||||
type RouteHandler = (ctx: RouteContext) => void | Promise<void>
|
||||
|
||||
function sendJson(res: ServerResponse, status: number, payload: unknown): void {
|
||||
@@ -36,12 +42,50 @@ function sendJson(res: ServerResponse, status: number, payload: unknown): void {
|
||||
res.writeHead(status, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Cache-Control': 'no-store'
|
||||
})
|
||||
res.end(body)
|
||||
}
|
||||
|
||||
function isAllowedCorsOrigin(origin: string): boolean {
|
||||
if (!/^http:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/i.test(origin)) return false
|
||||
try {
|
||||
const parsed = new URL(origin)
|
||||
if (parsed.protocol !== 'http:') return false
|
||||
if (parsed.username || parsed.password) return false
|
||||
return ['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname.toLowerCase())
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function applyCorsHeaders(req: IncomingMessage, res: ServerResponse): boolean {
|
||||
const origin = req.headers.origin
|
||||
if (!origin) return true
|
||||
if (!isAllowedCorsOrigin(origin)) return false
|
||||
res.setHeader('Access-Control-Allow-Origin', origin)
|
||||
res.setHeader('Vary', 'Origin')
|
||||
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
|
||||
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization')
|
||||
return true
|
||||
}
|
||||
|
||||
function isAuthorized(req: IncomingMessage, expectedToken: string | null): boolean {
|
||||
const header = req.headers.authorization
|
||||
const match = typeof header === 'string' ? /^Bearer ([A-Za-z0-9_-]+)$/.exec(header) : null
|
||||
if (!match || !expectedToken) return false
|
||||
const actualDigest = crypto.createHash('sha256').update(match[1], 'utf8').digest()
|
||||
const expectedDigest = crypto.createHash('sha256').update(expectedToken, 'utf8').digest()
|
||||
return crypto.timingSafeEqual(actualDigest, expectedDigest)
|
||||
}
|
||||
|
||||
function sendUnauthorized(res: ServerResponse): void {
|
||||
sendJson(res, 401, {
|
||||
error: 'unauthorized',
|
||||
message: 'Valid API token required'
|
||||
})
|
||||
}
|
||||
|
||||
function sendError(res: ServerResponse, status: number, message: string, extra?: unknown): void {
|
||||
sendJson(res, status, { error: message, status, ...(extra ? { details: extra } : {}) })
|
||||
}
|
||||
@@ -301,24 +345,28 @@ const routes: Record<string, RouteHandler> = {
|
||||
|
||||
export function startHttpServer(
|
||||
host: string = DEFAULT_HTTP_HOST,
|
||||
port: number = DEFAULT_HTTP_PORT
|
||||
port: number = DEFAULT_HTTP_PORT,
|
||||
options: HttpServerOptions = {}
|
||||
): Promise<HttpServerHandle> {
|
||||
const tokenProvider = options.tokenProvider || (() => apiTokenStore.getTokenForAuthentication())
|
||||
return new Promise((resolve, reject) => {
|
||||
const server: Server = http.createServer(async (req, res) => {
|
||||
try {
|
||||
const url = new URL(req.url || '/', `http://${host}:${port}`)
|
||||
if (!applyCorsHeaders(req, res)) {
|
||||
return sendError(res, 403, 'Origin 不允许访问本地 API')
|
||||
}
|
||||
if (req.method === 'OPTIONS') {
|
||||
res.writeHead(204, {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
||||
'Access-Control-Allow-Headers': '*'
|
||||
})
|
||||
res.writeHead(204)
|
||||
return res.end()
|
||||
}
|
||||
const handler = routes[url.pathname]
|
||||
if (!handler) {
|
||||
return sendError(res, 404, `端点不存在: ${url.pathname}`)
|
||||
}
|
||||
if (url.pathname !== '/api/v1/health' && !isAuthorized(req, tokenProvider())) {
|
||||
return sendUnauthorized(res)
|
||||
}
|
||||
let body: string | undefined
|
||||
if (req.method && req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
body = await readBody(req)
|
||||
@@ -391,11 +439,24 @@ export const apiServer = {
|
||||
return this.getState()
|
||||
}
|
||||
|
||||
const token = apiTokenStore.ensureToken()
|
||||
if (!token.success) {
|
||||
singletonState = {
|
||||
running: false,
|
||||
host,
|
||||
port,
|
||||
error: token.error || 'API Token 安全存储不可用'
|
||||
}
|
||||
return { ...singletonState }
|
||||
}
|
||||
|
||||
const maxAttempts = 4
|
||||
let lastError: (NodeJS.ErrnoException & { friendlyMessage?: string }) | null = null
|
||||
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
||||
try {
|
||||
singleton = await startHttpServer(host, port)
|
||||
singleton = await startHttpServer(host, port, {
|
||||
tokenProvider: () => apiTokenStore.getTokenForAuthentication()
|
||||
})
|
||||
singletonState = {
|
||||
running: true,
|
||||
host: singleton.host,
|
||||
|
||||
+40
-4
@@ -43,6 +43,7 @@ import type {
|
||||
LegacyAIConfig
|
||||
} from '../shared/ai-provider'
|
||||
import { DatabaseKeyStore } from './database-key-store'
|
||||
import { apiTokenStore } from './api-token-store'
|
||||
import { ImageKeyConfigService } from './services/image-key-config-service'
|
||||
import { AIProviderService } from './services/ai-provider-service'
|
||||
import { imageInsightService } from './services/image-insight-service'
|
||||
@@ -58,7 +59,7 @@ import { KeyService as KeyServiceWin } from './key-service-win'
|
||||
import * as chat from './services/chat-service'
|
||||
import { apiServer } from './http-server'
|
||||
import { skillResourceService } from './services/skill-resource-service'
|
||||
import { testLocalApiRequest } from './services/local-api-test-service'
|
||||
import { buildLocalApiCurlCommand, testLocalApiRequest } from './services/local-api-test-service'
|
||||
import { isWechatRunning } from './services/wechat-process-status'
|
||||
import {
|
||||
inspectImageDecryptionStatus,
|
||||
@@ -321,7 +322,10 @@ function getLocalMediaMimeType(filePath: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
function buildImageResponse(image: DecodedImage, includeData = false): {
|
||||
function buildImageResponse(
|
||||
image: DecodedImage,
|
||||
includeData = false
|
||||
): {
|
||||
success: true
|
||||
data: string
|
||||
isThumb: boolean
|
||||
@@ -443,8 +447,8 @@ app.whenReady().then(async () => {
|
||||
app.getPath('userData'),
|
||||
join(__dirname, 'knowledgeWorker.js')
|
||||
)
|
||||
knowledgeSearchService.setVoiceTranscriptResolver((reference) =>
|
||||
voiceRecognition?.getTranscriptSnapshot(reference) || { state: 'pending' }
|
||||
knowledgeSearchService.setVoiceTranscriptResolver(
|
||||
(reference) => voiceRecognition?.getTranscriptSnapshot(reference) || { state: 'pending' }
|
||||
)
|
||||
voiceRecognition.onTranscriptUpdate((update) =>
|
||||
knowledgeSearchService?.indexVoiceTranscript(update)
|
||||
@@ -1441,6 +1445,25 @@ app.whenReady().then(async () => {
|
||||
|
||||
ipcMain.handle('api:getStatus', () => apiServer.getState())
|
||||
|
||||
ipcMain.handle('api:tokenStatus', () => apiTokenStore.ensureToken())
|
||||
ipcMain.handle('api:revealToken', () => apiTokenStore.revealToken())
|
||||
ipcMain.handle('api:copyToken', () => {
|
||||
const result = apiTokenStore.revealToken()
|
||||
if (!result.token) return { ...result, success: false }
|
||||
try {
|
||||
clipboard.writeText(result.token)
|
||||
return {
|
||||
success: true,
|
||||
available: result.available,
|
||||
hasToken: result.hasToken,
|
||||
maskedToken: result.maskedToken
|
||||
}
|
||||
} catch {
|
||||
return { ...apiTokenStore.getStatus(), success: false, error: 'API Token 复制失败' }
|
||||
}
|
||||
})
|
||||
ipcMain.handle('api:rotateToken', () => apiTokenStore.rotateToken())
|
||||
|
||||
ipcMain.handle('api:start', async (_, host?: string, port?: number) => {
|
||||
const settings = loadSettings()
|
||||
const target = {
|
||||
@@ -1466,6 +1489,16 @@ app.whenReady().then(async () => {
|
||||
ipcMain.handle('api:revealSkill', () => skillResourceService.reveal())
|
||||
ipcMain.handle('api:openSkillGithub', () => skillResourceService.openGithub())
|
||||
ipcMain.handle('api:testLocalRequest', (_, request) => testLocalApiRequest(request))
|
||||
ipcMain.handle('api:copyCurl', (_, request) => {
|
||||
const result = buildLocalApiCurlCommand(request)
|
||||
if (!result.success || !result.command) return { success: false, error: result.error }
|
||||
try {
|
||||
clipboard.writeText(result.command)
|
||||
return { success: true }
|
||||
} catch {
|
||||
return { success: false, error: 'curl 命令复制失败' }
|
||||
}
|
||||
})
|
||||
ipcMain.handle('api:copyText', (_, text: unknown) => {
|
||||
if (typeof text !== 'string' || text.length > 1024 * 1024) {
|
||||
return { success: false, error: '复制内容无效或过大' }
|
||||
@@ -1499,6 +1532,9 @@ app.whenReady().then(async () => {
|
||||
|
||||
// 启动本地 HTTP API(由 settings.apiEnabled 控制)
|
||||
const settings = loadSettings()
|
||||
// v2.1.8 and earlier did not have an API token. Generate it once during
|
||||
// upgrade/startup without changing any existing API or database settings.
|
||||
apiTokenStore.ensureToken()
|
||||
if (settings.apiEnabled) {
|
||||
await apiServer.start(settings.apiHost, settings.apiPort)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import http from 'http'
|
||||
import { apiServer } from '../http-server'
|
||||
import { apiTokenStore } from '../api-token-store'
|
||||
import {
|
||||
LOCAL_API_ENDPOINTS,
|
||||
type LocalApiEndpointId,
|
||||
@@ -45,6 +46,47 @@ function parseBody(bodyText: string, contentType?: string): { json?: unknown; bo
|
||||
return { bodyText }
|
||||
}
|
||||
|
||||
export function buildLocalApiCurlCommand(payload: unknown): {
|
||||
success: boolean
|
||||
command?: string
|
||||
error?: string
|
||||
} {
|
||||
if (!payload || typeof payload !== 'object') return { success: false, error: '请求格式无效' }
|
||||
const { endpointId, query = {}, body = '' } = payload as Partial<LocalApiTestRequest>
|
||||
if (!isEndpointId(endpointId)) return { success: false, error: '不允许访问该 API 端点' }
|
||||
if (!query || typeof query !== 'object' || Array.isArray(query))
|
||||
return { success: false, error: '查询参数格式无效' }
|
||||
if (typeof body !== 'string' || Buffer.byteLength(body) > MAX_BODY_SIZE)
|
||||
return { success: false, error: '请求体格式无效' }
|
||||
|
||||
const endpoint = LOCAL_API_ENDPOINTS[endpointId]
|
||||
const entries = Object.entries(query)
|
||||
if (
|
||||
entries.some(
|
||||
([key, value]) => !endpoint.queryKeys.includes(key as never) || typeof value !== 'string'
|
||||
)
|
||||
) {
|
||||
return { success: false, error: '查询参数不属于当前端点' }
|
||||
}
|
||||
const service = apiServer.getState()
|
||||
const targetHost = requestHost(service.host)
|
||||
const hostPart = targetHost.includes(':') ? `[${targetHost}]` : targetHost
|
||||
const url = new URL(endpoint.path, `http://${hostPart}:${service.port}`)
|
||||
entries.forEach(([key, value]) => {
|
||||
if (value.trim()) url.searchParams.set(key, value.trim())
|
||||
})
|
||||
const token = endpointId === 'health' ? null : apiTokenStore.getTokenForAuthentication()
|
||||
if (endpointId !== 'health' && !token) {
|
||||
return { success: false, error: 'API Token 安全存储不可用,请在 API Center 检查 Token 状态' }
|
||||
}
|
||||
const authHeader = token ? ` -H 'Authorization: Bearer ${token}'` : ''
|
||||
const command =
|
||||
endpoint.method === 'POST'
|
||||
? `curl -X POST '${url.toString()}'${authHeader} -H 'Content-Type: application/json' -d '${body.replaceAll("'", "\\'")}'`
|
||||
: `curl '${url.toString()}'${authHeader}`
|
||||
return { success: true, command }
|
||||
}
|
||||
|
||||
export async function testLocalApiRequest(payload: unknown): Promise<LocalApiTestResponse> {
|
||||
if (!payload || typeof payload !== 'object') return invalidResponse('请求格式无效')
|
||||
const { endpointId, query = {}, body = '' } = payload as Partial<LocalApiTestRequest>
|
||||
@@ -94,11 +136,27 @@ export async function testLocalApiRequest(payload: unknown): Promise<LocalApiTes
|
||||
settled = true
|
||||
resolve(result)
|
||||
}
|
||||
const token = endpointId === 'health' ? null : apiTokenStore.getTokenForAuthentication()
|
||||
if (endpointId !== 'health' && !token) {
|
||||
return finish({
|
||||
ok: false,
|
||||
method: endpoint.method,
|
||||
path: endpoint.path,
|
||||
url: url.toString(),
|
||||
durationMs: Date.now() - startedAt,
|
||||
responseSize: 0,
|
||||
errorCode: 'TOKEN_UNAVAILABLE',
|
||||
error: 'API Token 安全存储不可用,请在 API Center 检查 Token 状态'
|
||||
})
|
||||
}
|
||||
const headers: Record<string, string> = {}
|
||||
if (endpoint.method === 'POST') headers['Content-Type'] = 'application/json'
|
||||
if (token) headers.Authorization = `Bearer ${token}`
|
||||
const request = http.request(
|
||||
url,
|
||||
{
|
||||
method: endpoint.method,
|
||||
headers: endpoint.method === 'POST' ? { 'Content-Type': 'application/json' } : undefined
|
||||
headers
|
||||
},
|
||||
(response) => {
|
||||
const chunks: Buffer[] = []
|
||||
|
||||
@@ -48,7 +48,7 @@ function getStatus(): SkillResourceStatus {
|
||||
}
|
||||
return {
|
||||
available: true,
|
||||
version: 'v1.0',
|
||||
version: 'v1.1',
|
||||
filePath,
|
||||
directoryPath,
|
||||
source,
|
||||
|
||||
Reference in New Issue
Block a user