WebSockets与GraphQL接口安全防护最佳实践概述实时与灵活查询接口需要额外的会话绑定、来源校验与复杂度限制,以避免滥用与资源枯竭。WebSockets握手安全function validateWsHandshake(origin: string, token: string, allowedOrigins: string[], verify: (t: string) => boolean): boolean {
if (!allowedOrigins.includes(origin)) return false
if (!verify(token)) return false
return true
}
GraphQL深度与复杂度限制type CostRule = { field: string; cost: number }
function computeDepth(node: any): number {
if (!node || !node.selectionSet) return 0
let m = 0
for (const sel of node.selectionSet.selections || []) m = Math.max(m, computeDepth(sel))
return 1 + m
}
function computeCost(ast: any, rules: CostRule[]): number {
let cost = 0
const stack = [ast]
while (stack.length) {
const cur = stack.pop()!
const name = cur.name?.value
const r = rules.find(x => x.field === name)
if (r) cost += r.cost
const sels = cur.selectionSet?.selections || []
for (const s of sels) stack.push(s)
}
return cost
}
订阅与速率治理class SubLimiter {
maxSubs: number
windowMs: number
timestamps: number[] = []
constructor(maxSubs: number, windowMs: number) { this.maxSubs = maxSubs; this.windowMs = windowMs }
allow(): boolean {
const now = Date.now()
this.timestamps = this.timestamps.filter(t => now - t < this.windowMs)
if (this.timestamps.length >= this.maxSubs) return false
this.timestamps.push(now)
return true
}
}
运维要点在握手中强制来源与令牌绑定并记录指纹对查询设置深度、复杂度与字段白名单对订阅与消息速率进行窗口化治理与封禁策略该方案可在实时与查询密集型场景中降低滥用与资源耗尽风险。

发表评论 取消回复