fix: config.yaml模型路径/加载模式待修改,提交了plugins目录的lua插件,以及config.yaml中的配置

This commit is contained in:
Автомата Калашникова committed 2026-10-13 13:51:12 +08:00
1 parent 45e45948bd
commit d93cf2d5e5
6 files changed
+1917 -114

No files matched your search

+1
View File
@@ -10,3 +10,4 @@ config.local.yaml
.env
tmp/
*.log
models/
+48 -29
View File
@@ -1,40 +1,59 @@
# Relative plugin paths resolve against this configuration file.
upstream: http://127.0.0.1:8000
listen_host: 0.0.0.0
listen_port: 8080
limits:
max_sessions: 4
hook_timeout_seconds: 5
lua_memory_bytes: 33554432
max_request_bytes: 2097152
max_response_bytes: 2097152
max_sse_frame_bytes: 262144
max_plugin_buffer_bytes: 1048576
max_host_calls_per_hook: 64
hook_timeout_seconds: 60 # guard 模型 CPU 推理慢,默认 5s 不够
upstream_timeout_seconds: 120
llm: []
llm:
- id: guard_model
type: guard
file: models/ # 待修改
load: {device: cpu} #待修改 (cude / cpu)
limits:
max_input_tokens: 4096
max_new_tokens: 32
timeout_seconds: 30
queue_size: 8
plugins:
- id: request-rewrite
file: plugins/request_rewrite.lua
enabled: false
config:
prefix: ""
- id: stream-redact
file: plugins/stream_redact.lua
enabled: false
- id: network-review
file: plugins/network_review.lua
enabled: false
config:
url: https://review.example.com/check
network:
timeout_seconds: 3
max_response_bytes: 1048576
allow:
- domain: review.example.com
- domain: '*.review.example.com'
# Explicit intranet example: enable only after replacing with actual deployment values.
# - domain: review.internal.example.com
# scheme: http
# ports: [8080]
# cidrs: [10.20.0.0/16]
- domain: review.example.com # 本地联调改 mock-review.local
scheme: https
ports: [443]
timeout_seconds: 5
max_response_bytes: 1048576
config:
url: https://review.example.com/check # 本地联调改 http://mock-review.local:8001/check
fields: [messages]
headers: {x-api-key: "injected-by-admin"}
paths: [/chat/stream]
- id: response-guard
file: plugins/response_guard.lua
llm: {allow: [guard_model]}
config:
model: guard_model # 必须与 llm 注册的 id 一致
content_path: content
paths: [/chat/stream]
- id: request-rewrite
file: plugins/request_rewrite.lua
config:
prefix: "[checked] "
paths: [/chat/stream]
- id: stream-redact
file: plugins/stream_redact.lua
config:
text_event: text_delta
content_path: content
terminal_error_events: [run_error]
control_event_names: [heartbeat, run_started, run_finished, run_error, run_completed]
max_buffer_bytes: 262144
paths: [/chat/stream]
+195 -12
View File
@@ -1,15 +1,198 @@
-- network_review.lua
-- Fail-closed inbound request review plugin.
--
-- Required plugin config:
-- url: "https://review.example.com/check"
-- fields: ["messages"] -- explicit top-level request-body fields allowed to leave this plugin
-- Optional:
-- headers:
-- x-api-key: "injected-by-admin"
--
-- Review API contract: HTTP 200 with JSON {"allow":true} permits the request.
-- The plugin forwards only configured fields; it never forwards the original
-- request body wholesale. The host remains responsible for network allowlists,
-- DNS/IP checks, TLS, timeouts, and response-size limits.
local plugin = {}
local config = {}
function plugin.init(ctx, options) config = options end
function plugin.on_request(ctx, request)
local response = host.http.request({
method='POST', url=config.url,
headers={['content-type']='application/json'},
body=request.body,
})
if response.status ~= 200 then return {action='block'} end
local verdict = host.json.decode(response.body)
if verdict.allow ~= true then return {action='block'} end
return {action='pass'}
local settings = {}
local RESERVED_HEADERS = {
["host"] = true,
["content-length"] = true,
["authorization"] = true,
["proxy-authorization"] = true,
["cookie"] = true,
["set-cookie"] = true,
["connection"] = true,
["keep-alive"] = true,
["proxy-connection"] = true,
["transfer-encoding"] = true,
["te"] = true,
["trailer"] = true,
["upgrade"] = true,
["expect"] = true,
["content-type"] = true,
["accept"] = true,
}
local function is_non_empty_string(value)
return type(value) == "string" and value ~= ""
end
local function is_allowed_review_url(value)
if not is_non_empty_string(value) then return false end
local lower = value:lower()
if lower:sub(1, 8) == "https://" then return true end
-- 本地测试例外:允许 http,但仅限回环地址/本地测试域名
if lower:sub(1, 7) == "http://" then
local host_part = value:match("^http://([^:/]+)")
return host_part == "127.0.0.1"
or host_part == "localhost"
or host_part == "mock-review.local"
or host_part:sub(-13) == ".localtest.me"
end
return false
end
function plugin.init(ctx, options)
if type(options) ~= "table" then
error("network_review config must be an object")
end
if not is_allowed_review_url(options.url) then
error("network_review config.url must use https:// (or http:// to a loopback host)")
end
if type(options.fields) ~= "table" or #options.fields == 0 then
error("network_review requires a non-empty config.fields allowlist")
end
if options.headers ~= nil and type(options.headers) ~= "table" then
error("network_review config.headers must be an object")
end
local fields = {}
local seen_fields = {}
for _, field in ipairs(options.fields) do
if not is_non_empty_string(field) then
error("network_review config.fields must contain non-empty strings")
end
if seen_fields[field] then
error("network_review config.fields contains a duplicate field")
end
seen_fields[field] = true
fields[#fields + 1] = field
end
local headers = {}
if options.headers ~= nil then
for name, value in pairs(options.headers) do
if type(name) ~= "string" or name == "" or type(value) ~= "string" then
error("network_review header names and values must be strings")
end
local lower_name = name:lower()
if RESERVED_HEADERS[lower_name] then
error("network_review config.headers contains a reserved header")
end
headers[name] = value
end
end
-- 新增:路径白名单(可选)。未配置时保持原行为——审核所有请求;
-- 配置后只有命中白名单的路径才走外发审核,其余请求直接放行。
local paths = {}
if options.paths ~= nil then
if type(options.paths) ~= "table" then
error("network_review config.paths must be an array")
end
local seen_paths = {}
for _, p in ipairs(options.paths) do
if not is_non_empty_string(p) or p:sub(1, 1) ~= "/" then
error("network_review config.paths entries must be non-empty path strings")
end
if seen_paths[p] then
error("network_review config.paths contains a duplicate path")
end
seen_paths[p] = true
paths[p] = true
end
end
settings = {
url = options.url,
fields = fields,
headers = headers,
paths = paths,
}
return nil
end
function plugin.on_request(ctx, request)
-- 新增:路径白名单判断。必须放在 body 检查之前,否则 GET /health 这类
-- 无 body 的非 AI 请求会被 "invalid request body" 拦截。
-- 未配置 paths 时此分支不生效,行为与原版完全一致(fail-closed 审核一切)。
if next(settings.paths) ~= nil then
local path = type(request) == "table" and request.path or nil
if path == nil or not settings.paths[path] then
return { action = "pass" }
end
end
if type(request) ~= "table" or type(request.body) ~= "string" then
return { action = "block", reason = "invalid request body" }
end
-- Decode and validate JSON before constructing a minimal allowlisted payload.
local decode_ok, input = pcall(function() return host.json.decode(request.body) end)
if not decode_ok or type(input) ~= "table" then
return { action = "block", reason = "invalid JSON request body" }
end
local payload = {}
local found_field = false
for _, field in ipairs(settings.fields) do
local value = input[field]
if value ~= nil then
payload[field] = value
found_field = true
end
end
if not found_field then
return { action = "block", reason = "no configured review fields present" }
end
local encode_ok, body = pcall(function() return host.json.encode(payload) end)
if not encode_ok or type(body) ~= "string" then
return { action = "block", reason = "failed to encode review payload" }
end
local headers = {
["content-type"] = "application/json",
["accept"] = "application/json",
}
for name, value in pairs(settings.headers) do
headers[name] = value
end
-- Never log request content, credentials, or external error details.
local http_ok, response = pcall(function()
return host.http.request({
method = "POST",
url = settings.url,
headers = headers,
body = body,
})
end)
if not http_ok or type(response) ~= "table" or response.status ~= 200
or type(response.body) ~= "string" then
return { action = "block", reason = "review service unavailable" }
end
local verdict_ok, verdict = pcall(function() return host.json.decode(response.body) end)
if not verdict_ok or type(verdict) ~= "table" or verdict.allow ~= true then
return { action = "block", reason = "review rejected request" }
end
return { action = "pass" }
end
return plugin
+183 -8
View File
@@ -1,11 +1,186 @@
-- request_rewrite.lua
-- Request rewrite example following docs/plugins.md (Lua plugin interface v1).
--
-- Example config:
-- prefix: "[checked] "
--
-- Scope:
-- Intended for route-level use on chat-style JSON requests with a string
-- "message" field. Requests that are not applicable (invalid/non-object JSON,
-- or missing/non-string message) pass through unchanged.
--
-- Important:
-- This implementation decodes and re-encodes the complete JSON object after
-- changing message. Other fields' serialized representation (key order,
-- whitespace, escapes, numeric representation, etc.) may change. Do not use
-- it where downstream systems require byte-identical body/signature stability.
--
-- Contract:
-- init(ctx, config) must return nil.
-- on_request may return pass, replace, or block.
-- method/path are preserved; a new request table is returned for replace.
local plugin = {}
local config = {}
function plugin.init(ctx, options) config = options end
function plugin.on_request(ctx, request)
local body = host.json.decode(request.body)
if type(body.message) ~= 'string' then return {action='block'} end
body.message = (config.prefix or '') .. body.message
request.body = host.json.encode(body)
return {action='replace', value=request}
local settings = {
prefix = "",
}
local MAX_PREFIX_BYTES = 1024
local function is_valid_utf8(value)
if type(value) ~= "string" then
return false
end
local i = 1
local n = #value
while i <= n do
local b1 = value:byte(i)
if b1 <= 0x7F then
i = i + 1
elseif b1 >= 0xC2 and b1 <= 0xDF then
local b2 = value:byte(i + 1)
if not b2 or b2 < 0x80 or b2 > 0xBF then return false end
i = i + 2
elseif b1 == 0xE0 then
local b2, b3 = value:byte(i + 1, i + 2)
if not b2 or not b3 or b2 < 0xA0 or b2 > 0xBF
or b3 < 0x80 or b3 > 0xBF then return false end
i = i + 3
elseif (b1 >= 0xE1 and b1 <= 0xEC) or (b1 >= 0xEE and b1 <= 0xEF) then
local b2, b3 = value:byte(i + 1, i + 2)
if not b2 or not b3 or b2 < 0x80 or b2 > 0xBF
or b3 < 0x80 or b3 > 0xBF then return false end
i = i + 3
elseif b1 == 0xED then
local b2, b3 = value:byte(i + 1, i + 2)
if not b2 or not b3 or b2 < 0x80 or b2 > 0x9F
or b3 < 0x80 or b3 > 0xBF then return false end
i = i + 3
elseif b1 == 0xF0 then
local b2, b3, b4 = value:byte(i + 1, i + 3)
if not b2 or not b3 or not b4 or b2 < 0x90 or b2 > 0xBF
or b3 < 0x80 or b3 > 0xBF
or b4 < 0x80 or b4 > 0xBF then return false end
i = i + 4
elseif b1 >= 0xF1 and b1 <= 0xF3 then
local b2, b3, b4 = value:byte(i + 1, i + 3)
if not b2 or not b3 or not b4
or b2 < 0x80 or b2 > 0xBF
or b3 < 0x80 or b3 > 0xBF
or b4 < 0x80 or b4 > 0xBF then return false end
i = i + 4
elseif b1 == 0xF4 then
local b2, b3, b4 = value:byte(i + 1, i + 3)
if not b2 or not b3 or not b4 or b2 < 0x80 or b2 > 0x8F
or b3 < 0x80 or b3 > 0xBF
or b4 < 0x80 or b4 > 0xBF then return false end
i = i + 4
else
return false
end
end
return true
end
function plugin.init(ctx, options)
if type(options) ~= "table" then
error("request_rewrite config must be an object")
end
local prefix = options.prefix
if prefix == nil then
prefix = ""
elseif type(prefix) ~= "string" then
error("request_rewrite config.prefix must be a string")
end
if #prefix > MAX_PREFIX_BYTES then
error("request_rewrite config.prefix exceeds 1024 bytes")
end
if not is_valid_utf8(prefix) then
error("request_rewrite config.prefix must be valid UTF-8")
end
for i = 1, #prefix do
local byte = prefix:byte(i)
if byte < 0x20 or byte == 0x7F then
error("request_rewrite config.prefix must not contain control characters")
end
end
-- 新增:路径白名单(可选)。未配置时保持原行为——对所有含 message
-- 字段的请求打标;配置后只有命中白名单的 AI 路径才改写,
-- 非 AI 路径(即使恰好有 message 字段)原样放行,不被加前缀。
local paths = {}
if options.paths ~= nil then
if type(options.paths) ~= "table" then
error("request_rewrite config.paths must be an array")
end
local count = 0
for _, p in ipairs(options.paths) do
if type(p) ~= "string" or p == "" or p:sub(1, 1) ~= "/" then
error("request_rewrite config.paths entries must be non-empty path strings")
end
paths[p] = true
count = count + 1
end
if count == 0 then
error("request_rewrite config.paths must be non-empty when present")
end
end
-- Atomically replace local settings; don't retain the caller's config table.
settings = { prefix = prefix, paths = paths }
-- plugins.md requires init to return nil.
return nil
end
function plugin.on_request(ctx, request)
-- 新增:路径白名单判断。放在 body 检查之前,保证无 body 的
-- 非 AI 请求(GET /health 等)也能通过,且不会被误加前缀。
-- 未配置 paths 时此分支不生效,行为与原版完全一致。
if next(settings.paths) ~= nil then
local path = type(request) == "table" and request.path or nil
if path == nil or not settings.paths[path] then
return { action = "pass" }
end
end
if type(request) ~= "table" or type(request.body) ~= "string" then
return { action = "block", reason = "invalid request object" }
end
-- This is a rewrite plugin, not a JSON validator or moderation plugin.
-- Non-applicable requests are passed through unchanged.
local decode_ok, body = pcall(function() return host.json.decode(request.body) end)
if not decode_ok or type(body) ~= "table" then
return { action = "pass" }
end
if type(body.message) ~= "string" then
return { action = "pass" }
end
local new_message = settings.prefix .. body.message
if not is_valid_utf8(new_message) then
return { action = "block", reason = "rewritten message is not valid UTF-8" }
end
body.message = new_message
-- The host codec re-serializes the complete object; see warning above.
local encode_ok, rewritten_body = pcall(function() return host.json.encode(body) end)
if not encode_ok or type(rewritten_body) ~= "string" then
return { action = "block", reason = "failed to encode rewritten body" }
end
-- Construct a new table so this plugin does not mutate the input request.
local rewritten = {}
for key, value in pairs(request) do
rewritten[key] = value
end
rewritten.body = rewritten_body
return { action = "replace", value = rewritten }
end
return plugin
+752 -30
View File
@@ -1,53 +1,775 @@
local plugin = {}
local config = {}
local prompt = ""
local pending = {}
local text = ""
local requests = {}
local DEFAULT_MAX_BUFFER_BYTES = 65536
local MAX_TAIL_BYTES = 512
local function key_for(ctx)
if type(ctx) == "table" and type(ctx.request_id) == "string" and ctx.request_id ~= "" then
return ctx.request_id
end
return nil
end
local function clear(key)
if key then requests[key] = nil end
end
local function block_and_clear(key, reason)
clear(key)
return { action = "block", reason = reason }
end
local DEFAULT_CONTENT_PATH = { "data", "content" }
local DEFAULT_NON_TEXT_EVENTS = {
heartbeat = true, ping = true, run_started = true, run_finished = true,
tool_started = true, tool_finished = true, tool_call_started = true,
tool_call_finished = true, run_error = true, run_completed = true,
}
local function copy_array(source)
local out = {}
for i, value in ipairs(source or {}) do out[i] = value end
return out
end
local function copy_map(source)
local out = {}
for k, v in pairs(source or {}) do out[k] = v end
return out
end
local function content_path(settings)
local path = (settings or config).content_path
if path == nil then return copy_array(DEFAULT_CONTENT_PATH) end
if type(path) == "table" then
local parts, count, max_index = {}, 0, 0
for k, part in pairs(path) do
if type(k) ~= "number" or k < 1 or k % 1 ~= 0
or type(part) ~= "string" or part == "" then
return nil
end
parts[k] = part
count = count + 1
if k > max_index then max_index = k end
end
if count == 0 or count ~= max_index then return nil end
return parts
end
if type(path) ~= "string" or path == "" then return nil end
local parts, from = {}, 1
while true do
local dot = path:find(".", from, true)
local part = dot and path:sub(from, dot - 1) or path:sub(from)
if part == "" then return nil end
parts[#parts + 1] = part
if not dot then break end
from = dot + 1
end
return parts
end
-- nil means use the defaults. If explicitly configured, reject malformed
-- entries instead of silently dropping them and reporting the plugin ready.
local function configured_non_text_events(settings)
local configured = (settings or config).non_text_events
if configured == nil then return copy_map(DEFAULT_NON_TEXT_EVENTS) end
if type(configured) ~= "table" then
return nil, "config.non_text_events must be an array or {name=true} map"
end
local result, mode, count, max_index = {}, nil, 0, 0
for k, v in pairs(configured) do
if type(k) == "number" then
if mode == "map" or k < 1 or k % 1 ~= 0
or type(v) ~= "string" or v == "" then
return nil, "invalid config.non_text_events array entry"
end
mode = "array"
result[v] = true
count = count + 1
if k > max_index then max_index = k end
elseif type(k) == "string" then
if mode == "array" or k == "" or v ~= true then
return nil, "invalid config.non_text_events map entry"
end
mode = "map"
result[k] = true
else
return nil, "invalid config.non_text_events key"
end
end
if mode == "array" and count ~= max_index then
return nil, "config.non_text_events array must be contiguous"
end
return result
end
local function extract_content(event, path)
if type(event.data) ~= "string" then
return nil, "event data is not a string"
end
local ok, decoded = pcall(host.json.decode, event.data)
if not ok or type(decoded) ~= "table" then
return nil, "invalid event JSON"
end
local value = decoded
for _, part in ipairs(path) do
if type(value) ~= "table" then value = nil; break end
value = value[part]
end
if type(value) == "string" then return value, nil, copy_array(path) end
-- Default compatibility: some Agent adapters emit the assistant message
-- object itself rather than wrapping its text under data.content.
local is_default_path = #path == 2 and path[1] == "data" and path[2] == "content"
if is_default_path and decoded.role == "assistant" and type(decoded.content) == "string" then
return decoded.content, nil, { "content" }
end
return nil, "event payload has no configured text field"
end
-- Redaction is deliberately local and deterministic: the guard model decides
-- whether content may pass, while these rules mask common secrets/identifiers
-- in assistant output. This is not a substitute for application-specific DLP.
local function redact_text(text)
local out = text
-- Bearer credentials and common API-key shapes.
out = out:gsub("([Bb]earer%s+)([%w%._~%+/%-]+=*)", function(prefix, token)
return prefix .. string.rep("*", #token)
end)
out = out:gsub("sk%-[%w_%-]+", function(token)
return "sk-" .. string.rep("*", #token - 3)
end)
out = out:gsub("AKIA[A-Z0-9]+", function(token)
if #token >= 12 then return "AKIA" .. string.rep("*", #token - 4) end
return token
end)
-- Email address: preserve domain and the first local-part character.
out = out:gsub("[%w%._%+%-]+@[%w%-%.]+%.[%a]+", function(email)
local at = email:find("@", 1, true)
if not at then return email end
local local_part, domain = email:sub(1, at - 1), email:sub(at + 1)
if #local_part <= 1 then return "*@" .. domain end
return local_part:sub(1, 1) .. string.rep("*", #local_part - 1) .. "@" .. domain
end)
-- 18-character Chinese resident identity number (17 digits plus digit/X).
out = out:gsub("%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d[%dXx]", function(id)
return id:sub(1, 6) .. "********" .. id:sub(-4)
end)
-- Numeric identifiers such as bank-card numbers, including digit groups
-- separated by spaces or hyphens. Preserve separators and byte length.
out = out:gsub("%d[%d %-]*%d", function(number_run)
local digits = number_run:gsub("%D", "")
if #digits < 16 or #digits > 19 then return number_run end
local total, index = #digits, 0
return (number_run:gsub("%d", function(digit)
index = index + 1
if index <= 4 or index > total - 4 then return digit end
return "*"
end))
end)
-- Mainland China mobile numbers.
out = out:gsub("1[3-9]%d%d%d%d%d%d%d%d%d", function(phone)
return phone:sub(1, 3) .. "****" .. phone:sub(-4)
end)
-- Common 10-digit phone numbers, optionally separated by spaces, dots or hyphens.
out = out:gsub("(%d%d%d)[%s%.%-]?(%d%d%d)[%s%.%-]?(%d%d%d%d)", function(a, b, c)
return a .. "***" .. c
end)
return out
end
local function redact_assistant_content(value)
if type(value) ~= "table" then return false, nil end
local changed = false
if value.role == "assistant" and value.content ~= nil then
if type(value.content) ~= "string" then
return false, "assistant.content is not a supported string"
end
local masked = redact_text(value.content)
if masked ~= value.content then
value.content = masked
changed = true
end
end
for _, child in pairs(value) do
if type(child) == "table" then
local child_changed, child_err = redact_assistant_content(child)
if child_err then return false, child_err end
if child_changed then changed = true end
end
end
return changed, nil
end
local function shallow_copy(value)
local out = {}
for k, v in pairs(value or {}) do out[k] = v end
return out
end
local function set_path(root, path, replacement)
local current = root
for i = 1, #path - 1 do
if type(current) ~= "table" or type(current[path[i]]) ~= "table" then
return false
end
current = current[path[i]]
end
if type(current) ~= "table" then return false end
current[path[#path]] = replacement
return true
end
local function event_with_content(event, path, original_content, replacement_content)
if original_content == replacement_content then return event end
local ok, decoded = pcall(host.json.decode, event.data)
if not ok or type(decoded) ~= "table" or not set_path(decoded, path, replacement_content) then
return nil, "failed to prepare redacted SSE event"
end
local encode_ok, encoded = pcall(host.json.encode, decoded)
if not encode_ok or type(encoded) ~= "string" then
return nil, "failed to encode redacted SSE event"
end
local copy = shallow_copy(event)
copy.data = encoded
return copy
end
-- Redact the concatenated pending text, not each delta independently. PII such
-- as an email or phone number may be split across SSE frames. Redaction rules
-- preserve byte length, allowing sanitized text to be mapped back to the exact
-- original event boundaries without changing protocol ordering or IDs.
local function redact_pending_events(state)
local original = table.concat(state.chunks)
local redacted = redact_text(original)
if #redacted ~= #original then
return nil, "redaction changed text byte length"
end
local result, offset = {}, 1
for i, event in ipairs(state.pending) do
local original_chunk = state.chunks[i]
if type(original_chunk) ~= "string" then
return nil, "pending event/text buffer mismatch"
end
local replacement_chunk = redacted:sub(offset, offset + #original_chunk - 1)
local event_path = state.pending_paths and state.pending_paths[i] or state.content_path
local replacement_event, err = event_with_content(
event, event_path, original_chunk, replacement_chunk)
if not replacement_event then return nil, err end
result[#result + 1] = replacement_event
offset = offset + #original_chunk
end
if offset - 1 ~= #original then
return nil, "pending event/text buffer length mismatch"
end
return result
end
local USER_INPUT_AUDIT_PROMPT = "Review the following user-provided input for safety before forwarding it to the Agent."
local function moderate_text(model, prompt, text)
local ok, result = pcall(host.llm.call, model, {
task = "response_moderation",
prompt = prompt or "",
response = text,
})
return ok and type(result) == "table" and result.safety == "Safe"
end
local closers = {
['"'] = true, ["'"] = true, [')'] = true, [']'] = true, ['}'] = true,
}
local function skip_utf8_closer(s, i)
for _, token in ipairs({ "”", "’", ")", "】", "》", "」", "』", "〉", "〕" }) do
if s:sub(i, i + #token - 1) == token then
return i + #token
end
end
return nil
end
local abbreviations = {
["mr"] = true, ["mrs"] = true, ["ms"] = true, ["dr"] = true,
["prof"] = true, ["sr"] = true, ["jr"] = true, ["st"] = true,
["vs"] = true, ["etc"] = true, ["e.g"] = true, ["i.e"] = true,
["fig"] = true, ["no"] = true, ["approx"] = true,
}
local function is_abbreviation_dot(s, i)
-- Only inspect a short suffix; scanning the whole response prefix for
-- every dot creates avoidable repeated copying.
local prefix_start = math.max(1, i - 64)
local prefix = s:sub(prefix_start, i - 1):lower()
local token = prefix:match("([%a%.]+)$")
if token and abbreviations[token] then return true end
-- Decimal/version fragments such as 3.14 or v1.2: do not treat a dot
-- as a sentence boundary when digits are on both sides.
local before = s:sub(i - 1, i - 1)
local after = s:sub(i + 1, i + 1)
if before:match("%d") and after:match("%d") then return true end
return false
end
local function has_sentence_boundary(s)
local i = 1
while i <= #s do
local ch = s:sub(i, i)
local punct_len = 1
local punct = (ch == "." or ch == "!" or ch == "?")
if not punct then
local utf = s:sub(i, i + 2)
if utf == "。" or utf == "!" or utf == "?" then
punct, punct_len = true, 3
end
end
if punct then
local after_punct = i + punct_len
if ch == "." and is_abbreviation_dot(s, i) then
i = i + punct_len
else
local j = after_punct
while j <= #s do
local c = s:sub(j, j)
if closers[c] then
j = j + 1
else
local next_j = skip_utf8_closer(s, j)
if next_j then j = next_j else break end
end
end
-- Chinese sentence punctuation is a complete boundary even
-- when the next sentence starts immediately with Han text.
-- ASCII punctuation keeps the whitespace requirement to avoid
-- splitting decimals/abbreviations and common inline syntax.
if (punct_len == 3) or (j <= #s and s:sub(j, j):match("%s")) then
return true
end
i = i + punct_len
end
else
i = i + 1
end
end
return false
end
local function response_text(state)
return table.concat(state.chunks)
end
local function utf8_safe_tail(s, max_bytes)
local start = math.max(1, #s - max_bytes + 1)
-- If truncation lands on a UTF-8 continuation byte, skip continuation
-- bytes until the next code-point start. The tail is only for scanning;
-- original events are always released unchanged.
while start <= #s do
local b = s:byte(start)
if not b or b < 128 or b >= 192 then break end
start = start + 1
end
return s:sub(start)
end
-- Default protocol metadata/lifecycle signals. Admins should calibrate this
-- list to the actual Agent protocol through config.non_text_events. Unknown
-- data-bearing events are never passed just because their names are unfamiliar.
local function moderate_and_release(key, terminal)
local state = key and requests[key]
-- An empty on_end is not evidence that buffered state should be erased:
-- preserve it, so a later event cannot accidentally be treated as unknown.
if not state or #state.pending == 0 then
return nil
end
local ok, result = pcall(host.llm.call, state.config.model, {
task = "response_moderation",
prompt = state.prompt,
response = response_text(state),
})
if not ok or type(result) ~= "table" or result.safety ~= "Safe" then
return block_and_clear(key, "moderation failed or unsafe")
end
-- Redact across frame boundaries after the original text passes moderation.
-- Failure to transform/serialize a release batch must fail closed.
local redaction_ok, sanitized_pending, redaction_err = pcall(redact_pending_events, state)
if not redaction_ok or type(sanitized_pending) ~= "table" then
return block_and_clear(key, redaction_err or "failed to redact response events")
end
-- The host contract documents host.json.array, but guard the conversion:
-- a bridge/serialization failure must fail closed, not crash this hook.
local array_ok, events = pcall(host.json.array, sanitized_pending)
if not array_ok or type(events) ~= "table" then
return block_and_clear(key, "failed to construct release event array")
end
-- A sentence-level release is not the end of the request: preserve the
-- request prompt so subsequent text_delta events can be moderated too.
state.pending = {}
state.pending_paths = {}
state.chunks = {}
state.text_bytes = 0
state.tail = ""
if terminal then clear(key) end
return { action = "replace", events = events }
end
function plugin.init(ctx, options)
config = options
if options ~= nil and type(options) ~= "table" then
error("response_guard config must be a table")
end
local candidate = options or {}
if type(candidate.model) ~= "string" or candidate.model:match("^%s*$") then
error("response_guard requires config.model")
end
local path = content_path(candidate)
if not path then
error("response_guard: invalid config.content_path")
end
local events, events_err = configured_non_text_events(candidate)
if not events then
error("response_guard: " .. events_err)
end
if candidate.max_buffer_bytes ~= nil then
local max_bytes = tonumber(candidate.max_buffer_bytes)
if not max_bytes or max_bytes < 1 or max_bytes % 1 ~= 0 then
error("response_guard: config.max_buffer_bytes must be a positive integer")
end
end
-- 新增:路径白名单(可选)。语义与 network_review.paths 一致:
-- 未配置时审核所有请求;配置后只有命中路径的请求才进入审核流程,
-- 其余请求登记 bypass 标记后放行(供响应阶段钩子识别)。
local paths = {}
if candidate.paths ~= nil then
if type(candidate.paths) ~= "table" then
error("response_guard config.paths must be an array")
end
for _, p in ipairs(candidate.paths) do
if type(p) ~= "string" or p == "" or p:sub(1, 1) ~= "/" then
error("response_guard config.paths entries must be non-empty path strings")
end
paths[p] = true
end
end
local normalized = {}
for k, v in pairs(candidate) do
normalized[k] = v
end
normalized.content_path = path
normalized.non_text_events = events
normalized.paths = paths
config = normalized
-- Do not reset requests here: hosts may invoke init during request
-- initialization. Per-request state is created by on_request and removed
-- by block/terminal release/close, preserving in-flight requests.
return nil
end
function plugin.on_request(ctx, request)
local body = host.json.decode(request.body)
prompt = body.message or ""
local key = key_for(ctx)
if not key then
return { action = "block", reason = "missing request_id" }
end
-- 新增:路径白名单判断。未命中白名单的请求(非 AI 流量)不做审核,
-- 但必须登记 bypass 标记后才能放行——响应阶段的 on_event/on_response
-- 依靠 requests[key] 区分"不需要审核"(bypass)和"状态丢失"(block)。
if next(config.paths) ~= nil then
local path = type(request) == "table" and request.path or nil
if path == nil or not config.paths[path] then
clear(key)
requests[key] = { bypass = true }
return { action = "pass" }
end
end
local body = type(request) == "table" and request.body or ""
local ok, decoded = pcall(host.json.decode, body or "")
if not ok or type(decoded) ~= "table" then
clear(key)
return { action = "block", reason = "invalid request JSON" }
end
local request_config = shallow_copy(config)
request_config.content_path = copy_array(config.content_path)
request_config.non_text_events = copy_map(config.non_text_events)
local user_contents = {}
if decoded.messages ~= nil then
if type(decoded.messages) ~= "table" then
clear(key)
return { action = "block", reason = "request messages must be an array" }
end
local count, max_index = 0, 0
for k, _ in pairs(decoded.messages) do
if type(k) ~= "number" or k < 1 or k % 1 ~= 0 then
clear(key)
return { action = "block", reason = "request messages must be a dense array" }
end
count = count + 1
if k > max_index then
max_index = k
end
end
if count ~= max_index then
clear(key)
return { action = "block", reason = "request messages array is sparse" }
end
local user_count = 0
for i = 1, max_index do
local message = decoded.messages[i]
if type(message) ~= "table" or type(message.role) ~= "string" then
clear(key)
return { action = "block", reason = "invalid request message shape" }
end
if message.role == "user" then
if type(message.content) ~= "string" then
clear(key)
return { action = "block", reason = "user message content must be a string" }
end
user_count = user_count + 1
if #user_contents >= 32 then
clear(key)
return { action = "block", reason = "too many user messages to moderate safely" }
end
user_contents[#user_contents + 1] = message.content
end
end
if user_count == 0 then
clear(key)
return { action = "block", reason = "request has no user message to moderate" }
end
elseif type(decoded.message) == "string" then
-- Backward compatibility for older single-message request bodies.
user_contents[1] = decoded.message
else
clear(key)
return { action = "block", reason = "request has no supported user content" }
end
-- Review all user turns in one model call to stay within the hook's latency
-- and host-call budgets. The separator is for readability; the classifier
-- still sees the full original user text. Worker token limits remain a
-- second guardrail and any rejection fails closed.
local combined_user_content = table.concat(user_contents, "\n\n---\n\n")
if combined_user_content ~= ""
and not moderate_text(
request_config.model,
USER_INPUT_AUDIT_PROMPT,
combined_user_content) then
clear(key)
return { action = "block", reason = "user input moderation failed or unsafe" }
end
local latest_user = user_contents[#user_contents] or ""
requests[key] = {
config = request_config,
content_path = request_config.content_path,
non_text_events = request_config.non_text_events,
prompt = latest_user,
chunks = {},
text_bytes = 0,
tail = "",
pending = {},
pending_paths = {},
}
return { action = "pass" }
end
local function check_and_release()
if #pending == 0 then return nil end
local ok, result = pcall(host.llm.call, config.model, {
task = "response_moderation",
prompt = prompt,
response = text,
})
if not ok or result.safety == "Unsafe" then
return {action = "block"}
-- The complete, non-streaming UTF-8 body is moderated here. SSE responses are
-- handled only by on_event; never attempt to replace their JSON-null body.
function plugin.on_response(ctx, response)
if type(response) ~= "table" then
return { action = "block", reason = "invalid response" }
end
if response.streaming == true then
return nil
end
local key = key_for(ctx)
if not key then
return { action = "block", reason = "missing request_id" }
end
local state = requests[key]
-- 新增:请求阶段已判定为非 AI 路径(bypass),本插件不参与其响应处理。
-- 非流式响应一次性结束,顺手清掉标记,避免残留状态。
if state and state.bypass then
clear(key)
return nil
end
if not state then
return { action = "block", reason = "request state missing for non-streaming response" }
end
if type(response.body) ~= "string" then
return block_and_clear(key, "non-streaming response body is not UTF-8 text")
end
local max_bytes = tonumber(state.config.max_buffer_bytes) or DEFAULT_MAX_BUFFER_BYTES
if #response.body > max_bytes then
return block_and_clear(key, "non-streaming response body exceeds moderation limit")
end
-- Audit the original, unredacted response first. Only Safe output is eligible
-- for sanitization and release; every LLM/serialization failure blocks.
if not moderate_text(state.config.model, state.prompt, response.body) then
return block_and_clear(key, "moderation failed or unsafe")
end
local sanitized_body = response.body
local decode_ok, decoded = pcall(host.json.decode, response.body)
if decode_ok and type(decoded) == "table" then
local changed, redact_err = redact_assistant_content(decoded)
if redact_err then
return block_and_clear(key, redact_err)
end
local released = host.json.array(pending)
pending = {}
text = ""
return {action = "replace", events = released}
if changed then
local encode_ok, encoded = pcall(host.json.encode, decoded)
if not encode_ok or type(encoded) ~= "string" then
return block_and_clear(key, "failed to encode redacted response")
end
sanitized_body = encoded
end
else
-- A plain UTF-8 response is still scrubbed for common identifiers.
sanitized_body = redact_text(response.body)
end
clear(key)
if sanitized_body ~= response.body then
local replacement = shallow_copy(response)
replacement.body = sanitized_body
return { action = "replace", value = replacement }
end
return { action = "pass" }
end
function plugin.on_event(ctx, event)
if event.event ~= "text_delta" then return nil end
local data = host.json.decode(event.data)
local content = data.data and data.data.content or ""
pending[#pending + 1] = event
text = text .. content
if text:match("[。!?.!?]\s*$") then
return check_and_release()
if type(event) ~= "table" then
return { action = "block", reason = "invalid event" }
end
if event.has_data == false then
return nil
end
if event.data == nil then
if event.has_data == true then
return { action = "block", reason = "has_data is true but data is missing" }
end
return {action = "hold"}
return nil
end
-- An empty SSE data field contains no output text to moderate or redact.
if event.data == "" then
return nil
end
local key = key_for(ctx)
local state = key and requests[key] or nil
-- 新增:请求阶段已判定为非 AI 路径(bypass),事件流不归本插件管。
-- 注意 bypass 判断必须放在 "request state missing" 之前,否则
-- 非 AI 流量的事件会被当作状态丢失而 fail-closed 拦截。
if state and state.bypass then
return nil
end
local event_name = type(event.event) == "string" and event.event or nil
if not state then
-- Preserve pre-request control frames only when they contain no text at
-- the default output path. A text-bearing frame without state is blocked
-- because neither moderation nor redaction can be safely performed.
if event_name and DEFAULT_NON_TEXT_EVENTS[event_name] then
local content = extract_content(event, DEFAULT_CONTENT_PATH)
if content == nil then
return nil
end
return { action = "block", reason = "text-bearing event has no request state" }
end
if not key then
return { action = "block", reason = "missing request_id" }
end
return { action = "block", reason = "request state missing" }
end
local content, err, actual_content_path = extract_content(event, state.content_path)
local allowlisted = event_name and state.non_text_events[event_name]
if content == nil then
if allowlisted then
return nil
end
return block_and_clear(key, err or "data-bearing event has no extractable text")
end
local max_bytes = tonumber(state.config.max_buffer_bytes) or DEFAULT_MAX_BUFFER_BYTES
if max_bytes < 1 then
max_bytes = DEFAULT_MAX_BUFFER_BYTES
end
if state.text_bytes + #content > max_bytes then
return block_and_clear(key, "response moderation buffer limit exceeded")
end
local scan = state.tail .. content
state.chunks[#state.chunks + 1] = content -- moderate original, unredacted text
state.text_bytes = state.text_bytes + #content
state.tail = utf8_safe_tail(scan, MAX_TAIL_BYTES)
state.pending[#state.pending + 1] = event -- redact the whole pending text on release
state.pending_paths[#state.pending_paths + 1] = actual_content_path or state.content_path
-- Whitelisted control names only bypass moderation if their payload has no
-- text at the configured content path. Text-bearing frames get both review
-- and redaction, just like ordinary assistant deltas.
if has_sentence_boundary(scan) then
return moderate_and_release(key)
end
return { action = "hold" }
end
function plugin.on_end(ctx)
return check_and_release()
local key = key_for(ctx)
local state = key and requests[key] or nil
-- bypass 请求全程未缓冲,清理标记后直接放行。
-- 不能落入 moderate_and_release:bypass 状态没有 pending 字段,
-- 对 #state.pending 取长度会抛 runtime error。
if state and state.bypass then
clear(key)
return nil
end
return moderate_and_release(key, true)
end
function plugin.close(ctx)
pending = {}
text = ""
-- An invalid/missing context must never clear unrelated requests.
local key = key_for(ctx)
if key then clear(key) end
return nil
end
return plugin
+738 -35
View File
@@ -1,43 +1,746 @@
-- Demonstrates cross-event inspection. Intentionally buffers the entire SSE response.
-- Masking keeps byte lengths, so redacted text can be placed back in original events.
-- Full-buffer SSE redaction example.
--
-- Scope: SSE only. Non-streaming responses are explicitly blocked by on_response
-- so they cannot silently bypass this streaming-only redaction rule.
-- All configured text events are held until normal end so sensitive values split
-- across frames/array blocks can be detected. The administrator MUST configure
-- terminal_error_events and control_event_names from the real Agent protocol;
-- no guessed event-name list is silently treated as authoritative.
-- Terminal errors discard held body text. Their own data is scrubbed for the
-- supported deterministic patterns before being sent to the client.
--
-- The local buffer limit counts a conservative estimated footprint, not merely
-- raw text bytes: event.data is weighted 3x and each frame has a fixed overhead.
-- The host's max_plugin_buffer_bytes and Lua memory limits remain authoritative.
-- This deterministic example is not a complete DLP implementation.
local plugin = {}
local frames = {}
function plugin.on_event(ctx, event)
frames[#frames+1] = event
return {action='hold'}
local states = {}
local DEFAULT_MAX_BUFFER_BYTES = 256 * 1024
local HARD_MAX_BUFFER_BYTES = 320 * 1024
local DEFAULT_TEXT_EVENT = "text_delta"
local DEFAULT_CONTENT_PATH = { "data", "content" }
local settings = nil
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
function plugin.on_end(ctx)
local text = {}
local payloads = {}
for i, event in ipairs(frames) do
if event.event == 'text_delta' then
local payload = host.json.decode(event.data)
local content = payload.data and payload.data.content
if type(content) ~= 'string' then return {action='block'} end
text[#text+1] = content
payloads[i] = payload
local function contains_cr_lf_nul(value)
for i = 1, #value do
local b = string.byte(value, i)
if b == 0 or b == 10 or b == 13 then return true end
end
return false
end
local function parse_content_path(value)
if value == nil then
local out = {}
for i, part in ipairs(DEFAULT_CONTENT_PATH) do out[i] = part end
return out
end
local parts = {}
if type(value) == "string" then
if value == "" or string.sub(value, 1, 1) == "."
or string.sub(value, -1) == "." or string.find(value, "%.%.") then
return nil
end
for part in string.gmatch(value, "[^%.]+") do
if part == "" or contains_cr_lf_nul(part) then return nil end
-- A single wildcard supports homogeneous content-block arrays,
-- e.g. content.*.text. Every selected leaf must be a string.
parts[#parts + 1] = part
end
if #parts == 0 then return nil end
return parts
end
if type(value) == "table" then
for i, part in ipairs(value) do
if type(part) ~= "string" or part == "" or contains_cr_lf_nul(part) then
return nil
end
parts[i] = part
end
local count = 0
for k in pairs(value) do
if type(k) ~= "number" or k < 1 or k ~= math.floor(k) then return nil end
count = count + 1
end
if count == 0 or count ~= #parts then return nil end
return parts
end
return nil
end
local function event_name_set(value, label, must_be_non_empty)
if type(value) ~= "table" then
error("stream_redact: config." .. label .. " must be an array of event names")
end
local set, count, max_index = {}, 0, 0
for k, name in pairs(value) do
if type(k) ~= "number" or k < 1 or k ~= math.floor(k) then
error("stream_redact: config." .. label .. " must be a dense array")
end
if type(name) ~= "string" or name == "" or contains_cr_lf_nul(name) then
error("stream_redact: config." .. label .. " entries must be non-empty event names without CR/LF/NUL")
end
if set[name] then
error("stream_redact: duplicate event name in config." .. label)
end
set[name] = true
count = count + 1
if k > max_index then max_index = k end
end
if count ~= max_index or (must_be_non_empty and count == 0) then
error("stream_redact: config." .. label .. " must be a dense" .. (must_be_non_empty and " non-empty" or "") .. " array")
end
return set
end
local function normalize_settings(options)
if options == nil then
options = {}
end
if type(options) ~= "table" then
error("stream_redact: config must be a table")
end
local max_buffer_bytes = options.max_buffer_bytes
if max_buffer_bytes == nil then
max_buffer_bytes = DEFAULT_MAX_BUFFER_BYTES
end
if type(max_buffer_bytes) ~= "number" or max_buffer_bytes ~= math.floor(max_buffer_bytes)
or max_buffer_bytes < 1 or max_buffer_bytes > HARD_MAX_BUFFER_BYTES then
error("stream_redact: config.max_buffer_bytes must be an integer from 1 to 327680")
end
local text_event = options.text_event
if text_event == nil then
text_event = DEFAULT_TEXT_EVENT
end
if type(text_event) ~= "string" or text_event == "" or contains_cr_lf_nul(text_event) then
error("stream_redact: config.text_event must be a non-empty event name without CR/LF/NUL")
end
-- These lists are intentionally required: the true Agent event protocol has
-- not been certified, so shipping hard-coded guesses can silently hold errors.
local terminal_error_events = event_name_set(options.terminal_error_events, "terminal_error_events", true)
local control_event_names = event_name_set(options.control_event_names, "control_event_names", true)
local redact_event_names
if options.redact_event_names == nil then
redact_event_names = { [text_event] = true }
else
redact_event_names = event_name_set(options.redact_event_names, "redact_event_names", true)
if not redact_event_names[text_event] then
error("stream_redact: config.redact_event_names must include config.text_event")
end
end
for name in pairs(terminal_error_events) do
if not control_event_names[name] then
error("stream_redact: every terminal_error_event must also be listed in control_event_names")
end
if redact_event_names[name] then
error("stream_redact: terminal error events are scrubbed separately and cannot be in redact_event_names")
end
end
if control_event_names[text_event] then
error("stream_redact: config.text_event cannot be a control or terminal event")
end
local content_path = parse_content_path(options.content_path)
if not content_path then
error("stream_redact: config.content_path must be a dot path or non-empty string array (use * for a dense content array)")
end
-- 新增:路径白名单(可选)。语义与 network_review/response_guard 的
-- paths 一致:未配置时对所有 SSE 流生效;配置后只对命中路径的
-- 请求缓冲/脱敏,其余请求由 on_request 登记 bypass 后全程放行。
local paths = {}
if options.paths ~= nil then
if type(options.paths) ~= "table" then
error("stream_redact: config.paths must be an array")
end
local count = 0
for _, p in ipairs(options.paths) do
if type(p) ~= "string" or p == "" or string.sub(p, 1, 1) ~= "/"
or contains_cr_lf_nul(p) then
error("stream_redact: config.paths entries must be non-empty path strings without CR/LF/NUL")
end
paths[p] = true
count = count + 1
end
if count == 0 then
error("stream_redact: config.paths must be non-empty when present")
end
end
return {
max_buffer_bytes = max_buffer_bytes,
text_event = text_event,
content_path = content_path,
redact_event_names = redact_event_names,
terminal_error_events = terminal_error_events,
control_event_names = control_event_names,
paths = paths,
}
end
local function copy_set(source)
local out = {}
for k, v in pairs(source) do out[k] = v end
return out
end
local function copy_settings(source)
local path = {}
for i, part in ipairs(source.content_path) do
path[i] = part
end
return {
max_buffer_bytes = source.max_buffer_bytes,
text_event = source.text_event,
content_path = path,
redact_event_names = copy_set(source.redact_event_names),
terminal_error_events = copy_set(source.terminal_error_events),
control_event_names = copy_set(source.control_event_names),
paths = copy_set(source.paths),
}
end
local function clear_state(key)
if key ~= nil then states[key] = nil end
end
local function block_and_clear(key, reason)
clear_state(key)
return { action = "block", reason = reason or "stream redaction failed" }
end
local function finite_number(value)
return type(value) == "number" and value == value
and value ~= math.huge and value ~= -math.huge
end
-- Estimate retained + processing footprint rather than counting raw body bytes.
-- The 3x data weight budgets for raw event JSON, joined text/masked text, and
-- transient decoded/encoded structures; 128 bytes/frame budgets Lua table data.
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.data ~= nil and type(event.data) ~= "string" then return nil end
if event.has_data and type(event.data) ~= "string" then return nil end
if not event.has_data and event.data ~= nil and event.data ~= "" then return nil end
if event.event and contains_cr_lf_nul(event.event) then return nil end
if event.id and contains_cr_lf_nul(event.id) then return nil end
if event.comments ~= nil and type(event.comments) ~= "table" then return nil end
if event.retry ~= nil then
if not finite_number(event.retry) or event.retry < 0
or event.retry ~= math.floor(event.retry) then
return nil
end
end
local combined = table.concat(text)
local masked = string.gsub(combined, string.rep('%d',17)..'[%dXx]', function(v)
return string.rep('*', #v)
end)
masked = string.gsub(masked, '1[3-9]'..string.rep('%d',9), function(v)
return string.rep('*', #v)
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.retry ~= nil then size = size + #tostring(event.retry) end
if event.comments then
local count = 0
for k, comment in pairs(event.comments) do
if type(k) ~= "number" or k < 1 or k ~= math.floor(k)
or type(comment) ~= "string" then
return nil
end
count = count + 1
end
if count ~= #event.comments then return nil end
for _, comment in ipairs(event.comments) do
size = size + #comment + 16
end
end
return size
end
local function dense_array_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 ~= math.floor(k) 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
-- Resolve one path to one or more string leaves. `*` expands a dense array
-- such as content.*.text. Any missing/non-string leaf fails closed to avoid
-- silently skipping a potentially textual block.
local function get_content_locations(payload, path)
local found = {}
local function walk(node, depth)
if depth > #path then
if type(node) ~= "string" then return false end
found[#found + 1] = { parent = nil, key = nil, content = node }
return true
end
local segment = path[depth]
if segment == "*" then
local length = dense_array_length(node)
if not length or length == 0 then return false end
for i = 1, length do
local before = #found
if not walk(node[i], depth + 1) or #found == before then return false end
end
return true
end
if type(node) ~= "table" then return false end
local child = node[segment]
if child == nil then return false end
if depth == #path then
if type(child) ~= "string" then return false end
found[#found + 1] = { parent = node, key = segment, content = child }
return true
end
return walk(child, depth + 1)
end
if not walk(payload, 1) or #found == 0 then return nil end
-- For wildcard paths, resolve the parent/key pairs from the original tree
-- through a second walk. The first walk's temporary leaf parent is unused.
local locations = {}
local function walk_locations(node, depth)
if depth > #path then return end
local segment = path[depth]
if segment == "*" then
local length = dense_array_length(node)
if not length then return end
for i = 1, length do
if depth == #path then
-- A terminal wildcard (e.g. content.*) makes each array
-- element itself the string leaf, so its parent is the
-- array and its key is the numeric index.
if type(node[i]) ~= "string" then return end
locations[#locations + 1] = { parent = node, key = i, content = node[i] }
else
walk_locations(node[i], depth + 1)
end
end
return
end
if type(node) ~= "table" then return end
if depth == #path then
locations[#locations + 1] = { parent = node, key = segment, content = node[segment] }
return
end
walk_locations(node[segment], depth + 1)
end
walk_locations(payload, 1)
if #locations ~= #found then return nil end
return locations
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
local expected = ID_CHECK_CHARS[(sum % 11) + 1]
return string.upper(string.sub(token, 18, 18)) == expected
end
-- Conservative token-based patterns:
-- * valid-format 18-char mainland resident IDs (date + checksum checked)
-- * 11-digit mainland mobile-number candidates (prefix check only)
-- Longer contiguous digit runs, spaced/hyphenated values, 16-digit cards,
-- passport numbers and semantic secrets are outside this example's coverage.
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 redact_and_release(key, state)
local text_parts = {}
local entries = {}
-- First pass: extract all configured string leaves without retaining decoded
-- payload tables. Wildcard paths support homogeneous content-block arrays.
for index, event in ipairs(state.frames) do
if state.settings.redact_event_names[event.event] and event.has_data then
local ok, payload = pcall(host.json.decode, event.data)
if not ok or type(payload) ~= "table" then
return block_and_clear(key, "invalid text event payload")
end
local locations = get_content_locations(payload, state.settings.content_path)
if not locations then
return block_and_clear(key, "text event payload does not match configured content_path")
end
local lengths = {}
for _, location in ipairs(locations) do
local content = location.content
lengths[#lengths + 1] = #content
text_parts[#text_parts + 1] = content
end
entries[#entries + 1] = { frame_index = index, content_lengths = lengths }
payload = nil
end
end
local combined = table.concat(text_parts)
text_parts = nil
local masked = mask_sensitive_tokens(combined)
if #masked ~= #combined then
return block_and_clear(key, "redaction changed byte length")
end
combined = nil
-- Second pass: decode/mutate/encode one payload at a time to lower peak memory.
local offset = 1
for i, event in ipairs(frames) do
local payload = payloads[i]
if payload then
local length = #payload.data.content
payload.data.content = string.sub(masked, offset, offset+length-1)
offset = offset + length
event.data = host.json.encode(payload)
for _, entry in ipairs(entries) do
local frame = state.frames[entry.frame_index]
local ok, payload = pcall(host.json.decode, frame.data)
if not ok or type(payload) ~= "table" then
return block_and_clear(key, "text event re-decode failed")
end
local locations = get_content_locations(payload, state.settings.content_path)
if not locations or #locations ~= #entry.content_lengths then
return block_and_clear(key, "text event structure changed during redaction")
end
for j, location in ipairs(locations) do
local old_content = location.content
local expected_length = entry.content_lengths[j]
if type(old_content) ~= "string" or #old_content ~= expected_length then
return block_and_clear(key, "text event changed during redaction")
end
local replacement = ""
if expected_length > 0 then
replacement = string.sub(masked, offset, offset + expected_length - 1)
end
offset = offset + expected_length
location.parent[location.key] = replacement
end
local encode_ok, encoded = pcall(host.json.encode, payload)
payload = nil
if not encode_ok or type(encoded) ~= "string" then
return block_and_clear(key, "text event serialization failed")
end
frame.data = encoded
end
masked = nil
entries = nil
local ok, released = pcall(host.json.array, state.frames)
if not ok or type(released) ~= "table" then
return block_and_clear(key, "event array creation failed")
end
clear_state(key)
return { action = "replace", events = released }
end
local function pending_text_tail(state, limit)
-- Maintained incrementally while frames are buffered; terminal-error handling
-- must not re-decode every pending frame on a failure path.
local tail = state.text_tail or ""
if #tail > limit then return string.sub(tail, -limit) end
return tail
end
local function update_pending_text_tail(state, event)
if event.has_data ~= true or not state.settings.redact_event_names[event.event] then
return true
end
local decode_ok, payload = pcall(host.json.decode, event.data)
if not decode_ok or type(payload) ~= "table" then return false end
local locations = get_content_locations(payload, state.settings.content_path)
if not locations then return false end
local tail = state.text_tail or ""
for _, location in ipairs(locations) do
local joined = tail .. location.content
if #joined > 18 then
tail = string.sub(joined, -18)
else
tail = joined
end
end
local released = host.json.array(frames)
frames = {}
return {action='replace', events=released}
state.text_tail = tail
return true
end
function plugin.close(ctx) frames = {} end
return plugin
local function mask_with_context(value, context)
local prefix = context or ""
local probe = prefix .. value
local masked = mask_sensitive_tokens(probe)
if #masked ~= #probe then return nil end
return string.sub(masked, #prefix + 1)
end
local function redact_terminal_error_event(key, state, event)
-- Pending response text is never released after an upstream failure.
-- Keep only a short text tail long enough to detect supported patterns
-- split between the last held text frame and the error payload.
local context = pending_text_tail(state, 18)
if context == nil then
state.frames = {}
state.buffer_bytes = 0
state.aborted = true
return { action = "block", reason = "cannot safely inspect pending text before terminal error" }
end
state.frames = {}
state.buffer_bytes = 0
state.aborted = true
if event.has_data ~= true or type(event.data) ~= "string" or event.data == "" then
return { action = "pass" }
end
-- Error payloads are not assumed to be body-free. Prefer JSON-aware string
-- value redaction; if this isn't JSON, scrub raw text. The last 18 bytes of
-- held text are prepended only for matching, then removed from the output.
local decoded_ok, payload = pcall(host.json.decode, event.data)
if decoded_ok then
local changed = false
local function scrub(value)
if type(value) == "string" then
local masked_value = mask_with_context(value, context)
if masked_value == nil then error("redaction length changed") end
if masked_value ~= value then changed = true end
return masked_value
end
if type(value) == "table" then
for k, child in pairs(value) do
if type(child) == "string" then
local masked_value = mask_with_context(child, context)
if masked_value == nil then error("redaction length changed") end
if masked_value ~= child then changed = true end
value[k] = masked_value
elseif type(child) == "table" then
scrub(child)
end
end
end
return value
end
local scrub_ok, cleaned = pcall(scrub, payload)
if not scrub_ok then
return { action = "block", reason = "terminal error redaction failed" }
end
payload = cleaned
if not changed then return { action = "pass" } end
local encode_ok, encoded = pcall(host.json.encode, payload)
if not encode_ok or type(encoded) ~= "string" then
return { action = "block", reason = "terminal error payload serialization failed" }
end
event.data = encoded
else
local masked = mask_with_context(event.data, context)
if masked == nil then
return { action = "block", reason = "terminal error redaction failed" }
end
if masked == event.data then return { action = "pass" } end
event.data = masked
end
local array_ok, single = pcall(host.json.array, { event })
if not array_ok or type(single) ~= "table" then
return { action = "block", reason = "terminal error event array creation failed" }
end
return { action = "replace", events = single }
end
function plugin.init(ctx, options)
-- init may run during startup validation and request setup; do not clear states.
settings = normalize_settings(options)
return nil
end
function plugin.on_request(ctx, request)
-- 新增钩子:本插件原本看不到请求路径,靠这个回调在请求阶段判断。
-- 未命中白名单(非 AI 路径)的请求登记 bypass 标记,其 SSE 事件流
-- 与非流式响应在 on_event/on_response/on_end 中直接放行,
-- 不缓冲、不拦截。配置了 paths 时必须保证宿主会调用本钩子。
if next(settings.paths) == nil then
return nil
end
local key = request_key(ctx)
if not key then
return nil -- 与其他请求侧插件不同:这里没有审核职责,不 fail-closed
end
local path = type(request) == "table" and request.path or nil
if path == nil or not settings.paths[path] then
clear_state(key)
states[key] = { bypass = true }
end
return nil
end
function plugin.on_response(ctx, response)
-- This example's guarantee is SSE-only. Refuse ordinary responses rather
-- than silently passing unredacted content through the same enabled rule.
if type(response) ~= "table" then
return { action = "block", reason = "invalid response object" }
end
-- 新增:请求阶段已判定为非 AI 路径(bypass),本插件不参与其响应处理。
-- 非流式响应一次性结束,顺手清掉标记;流式响应交给 on_event/on_end 收尾。
local key = request_key(ctx)
local state = key and states[key] or nil
if state and state.bypass then
if response.streaming ~= true then
clear_state(key)
end
return nil
end
if response.streaming == true then
return nil
end
return { action = "block", reason = "stream_redact only supports SSE responses" }
end
function plugin.on_event(ctx, event)
local key = request_key(ctx)
if not key then
return { action = "block", reason = "missing request id" }
end
-- 新增:请求阶段已判定为非 AI 路径(bypass),事件流不归本插件管。
-- 必须放在事件合法性检查和状态创建之前,否则非 AI 流量会被
-- 无条件缓冲到流结束,甚至因事件形态不符被 fail-closed 拦截。
local existing = states[key]
if existing and existing.bypass then
return nil
end
local size = estimate_event_bytes(event)
if not size then
return block_and_clear(key, "invalid SSE event")
end
local state = existing
-- Once a terminal failure was observed, *all* subsequent events, including
-- duplicate terminal errors, are rejected. This check must precede name lookup.
if state and state.aborted then
return { action = "block", reason = "event received after terminal error" }
end
if not state then
if not settings then
return { action = "block", reason = "plugin not initialized" }
end
state = {
settings = copy_settings(settings),
frames = {},
buffer_bytes = 0,
text_tail = "",
}
states[key] = state
end
-- Terminal error names come only from the validated, request-snapshotted config.
if event.event and state.settings.terminal_error_events[event.event] then
return redact_terminal_error_event(key, state, event)
end
-- Valid no-data SSE frames (typically comment heartbeats) carry no content.
-- They pass immediately, but only after checking terminal state above.
if event.has_data == false then
return { action = "pass" }
end
if state.buffer_bytes + size > state.settings.max_buffer_bytes then
return block_and_clear(key, "estimated stream redaction buffer limit exceeded")
end
-- Validate and update the <=18-byte cross-frame inspection tail as each
-- configured text-bearing event arrives. This avoids O(frame_count) decode
-- work if a terminal error arrives after a large buffered response.
if not update_pending_text_tail(state, event) then
return block_and_clear(key, "text event payload does not match configured content_path")
end
state.frames[#state.frames + 1] = event
state.buffer_bytes = state.buffer_bytes + size
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
-- 新增:bypass 请求全程未缓冲,结束钩子只需清理标记。
if state.bypass then
clear_state(key)
return nil
end
if state.aborted then
clear_state(key)
return nil
end
if #state.frames == 0 then
clear_state(key)
return nil
end
return redact_and_release(key, state)
end
function plugin.close(ctx)
-- Only clear this request. On abnormal close, held text is deliberately dropped.
clear_state(request_key(ctx))
end
return plugin