清理冗余注释
只保留不写就会改错的说明(宿主 block 只给固定 403、UTF-8 边界、脱敏长度不变、 messages 需稠密整数表才能编成数组、input_text 绕过等),其余说明性段落删掉。 response_guard 注释 129 → 42 行;config.yaml 注释 51 → 13 行;配置结构未变。
This commit is contained in:
1 parent
5b4438a306
commit
ec6f5fc811
5 files changed
+56
-258
No files matched your search
@@ -1,18 +1,5 @@
|
||||
-- ============================================================================
|
||||
-- request_rewrite.lua —— OpenAI Chat Completions 请求改写(Lua 插件接口 v1)
|
||||
--
|
||||
-- 作用
|
||||
-- 在最后一条 user 消息的正文前加上配置的前缀,用于打标/灰度/审计定位。
|
||||
-- 只认 OpenAI 的 messages 结构,不再处理旧的单 message 字段。
|
||||
--
|
||||
-- 适用性
|
||||
-- content 为字符串,或 content 为 [{type:"text",text:"..."}] 数组时改写;
|
||||
-- 其它情况(非 JSON、无 user 消息、多模态纯图片等)原样放行。
|
||||
--
|
||||
-- 注意
|
||||
-- 改写会重新序列化整个 body(键序、空白、转义可能与原始字节不同),
|
||||
-- 下游若要求签名稳定的字节级一致,请不要启用本插件。
|
||||
-- ============================================================================
|
||||
-- request_rewrite.lua —— 给最后一条 user 消息加前缀打标。
|
||||
-- 会重新序列化整个 body,字节级签名校验的下游不要启用。
|
||||
|
||||
local plugin = {}
|
||||
local settings = { prefix = "" }
|
||||
|
||||
+14
-110
@@ -1,43 +1,9 @@
|
||||
-- ============================================================================
|
||||
-- response_guard.lua —— OpenAI 兼容内容安全插件(Lua 插件接口 v1)
|
||||
--
|
||||
-- 审核后端
|
||||
-- 直接调用 OpenAI 兼容的 /chat/completions 接口做判定(不再使用本地
|
||||
-- host.llm 守卫模型)。请求与响应都按 OpenAI Chat Completions 协议解析:
|
||||
-- 请求 : POST /v1/chat/completions {model, messages[], stream}
|
||||
-- 非流式 : choices[*].message.content
|
||||
-- 流式 : choices[*].delta.content + 终止帧 data: [DONE]
|
||||
-- 判定请求体(见 judge_body):model / messages[{role,content}] / stream=false
|
||||
-- 固定为 JSON 数组与显式 false;temperature、生成上限参数名、response_format、
|
||||
-- reasoning_effort 按后端能力配置,默认值对 DeepSeek 一类兼容服务可直接跑。
|
||||
--
|
||||
-- 输出契约(客户端只会看到 OpenAI 形态)
|
||||
-- 非流式拦截 : HTTP 400 + {"error":{"message","type":"invalid_request_error",
|
||||
-- "param":null,"code":"content_policy_violation"}}
|
||||
-- 流式拦截 : 单帧 data: {"error":{...}},随后直接关闭(不再发 [DONE])
|
||||
-- 审核不可用 : HTTP 503 + type "server_error" / code "safety_review_unavailable"
|
||||
--
|
||||
-- 为什么拦截要放到响应阶段
|
||||
-- 宿主对 {action='block'} 只返回它自己固定的 403 正文,插件无法自定义;
|
||||
-- 因此请求侧判定不通过时不再 block,而是:
|
||||
-- 1) 保留判定结果;
|
||||
-- 2) 把发往上游的请求体替换成一段最小 stub(原文绝不发给模型);
|
||||
-- 3) 在响应侧用 replace 输出上面的 OpenAI 错误体。
|
||||
-- 客户端看到的始终是 OpenAI 风格,且风险内容一次都没有离开网关。
|
||||
--
|
||||
-- 请求格式统一为 OpenAI Chat Completions
|
||||
-- 本插件发出的每一个请求体都按 OpenAI 规范构造,不夹带自定义字段:
|
||||
-- 判定请求(judge_body): {model, messages[system,user], stream:false,
|
||||
-- temperature?, max_tokens?, response_format?,
|
||||
-- reasoning_effort?}
|
||||
-- 占位请求(encode_stub): {model, messages[user:"ping"], stream, max_tokens?}
|
||||
-- 占位请求刻意不带 temperature / response_format / tools——这些与占位无关,
|
||||
-- 且 o 系列、gpt-5 会直接 400,而上游一旦报错就会在我们的日志里制造噪声。
|
||||
--
|
||||
-- 放行路径
|
||||
-- 流式按句读缓冲(可配 flush_chars)→ 审核 → 确定性脱敏 → 按原顺序放行;
|
||||
-- 非流式整体审核 → 脱敏 → 放行。审核或脱敏任一步失败一律 fail-closed。
|
||||
-- ============================================================================
|
||||
-- 宿主对 {action="block"} 只返回它自己固定的 403 正文,插件改不了;所以请求侧判定
|
||||
-- 不通过时不 block,而是把请求体换成 stub(原文不出网关),再在响应侧 replace 成
|
||||
-- OpenAI 错误体:400 content_policy_violation / 503 safety_review_unavailable。
|
||||
-- 插件发出的请求体(判定、占位)都只含 OpenAI Chat Completions 规范字段。
|
||||
|
||||
local plugin = {}
|
||||
local config = {}
|
||||
@@ -73,10 +39,6 @@ local DEFAULT_SYSTEM_PROMPT = table.concat({
|
||||
'or {"allow":false,"category":"weapons|cyber|sexual_minors|harassment|self_harm|privacy|other","reason":"<=12 words"}',
|
||||
}, "\n")
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 基础工具
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local function key_for(ctx)
|
||||
if type(ctx) == "table" and type(ctx.request_id) == "string" and ctx.request_id ~= "" then
|
||||
return ctx.request_id
|
||||
@@ -197,15 +159,7 @@ local function parse_paths(value, default_text)
|
||||
return list
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- OpenAI 内容定位:choices[*].delta.content / choices[*].message.content
|
||||
--
|
||||
-- 返回 locations(有序,含 parent/key 便于原地改写)与 malformed 标记。
|
||||
-- segment 为 "*" 时展开同构数组;
|
||||
-- 字段缺失(nil)视为「本帧没有文本」,属正常情况(role/finish 帧);
|
||||
-- 字段存在但不是字符串 → malformed,调用方必须 fail-closed。
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
-- 字段缺失 = 本帧没文本(role/finish 帧);存在但不是字符串 = malformed,必须 fail-closed
|
||||
local function collect_locations(root, parts)
|
||||
local found = {}
|
||||
local malformed = false
|
||||
@@ -277,8 +231,7 @@ local function join_locations(locations)
|
||||
return table.concat(parts)
|
||||
end
|
||||
|
||||
-- 多条内容路径(正文 + 工具调用参数)统一按顺序收集;顺序必须稳定,
|
||||
-- 放行时依赖同样的顺序把脱敏结果切回各字段。
|
||||
-- 顺序必须稳定:放行时按同样的顺序把脱敏结果切回各字段
|
||||
local function collect_all(root, path_list)
|
||||
local locations = {}
|
||||
local malformed = false
|
||||
@@ -292,10 +245,9 @@ local function collect_all(root, path_list)
|
||||
return locations, malformed
|
||||
end
|
||||
|
||||
-- 前置声明:redact_locations 会用到下方定义的 redact_text
|
||||
local redact_text
|
||||
|
||||
-- 就地脱敏;返回 changed, err。脱敏不改变字节长度,失败即 fail-closed。
|
||||
-- 就地脱敏;脱敏不改变字节长度,失败即 fail-closed
|
||||
local function redact_locations(locations)
|
||||
if #locations == 0 then return false, nil end
|
||||
local original = join_locations(locations)
|
||||
@@ -314,10 +266,6 @@ local function redact_locations(locations)
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 确定性脱敏(与语义审核互补;所有规则保持字节长度不变)
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
redact_text = function(text)
|
||||
local out = text
|
||||
|
||||
@@ -364,7 +312,7 @@ redact_text = function(text)
|
||||
return phone:sub(1, 3) .. "****" .. phone:sub(-4)
|
||||
end)
|
||||
|
||||
-- 10 位固话,保留分隔符(原实现会吃掉分隔符,导致长度变化)
|
||||
-- 10 位固话:保留分隔符,长度必须不变
|
||||
out = out:gsub("(%d%d%d)([%s%.%-]?)(%d%d%d)([%s%.%-]?)(%d%d%d%d)",
|
||||
function(a, sep1, b, sep2, c)
|
||||
return a .. sep1 .. "***" .. sep2 .. c
|
||||
@@ -373,10 +321,6 @@ redact_text = function(text)
|
||||
return out
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 句边界检测(中英文标点,排除缩写与小数点)
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local closers = {
|
||||
['"'] = true, ["'"] = true, [')'] = true, [']'] = true, ['}'] = true,
|
||||
}
|
||||
@@ -447,10 +391,6 @@ local function has_sentence_boundary(s)
|
||||
return false
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- OpenAI 错误体
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local function policy_denied(verdict, kind)
|
||||
return {
|
||||
status = config.block_status,
|
||||
@@ -497,10 +437,6 @@ local function error_frame(policy)
|
||||
return { has_data = true, data = error_body(policy) }
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 判定调用:OpenAI 兼容 /chat/completions
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local function strip_code_fence(text)
|
||||
local s = text
|
||||
if s:match("^%s*```") then
|
||||
@@ -551,11 +487,7 @@ local function judge_user_payload(kind, context, part, index, total)
|
||||
return table.concat(lines, "\n")
|
||||
end
|
||||
|
||||
-- OpenAI Chat Completions 请求体。
|
||||
-- messages 必须是真正的 JSON 数组(Lua 里写成稠密整数表即可,宿主按数组编码);
|
||||
-- 可选字段按后端能力开关,默认组合与 DeepSeek 一类兼容服务一致:
|
||||
-- temperature=0 / max_tokens / response_format=json_object / stream=false
|
||||
-- gpt-5、o 系列只认 max_completion_tokens 且拒绝 temperature=0,换后端时改配置。
|
||||
-- messages 必须是稠密整数表,宿主才会编码成 JSON 数组而不是对象
|
||||
local function judge_body(payload_text)
|
||||
local body = {
|
||||
model = config.model,
|
||||
@@ -563,7 +495,6 @@ local function judge_body(payload_text)
|
||||
{ role = "system", content = config.system_prompt },
|
||||
{ role = "user", content = payload_text },
|
||||
},
|
||||
-- 判定只解析完整 JSON 响应体,显式声明不流式,避免后端默认开流
|
||||
stream = false,
|
||||
}
|
||||
if config.judge_temperature ~= nil then
|
||||
@@ -573,8 +504,6 @@ local function judge_body(payload_text)
|
||||
if config.judge_json_mode then
|
||||
body.response_format = { type = "json_object" }
|
||||
end
|
||||
-- 推理型模型会在判定前刷掉大量思维链;后端支持时设成 none 可显著降时延,
|
||||
-- 同时避免 max_tokens 被思维链吃光导致 content 为空。不支持就留空。
|
||||
if config.judge_reasoning_effort then
|
||||
body.reasoning_effort = config.judge_reasoning_effort
|
||||
end
|
||||
@@ -644,13 +573,7 @@ local function judge(kind, user_text, model_text)
|
||||
return { allow = true }
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 请求解析
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
-- 正文既可能是字符串,也可能是内容块数组。只取文本块:
|
||||
-- chat 风格 {type="text"},Responses 风格 {type="input_text"} 都要认,
|
||||
-- 否则客户端换一种写法就能绕过输入审核(图片块没有 text 字段,天然跳过)。
|
||||
-- chat 的 {type="text"} 和 Responses 的 {type="input_text"} 都要认,否则换个写法就能绕过审核
|
||||
local function message_text(content)
|
||||
if type(content) == "string" then return content end
|
||||
if type(content) ~= "table" then return nil end
|
||||
@@ -687,14 +610,7 @@ local function collect_user_text(decoded)
|
||||
return table.concat(texts, "\n\n---\n\n")
|
||||
end
|
||||
|
||||
-- 拦截不通过时发往上游的占位请求。它必须是一个【完全符合 OpenAI Chat Completions
|
||||
-- 规范的请求体】,否则上游会先用自己的 400 拒掉它,日志里凭空多一条与我们无关的错误。
|
||||
-- 只带规范字段:
|
||||
-- model : 客户端原样给的模型名(规范必填);客户端没给时用 stub_model 兜底
|
||||
-- messages : 固定 ping,被拦截的原文不出网关
|
||||
-- stream : 显式布尔,客户端流式就 true,否则 false
|
||||
-- max_tokens: 可选生成长度上限,stub_max_tokens=false 时不发送
|
||||
-- 不发送 temperature / response_format / tools 等与占位无关的字段。
|
||||
-- 拦截后发往上游的占位请求:只带 OpenAI 规范字段,否则上游会先用自己的 400 拒掉它
|
||||
local function encode_stub(state)
|
||||
local body = {
|
||||
messages = { { role = "user", content = "ping" } },
|
||||
@@ -709,10 +625,6 @@ local function encode_stub(state)
|
||||
return host.json.encode(body)
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 缓冲放行
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local function should_flush(state)
|
||||
if state.text_bytes < config.flush_chars then return false end
|
||||
if has_sentence_boundary(state.tail) then return true end
|
||||
@@ -781,10 +693,6 @@ local function release(state)
|
||||
return host.json.array(events), nil
|
||||
end
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- 生命周期
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
local function positive_int(value, default, label)
|
||||
if value == nil then return default end
|
||||
local number = tonumber(value)
|
||||
@@ -800,10 +708,7 @@ local function boolean(value, default)
|
||||
error("response_guard: boolean config value must be true or false")
|
||||
end
|
||||
|
||||
-- base_url 的三种写法都要落到同一个端点:
|
||||
-- https://host -> https://host/v1/chat/completions
|
||||
-- https://host/v1 -> https://host/v1/chat/completions
|
||||
-- https://host/v1/chat/completions(完整端点) -> 原样使用
|
||||
-- 主机、/v1、完整端点三种写法都落到 /v1/chat/completions
|
||||
local function build_judge_url(base_url)
|
||||
if base_url:match("/chat/completions$") then return base_url end
|
||||
if base_url:match("^https?://[^/]+$") then return base_url .. "/v1/chat/completions" end
|
||||
@@ -842,7 +747,7 @@ function plugin.init(ctx, options)
|
||||
end
|
||||
|
||||
-- response_format=json_object 的后端要求 messages 里出现 "json",
|
||||
-- 自定义 system_prompt 漏了这个词会被 400 顶回来,这里补一句兜底。
|
||||
-- json_object 模式要求 messages 里出现 "json",漏了会被 400,这里补一句兜底
|
||||
local json_mode = boolean(o.judge_json_mode, true)
|
||||
local system_prompt = o.system_prompt
|
||||
if system_prompt == nil then system_prompt = DEFAULT_SYSTEM_PROMPT end
|
||||
@@ -911,8 +816,7 @@ function plugin.init(ctx, options)
|
||||
error("response_guard: config.stub_model must be a non-empty string or absent")
|
||||
end
|
||||
|
||||
-- 占位请求的生成长度上限:默认 16;false 表示不发 max_tokens
|
||||
-- (上游换成 gpt-5 / o 系列这类只认 max_completion_tokens 的服务时设 false)
|
||||
-- 占位请求生成长度上限:默认 16;false 表示不发(上游只认 max_completion_tokens 时用)
|
||||
local stub_max_tokens
|
||||
if o.stub_max_tokens == false then
|
||||
stub_max_tokens = nil
|
||||
|
||||
@@ -1,21 +1,5 @@
|
||||
-- ============================================================================
|
||||
-- stream_redact.lua —— OpenAI SSE 全缓冲 PII 脱敏(Lua 插件接口 v1)
|
||||
--
|
||||
-- 定位
|
||||
-- response_guard 已经做「语义审核 + 脱敏」,本插件是第二道确定性兜底:
|
||||
-- 把整条流缓冲到结束,再统一脱敏后一次性放行,因此能命中跨帧拆分的
|
||||
-- 身份证号/手机号/卡号。代价是客户端拿不到增量输出,默认 enabled: false。
|
||||
--
|
||||
-- OpenAI 协议
|
||||
-- 只处理 SSE(POST /v1/chat/completions,stream=true):
|
||||
-- 正文路径 : choices[*].delta.content
|
||||
-- 终止帧 : data: [DONE]
|
||||
-- 非流式响应不归本插件管(response_guard 已覆盖),直接放行。
|
||||
--
|
||||
-- 拦截输出(与 response_guard 保持一致的 OpenAI 形态)
|
||||
-- data: {"error":{"message":...,"type":"server_error",
|
||||
-- "param":null,"code":"safety_review_unavailable"}}
|
||||
-- ============================================================================
|
||||
-- stream_redact.lua —— OpenAI SSE 全缓冲 PII 兜底,能命中跨帧拆分的证件号;
|
||||
-- 代价是客户端失去增量输出,所以默认 enabled: false。
|
||||
|
||||
local plugin = {}
|
||||
local config = {}
|
||||
|
||||
Reference in new issue
Block a user