Files
Автомата Калашникова ec6f5fc811 清理冗余注释
只保留不写就会改错的说明(宿主 block 只给固定 403、UTF-8 边界、脱敏长度不变、
messages 需稠密整数表才能编成数组、input_text 绕过等),其余说明性段落删掉。
response_guard 注释 129 → 42 行;config.yaml 注释 51 → 13 行;配置结构未变。
2026-11-27 19:07:04 +08:00

339 lines
10 KiB
Lua

-- stream_redact.lua —— OpenAI SSE 全缓冲 PII 兜底,能命中跨帧拆分的证件号;
-- 代价是客户端失去增量输出,所以默认 enabled: false。
local plugin = {}
local config = {}
local states = {}
local MAX_BUFFER_BYTES = 320 * 1024
local DEFAULT_PATH = "choices.*.delta.content"
local function request_key(ctx)
if type(ctx) ~= "table" then return nil end
local key = ctx.request_id
if type(key) ~= "string" or key == "" then return nil end
return key
end
local function clear_state(key)
if key then states[key] = nil end
end
local function is_continuation(byte)
return byte ~= nil and byte >= 0x80 and byte <= 0xBF
end
local function dense_length(value)
if type(value) ~= "table" then return nil end
local count, max_index = 0, 0
for k in pairs(value) do
if type(k) ~= "number" or k < 1 or k % 1 ~= 0 then return nil end
count = count + 1
if k > max_index then max_index = k end
end
if count ~= max_index then return nil end
return count
end
local function parse_path(value)
if type(value) ~= "string" or value == "" then return nil end
local parts = {}
for part in string.gmatch(value, "[^%.]+") do
if part == "" then return nil end
parts[#parts + 1] = part
end
if #parts == 0 then return nil end
return parts
end
local function collect_locations(root, parts)
local found = {}
local malformed = false
local function walk(node, depth)
local segment = parts[depth]
if segment == "*" then
local length = dense_length(node)
if not length or length == 0 then
malformed = true
return false
end
for i = 1, length do
local child = node[i]
if depth == #parts then
if child == nil or child == host.json.null then
-- 无文本
elseif type(child) ~= "string" then
malformed = true
return false
else
found[#found + 1] = { parent = node, key = i }
end
else
if type(child) ~= "table" then
malformed = true
return false
end
if not walk(child, depth + 1) then return false end
end
end
return true
end
if type(node) ~= "table" then
malformed = true
return false
end
local child = node[segment]
if depth == #parts then
if child == nil or child == host.json.null then return true end
if type(child) ~= "string" then
malformed = true
return false
end
found[#found + 1] = { parent = node, key = segment }
return true
end
if child == nil or child == host.json.null then return true end
if type(child) ~= "table" then
malformed = true
return false
end
return walk(child, depth + 1)
end
walk(root, 1)
return found, malformed
end
local function is_leap_year(year)
return year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0)
end
local ID_WEIGHTS = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }
local ID_CHECK_CHARS = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" }
local function valid_cn_resident_id(token)
if #token ~= 18 or not string.match(token, "^%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d[%dXx]$") then
return false
end
local year = tonumber(string.sub(token, 7, 10))
local month = tonumber(string.sub(token, 11, 12))
local day = tonumber(string.sub(token, 13, 14))
if not year or not month or not day or year < 1800 or year > 2200 or month < 1 or month > 12 then
return false
end
local days = { 31, is_leap_year(year) and 29 or 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
if day < 1 or day > days[month] then return false end
local sum = 0
for i = 1, 17 do
local digit = tonumber(string.sub(token, i, i))
if not digit then return false end
sum = sum + digit * ID_WEIGHTS[i]
end
return string.upper(string.sub(token, 18, 18)) == ID_CHECK_CHARS[(sum % 11) + 1]
end
-- 字节长度不变:身份证/手机号按位替换成 *
local function mask_sensitive_tokens(text)
return (string.gsub(text, "[%dXx]+", function(token)
if valid_cn_resident_id(token) then
return string.rep("*", #token)
end
if #token == 11 and string.match(token, "^1[3-9]%d%d%d%d%d%d%d%d%d$") then
return string.rep("*", #token)
end
return token
end))
end
local function error_frame(code, message)
local body = host.json.encode({
error = {
message = message,
type = "server_error",
param = host.json.null,
code = code,
},
})
return { has_data = true, data = body }
end
local function fail(key, code, message)
clear_state(key)
return { action = "replace", events = host.json.array({ error_frame(code, message) }) }
end
local function estimate_event_bytes(event)
if type(event) ~= "table" then return nil end
if type(event.has_data) ~= "boolean" then return nil end
if event.event ~= nil and type(event.event) ~= "string" then return nil end
if event.id ~= nil and type(event.id) ~= "string" then return nil end
if event.has_data and type(event.data) ~= "string" then return nil end
local size = 128
if event.event then size = size + #event.event end
if event.id then size = size + #event.id end
if event.has_data and event.data then size = size + 3 * #event.data end
if event.comments then
for _, comment in ipairs(event.comments) do
if type(comment) ~= "string" then return nil end
size = size + #comment + 16
end
end
return size
end
local function redact_and_release(key, state)
local combined = table.concat(state.texts)
local masked = mask_sensitive_tokens(combined)
if #masked ~= #combined then
return fail(key, "redaction_failed", "The response could not be redacted safely.")
end
local events = {}
local offset = 1
for _, entry in ipairs(state.frames) do
if #entry.lengths == 0 then
events[#events + 1] = entry.event
else
local ok_decode, decoded = pcall(host.json.decode, entry.event.data)
if not ok_decode or type(decoded) ~= "table" then
return fail(key, "redaction_failed", "The response could not be redacted safely.")
end
local locations, malformed = collect_locations(decoded, config.content_path)
if malformed or #locations ~= #entry.lengths then
return fail(key, "redaction_failed", "The response could not be redacted safely.")
end
for i, location in ipairs(locations) do
local length = entry.lengths[i]
local replacement = ""
if length > 0 then
replacement = string.sub(masked, offset, offset + length - 1)
end
offset = offset + length
location.parent[location.key] = replacement
end
local ok_encode, encoded = pcall(host.json.encode, decoded)
if not ok_encode or type(encoded) ~= "string" then
return fail(key, "redaction_failed", "The response could not be redacted safely.")
end
local copy = {}
for k, v in pairs(entry.event) do copy[k] = v end
copy.data = encoded
events[#events + 1] = copy
end
end
clear_state(key)
return { action = "replace", events = host.json.array(events) }
end
function plugin.init(ctx, options)
if type(options) ~= "table" then
error("stream_redact config must be a table")
end
local content_path = parse_path(options.content_path or DEFAULT_PATH)
if not content_path then
error("stream_redact: config.content_path must be a dot path like 'choices.*.delta.content'")
end
local max_buffer_bytes = tonumber(options.max_buffer_bytes) or MAX_BUFFER_BYTES
if max_buffer_bytes < 1 or max_buffer_bytes % 1 ~= 0 or max_buffer_bytes > MAX_BUFFER_BYTES then
error("stream_redact: config.max_buffer_bytes must be an integer from 1 to " .. MAX_BUFFER_BYTES)
end
config = {
content_path = content_path,
max_buffer_bytes = max_buffer_bytes,
}
return nil
end
function plugin.on_response(ctx, response)
if type(response) ~= "table" then
return { action = "block", reason = "invalid response object" }
end
-- 非流式由 response_guard 负责,这里不重复加工
if response.streaming ~= true then return { action = "pass" } end
return nil
end
function plugin.on_event(ctx, event)
local key = request_key(ctx)
if not key then
return { action = "block", reason = "missing request id" }
end
local size = estimate_event_bytes(event)
if not size then
return fail(key, "invalid_stream_frame", "The response stream contained an invalid frame.")
end
local state = states[key]
if not state then
state = { frames = {}, buffer_bytes = 0, texts = {} }
states[key] = state
end
if state.aborted then
return { action = "replace", events = host.json.array() }
end
if state.buffer_bytes + size > config.max_buffer_bytes then
state.aborted = true
return fail(key, "response_too_large",
"The model response exceeded the redaction buffer limit.")
end
local entry = { event = event, lengths = {} }
if event.has_data == true and type(event.data) == "string" and event.data ~= ""
and event.data ~= "[DONE]" then
local ok_decode, decoded = pcall(host.json.decode, event.data)
if not ok_decode or type(decoded) ~= "table" then
state.aborted = true
return fail(key, "invalid_stream_frame", "The response stream contained an invalid frame.")
end
local locations, malformed = collect_locations(decoded, config.content_path)
if malformed then
state.aborted = true
return fail(key, "unexpected_stream_shape",
"The response stream shape was not recognised.")
end
for i, location in ipairs(locations) do
local text = location.parent[location.key]
entry.lengths[i] = #text
state.texts[#state.texts + 1] = text
end
end
state.frames[#state.frames + 1] = entry
state.buffer_bytes = state.buffer_bytes + size
if event.has_data == true and event.data == "[DONE]" then
return redact_and_release(key, state)
end
return { action = "hold" }
end
function plugin.on_end(ctx)
local key = request_key(ctx)
if not key then
return { action = "block", reason = "missing request id at end" }
end
local state = states[key]
if not state then return nil end
if state.aborted then
clear_state(key)
return nil
end
return redact_and_release(key, state)
end
function plugin.close(ctx)
clear_state(request_key(ctx))
return nil
end
return plugin